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 |
|---|---|---|---|---|---|---|---|---|---|---|
CmosWolf1/Code_implementation_for_paper_SKZC | demo.py | [
{
"identifier": "VisualizationDemo",
"path": "diffusiondet/predictor.py",
"snippet": "class VisualizationDemo(object):\n def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False):\n \"\"\"\n Args:\n cfg (CfgNode):\n instance_mode (ColorMode):\n ... | import argparse
import glob
import multiprocessing as mp
import numpy as np
import os
import tempfile
import time
import warnings
import cv2
import tqdm
from detectron2.config import get_cfg
from detectron2.data.detection_utils import read_image
from detectron2.utils.logger import setup_logger
from diffusiondet.predictor import VisualizationDemo
from diffusiondet import DiffusionDetDatasetMapper, add_diffusiondet_config, DiffusionDetWithTTA
from diffusiondet.util.model_ema import add_model_ema_configs, may_build_model_ema, may_get_ema_checkpointer, EMAHook, \
apply_model_ema_and_restore, EMADetectionCheckpointer | 6,691 | # Copyright (c) Facebook, Inc. and its affiliates.
# constants
WINDOW_NAME = "COCO detections"
def setup_cfg(args):
# load config from file and command-line arguments
cfg = get_cfg()
# To use demo for Panoptic-DeepLab, please uncomment the following two lines.
# from detectron2.projects.panoptic_deeplab import add_panoptic_deeplab_config # noqa
# add_panoptic_deeplab_config(cfg)
add_diffusiondet_config(cfg)
| # Copyright (c) Facebook, Inc. and its affiliates.
# constants
WINDOW_NAME = "COCO detections"
def setup_cfg(args):
# load config from file and command-line arguments
cfg = get_cfg()
# To use demo for Panoptic-DeepLab, please uncomment the following two lines.
# from detectron2.projects.panoptic_deeplab import add_panoptic_deeplab_config # noqa
# add_panoptic_deeplab_config(cfg)
add_diffusiondet_config(cfg) | add_model_ema_configs(cfg) | 4 | 2023-11-17 02:37:37+00:00 | 8k |
fg320/DEASC | examples/12A_5x1_farm_dyn_tuning_dataset_grouping.py | [
{
"identifier": "WfModel",
"path": "deasc/wf_model.py",
"snippet": "class WfModel:\n \"\"\"\n Class for wind farm modelling (Interface setup but not limited to FLORIS\n framework).\n \"\"\"\n\n def __init__(self, input_file, path):\n \"\"\"\n Initialise wind farm object by p... | import numpy as np
import multiprocessing as mp
from deasc import WfModel
from deasc import Tuning
from deasc.utils import yaw_permutations_grouping_0last
from deasc.utils_floris import (
floris_extract_object_dict,
floris_extract_parameter,
floris_param_change_object_dict,
floris_param_change_object
) | 5,769 |
"""
This example shows how to create, in parallel, an optimal parameter dataset for Jensen
wake expansion parameter k tuned to GCH model power predictions using the grouping
approach for a 5x1 wind farm of NREL 5 MW turbines. The training conditions are defined
as the yaw permutations of the two most upstream groups, each of two turbines. For each
condition, parameter k is tuned on that single condition and added to the optimal
parameter dataset.
"""
# %% Parameter tuning function - Run a single optimisation for each trainign condition
def function(i, yaw, inflow, wt_pow_training_list):
# Extract inflow
wd, ws, ti, shear = inflow
# Initialise trainee and set farm layout
path = "./inputs/"
input_file_trainee = "jensen.yaml"
trainee = WfModel(input_file_trainee, path)
trainee.set_aligned_layout(5, 1, 7, 5)
# Set kd deflection parameter
trainee_dict = floris_extract_object_dict(trainee)
trainee_dict = floris_param_change_object_dict(trainee_dict,
'wake_deflection_parameters',
'kd',
0.3)
|
"""
This example shows how to create, in parallel, an optimal parameter dataset for Jensen
wake expansion parameter k tuned to GCH model power predictions using the grouping
approach for a 5x1 wind farm of NREL 5 MW turbines. The training conditions are defined
as the yaw permutations of the two most upstream groups, each of two turbines. For each
condition, parameter k is tuned on that single condition and added to the optimal
parameter dataset.
"""
# %% Parameter tuning function - Run a single optimisation for each trainign condition
def function(i, yaw, inflow, wt_pow_training_list):
# Extract inflow
wd, ws, ti, shear = inflow
# Initialise trainee and set farm layout
path = "./inputs/"
input_file_trainee = "jensen.yaml"
trainee = WfModel(input_file_trainee, path)
trainee.set_aligned_layout(5, 1, 7, 5)
# Set kd deflection parameter
trainee_dict = floris_extract_object_dict(trainee)
trainee_dict = floris_param_change_object_dict(trainee_dict,
'wake_deflection_parameters',
'kd',
0.3) | trainee = floris_param_change_object(trainee, trainee_dict) | 6 | 2023-11-10 18:13:27+00:00 | 8k |
CPES-Power-and-Energy-Systems/interoperable-recommender-tso | energy_app/packages/entsoe-py/entsoe/parsers.py | [
{
"identifier": "PSRTYPE_MAPPINGS",
"path": "energy_app/packages/entsoe-py/entsoe/mappings.py",
"snippet": "PSRTYPE_MAPPINGS = {\n 'A03': 'Mixed',\n 'A04': 'Generation',\n 'A05': 'Load',\n 'B01': 'Biomass',\n 'B02': 'Fossil Brown coal/Lignite',\n 'B03': 'Fossil Coal-derived gas',\n ... | import sys
import zipfile
import warnings
import bs4
import pandas as pd
from io import BytesIO
from typing import Union
from bs4.builder import XMLParsedAsHTMLWarning
from .mappings import PSRTYPE_MAPPINGS, DOCSTATUS, BSNTYPE, Area | 6,229 | series = series.sort_index()
series.index = _parse_datetimeindex(soup, tz)
return series
def _parse_installed_capacity_per_plant(soup):
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
extract_vals = {'Name': 'registeredresource.name',
'Production Type': 'psrtype',
'Bidding Zone': 'inbiddingzone_domain.mrid',
# 'Status': 'businesstype',
'Voltage Connection Level [kV]':
'voltage_powersystemresources.highvoltagelimit'}
series = pd.Series(extract_vals).apply(lambda v: soup.find(v).text)
# extract only first point
series['Installed Capacity [MW]'] = \
soup.find_all('point')[0].find('quantity').text
series.name = soup.find('registeredresource.mrid').text
return series
def _parse_datetimeindex(soup, tz=None):
"""
Create a datetimeindex from a parsed beautifulsoup,
given that it contains the elements 'start', 'end'
and 'resolution'
Parameters
----------
soup : bs4.element.tag
tz: str
Returns
-------
pd.DatetimeIndex
"""
start = pd.Timestamp(soup.find('start').text)
end = pd.Timestamp(soup.find_all('end')[-1].text)
if tz is not None:
start = start.tz_convert(tz)
end = end.tz_convert(tz)
delta = _resolution_to_timedelta(res_text=soup.find('resolution').text)
index = pd.date_range(start=start, end=end, freq=delta, inclusive='left')
if tz is not None:
dst_jump = len(set(index.map(lambda d: d.dst()))) > 1
if dst_jump and delta == "7D":
# For a weekly granularity, if we jump over the DST date in October,
# date_range erronously returns an additional index element
# because that week contains 169 hours instead of 168.
index = index[:-1]
index = index.tz_convert("UTC")
return index
def _parse_crossborder_flows_timeseries(soup):
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
positions = []
flows = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
flows.append(float(point.find('quantity').text))
series = pd.Series(index=positions, data=flows)
series = series.sort_index()
try:
series.index = _parse_datetimeindex(soup)
except ValueError as ex:
if "Length mismatch" in str(ex):
series.index = _parse_datetimeindex(soup)[:-1]
return series
def _resolution_to_timedelta(res_text: str) -> str:
"""
Convert an Entsoe resolution to something that pandas can understand
"""
resolutions = {
'PT60M': '60min',
'P1Y': '12M',
'PT15M': '15min',
'PT30M': '30min',
'P1D': '1D',
'P7D': '7D',
'P1M': '1M',
}
delta = resolutions.get(res_text)
if delta is None:
raise NotImplementedError("Sorry, I don't know what to do with the "
"resolution '{}', because there was no "
"documentation to be found of this format. "
"Everything is hard coded. Please open an "
"issue.".format(res_text))
return delta
# Define inverse bidding zone dico to look up bidding zone labels from the
# domain code in the unavailibility parsers:
|
warnings.filterwarnings('ignore', category=XMLParsedAsHTMLWarning)
GENERATION_ELEMENT = "inBiddingZone_Domain.mRID"
CONSUMPTION_ELEMENT = "outBiddingZone_Domain.mRID"
def _extract_timeseries(xml_text):
"""
Parameters
----------
xml_text : str
Yields
-------
bs4.element.tag
"""
if not xml_text:
return
soup = bs4.BeautifulSoup(xml_text, 'html.parser')
for timeseries in soup.find_all('timeseries'):
yield timeseries
def parse_prices(xml_text):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.Series
"""
series = {
'15T': [],
'30T': [],
'60T': []
}
for soup in _extract_timeseries(xml_text):
soup_series = _parse_price_timeseries(soup)
series[soup_series.index.freqstr].append(soup_series)
for freq, freq_series in series.items():
if len(freq_series) > 0:
series[freq] = pd.concat(freq_series).sort_index()
return series
def parse_netpositions(xml_text):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.Series
"""
series = []
for soup in _extract_timeseries(xml_text):
series.append(_parse_netposition_timeseries(soup))
series = pd.concat(series)
series = series.sort_index()
return series
def parse_loads(xml_text, process_type='A01'):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.DataFrame
"""
if process_type == 'A01' or process_type == 'A16':
series = []
for soup in _extract_timeseries(xml_text):
series.append(_parse_load_timeseries(soup))
series = pd.concat(series)
series = series.sort_index()
return pd.DataFrame({
'Forecasted Load' if process_type == 'A01' else 'Actual Load': series
})
else:
series_min = pd.Series(dtype='object')
series_max = pd.Series(dtype='object')
for soup in _extract_timeseries(xml_text):
t = _parse_load_timeseries(soup)
if soup.find('businesstype').text == 'A60':
series_min = series_min.append(t)
elif soup.find('businesstype').text == 'A61':
series_max = series_max.append(t)
else:
continue
return pd.DataFrame({
'Min Forecasted Load': series_min,
'Max Forecasted Load': series_max
})
def parse_generation(
xml_text: str,
per_plant: bool = False,
include_eic: bool = False,
nett: bool = False) -> Union[pd.DataFrame, pd.Series]:
"""
Parameters
----------
xml_text : str
per_plant : bool
Decide if you need the parser that can extract plant info as well.
nett : bool
If you want to condense generation and consumption of a plant into a
nett number
include_eic: bool
If you want to include the eic code of a plan in the output
Returns
-------
pd.DataFrame | pd.Series
"""
all_series = dict()
for soup in _extract_timeseries(xml_text):
ts = _parse_generation_timeseries(soup, per_plant=per_plant, include_eic=include_eic)
# check if we already have a series of this name
series = all_series.get(ts.name)
if series is None:
# If not, we just save ts
all_series[ts.name] = ts
else:
# If yes, we extend it
series = pd.concat([series, ts])
series.sort_index(inplace=True)
all_series[series.name] = series
# drop duplicates in all series
for name in all_series:
ts = all_series[name]
all_series[name] = ts[~ts.index.duplicated(keep='first')]
df = pd.DataFrame.from_dict(all_series)
df.sort_index(inplace=True)
df = _calc_nett_and_drop_redundant_columns(df, nett=nett)
return df
def _calc_nett_and_drop_redundant_columns(
df: pd.DataFrame, nett: bool) -> pd.DataFrame:
def _calc_nett(_df):
try:
if set(['Actual Aggregated']).issubset(_df):
if set(['Actual Consumption']).issubset(_df):
_new = _df['Actual Aggregated'].fillna(0) - _df[
'Actual Consumption'].fillna(0)
else:
_new = _df['Actual Aggregated'].fillna(0)
else:
_new = -_df['Actual Consumption'].fillna(0)
except KeyError:
print ('Netting production and consumption not possible. Column not found')
return _new
if hasattr(df.columns, 'levels'):
if len(df.columns.levels[-1]) == 1:
# Drop the extra header, if it is redundant
df = df.droplevel(axis=1, level=-1)
elif nett:
frames = []
for column in df.columns.levels[-2]:
new = _calc_nett(df[column])
new.name = column
frames.append(new)
df = pd.concat(frames, axis=1)
else:
if nett:
df = _calc_nett(df)
elif len(df.columns) == 1:
df = df.squeeze()
return df
def parse_installed_capacity_per_plant(xml_text):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.DataFrame
"""
all_series = {}
for soup in _extract_timeseries(xml_text):
s = _parse_installed_capacity_per_plant(soup)
series = all_series.get(s.name)
if series is None:
all_series[s.name] = s
else:
series = pd.concat([series, s])
series.sort_index()
all_series[series.name] = series
for name in all_series:
ts = all_series[name]
all_series[name] = ts[~ts.index.duplicated(keep='first')]
df = pd.DataFrame.from_dict(all_series).T
df['Production Type'] = df['Production Type'].map(PSRTYPE_MAPPINGS)
df['Name'] = df['Name'].str.encode('latin-1').str.decode('utf-8')
# df['Status'] = df['Status'].map(BSNTYPE)
return df
def parse_water_hydro(xml_text, tz):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.Series
"""
all_series = []
for soup in _extract_timeseries(xml_text):
all_series.append(_parse_water_hydro_timeseries(soup, tz=tz))
series = pd.concat(all_series)
return series
def parse_crossborder_flows(xml_text):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.Series
"""
series = []
for soup in _extract_timeseries(xml_text):
series.append(_parse_crossborder_flows_timeseries(soup))
series = pd.concat(series)
series = series.sort_index()
return series
def parse_imbalance_prices(xml_text):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.DataFrame
"""
timeseries_blocks = _extract_timeseries(xml_text)
frames = (_parse_imbalance_prices_timeseries(soup)
for soup in timeseries_blocks)
df = pd.concat(frames, axis=1)
df = df.stack().unstack() # ad-hoc fix to prevent column splitting by NaNs
df.sort_index(inplace=True)
return df
def parse_imbalance_volumes(xml_text):
"""
Parameters
----------
xml_text : str
Returns
-------
pd.DataFrame
"""
timeseries_blocks = _extract_timeseries(xml_text)
frames = (_parse_imbalance_volumes_timeseries(soup)
for soup in timeseries_blocks)
df = pd.concat(frames, axis=1)
df = df.stack().unstack() # ad-hoc fix to prevent column splitting by NaNs
df.sort_index(inplace=True)
return df
def parse_procured_balancing_capacity(xml_text, tz):
"""
Parameters
----------
xml_text : str
tz: str
Returns
-------
pd.DataFrame
"""
timeseries_blocks = _extract_timeseries(xml_text)
frames = (_parse_procured_balancing_capacity(soup, tz)
for soup in timeseries_blocks)
df = pd.concat(frames, axis=1)
df.sort_index(axis=0, inplace=True)
df.sort_index(axis=1, inplace=True)
return df
def _parse_procured_balancing_capacity(soup, tz):
"""
Parameters
----------
soup : bs4.element.tag
tz: str
Returns
-------
pd.DataFrame
"""
direction = {
'A01': 'Up',
'A02': 'Down'
}
flow_direction = direction[soup.find('flowdirection.direction').text]
period = soup.find('period')
start = pd.to_datetime(period.find('timeinterval').find('start').text)
end = pd.to_datetime(period.find('timeinterval').find('end').text)
resolution = _resolution_to_timedelta(period.find('resolution').text)
tx = pd.date_range(start=start, end=end, freq=resolution, inclusive='left')
points = period.find_all('point')
df = pd.DataFrame(index=tx, columns=['Price', 'Volume'])
for dt, point in zip(tx, points):
df.loc[dt, 'Price'] = float(point.find('procurement_price.amount').text)
df.loc[dt, 'Volume'] = float(point.find('quantity').text)
mr_id = int(soup.find('mrid').text)
df.columns = pd.MultiIndex.from_product(
[[flow_direction], [mr_id], df.columns],
names=('direction', 'mrid', 'unit')
)
return df
def parse_contracted_reserve(xml_text, tz, label):
"""
Parameters
----------
xml_text : str
tz: str
label: str
Returns
-------
pd.DataFrame
"""
timeseries_blocks = _extract_timeseries(xml_text)
frames = (_parse_contracted_reserve_series(soup, tz, label)
for soup in timeseries_blocks)
df = pd.concat(frames, axis=1)
# Ad-hoc fix to prevent that columns are split by NaNs:
df = df.groupby(axis=1, level = [0,1]).mean()
df.sort_index(inplace=True)
return df
def _parse_contracted_reserve_series(soup, tz, label):
"""
Parameters
----------
soup : bs4.element.tag
tz: str
label: str
Returns
-------
pd.Series
"""
positions = []
prices = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
prices.append(float(point.find(label).text))
df = pd.DataFrame(data={'position': positions,
label: prices})
df = df.set_index(['position'])
df.sort_index(inplace=True)
index = _parse_datetimeindex(soup, tz)
if len(index) > len(df.index):
print("Shortening index", file=sys.stderr)
df.index = index[:len(df.index)]
else:
df.index = index
df.index.name = None
df.columns.name = None
direction_dico = {'A01': 'Up',
'A02': 'Down',
'A03': 'Symmetric'}
# First column level: the type of reserve
reserve_type = BSNTYPE[soup.find("businesstype").text]
df.rename(columns={label: reserve_type}, inplace=True)
# Second column level: the flow direction
direction = direction_dico[soup.find("flowdirection.direction").text]
df.columns = pd.MultiIndex.from_product([df.columns, [direction]])
return df
def parse_imbalance_prices_zip(zip_contents: bytes) -> pd.DataFrame:
"""
Parameters
----------
zip_contents : bytes
Returns
-------
pd.DataFrame
"""
def gen_frames(archive):
with zipfile.ZipFile(BytesIO(archive), 'r') as arc:
for f in arc.infolist():
if f.filename.endswith('xml'):
frame = parse_imbalance_prices(xml_text=arc.read(f))
yield frame
frames = gen_frames(zip_contents)
df = pd.concat(frames)
df.sort_index(inplace=True)
return df
def _parse_imbalance_prices_timeseries(soup) -> pd.DataFrame:
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.DataFrame
"""
positions = []
amounts = []
categories = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
amounts.append(float(point.find('imbalance_price.amount').text))
if point.find('imbalance_price.category'):
categories.append(point.find('imbalance_price.category').text)
else:
categories.append('None')
df = pd.DataFrame(data={'position': positions,
'amount': amounts, 'category': categories})
df = df.set_index(['position', 'category']).unstack()
df.sort_index(inplace=True)
df.index = _parse_datetimeindex(soup)
df = df.xs('amount', axis=1)
df.index.name = None
df.columns.name = None
df.rename(columns={'A04': 'Long', 'A05': 'Short',
'None': 'Price for Consumption'}, inplace=True)
return df
def parse_imbalance_volumes_zip(zip_contents: bytes) -> pd.DataFrame:
"""
Parameters
----------
zip_contents : bytes
Returns
-------
pd.DataFrame
"""
def gen_frames(archive):
with zipfile.ZipFile(BytesIO(archive), 'r') as arc:
for f in arc.infolist():
if f.filename.endswith('xml'):
frame = parse_imbalance_volumes(xml_text=arc.read(f))
yield frame
frames = gen_frames(zip_contents)
df = pd.concat(frames)
df.sort_index(inplace=True)
return df
def _parse_imbalance_volumes_timeseries(soup) -> pd.DataFrame:
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.DataFrame
"""
flow_direction = soup.find('flowdirection.direction')
if flow_direction:
# time series uses flow direction codes
flow_direction_factor = {
'A01': 1, # in
'A02': -1 # out
}[flow_direction.text]
else:
# time series uses positive and negative values
flow_direction_factor = 1
df = pd.DataFrame(columns=['Imbalance Volume'])
for period in soup.find_all('period'):
start = pd.to_datetime(period.find('timeinterval').find('start').text)
end = pd.to_datetime(period.find('timeinterval').find('end').text)
resolution = _resolution_to_timedelta(period.find('resolution').text)
tx = pd.date_range(start=start, end=end, freq=resolution, inclusive='left')
points = period.find_all('point')
for dt, point in zip(tx, points):
df.loc[dt, 'Imbalance Volume'] = \
float(point.find('quantity').text) * flow_direction_factor
df.set_index(['Imbalance Volume'])
return df
def _parse_netposition_timeseries(soup):
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
positions = []
quantities = []
if 'REGION' in soup.find('out_domain.mrid').text:
factor = -1 # flow is import so negative
else:
factor = 1
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
quantities.append(factor * float(point.find('quantity').text))
series = pd.Series(index=positions, data=quantities)
series = series.sort_index()
series.index = _parse_datetimeindex(soup)
return series
def _parse_price_timeseries(soup):
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
positions = []
prices = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
prices.append(float(point.find('price.amount').text))
series = pd.Series(index=positions, data=prices)
series = series.sort_index()
series.index = _parse_datetimeindex(soup)
return series
def _parse_load_timeseries(soup):
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
positions = []
prices = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
prices.append(float(point.find('quantity').text))
series = pd.Series(index=positions, data=prices)
series = series.sort_index()
series.index = _parse_datetimeindex(soup)
return series
def _parse_generation_timeseries(soup, per_plant: bool = False, include_eic: bool = False) -> pd.Series:
"""
Works for generation by type, generation forecast, and wind and solar
forecast
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
positions = []
quantities = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
quantity = point.find('quantity')
if quantity is None:
raise LookupError(
f'No quantity found in this point, it should have one: {point}')
quantities.append(float(quantity.text))
series = pd.Series(index=positions, data=quantities)
series = series.sort_index()
series.index = _parse_datetimeindex(soup)
# Check if there is a psrtype, if so, get it.
_psrtype = soup.find('psrtype')
if _psrtype is not None:
psrtype = _psrtype.text
else:
psrtype = None
# Check if the Direction is IN or OUT
# If IN, this means Actual Consumption is measured
# If OUT, this means Consumption is measured.
# OUT means Consumption of a generation plant, eg. charging a pumped hydro plant
if soup.find(CONSUMPTION_ELEMENT.lower()):
metric = 'Actual Consumption'
else:
metric = 'Actual Aggregated'
name = [metric]
# Set both psrtype and metric as names of the series
if psrtype:
psrtype_name = PSRTYPE_MAPPINGS[psrtype]
name.append(psrtype_name)
if per_plant:
plantname = soup.find('name').text
name.append(plantname)
if include_eic:
eic = soup.find("mrid", codingscheme="A01").text
name.insert(0, eic)
if len(name) == 1:
series.name = name[0]
else:
# We give the series multiple names in a tuple
# This will result in a multi-index upon concatenation
name.reverse()
series.name = tuple(name)
return series
def _parse_water_hydro_timeseries(soup, tz):
"""
Parses timeseries for water reservoirs and hydro storage plants
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
positions = []
quantities = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
quantity = point.find('quantity')
if quantity is None:
raise LookupError(
f'No quantity found in this point, it should have one: {point}')
quantities.append(float(quantity.text))
series = pd.Series(index=positions, data=quantities)
series = series.sort_index()
series.index = _parse_datetimeindex(soup, tz)
return series
def _parse_installed_capacity_per_plant(soup):
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
extract_vals = {'Name': 'registeredresource.name',
'Production Type': 'psrtype',
'Bidding Zone': 'inbiddingzone_domain.mrid',
# 'Status': 'businesstype',
'Voltage Connection Level [kV]':
'voltage_powersystemresources.highvoltagelimit'}
series = pd.Series(extract_vals).apply(lambda v: soup.find(v).text)
# extract only first point
series['Installed Capacity [MW]'] = \
soup.find_all('point')[0].find('quantity').text
series.name = soup.find('registeredresource.mrid').text
return series
def _parse_datetimeindex(soup, tz=None):
"""
Create a datetimeindex from a parsed beautifulsoup,
given that it contains the elements 'start', 'end'
and 'resolution'
Parameters
----------
soup : bs4.element.tag
tz: str
Returns
-------
pd.DatetimeIndex
"""
start = pd.Timestamp(soup.find('start').text)
end = pd.Timestamp(soup.find_all('end')[-1].text)
if tz is not None:
start = start.tz_convert(tz)
end = end.tz_convert(tz)
delta = _resolution_to_timedelta(res_text=soup.find('resolution').text)
index = pd.date_range(start=start, end=end, freq=delta, inclusive='left')
if tz is not None:
dst_jump = len(set(index.map(lambda d: d.dst()))) > 1
if dst_jump and delta == "7D":
# For a weekly granularity, if we jump over the DST date in October,
# date_range erronously returns an additional index element
# because that week contains 169 hours instead of 168.
index = index[:-1]
index = index.tz_convert("UTC")
return index
def _parse_crossborder_flows_timeseries(soup):
"""
Parameters
----------
soup : bs4.element.tag
Returns
-------
pd.Series
"""
positions = []
flows = []
for point in soup.find_all('point'):
positions.append(int(point.find('position').text))
flows.append(float(point.find('quantity').text))
series = pd.Series(index=positions, data=flows)
series = series.sort_index()
try:
series.index = _parse_datetimeindex(soup)
except ValueError as ex:
if "Length mismatch" in str(ex):
series.index = _parse_datetimeindex(soup)[:-1]
return series
def _resolution_to_timedelta(res_text: str) -> str:
"""
Convert an Entsoe resolution to something that pandas can understand
"""
resolutions = {
'PT60M': '60min',
'P1Y': '12M',
'PT15M': '15min',
'PT30M': '30min',
'P1D': '1D',
'P7D': '7D',
'P1M': '1M',
}
delta = resolutions.get(res_text)
if delta is None:
raise NotImplementedError("Sorry, I don't know what to do with the "
"resolution '{}', because there was no "
"documentation to be found of this format. "
"Everything is hard coded. Please open an "
"issue.".format(res_text))
return delta
# Define inverse bidding zone dico to look up bidding zone labels from the
# domain code in the unavailibility parsers: | _INV_BIDDING_ZONE_DICO = {area.code: area.name for area in Area} | 3 | 2023-11-17 09:23:38+00:00 | 8k |
PlaxtonFlarion/NexaFlow | nexaflow/classifier/base.py | [
{
"identifier": "toolbox",
"path": "nexaflow/toolbox.py",
"snippet": "def video_capture(video_path: str):\ndef video_jump(video_cap: cv2.VideoCapture, frame_id: int):\ndef compare_ssim(pic1: np.ndarray, pic2: np.ndarray) -> float:\ndef multi_compare_ssim(\n pic1_list: typing.List, pic2_list: typing.L... | import os
import cv2
import json
import time
import typing
import pathlib
import difflib
import numpy as np
from loguru import logger
from collections import OrderedDict
from nexaflow import toolbox, constants
from nexaflow.video import VideoFrame, VideoObject
from nexaflow.cutter.cut_range import VideoCutRange
from nexaflow.hook import BaseHook, CompressHook, GreyHook | 4,809 |
class SingleClassifierResult(object):
def __init__(
self,
video_path: str,
frame_id: int,
timestamp: float,
stage: str,
data: np.ndarray = None,
):
self.video_path: str = video_path
self.frame_id: int = frame_id
self.timestamp: float = timestamp
self.stage: str = stage
self.data: np.ndarray = data
def to_video_frame(self, *args, **kwargs) -> VideoFrame:
if self.data is not None:
return VideoFrame(self.frame_id, self.timestamp, self.data)
with toolbox.video_capture(self.video_path) as cap:
frame = toolbox.get_frame(cap, self.frame_id)
compressed = toolbox.compress_frame(frame, *args, **kwargs)
return VideoFrame(self.frame_id, self.timestamp, compressed)
def get_data(self) -> np.ndarray:
return self.to_video_frame().data
def is_stable(self) -> bool:
return self.stage not in (
|
class SingleClassifierResult(object):
def __init__(
self,
video_path: str,
frame_id: int,
timestamp: float,
stage: str,
data: np.ndarray = None,
):
self.video_path: str = video_path
self.frame_id: int = frame_id
self.timestamp: float = timestamp
self.stage: str = stage
self.data: np.ndarray = data
def to_video_frame(self, *args, **kwargs) -> VideoFrame:
if self.data is not None:
return VideoFrame(self.frame_id, self.timestamp, self.data)
with toolbox.video_capture(self.video_path) as cap:
frame = toolbox.get_frame(cap, self.frame_id)
compressed = toolbox.compress_frame(frame, *args, **kwargs)
return VideoFrame(self.frame_id, self.timestamp, compressed)
def get_data(self) -> np.ndarray:
return self.to_video_frame().data
def is_stable(self) -> bool:
return self.stage not in ( | constants.UNSTABLE_FLAG, | 1 | 2023-11-13 05:27:34+00:00 | 8k |
OpenBMB/XAgent | XAgent/recorder.py | [
{
"identifier": "AutoGPTQuery",
"path": "XAgent/workflow/base_query.py",
"snippet": "class AutoGPTQuery(BaseQuery):\n \"\"\"\n A specific type of query that inherits from the BaseQuery class.\n Used for specific GPT model actions.\n \"\"\"\n\n def __init__(self,**args):\n \"\"\"\n ... | from contextlib import contextmanager
from colorama import Fore
from XAgent.workflow.base_query import AutoGPTQuery
from XAgent.config import XAgentConfig
from XAgentServer.database.connect import SessionLocal
from XAgentServer.loggers.logs import Logger
from XAgentServer.models.recorder import XAgentRunningRecord
from XAgentServer.application.cruds.recorder import RunningRecordCRUD
from XAgentServer.enums.recorder_type import RecorderTypeEnum
import datetime
import os
import time
import json
import re | 4,735 | """XAgent Running Recorder Util"""
def dump_common_things(object):
"""common"""
if type(object) in [str, int, float, bool]:
return object
if isinstance(object, dict):
return {dump_common_things(key): dump_common_things(value) for key, value in object.items()}
if isinstance(object, list):
return [dump_common_things(cont) for cont in object]
method = getattr(object, 'to_json', None)
if callable(method):
return method()
@contextmanager
def get_db():
"""
Provide a transactional scope around a series of operations.
"""
session = SessionLocal()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
class RunningRecoder():
"""A class used to record the running sequences of the program, also including program query status and config data.
"""
def __init__(self, record_id: str, newly_start=True, root_dir=None, logger: Logger=None):
self.record_id = record_id
self.record_root_dir = root_dir
if not os.path.exists(self.record_root_dir):
os.makedirs(self.record_root_dir, exist_ok=True)
self.newly_start = newly_start # 是全新启动的
self.logger = logger
self.query = {}
self.config = {}
self.llm_interface_id = 0
self.toolserver_interface_id = 0
self.tool_call_id = 0
self.plan_refine_id = 0
self.llm_server_cache = []
self.tool_server_cache = []
self.tool_call_cache = []
self.plan_refine_cache = []
self.now_subtask_id = None
def change_now_task(self, new_subtask_id):
"""change now task"""
self.now_subtask_id = new_subtask_id
self.tool_call_id = 0
self.plan_refine_id = 0
def generate_record(self, current, node_id, node_type, data):
"""generate a recorder"""
self.logger.typewriter_log(title="-=-=-=-=-=-=-=Recorder Start-=-=-=-=-=-=-=\n",
title_color=Fore.GREEN,
content=f"Current: {current} Node: {node_type} {node_id}")
json_str = json.dumps(data, ensure_ascii=False, indent=4)
json_str=re.sub(r'"api_key": "(.+?)"', r'"api_key": "**"', json_str)
self.logger.typewriter_log(title="-=-=-=-=-=-=-=Data -=-=-=-=-=-=-=\n",
title_color=Fore.GREEN,
content=json_str)
self.logger.typewriter_log(title="-=-=-=-=-=-=-=Recorder End-=-=-=-=-=-=-=",
title_color=Fore.GREEN,
content="")
return XAgentRunningRecord(
record_id=self.record_id,
current=current,
node_id=node_id,
node_type=node_type,
data=data,
create_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
update_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
is_deleted=False,
)
def regist_plan_modify(self,
refine_function_name,
refine_function_input,
refine_function_output,
plan_after):
"""注册一个plan_refine的记录"""
plan_refine_record = {
"refine_function_name": dump_common_things(refine_function_name),
"refine_function_input": dump_common_things(refine_function_input),
"refine_function_output": dump_common_things(refine_function_output),
"plan_after": dump_common_things(plan_after),
}
record = self.generate_record(
current=self.now_subtask_id,
node_id=self.plan_refine_id,
node_type=RecorderTypeEnum.PLAN_REFINE,
data=plan_refine_record,
)
with get_db() as db:
| """XAgent Running Recorder Util"""
def dump_common_things(object):
"""common"""
if type(object) in [str, int, float, bool]:
return object
if isinstance(object, dict):
return {dump_common_things(key): dump_common_things(value) for key, value in object.items()}
if isinstance(object, list):
return [dump_common_things(cont) for cont in object]
method = getattr(object, 'to_json', None)
if callable(method):
return method()
@contextmanager
def get_db():
"""
Provide a transactional scope around a series of operations.
"""
session = SessionLocal()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
class RunningRecoder():
"""A class used to record the running sequences of the program, also including program query status and config data.
"""
def __init__(self, record_id: str, newly_start=True, root_dir=None, logger: Logger=None):
self.record_id = record_id
self.record_root_dir = root_dir
if not os.path.exists(self.record_root_dir):
os.makedirs(self.record_root_dir, exist_ok=True)
self.newly_start = newly_start # 是全新启动的
self.logger = logger
self.query = {}
self.config = {}
self.llm_interface_id = 0
self.toolserver_interface_id = 0
self.tool_call_id = 0
self.plan_refine_id = 0
self.llm_server_cache = []
self.tool_server_cache = []
self.tool_call_cache = []
self.plan_refine_cache = []
self.now_subtask_id = None
def change_now_task(self, new_subtask_id):
"""change now task"""
self.now_subtask_id = new_subtask_id
self.tool_call_id = 0
self.plan_refine_id = 0
def generate_record(self, current, node_id, node_type, data):
"""generate a recorder"""
self.logger.typewriter_log(title="-=-=-=-=-=-=-=Recorder Start-=-=-=-=-=-=-=\n",
title_color=Fore.GREEN,
content=f"Current: {current} Node: {node_type} {node_id}")
json_str = json.dumps(data, ensure_ascii=False, indent=4)
json_str=re.sub(r'"api_key": "(.+?)"', r'"api_key": "**"', json_str)
self.logger.typewriter_log(title="-=-=-=-=-=-=-=Data -=-=-=-=-=-=-=\n",
title_color=Fore.GREEN,
content=json_str)
self.logger.typewriter_log(title="-=-=-=-=-=-=-=Recorder End-=-=-=-=-=-=-=",
title_color=Fore.GREEN,
content="")
return XAgentRunningRecord(
record_id=self.record_id,
current=current,
node_id=node_id,
node_type=node_type,
data=data,
create_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
update_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
is_deleted=False,
)
def regist_plan_modify(self,
refine_function_name,
refine_function_input,
refine_function_output,
plan_after):
"""注册一个plan_refine的记录"""
plan_refine_record = {
"refine_function_name": dump_common_things(refine_function_name),
"refine_function_input": dump_common_things(refine_function_input),
"refine_function_output": dump_common_things(refine_function_output),
"plan_after": dump_common_things(plan_after),
}
record = self.generate_record(
current=self.now_subtask_id,
node_id=self.plan_refine_id,
node_type=RecorderTypeEnum.PLAN_REFINE,
data=plan_refine_record,
)
with get_db() as db: | RunningRecordCRUD.insert_record(db=db, record=record) | 5 | 2023-10-16 03:44:57+00:00 | 8k |
deepseek-ai/DeepSeek-Coder | Evaluation/HumanEval/human_eval/evaluation.py | [
{
"identifier": "stream_jsonl",
"path": "Evaluation/HumanEval/human_eval/data.py",
"snippet": "def stream_jsonl(filename: str) -> Iterable[Dict]:\n \"\"\"\n Parses each jsonl line and yields it as a dictionary\n \"\"\"\n if filename.endswith(\".gz\"):\n with open(filename, \"rb\") as ... | import os
import sys
import fire
import json
import gzip
import regex
import numpy as np
import itertools
from typing import *
from tqdm.auto import tqdm
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from .data import stream_jsonl
from .execution import check_correctness | 7,149 | if is_mbpp:
return sample["generation"] + "\n" + "\n".join(problems[task_id]["test"])
prompt = sample["prompt"]
if example_test and "example_test" in problems[task_id] and problems[task_id]["example_test"] != "":
test = problems[task_id]["example_test"]
else:
test = problems[task_id]["test"]
code = sample["generation"]
# Pre-process for different languages
if language == "python":
test_setup = "\n".join(IMPORT_HELPER["python"]) + "\n"
test_string = test_setup + code + "\n" + test + "\n"
elif language == "cpp":
test_set_up = ""
for s in IMPORT_HELPER["cpp"]:
if s not in prompt:
test_set_up += s + "\n"
test_string = test_set_up + "\n" + code + "\n" + test
elif language == "java":
test_string = code + "\n" + test
elif language == "cs":
test_set_up = ""
for s in IMPORT_HELPER["cs"]:
test_set_up += s + "\n"
test_string = test_set_up + "\n" + code + "\n" + test
elif language in ["js", "javascript", "ts", "sh", "go"]:
test_string = code + "\n" + test
elif language == "go232":
import_string = problems[task_id]["import"]
prompt = prompt.replace(import_string, "")
if example_test and "example_test" in problems[task_id]:
test = problems[task_id]["example_test"]
else:
test = problems[task_id]["test"]
test_setup = problems[task_id]["test_setup"]
other_pkgs = []
for pkg in IMPORT_HELPER["go"]:
if pkg not in test_setup:
p = pkg.split("/")[-1]
if p + "." in code:
other_pkgs.append(f"\"{pkg}\"")
if other_pkgs:
import_other_pkgs = "import (\n" + " ".join([p + "\n" for p in other_pkgs]) + ")"
test_string = test_setup + "\n" + import_other_pkgs + "\n" + prompt + code + "\n" + test
else:
test_string = test_setup + "\n" + prompt + code + "\n" + test
elif language == "rust":
main = "\nfn main(){ \n } \n"
declaration = problems[task_id]["declaration"]
test_string = main + declaration + prompt + code + test
elif language == "php":
if code[:5] != "<?php":
code = "<?php\n" + code
test_string = code + "\n" + test + "?>"
return test_string
def stream_jsonl_all(filename: str) -> Iterable[Dict]:
"""
Streams a JSONL file.
"""
results = []
if filename.endswith(".gz"):
fp = gzip.open(open(filename, "rb"), "rt")
else:
fp = open(filename, "r")
for line in fp:
if any(not x.isspace() for x in line):
results.append(json.loads(line))
fp.close()
return results
def evaluate_functional_correctness(
input_file: str = None,
tmp_dir: str = "./",
n_workers: int = 32,
timeout: float = 10.0,
problem_file: str = "../data/humaneval_python.jsonl.gz",
out_dir: str = None,
k: List[int] = [1, 10, 100],
test_groundtruth: bool = False,
example_test: bool = False,
is_mbpp: bool = False,
language: str = "python",
):
"""
Evaluates the functional correctness of a model.
"""
if example_test:
print("Example test...")
problems = read_dataset(problem_file,
dataset_type="humaneval")
sample_jsonl = stream_jsonl_all(input_file)
with ThreadPoolExecutor(max_workers=n_workers) as executor:
futures = []
completion_id = Counter()
n_samples = 0
results = defaultdict(list)
if test_groundtruth:
print("Testing ground truth...")
for sample in tqdm(problems.values()):
task_id = sample["task_id"]
lang = task_id.split("/")[0].lower()
if lang == "javascript":
lang = "js"
tmp_dir_ = os.path.join(tmp_dir, lang, "evaluation")
sample["generation"] = sample["canonical_solution"]
sample["test_code"] = process_humaneval_test(sample, problems, example_test, language)
if sample["test_code"] is None:
continue
args = (task_id, sample, lang, timeout, tmp_dir_, completion_id[task_id])
|
IMPORT_HELPER = {
"python": [
"import math",
"import re",
"import sys",
"import copy",
"import datetime",
"import itertools",
"import collections",
"import heapq",
"import functools",
"import hashlib",
"import numpy",
"import numpy as np",
"import string",
"from typing import *",
"from collections import *",
],
"go" : [
"math",
"strings",
"fmt",
"strconv",
"time",
"bytes",
"regexp",
"sort",
"math/rand",
"crypto/md5",
],
"cpp" : [
"#include<stdlib.h>",
"#include<algorithm>",
"#include<math.h>",
"#include<stdio.h>",
"#include<vector>",
"#include<string>",
"#include<climits>",
"#include<cstring>",
"#include<iostream>",
"#include<cassert>"
],
"cs": ["using System.Numerics;", "using System.Diagnostics;", "using System.Collections.Generic;", "using System.Linq;", "using System.Text;", "using System.Security.Cryptography;", "using System.Collections.Generic;"]
}
LANGUAGE_NAME = {
"cpp" : "CPP",
"go" : "Go",
"java" : "Java",
"js" : "JavaScript",
"python": "Python",
}
def read_dataset(
data_file: str = None,
dataset_type: str = "humaneval",
num_shot=None,
) -> Dict:
"""
Reads a dataset and returns a dictionary of tasks.
"""
if num_shot is not None:
print(f"{num_shot}-shot setting...")
if "humaneval" in dataset_type.lower():
if data_file is None:
current_path = os.path.dirname(os.path.abspath(__file__))
data_file = os.path.join(current_path, "..", "humaneval-x", "python", "data", "humaneval_python.jsonl.gz")
dataset = {task["task_id"]: task for task in stream_jsonl(data_file)}
else:
raise f"Dataset: {dataset_type} not supported."
return dataset
def estimate_pass_at_k(
num_samples: Union[int, List[int], np.ndarray],
num_correct: Union[List[int], np.ndarray],
k: int
) -> np.ndarray:
"""
Estimates pass@k of each problem and returns them in an array.
"""
def estimator(n: int, c: int, k: int) -> float:
"""
Calculates 1 - comb(n - c, k) / comb(n, k).
"""
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
if isinstance(num_samples, int):
num_samples_it = itertools.repeat(num_samples, len(num_correct))
else:
assert len(num_samples) == len(num_correct)
num_samples_it = iter(num_samples)
return np.array([estimator(int(n), int(c), k) for n, c in zip(num_samples_it, num_correct)])
def process_humaneval_test(sample, problems, example_test=False, is_mbpp=False, language="python"):
"""
Processes a sample for evaluation.
"""
task_id = sample["task_id"]
if is_mbpp:
return sample["generation"] + "\n" + "\n".join(problems[task_id]["test"])
prompt = sample["prompt"]
if example_test and "example_test" in problems[task_id] and problems[task_id]["example_test"] != "":
test = problems[task_id]["example_test"]
else:
test = problems[task_id]["test"]
code = sample["generation"]
# Pre-process for different languages
if language == "python":
test_setup = "\n".join(IMPORT_HELPER["python"]) + "\n"
test_string = test_setup + code + "\n" + test + "\n"
elif language == "cpp":
test_set_up = ""
for s in IMPORT_HELPER["cpp"]:
if s not in prompt:
test_set_up += s + "\n"
test_string = test_set_up + "\n" + code + "\n" + test
elif language == "java":
test_string = code + "\n" + test
elif language == "cs":
test_set_up = ""
for s in IMPORT_HELPER["cs"]:
test_set_up += s + "\n"
test_string = test_set_up + "\n" + code + "\n" + test
elif language in ["js", "javascript", "ts", "sh", "go"]:
test_string = code + "\n" + test
elif language == "go232":
import_string = problems[task_id]["import"]
prompt = prompt.replace(import_string, "")
if example_test and "example_test" in problems[task_id]:
test = problems[task_id]["example_test"]
else:
test = problems[task_id]["test"]
test_setup = problems[task_id]["test_setup"]
other_pkgs = []
for pkg in IMPORT_HELPER["go"]:
if pkg not in test_setup:
p = pkg.split("/")[-1]
if p + "." in code:
other_pkgs.append(f"\"{pkg}\"")
if other_pkgs:
import_other_pkgs = "import (\n" + " ".join([p + "\n" for p in other_pkgs]) + ")"
test_string = test_setup + "\n" + import_other_pkgs + "\n" + prompt + code + "\n" + test
else:
test_string = test_setup + "\n" + prompt + code + "\n" + test
elif language == "rust":
main = "\nfn main(){ \n } \n"
declaration = problems[task_id]["declaration"]
test_string = main + declaration + prompt + code + test
elif language == "php":
if code[:5] != "<?php":
code = "<?php\n" + code
test_string = code + "\n" + test + "?>"
return test_string
def stream_jsonl_all(filename: str) -> Iterable[Dict]:
"""
Streams a JSONL file.
"""
results = []
if filename.endswith(".gz"):
fp = gzip.open(open(filename, "rb"), "rt")
else:
fp = open(filename, "r")
for line in fp:
if any(not x.isspace() for x in line):
results.append(json.loads(line))
fp.close()
return results
def evaluate_functional_correctness(
input_file: str = None,
tmp_dir: str = "./",
n_workers: int = 32,
timeout: float = 10.0,
problem_file: str = "../data/humaneval_python.jsonl.gz",
out_dir: str = None,
k: List[int] = [1, 10, 100],
test_groundtruth: bool = False,
example_test: bool = False,
is_mbpp: bool = False,
language: str = "python",
):
"""
Evaluates the functional correctness of a model.
"""
if example_test:
print("Example test...")
problems = read_dataset(problem_file,
dataset_type="humaneval")
sample_jsonl = stream_jsonl_all(input_file)
with ThreadPoolExecutor(max_workers=n_workers) as executor:
futures = []
completion_id = Counter()
n_samples = 0
results = defaultdict(list)
if test_groundtruth:
print("Testing ground truth...")
for sample in tqdm(problems.values()):
task_id = sample["task_id"]
lang = task_id.split("/")[0].lower()
if lang == "javascript":
lang = "js"
tmp_dir_ = os.path.join(tmp_dir, lang, "evaluation")
sample["generation"] = sample["canonical_solution"]
sample["test_code"] = process_humaneval_test(sample, problems, example_test, language)
if sample["test_code"] is None:
continue
args = (task_id, sample, lang, timeout, tmp_dir_, completion_id[task_id]) | future = executor.submit(check_correctness, *args) | 1 | 2023-10-20 06:38:01+00:00 | 8k |
PKU-YuanGroup/Video-LLaVA | llava/model/language_model/mpt/modeling_mpt.py | [
{
"identifier": "attn_bias_shape",
"path": "llava/model/language_model/mpt/attention.py",
"snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if al... | import math
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List, Optional, Tuple, Union
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from .attention import attn_bias_shape, build_attn_bias
from .blocks import MPTBlock
from .custom_embedding import SharedEmbedding
from .norm import NORM_CLASS_REGISTRY
from .configuration_mpt import MPTConfig
from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
from .meta_init_context import init_empty_weights
from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
from .flash_attn_triton import flash_attn_func | 6,754 | """A simple, flexible implementation of a GPT model.
Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
"""
try:
except:
pass
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
class MPTPreTrainedModel(PreTrainedModel):
config_class = MPTConfig
base_model_prefix = 'model'
_no_split_modules = ['MPTBlock']
class MPTModel(MPTPreTrainedModel):
def __init__(self, config: MPTConfig):
config._validate_config()
super().__init__(config)
self.attn_impl = config.attn_config['attn_impl']
self.prefix_lm = config.attn_config['prefix_lm']
self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
self.alibi = config.attn_config['alibi']
self.alibi_bias_max = config.attn_config['alibi_bias_max']
if config.init_device == 'mixed':
if dist.get_local_rank() == 0:
config.init_device = 'cpu'
else:
config.init_device = 'meta'
| """A simple, flexible implementation of a GPT model.
Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
"""
try:
except:
pass
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
class MPTPreTrainedModel(PreTrainedModel):
config_class = MPTConfig
base_model_prefix = 'model'
_no_split_modules = ['MPTBlock']
class MPTModel(MPTPreTrainedModel):
def __init__(self, config: MPTConfig):
config._validate_config()
super().__init__(config)
self.attn_impl = config.attn_config['attn_impl']
self.prefix_lm = config.attn_config['prefix_lm']
self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
self.alibi = config.attn_config['alibi']
self.alibi_bias_max = config.attn_config['alibi_bias_max']
if config.init_device == 'mixed':
if dist.get_local_rank() == 0:
config.init_device = 'cpu'
else:
config.init_device = 'meta' | if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): | 4 | 2023-10-23 05:43:54+00:00 | 8k |
deepseek-ai/DreamCraft3D | threestudio/models/guidance/stable_diffusion_guidance.py | [
{
"identifier": "PromptProcessorOutput",
"path": "threestudio/models/prompt_processors/base.py",
"snippet": "class PromptProcessorOutput:\n text_embeddings: Float[Tensor, \"N Nf\"]\n uncond_text_embeddings: Float[Tensor, \"N Nf\"]\n text_embeddings_vd: Float[Tensor, \"Nv N Nf\"]\n uncond_tex... | from dataclasses import dataclass, field
from diffusers import DDIMScheduler, DDPMScheduler, StableDiffusionPipeline
from diffusers.utils.import_utils import is_xformers_available
from tqdm import tqdm
from threestudio.models.prompt_processors.base import PromptProcessorOutput
from threestudio.utils.base import BaseObject
from threestudio.utils.misc import C, cleanup, parse_version
from threestudio.utils.ops import perpendicular_component
from threestudio.utils.typing import *
import torch
import torch.nn as nn
import torch.nn.functional as F
import threestudio
import tomesd | 5,010 | latent_model_input,
torch.cat([t.reshape(1)] * 4).to(self.device),
encoder_hidden_states=text_embeddings,
) # (4B, 3, 64, 64)
noise_pred_text = noise_pred[:batch_size]
noise_pred_uncond = noise_pred[batch_size : batch_size * 2]
noise_pred_neg = noise_pred[batch_size * 2 :]
e_pos = noise_pred_text - noise_pred_uncond
accum_grad = 0
n_negative_prompts = neg_guidance_weights.shape[-1]
for i in range(n_negative_prompts):
e_i_neg = noise_pred_neg[i::n_negative_prompts] - noise_pred_uncond
accum_grad += neg_guidance_weights[:, i].view(
-1, 1, 1, 1
) * perpendicular_component(e_i_neg, e_pos)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
e_pos + accum_grad
)
else:
# pred noise
latent_model_input = torch.cat([latents_noisy] * 2, dim=0)
noise_pred = self.forward_unet(
latent_model_input,
torch.cat([t.reshape(1)] * 2).to(self.device),
encoder_hidden_states=text_embeddings,
)
# perform guidance (high scale from paper!)
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_text + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
return noise_pred
@torch.cuda.amp.autocast(enabled=False)
@torch.no_grad()
def guidance_eval(
self,
t_orig,
text_embeddings,
latents_noisy,
noise_pred,
use_perp_neg=False,
neg_guidance_weights=None,
):
# use only 50 timesteps, and find nearest of those to t
self.scheduler.set_timesteps(50)
self.scheduler.timesteps_gpu = self.scheduler.timesteps.to(self.device)
bs = (
min(self.cfg.max_items_eval, latents_noisy.shape[0])
if self.cfg.max_items_eval > 0
else latents_noisy.shape[0]
) # batch size
large_enough_idxs = self.scheduler.timesteps_gpu.expand([bs, -1]) > t_orig[
:bs
].unsqueeze(
-1
) # sized [bs,50] > [bs,1]
idxs = torch.min(large_enough_idxs, dim=1)[1]
t = self.scheduler.timesteps_gpu[idxs]
fracs = list((t / self.scheduler.config.num_train_timesteps).cpu().numpy())
imgs_noisy = self.decode_latents(latents_noisy[:bs]).permute(0, 2, 3, 1)
# get prev latent
latents_1step = []
pred_1orig = []
for b in range(bs):
step_output = self.scheduler.step(
noise_pred[b : b + 1], t[b], latents_noisy[b : b + 1], eta=1
)
latents_1step.append(step_output["prev_sample"])
pred_1orig.append(step_output["pred_original_sample"])
latents_1step = torch.cat(latents_1step)
pred_1orig = torch.cat(pred_1orig)
imgs_1step = self.decode_latents(latents_1step).permute(0, 2, 3, 1)
imgs_1orig = self.decode_latents(pred_1orig).permute(0, 2, 3, 1)
latents_final = []
for b, i in enumerate(idxs):
latents = latents_1step[b : b + 1]
text_emb = (
text_embeddings[
[b, b + len(idxs), b + 2 * len(idxs), b + 3 * len(idxs)], ...
]
if use_perp_neg
else text_embeddings[[b, b + len(idxs)], ...]
)
neg_guid = neg_guidance_weights[b : b + 1] if use_perp_neg else None
for t in tqdm(self.scheduler.timesteps[i + 1 :], leave=False):
# pred noise
noise_pred = self.get_noise_pred(
latents, t, text_emb, use_perp_neg, neg_guid
)
# get prev latent
latents = self.scheduler.step(noise_pred, t, latents, eta=1)[
"prev_sample"
]
latents_final.append(latents)
latents_final = torch.cat(latents_final)
imgs_final = self.decode_latents(latents_final).permute(0, 2, 3, 1)
return {
"bs": bs,
"noise_levels": fracs,
"imgs_noisy": imgs_noisy,
"imgs_1step": imgs_1step,
"imgs_1orig": imgs_1orig,
"imgs_final": imgs_final,
}
def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):
# clip grad for stable training as demonstrated in
# Debiasing Scores and Prompts of 2D Diffusion for Robust Text-to-3D Generation
# http://arxiv.org/abs/2303.15413
if self.cfg.grad_clip is not None:
|
@threestudio.register("stable-diffusion-guidance")
class StableDiffusionGuidance(BaseObject):
@dataclass
class Config(BaseObject.Config):
cache_dir: Optional[str] = None
local_files_only: Optional[bool] = False
pretrained_model_name_or_path: str = "runwayml/stable-diffusion-v1-5"
enable_memory_efficient_attention: bool = False
enable_sequential_cpu_offload: bool = False
enable_attention_slicing: bool = False
enable_channels_last_format: bool = False
guidance_scale: float = 100.0
grad_clip: Optional[
Any
] = None # field(default_factory=lambda: [0, 2.0, 8.0, 1000])
time_prior: Optional[Any] = None # [w1,w2,s1,s2]
half_precision_weights: bool = True
min_step_percent: float = 0.02
max_step_percent: float = 0.98
max_step_percent_annealed: float = 0.5
anneal_start_step: Optional[int] = None
use_sjc: bool = False
var_red: bool = True
weighting_strategy: str = "sds"
token_merging: bool = False
token_merging_params: Optional[dict] = field(default_factory=dict)
view_dependent_prompting: bool = True
"""Maximum number of batch items to evaluate guidance for (for debugging) and to save on disk. -1 means save all items."""
max_items_eval: int = 4
cfg: Config
def configure(self) -> None:
threestudio.info(f"Loading Stable Diffusion ...")
self.weights_dtype = (
torch.float16 if self.cfg.half_precision_weights else torch.float32
)
pipe_kwargs = {
"tokenizer": None,
"safety_checker": None,
"feature_extractor": None,
"requires_safety_checker": False,
"torch_dtype": self.weights_dtype,
"cache_dir": self.cfg.cache_dir,
"local_files_only": self.cfg.local_files_only
}
self.pipe = StableDiffusionPipeline.from_pretrained(
self.cfg.pretrained_model_name_or_path,
**pipe_kwargs,
).to(self.device)
if self.cfg.enable_memory_efficient_attention:
if parse_version(torch.__version__) >= parse_version("2"):
threestudio.info(
"PyTorch2.0 uses memory efficient attention by default."
)
elif not is_xformers_available():
threestudio.warn(
"xformers is not available, memory efficient attention is not enabled."
)
else:
self.pipe.enable_xformers_memory_efficient_attention()
if self.cfg.enable_sequential_cpu_offload:
self.pipe.enable_sequential_cpu_offload()
if self.cfg.enable_attention_slicing:
self.pipe.enable_attention_slicing(1)
if self.cfg.enable_channels_last_format:
self.pipe.unet.to(memory_format=torch.channels_last)
del self.pipe.text_encoder
cleanup()
# Create model
self.vae = self.pipe.vae.eval()
self.unet = self.pipe.unet.eval()
for p in self.vae.parameters():
p.requires_grad_(False)
for p in self.unet.parameters():
p.requires_grad_(False)
if self.cfg.token_merging:
tomesd.apply_patch(self.unet, **self.cfg.token_merging_params)
if self.cfg.use_sjc:
# score jacobian chaining use DDPM
self.scheduler = DDPMScheduler.from_pretrained(
self.cfg.pretrained_model_name_or_path,
subfolder="scheduler",
torch_dtype=self.weights_dtype,
beta_start=0.00085,
beta_end=0.0120,
beta_schedule="scaled_linear",
cache_dir=self.cfg.cache_dir,
)
else:
self.scheduler = DDIMScheduler.from_pretrained(
self.cfg.pretrained_model_name_or_path,
subfolder="scheduler",
torch_dtype=self.weights_dtype,
cache_dir=self.cfg.cache_dir,
local_files_only=self.cfg.local_files_only,
)
self.num_train_timesteps = self.scheduler.config.num_train_timesteps
self.set_min_max_steps() # set to default value
if self.cfg.time_prior is not None:
m1, m2, s1, s2 = self.cfg.time_prior
weights = torch.cat(
(
torch.exp(
-((torch.arange(self.num_train_timesteps, m1, -1) - m1) ** 2)
/ (2 * s1**2)
),
torch.ones(m1 - m2 + 1),
torch.exp(
-((torch.arange(m2 - 1, 0, -1) - m2) ** 2) / (2 * s2**2)
),
)
)
weights = weights / torch.sum(weights)
self.time_prior_acc_weights = torch.cumsum(weights, dim=0)
self.alphas: Float[Tensor, "..."] = self.scheduler.alphas_cumprod.to(
self.device
)
if self.cfg.use_sjc:
# score jacobian chaining need mu
self.us: Float[Tensor, "..."] = torch.sqrt((1 - self.alphas) / self.alphas)
self.grad_clip_val: Optional[float] = None
threestudio.info(f"Loaded Stable Diffusion!")
@torch.cuda.amp.autocast(enabled=False)
def set_min_max_steps(self, min_step_percent=0.02, max_step_percent=0.98):
self.min_step = int(self.num_train_timesteps * min_step_percent)
self.max_step = int(self.num_train_timesteps * max_step_percent)
@torch.cuda.amp.autocast(enabled=False)
def forward_unet(
self,
latents: Float[Tensor, "..."],
t: Float[Tensor, "..."],
encoder_hidden_states: Float[Tensor, "..."],
) -> Float[Tensor, "..."]:
input_dtype = latents.dtype
return self.unet(
latents.to(self.weights_dtype),
t.to(self.weights_dtype),
encoder_hidden_states=encoder_hidden_states.to(self.weights_dtype),
).sample.to(input_dtype)
@torch.cuda.amp.autocast(enabled=False)
def encode_images(
self, imgs: Float[Tensor, "B 3 512 512"]
) -> Float[Tensor, "B 4 64 64"]:
input_dtype = imgs.dtype
imgs = imgs * 2.0 - 1.0
posterior = self.vae.encode(imgs.to(self.weights_dtype)).latent_dist
latents = posterior.sample() * self.vae.config.scaling_factor
return latents.to(input_dtype)
@torch.cuda.amp.autocast(enabled=False)
def decode_latents(
self,
latents: Float[Tensor, "B 4 H W"],
latent_height: int = 64,
latent_width: int = 64,
) -> Float[Tensor, "B 3 512 512"]:
input_dtype = latents.dtype
latents = F.interpolate(
latents, (latent_height, latent_width), mode="bilinear", align_corners=False
)
latents = 1 / self.vae.config.scaling_factor * latents
image = self.vae.decode(latents.to(self.weights_dtype)).sample
image = (image * 0.5 + 0.5).clamp(0, 1)
return image.to(input_dtype)
def compute_grad_sds(
self,
latents: Float[Tensor, "B 4 64 64"],
t: Int[Tensor, "B"],
prompt_utils: PromptProcessorOutput,
elevation: Float[Tensor, "B"],
azimuth: Float[Tensor, "B"],
camera_distances: Float[Tensor, "B"],
):
batch_size = elevation.shape[0]
if prompt_utils.use_perp_neg:
(
text_embeddings,
neg_guidance_weights,
) = prompt_utils.get_text_embeddings_perp_neg(
elevation, azimuth, camera_distances, self.cfg.view_dependent_prompting
)
with torch.no_grad():
noise = torch.randn_like(latents)
latents_noisy = self.scheduler.add_noise(latents, noise, t)
latent_model_input = torch.cat([latents_noisy] * 4, dim=0)
noise_pred = self.forward_unet(
latent_model_input,
torch.cat([t] * 4),
encoder_hidden_states=text_embeddings,
) # (4B, 3, 64, 64)
noise_pred_text = noise_pred[:batch_size]
noise_pred_uncond = noise_pred[batch_size : batch_size * 2]
noise_pred_neg = noise_pred[batch_size * 2 :]
e_pos = noise_pred_text - noise_pred_uncond
accum_grad = 0
n_negative_prompts = neg_guidance_weights.shape[-1]
for i in range(n_negative_prompts):
e_i_neg = noise_pred_neg[i::n_negative_prompts] - noise_pred_uncond
accum_grad += neg_guidance_weights[:, i].view(
-1, 1, 1, 1
) * perpendicular_component(e_i_neg, e_pos)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
e_pos + accum_grad
)
else:
neg_guidance_weights = None
text_embeddings = prompt_utils.get_text_embeddings(
elevation, azimuth, camera_distances, self.cfg.view_dependent_prompting
)
# predict the noise residual with unet, NO grad!
with torch.no_grad():
# add noise
noise = torch.randn_like(latents) # TODO: use torch generator
latents_noisy = self.scheduler.add_noise(latents, noise, t)
# pred noise
latent_model_input = torch.cat([latents_noisy] * 2, dim=0)
noise_pred = self.forward_unet(
latent_model_input,
torch.cat([t] * 2),
encoder_hidden_states=text_embeddings,
)
# perform guidance (high scale from paper!)
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_text + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
if self.cfg.weighting_strategy == "sds":
# w(t), sigma_t^2
w = (1 - self.alphas[t]).view(-1, 1, 1, 1)
elif self.cfg.weighting_strategy == "uniform":
w = 1
elif self.cfg.weighting_strategy == "fantasia3d":
w = (self.alphas[t] ** 0.5 * (1 - self.alphas[t])).view(-1, 1, 1, 1)
else:
raise ValueError(
f"Unknown weighting strategy: {self.cfg.weighting_strategy}"
)
grad = w * (noise_pred - noise)
guidance_eval_utils = {
"use_perp_neg": prompt_utils.use_perp_neg,
"neg_guidance_weights": neg_guidance_weights,
"text_embeddings": text_embeddings,
"t_orig": t,
"latents_noisy": latents_noisy,
"noise_pred": noise_pred,
}
return grad, guidance_eval_utils
def compute_grad_sjc(
self,
latents: Float[Tensor, "B 4 64 64"],
t: Int[Tensor, "B"],
prompt_utils: PromptProcessorOutput,
elevation: Float[Tensor, "B"],
azimuth: Float[Tensor, "B"],
camera_distances: Float[Tensor, "B"],
):
batch_size = elevation.shape[0]
sigma = self.us[t]
sigma = sigma.view(-1, 1, 1, 1)
if prompt_utils.use_perp_neg:
(
text_embeddings,
neg_guidance_weights,
) = prompt_utils.get_text_embeddings_perp_neg(
elevation, azimuth, camera_distances, self.cfg.view_dependent_prompting
)
with torch.no_grad():
noise = torch.randn_like(latents)
y = latents
zs = y + sigma * noise
scaled_zs = zs / torch.sqrt(1 + sigma**2)
# pred noise
latent_model_input = torch.cat([scaled_zs] * 4, dim=0)
noise_pred = self.forward_unet(
latent_model_input,
torch.cat([t] * 4),
encoder_hidden_states=text_embeddings,
) # (4B, 3, 64, 64)
noise_pred_text = noise_pred[:batch_size]
noise_pred_uncond = noise_pred[batch_size : batch_size * 2]
noise_pred_neg = noise_pred[batch_size * 2 :]
e_pos = noise_pred_text - noise_pred_uncond
accum_grad = 0
n_negative_prompts = neg_guidance_weights.shape[-1]
for i in range(n_negative_prompts):
e_i_neg = noise_pred_neg[i::n_negative_prompts] - noise_pred_uncond
accum_grad += neg_guidance_weights[:, i].view(
-1, 1, 1, 1
) * perpendicular_component(e_i_neg, e_pos)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
e_pos + accum_grad
)
else:
neg_guidance_weights = None
text_embeddings = prompt_utils.get_text_embeddings(
elevation, azimuth, camera_distances, self.cfg.view_dependent_prompting
)
# predict the noise residual with unet, NO grad!
with torch.no_grad():
# add noise
noise = torch.randn_like(latents) # TODO: use torch generator
y = latents
zs = y + sigma * noise
scaled_zs = zs / torch.sqrt(1 + sigma**2)
# pred noise
latent_model_input = torch.cat([scaled_zs] * 2, dim=0)
noise_pred = self.forward_unet(
latent_model_input,
torch.cat([t] * 2),
encoder_hidden_states=text_embeddings,
)
# perform guidance (high scale from paper!)
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_text + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
Ds = zs - sigma * noise_pred
if self.cfg.var_red:
grad = -(Ds - y) / sigma
else:
grad = -(Ds - zs) / sigma
guidance_eval_utils = {
"use_perp_neg": prompt_utils.use_perp_neg,
"neg_guidance_weights": neg_guidance_weights,
"text_embeddings": text_embeddings,
"t_orig": t,
"latents_noisy": scaled_zs,
"noise_pred": noise_pred,
}
return grad, guidance_eval_utils
def __call__(
self,
rgb: Float[Tensor, "B H W C"],
prompt_utils: PromptProcessorOutput,
elevation: Float[Tensor, "B"],
azimuth: Float[Tensor, "B"],
camera_distances: Float[Tensor, "B"],
rgb_as_latents=False,
guidance_eval=False,
current_step_ratio=None,
**kwargs,
):
batch_size = rgb.shape[0]
rgb_BCHW = rgb.permute(0, 3, 1, 2)
latents: Float[Tensor, "B 4 64 64"]
if rgb_as_latents:
latents = F.interpolate(
rgb_BCHW, (64, 64), mode="bilinear", align_corners=False
)
else:
rgb_BCHW_512 = F.interpolate(
rgb_BCHW, (512, 512), mode="bilinear", align_corners=False
)
# encode image into latents with vae
latents = self.encode_images(rgb_BCHW_512)
if self.cfg.time_prior is not None:
time_index = torch.where(
(self.time_prior_acc_weights - current_step_ratio) > 0
)[0][0]
if time_index == 0 or torch.abs(
self.time_prior_acc_weights[time_index] - current_step_ratio
) < torch.abs(
self.time_prior_acc_weights[time_index - 1] - current_step_ratio
):
t = self.num_train_timesteps - time_index
else:
t = self.num_train_timesteps - time_index + 1
t = torch.clip(t, self.min_step, self.max_step + 1)
t = torch.full((batch_size,), t, dtype=torch.long, device=self.device)
else:
# timestep ~ U(0.02, 0.98) to avoid very high/low noise level
t = torch.randint(
self.min_step,
self.max_step + 1,
[batch_size],
dtype=torch.long,
device=self.device,
)
if self.cfg.use_sjc:
grad, guidance_eval_utils = self.compute_grad_sjc(
latents, t, prompt_utils, elevation, azimuth, camera_distances
)
else:
grad, guidance_eval_utils = self.compute_grad_sds(
latents, t, prompt_utils, elevation, azimuth, camera_distances
)
grad = torch.nan_to_num(grad)
# clip grad for stable training?
if self.grad_clip_val is not None:
grad = grad.clamp(-self.grad_clip_val, self.grad_clip_val)
# loss = SpecifyGradient.apply(latents, grad)
# SpecifyGradient is not straghtforward, use a reparameterization trick instead
target = (latents - grad).detach()
# d(loss)/d(latents) = latents - target = latents - (latents - grad) = grad
loss_sds = 0.5 * F.mse_loss(latents, target, reduction="sum") / batch_size
guidance_out = {
"loss_sd": loss_sds,
"grad_norm": grad.norm(),
"min_step": self.min_step,
"max_step": self.max_step,
}
if guidance_eval:
guidance_eval_out = self.guidance_eval(**guidance_eval_utils)
texts = []
for n, e, a, c in zip(
guidance_eval_out["noise_levels"], elevation, azimuth, camera_distances
):
texts.append(
f"n{n:.02f}\ne{e.item():.01f}\na{a.item():.01f}\nc{c.item():.02f}"
)
guidance_eval_out.update({"texts": texts})
guidance_out.update({"eval": guidance_eval_out})
return guidance_out
@torch.cuda.amp.autocast(enabled=False)
@torch.no_grad()
def get_noise_pred(
self,
latents_noisy,
t,
text_embeddings,
use_perp_neg=False,
neg_guidance_weights=None,
):
batch_size = latents_noisy.shape[0]
if use_perp_neg:
# pred noise
latent_model_input = torch.cat([latents_noisy] * 4, dim=0)
noise_pred = self.forward_unet(
latent_model_input,
torch.cat([t.reshape(1)] * 4).to(self.device),
encoder_hidden_states=text_embeddings,
) # (4B, 3, 64, 64)
noise_pred_text = noise_pred[:batch_size]
noise_pred_uncond = noise_pred[batch_size : batch_size * 2]
noise_pred_neg = noise_pred[batch_size * 2 :]
e_pos = noise_pred_text - noise_pred_uncond
accum_grad = 0
n_negative_prompts = neg_guidance_weights.shape[-1]
for i in range(n_negative_prompts):
e_i_neg = noise_pred_neg[i::n_negative_prompts] - noise_pred_uncond
accum_grad += neg_guidance_weights[:, i].view(
-1, 1, 1, 1
) * perpendicular_component(e_i_neg, e_pos)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
e_pos + accum_grad
)
else:
# pred noise
latent_model_input = torch.cat([latents_noisy] * 2, dim=0)
noise_pred = self.forward_unet(
latent_model_input,
torch.cat([t.reshape(1)] * 2).to(self.device),
encoder_hidden_states=text_embeddings,
)
# perform guidance (high scale from paper!)
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_text + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
return noise_pred
@torch.cuda.amp.autocast(enabled=False)
@torch.no_grad()
def guidance_eval(
self,
t_orig,
text_embeddings,
latents_noisy,
noise_pred,
use_perp_neg=False,
neg_guidance_weights=None,
):
# use only 50 timesteps, and find nearest of those to t
self.scheduler.set_timesteps(50)
self.scheduler.timesteps_gpu = self.scheduler.timesteps.to(self.device)
bs = (
min(self.cfg.max_items_eval, latents_noisy.shape[0])
if self.cfg.max_items_eval > 0
else latents_noisy.shape[0]
) # batch size
large_enough_idxs = self.scheduler.timesteps_gpu.expand([bs, -1]) > t_orig[
:bs
].unsqueeze(
-1
) # sized [bs,50] > [bs,1]
idxs = torch.min(large_enough_idxs, dim=1)[1]
t = self.scheduler.timesteps_gpu[idxs]
fracs = list((t / self.scheduler.config.num_train_timesteps).cpu().numpy())
imgs_noisy = self.decode_latents(latents_noisy[:bs]).permute(0, 2, 3, 1)
# get prev latent
latents_1step = []
pred_1orig = []
for b in range(bs):
step_output = self.scheduler.step(
noise_pred[b : b + 1], t[b], latents_noisy[b : b + 1], eta=1
)
latents_1step.append(step_output["prev_sample"])
pred_1orig.append(step_output["pred_original_sample"])
latents_1step = torch.cat(latents_1step)
pred_1orig = torch.cat(pred_1orig)
imgs_1step = self.decode_latents(latents_1step).permute(0, 2, 3, 1)
imgs_1orig = self.decode_latents(pred_1orig).permute(0, 2, 3, 1)
latents_final = []
for b, i in enumerate(idxs):
latents = latents_1step[b : b + 1]
text_emb = (
text_embeddings[
[b, b + len(idxs), b + 2 * len(idxs), b + 3 * len(idxs)], ...
]
if use_perp_neg
else text_embeddings[[b, b + len(idxs)], ...]
)
neg_guid = neg_guidance_weights[b : b + 1] if use_perp_neg else None
for t in tqdm(self.scheduler.timesteps[i + 1 :], leave=False):
# pred noise
noise_pred = self.get_noise_pred(
latents, t, text_emb, use_perp_neg, neg_guid
)
# get prev latent
latents = self.scheduler.step(noise_pred, t, latents, eta=1)[
"prev_sample"
]
latents_final.append(latents)
latents_final = torch.cat(latents_final)
imgs_final = self.decode_latents(latents_final).permute(0, 2, 3, 1)
return {
"bs": bs,
"noise_levels": fracs,
"imgs_noisy": imgs_noisy,
"imgs_1step": imgs_1step,
"imgs_1orig": imgs_1orig,
"imgs_final": imgs_final,
}
def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False):
# clip grad for stable training as demonstrated in
# Debiasing Scores and Prompts of 2D Diffusion for Robust Text-to-3D Generation
# http://arxiv.org/abs/2303.15413
if self.cfg.grad_clip is not None: | self.grad_clip_val = C(self.cfg.grad_clip, epoch, global_step) | 2 | 2023-10-23 07:40:20+00:00 | 8k |
YORG-AI/Open-Assistant | package/src/yorgassistant/core/assistant/async_threads.py | [
{
"identifier": "Assistants",
"path": "package/src/yorgassistant/core/assistant/assistant.py",
"snippet": "class Assistants():\n def __init__(self, config,yaml_path:Optional[str] = None):\n self.config = config\n YamlPathConfig.assistants_yaml_path = yaml_path if yaml_path else 'assista... | import uuid
import time
import yaml
import os
import re
import logging
import json
import inspect
from typing import Any, List, Optional,Dict
from .assistant import Assistants
from ..nodes.openai.openai import OpenAINode,AsyncOpenAINode
from ..nodes.openai.openai_model import *
from .tools.tools import Tools, Tool
from .config import *
from .prompt.few_shot_cot_tools_choose_prompt import *
from .prompt.parameters_generate_prompt import *
from .prompt.response_generate_prompt import * | 6,211 |
def extract_bracket_content(s: str) -> list:
content = re.findall(r"\[(.*?)\]", s)
content = [c.replace("'", "") for c in content]
content = filter(lambda x: x != "", content)
ret = []
for item in content:
if "," in item:
ret.extend(item.split(","))
else:
ret.append(item)
return ret
class AsyncThreads:
|
def extract_bracket_content(s: str) -> list:
content = re.findall(r"\[(.*?)\]", s)
content = [c.replace("'", "") for c in content]
content = filter(lambda x: x != "", content)
ret = []
for item in content:
if "," in item:
ret.extend(item.split(","))
else:
ret.append(item)
return ret
class AsyncThreads: | current_tool: Tool | 4 | 2023-10-24 15:15:48+00:00 | 8k |
zju3dv/4K4D | scripts/preprocess/tools/align_cameras.py | [
{
"identifier": "as_torch_func",
"path": "easyvolcap/utils/data_utils.py",
"snippet": "def as_torch_func(func):\n def wrapper(*args, **kwargs):\n args = to_numpy(args)\n kwargs = to_numpy(kwargs)\n ret = func(*args, **kwargs)\n return to_tensor(ret)\n return wrapper"
... | import torch
import argparse
import numpy as np
from os.path import join
from easyvolcap.utils.console_utils import *
from easyvolcap.utils.data_utils import as_torch_func
from easyvolcap.utils.cam_utils import average_c2ws, average_w2cs
from easyvolcap.utils.easy_utils import read_camera, write_camera, to_easymocap
from easyvolcap.utils.net_utils import affine_inverse, monotonic_near_far, affine_padding | 5,186 | # This script is used to perform camera alignment for a given `easyvolcap` format dataset.
# Namely, it does the same things as in `VolumetricVideoDataset.align_points()`, this script
# is just a standalone version of that function for you to export the aligned cameras.
def load_align_cameras(data_root: str, intri_file: str, extri_file: str, camera_dir: str = 'cameras',
n_frame_total: int = 1, near: float = 0.2, far: float = 100.0,
avg_using_all: bool = False, avg_max_count: int = 100):
# Multiview dataset loading, need to expand, will have redundant information
if exists(join(data_root, intri_file)) and exists(join(data_root, extri_file)):
cameras = read_camera(join(data_root, intri_file), join(data_root, extri_file))
camera_names = np.asarray(sorted(list(cameras.keys()))) # NOTE: sorting camera names
cameras = dotdict({k: [cameras[k] for i in range(n_frame_total)] for k in camera_names})
# Monocular dataset loading, each camera has a separate folder
elif exists(join(data_root, camera_dir)):
camera_names = np.asarray(sorted(os.listdir(join(data_root, camera_dir)))) # NOTE: sorting here is very important!
cameras = dotdict({
k: [v[1] for v in sorted(
read_camera(join(data_root, camera_dir, k, intri_file),
join(data_root, camera_dir, k, extri_file)).items()
)] for k in camera_names
})
# Whatever else, for now, raise error
else: raise NotImplementedError(f'Could not find [intri.yml, extri.yml] or [cameras] folder in {data_root}, check your dataset configuration')
# cameras: a mapping from camera names to a list of camera objects, (every element in list is an actual camera for that particular view and frame)
Hs = torch.as_tensor([[cam.H for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
Ws = torch.as_tensor([[cam.W for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
Ks = torch.as_tensor([[cam.K for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 3, 3)
Rs = torch.as_tensor([[cam.R for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 3, 3)
Ts = torch.as_tensor([[cam.T for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 3, 1)
Ds = torch.as_tensor([[cam.D for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 1, 5)
ts = torch.as_tensor([[cam.t for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F) # UNUSED: time index from camera, not used for now
ns = torch.as_tensor([[cam.n for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
fs = torch.as_tensor([[cam.f for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
w2cs = torch.cat([Rs, Ts], dim=-1) # (V, F, 3, 4)
c2ws = affine_inverse(w2cs) # (V, F, 3, 4)
ns, fs = monotonic_near_far(ns, fs, torch.as_tensor(near, dtype=torch.float), torch.as_tensor(far, dtype=torch.float))
# Move cameras to the center of the frame (!: intrusive)
c2ws, w2cs, Rs, Ts, c2w_avg = align_points(c2ws, avg_using_all, avg_max_count)
# Return the aligned cameras
return Ks, Hs, Ws, Rs, Ts, ts, ns, fs, Ds
def align_points(c2ws: torch.Tensor, avg_using_all: bool = False, avg_max_count: int = 100):
sh = c2ws.shape # (V, F, 3, 4)
c2ws = c2ws.view((-1,) + sh[-2:]) # (V*F, 3, 4)
if avg_using_all:
stride = max(len(c2ws) // avg_max_count, 1)
inds = torch.arange(len(c2ws))[::stride][:avg_max_count]
c2w_avg = as_torch_func(average_c2ws)(c2ws[inds]) # (V*F, 3, 4), # !: HEAVY
else:
c2w_avg = as_torch_func(average_c2ws)(c2ws.view(sh)[:, 0]) # (V, 3, 4)
c2w_avg = c2w_avg
c2ws = (affine_inverse(affine_padding(c2w_avg))[None] @ affine_padding(c2ws))[..., :3, :] # (1, 4, 4) @ (V*F, 4, 4) -> (V*F, 3, 4)
w2cs = affine_inverse(c2ws) # (V*F, 3, 4)
c2ws = c2ws.view(sh)
w2cs = w2cs.view(sh)
Rs = w2cs[..., :-1]
Ts = w2cs[..., -1:]
return c2ws, w2cs, Rs, Ts, c2w_avg
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data_root', type=str, default='data/webcam/simple/light/calib_gather_230928/colmap/align/static/images')
parser.add_argument('--intri_file', type=str, default='intri.yml')
parser.add_argument('--extri_file', type=str, default='extri.yml')
parser.add_argument('--camera_dir', type=str, default='cameras')
parser.add_argument('--n_frame_total', type=int, default=1)
parser.add_argument('--near', type=float, default=0.25)
parser.add_argument('--far', type=float, default=2.00)
parser.add_argument('--avg_using_all', action='store_true')
parser.add_argument('--avg_max_count', type=int, default=100)
parser.add_argument('--cam_digit', type=int, default=1)
parser.add_argument('--save_root', type=str, default='data/webcam/simple/light/calib_gather_230928/aligned')
args = parser.parse_args()
# Load and align cameras
Ks, Hs, Ws, Rs, Ts, ts, ns, fs, Ds = load_align_cameras(
args.data_root, args.intri_file, args.extri_file, args.camera_dir,
args.n_frame_total, args.near, args.far, args.avg_using_all, args.avg_max_count
)
# Convert loaded and aligned cameras to `EasyMocap` format
# TODO: support for monocular cameras
| # This script is used to perform camera alignment for a given `easyvolcap` format dataset.
# Namely, it does the same things as in `VolumetricVideoDataset.align_points()`, this script
# is just a standalone version of that function for you to export the aligned cameras.
def load_align_cameras(data_root: str, intri_file: str, extri_file: str, camera_dir: str = 'cameras',
n_frame_total: int = 1, near: float = 0.2, far: float = 100.0,
avg_using_all: bool = False, avg_max_count: int = 100):
# Multiview dataset loading, need to expand, will have redundant information
if exists(join(data_root, intri_file)) and exists(join(data_root, extri_file)):
cameras = read_camera(join(data_root, intri_file), join(data_root, extri_file))
camera_names = np.asarray(sorted(list(cameras.keys()))) # NOTE: sorting camera names
cameras = dotdict({k: [cameras[k] for i in range(n_frame_total)] for k in camera_names})
# Monocular dataset loading, each camera has a separate folder
elif exists(join(data_root, camera_dir)):
camera_names = np.asarray(sorted(os.listdir(join(data_root, camera_dir)))) # NOTE: sorting here is very important!
cameras = dotdict({
k: [v[1] for v in sorted(
read_camera(join(data_root, camera_dir, k, intri_file),
join(data_root, camera_dir, k, extri_file)).items()
)] for k in camera_names
})
# Whatever else, for now, raise error
else: raise NotImplementedError(f'Could not find [intri.yml, extri.yml] or [cameras] folder in {data_root}, check your dataset configuration')
# cameras: a mapping from camera names to a list of camera objects, (every element in list is an actual camera for that particular view and frame)
Hs = torch.as_tensor([[cam.H for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
Ws = torch.as_tensor([[cam.W for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
Ks = torch.as_tensor([[cam.K for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 3, 3)
Rs = torch.as_tensor([[cam.R for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 3, 3)
Ts = torch.as_tensor([[cam.T for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 3, 1)
Ds = torch.as_tensor([[cam.D for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F, 1, 5)
ts = torch.as_tensor([[cam.t for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F) # UNUSED: time index from camera, not used for now
ns = torch.as_tensor([[cam.n for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
fs = torch.as_tensor([[cam.f for cam in cameras[k]] for k in camera_names], dtype=torch.float) # (V, F)
w2cs = torch.cat([Rs, Ts], dim=-1) # (V, F, 3, 4)
c2ws = affine_inverse(w2cs) # (V, F, 3, 4)
ns, fs = monotonic_near_far(ns, fs, torch.as_tensor(near, dtype=torch.float), torch.as_tensor(far, dtype=torch.float))
# Move cameras to the center of the frame (!: intrusive)
c2ws, w2cs, Rs, Ts, c2w_avg = align_points(c2ws, avg_using_all, avg_max_count)
# Return the aligned cameras
return Ks, Hs, Ws, Rs, Ts, ts, ns, fs, Ds
def align_points(c2ws: torch.Tensor, avg_using_all: bool = False, avg_max_count: int = 100):
sh = c2ws.shape # (V, F, 3, 4)
c2ws = c2ws.view((-1,) + sh[-2:]) # (V*F, 3, 4)
if avg_using_all:
stride = max(len(c2ws) // avg_max_count, 1)
inds = torch.arange(len(c2ws))[::stride][:avg_max_count]
c2w_avg = as_torch_func(average_c2ws)(c2ws[inds]) # (V*F, 3, 4), # !: HEAVY
else:
c2w_avg = as_torch_func(average_c2ws)(c2ws.view(sh)[:, 0]) # (V, 3, 4)
c2w_avg = c2w_avg
c2ws = (affine_inverse(affine_padding(c2w_avg))[None] @ affine_padding(c2ws))[..., :3, :] # (1, 4, 4) @ (V*F, 4, 4) -> (V*F, 3, 4)
w2cs = affine_inverse(c2ws) # (V*F, 3, 4)
c2ws = c2ws.view(sh)
w2cs = w2cs.view(sh)
Rs = w2cs[..., :-1]
Ts = w2cs[..., -1:]
return c2ws, w2cs, Rs, Ts, c2w_avg
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data_root', type=str, default='data/webcam/simple/light/calib_gather_230928/colmap/align/static/images')
parser.add_argument('--intri_file', type=str, default='intri.yml')
parser.add_argument('--extri_file', type=str, default='extri.yml')
parser.add_argument('--camera_dir', type=str, default='cameras')
parser.add_argument('--n_frame_total', type=int, default=1)
parser.add_argument('--near', type=float, default=0.25)
parser.add_argument('--far', type=float, default=2.00)
parser.add_argument('--avg_using_all', action='store_true')
parser.add_argument('--avg_max_count', type=int, default=100)
parser.add_argument('--cam_digit', type=int, default=1)
parser.add_argument('--save_root', type=str, default='data/webcam/simple/light/calib_gather_230928/aligned')
args = parser.parse_args()
# Load and align cameras
Ks, Hs, Ws, Rs, Ts, ts, ns, fs, Ds = load_align_cameras(
args.data_root, args.intri_file, args.extri_file, args.camera_dir,
args.n_frame_total, args.near, args.far, args.avg_using_all, args.avg_max_count
)
# Convert loaded and aligned cameras to `EasyMocap` format
# TODO: support for monocular cameras | cameras = to_easymocap(Ks, Hs, Ws, Rs, Ts, ts, ns, fs, Ds, cam_digit=args.cam_digit) | 5 | 2023-10-17 04:48:46+00:00 | 8k |
chengzeyi/stable-fast | src/sfast/triton/torch_ops.py | [
{
"identifier": "copy",
"path": "src/sfast/triton/ops/copy.py",
"snippet": "def copy(dst, src):\n dst_device = dst.device\n src_device = src.device\n assert dst_device.type == 'cuda'\n assert dst_device == src_device\n dst_shape = dst.shape\n src_shape = src.shape\n assert dst_shape... | import torch
import sfast
from sfast.utils.custom_python_operator import register_custom_python_operator
from .ops.copy import copy
from .ops.group_norm import (group_norm_forward, group_norm_silu_forward)
from .ops.layer_norm import LayerNorm as TritonLayerNorm
from .ops.conv import conv_forward | 4,803 | aten = torch.ops.aten
def construct_triton_contiguous_torch_op():
class TritonContiguous(torch.autograd.Function):
@staticmethod
def forward(ctx, x, memory_format=torch.contiguous_format):
if x.device.type != 'cuda' or x.ndim > 4 or x.is_contiguous(
memory_format=memory_format):
return aten.contiguous(x, memory_format=memory_format)
else:
dst = torch.empty_like(x, memory_format=memory_format)
return copy(dst, x)
@staticmethod
def backward(ctx, grad_output):
return grad_output, None
def contiguous(x, memory_format=torch.contiguous_format):
return TritonContiguous.apply(x, memory_format)
return contiguous
contiguous = construct_triton_contiguous_torch_op()
register_custom_python_operator(
'sfast_triton::contiguous(Tensor a, MemoryFormat memory_format) -> Tensor',
contiguous)
def constuct_triton_clone_torch_op():
class TritonClone(torch.autograd.Function):
@staticmethod
def forward(ctx, x, memory_format=torch.preserve_format):
if x.device.type != 'cuda' or x.ndim > 4 or x.is_contiguous(
memory_format=memory_format):
return aten.clone(x, memory_format=memory_format)
else:
dst = torch.empty_like(x, memory_format=memory_format)
return copy(dst, x)
@staticmethod
def backward(ctx, grad_output):
return grad_output, None
def clone(x, memory_format=torch.preserve_format):
return TritonClone.apply(x, memory_format)
return clone
clone = constuct_triton_clone_torch_op()
register_custom_python_operator(
'sfast_triton::clone(Tensor a, MemoryFormat memory_format) -> Tensor',
clone)
def construct_triton_reshape_torch_op():
class TritonReshape(torch.autograd.Function):
@staticmethod
def forward(ctx, x, shape):
ctx.shape = x.shape
if x.device.type != 'cuda' or x.ndim > 4 or sfast._C._compute_stride(
x.shape, x.stride(), shape) is not None:
return aten.reshape(x, shape)
else:
dst = torch.empty_like(x,
memory_format=torch.contiguous_format)
copy(dst, x)
return aten.reshape(dst, shape)
@staticmethod
def backward(ctx, grad_output):
if grad_output.device.type != 'cuda' or grad_output.ndim > 4 or sfast._C._compute_stride(
grad_output.shape, grad_output.stride(),
ctx.shape) is not None:
return grad_output.reshape(ctx.shape), None
else:
dst = torch.empty_like(grad_output,
memory_format=torch.contiguous_format)
copy(dst, grad_output)
return dst.reshape(ctx.shape), None
def reshape(x, shape):
return TritonReshape.apply(x, shape)
return reshape
reshape = construct_triton_reshape_torch_op()
register_custom_python_operator(
'sfast_triton::reshape(Tensor a, int[] shape) -> Tensor', reshape)
def construct_triton_group_norm_torch_op():
class TritonGroupNorm(torch.autograd.Function):
@staticmethod
def forward(ctx, input, num_groups, weight=None, bias=None, eps=1e-05):
device_type = input.device.type
if device_type != 'cuda' or input.ndim > 4:
input = input.contiguous()
if weight is not None:
weight = weight.contiguous()
if bias is not None:
bias = bias.contiguous()
N, C = input.shape[:2]
HxW = input.numel() // (N * C)
output, mean, rstd = aten.native_group_norm(
input, weight, bias, N, C, HxW, num_groups, eps)
else:
needs_backward = any(x is not None and x.requires_grad
for x in [input, weight, bias])
|
aten = torch.ops.aten
def construct_triton_contiguous_torch_op():
class TritonContiguous(torch.autograd.Function):
@staticmethod
def forward(ctx, x, memory_format=torch.contiguous_format):
if x.device.type != 'cuda' or x.ndim > 4 or x.is_contiguous(
memory_format=memory_format):
return aten.contiguous(x, memory_format=memory_format)
else:
dst = torch.empty_like(x, memory_format=memory_format)
return copy(dst, x)
@staticmethod
def backward(ctx, grad_output):
return grad_output, None
def contiguous(x, memory_format=torch.contiguous_format):
return TritonContiguous.apply(x, memory_format)
return contiguous
contiguous = construct_triton_contiguous_torch_op()
register_custom_python_operator(
'sfast_triton::contiguous(Tensor a, MemoryFormat memory_format) -> Tensor',
contiguous)
def constuct_triton_clone_torch_op():
class TritonClone(torch.autograd.Function):
@staticmethod
def forward(ctx, x, memory_format=torch.preserve_format):
if x.device.type != 'cuda' or x.ndim > 4 or x.is_contiguous(
memory_format=memory_format):
return aten.clone(x, memory_format=memory_format)
else:
dst = torch.empty_like(x, memory_format=memory_format)
return copy(dst, x)
@staticmethod
def backward(ctx, grad_output):
return grad_output, None
def clone(x, memory_format=torch.preserve_format):
return TritonClone.apply(x, memory_format)
return clone
clone = constuct_triton_clone_torch_op()
register_custom_python_operator(
'sfast_triton::clone(Tensor a, MemoryFormat memory_format) -> Tensor',
clone)
def construct_triton_reshape_torch_op():
class TritonReshape(torch.autograd.Function):
@staticmethod
def forward(ctx, x, shape):
ctx.shape = x.shape
if x.device.type != 'cuda' or x.ndim > 4 or sfast._C._compute_stride(
x.shape, x.stride(), shape) is not None:
return aten.reshape(x, shape)
else:
dst = torch.empty_like(x,
memory_format=torch.contiguous_format)
copy(dst, x)
return aten.reshape(dst, shape)
@staticmethod
def backward(ctx, grad_output):
if grad_output.device.type != 'cuda' or grad_output.ndim > 4 or sfast._C._compute_stride(
grad_output.shape, grad_output.stride(),
ctx.shape) is not None:
return grad_output.reshape(ctx.shape), None
else:
dst = torch.empty_like(grad_output,
memory_format=torch.contiguous_format)
copy(dst, grad_output)
return dst.reshape(ctx.shape), None
def reshape(x, shape):
return TritonReshape.apply(x, shape)
return reshape
reshape = construct_triton_reshape_torch_op()
register_custom_python_operator(
'sfast_triton::reshape(Tensor a, int[] shape) -> Tensor', reshape)
def construct_triton_group_norm_torch_op():
class TritonGroupNorm(torch.autograd.Function):
@staticmethod
def forward(ctx, input, num_groups, weight=None, bias=None, eps=1e-05):
device_type = input.device.type
if device_type != 'cuda' or input.ndim > 4:
input = input.contiguous()
if weight is not None:
weight = weight.contiguous()
if bias is not None:
bias = bias.contiguous()
N, C = input.shape[:2]
HxW = input.numel() // (N * C)
output, mean, rstd = aten.native_group_norm(
input, weight, bias, N, C, HxW, num_groups, eps)
else:
needs_backward = any(x is not None and x.requires_grad
for x in [input, weight, bias]) | output, mean, rstd = group_norm_forward( | 1 | 2023-10-17 06:49:59+00:00 | 8k |
microsoft/SoM | demo_som.py | [
{
"identifier": "interactive_seem_m2m_auto",
"path": "task_adapter/seem/tasks/interactive_seem_m2m_auto.py",
"snippet": "def interactive_seem_m2m_auto(model, image, text_size, label_mode='1', alpha=0.1, anno_mode=['Mask']):\n t = []\n t.append(transforms.Resize(int(text_size), interpolation=Image.... | import gradio as gr
import torch
import argparse
import numpy as np
from seem.modeling.BaseModel import BaseModel as BaseModel_Seem
from seem.utils.distributed import init_distributed as init_distributed_seem
from seem.modeling import build_model as build_model_seem
from task_adapter.seem.tasks import interactive_seem_m2m_auto, inference_seem_pano, inference_seem_interactive
from semantic_sam.BaseModel import BaseModel
from semantic_sam import build_model
from semantic_sam.utils.dist import init_distributed_mode
from semantic_sam.utils.arguments import load_opt_from_config_file
from semantic_sam.utils.constants import COCO_PANOPTIC_CLASSES
from task_adapter.semantic_sam.tasks import inference_semsam_m2m_auto, prompt_switch
from segment_anything import sam_model_registry
from task_adapter.sam.tasks.inference_sam_m2m_auto import inference_sam_m2m_auto
from task_adapter.sam.tasks.inference_sam_m2m_interactive import inference_sam_m2m_interactive
from scipy.ndimage import label | 6,179 | # --------------------------------------------------------
# Set-of-Mark (SoM) Prompting for Visual Grounding in GPT-4V
# Copyright (c) 2023 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by:
# Jianwei Yang (jianwyan@microsoft.com)
# Xueyan Zou (xueyan@cs.wisc.edu)
# Hao Zhang (hzhangcx@connect.ust.hk)
# --------------------------------------------------------
# seem
# semantic sam
# sam
'''
build args
'''
semsam_cfg = "configs/semantic_sam_only_sa-1b_swinL.yaml"
seem_cfg = "configs/seem_focall_unicl_lang_v1.yaml"
semsam_ckpt = "./swinl_only_sam_many2many.pth"
sam_ckpt = "./sam_vit_h_4b8939.pth"
seem_ckpt = "./seem_focall_v1.pt"
opt_semsam = load_opt_from_config_file(semsam_cfg)
opt_seem = load_opt_from_config_file(seem_cfg)
opt_seem = init_distributed_seem(opt_seem)
'''
build model
'''
model_semsam = BaseModel(opt_semsam, build_model(opt_semsam)).from_pretrained(semsam_ckpt).eval().cuda()
model_sam = sam_model_registry["vit_h"](checkpoint=sam_ckpt).eval().cuda()
model_seem = BaseModel_Seem(opt_seem, build_model_seem(opt_seem)).from_pretrained(seem_ckpt).eval().cuda()
with torch.no_grad():
with torch.autocast(device_type='cuda', dtype=torch.float16):
model_seem.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(COCO_PANOPTIC_CLASSES + ["background"], is_eval=True)
@torch.no_grad()
def inference(image, slider, mode, alpha, label_mode, anno_mode, *args, **kwargs):
if slider < 1.5:
model_name = 'seem'
elif slider > 2.5:
model_name = 'sam'
else:
if mode == 'Automatic':
model_name = 'semantic-sam'
if slider < 1.5 + 0.14:
level = [1]
elif slider < 1.5 + 0.28:
level = [2]
elif slider < 1.5 + 0.42:
level = [3]
elif slider < 1.5 + 0.56:
level = [4]
elif slider < 1.5 + 0.70:
level = [5]
elif slider < 1.5 + 0.84:
level = [6]
else:
level = [6, 1, 2, 3, 4, 5]
else:
model_name = 'sam'
if label_mode == 'Alphabet':
label_mode = 'a'
else:
label_mode = '1'
text_size, hole_scale, island_scale=640,100,100
text, text_part, text_thresh = '','','0.0'
with torch.autocast(device_type='cuda', dtype=torch.float16):
semantic=False
if mode == "Interactive":
labeled_array, num_features = label(np.asarray(image['mask'].convert('L')))
spatial_masks = torch.stack([torch.from_numpy(labeled_array == i+1) for i in range(num_features)])
if model_name == 'semantic-sam':
model = model_semsam
output, mask = inference_semsam_m2m_auto(model, image['image'], level, text, text_part, text_thresh, text_size, hole_scale, island_scale, semantic, label_mode=label_mode, alpha=alpha, anno_mode=anno_mode, *args, **kwargs)
elif model_name == 'sam':
model = model_sam
if mode == "Automatic":
| # --------------------------------------------------------
# Set-of-Mark (SoM) Prompting for Visual Grounding in GPT-4V
# Copyright (c) 2023 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by:
# Jianwei Yang (jianwyan@microsoft.com)
# Xueyan Zou (xueyan@cs.wisc.edu)
# Hao Zhang (hzhangcx@connect.ust.hk)
# --------------------------------------------------------
# seem
# semantic sam
# sam
'''
build args
'''
semsam_cfg = "configs/semantic_sam_only_sa-1b_swinL.yaml"
seem_cfg = "configs/seem_focall_unicl_lang_v1.yaml"
semsam_ckpt = "./swinl_only_sam_many2many.pth"
sam_ckpt = "./sam_vit_h_4b8939.pth"
seem_ckpt = "./seem_focall_v1.pt"
opt_semsam = load_opt_from_config_file(semsam_cfg)
opt_seem = load_opt_from_config_file(seem_cfg)
opt_seem = init_distributed_seem(opt_seem)
'''
build model
'''
model_semsam = BaseModel(opt_semsam, build_model(opt_semsam)).from_pretrained(semsam_ckpt).eval().cuda()
model_sam = sam_model_registry["vit_h"](checkpoint=sam_ckpt).eval().cuda()
model_seem = BaseModel_Seem(opt_seem, build_model_seem(opt_seem)).from_pretrained(seem_ckpt).eval().cuda()
with torch.no_grad():
with torch.autocast(device_type='cuda', dtype=torch.float16):
model_seem.model.sem_seg_head.predictor.lang_encoder.get_text_embeddings(COCO_PANOPTIC_CLASSES + ["background"], is_eval=True)
@torch.no_grad()
def inference(image, slider, mode, alpha, label_mode, anno_mode, *args, **kwargs):
if slider < 1.5:
model_name = 'seem'
elif slider > 2.5:
model_name = 'sam'
else:
if mode == 'Automatic':
model_name = 'semantic-sam'
if slider < 1.5 + 0.14:
level = [1]
elif slider < 1.5 + 0.28:
level = [2]
elif slider < 1.5 + 0.42:
level = [3]
elif slider < 1.5 + 0.56:
level = [4]
elif slider < 1.5 + 0.70:
level = [5]
elif slider < 1.5 + 0.84:
level = [6]
else:
level = [6, 1, 2, 3, 4, 5]
else:
model_name = 'sam'
if label_mode == 'Alphabet':
label_mode = 'a'
else:
label_mode = '1'
text_size, hole_scale, island_scale=640,100,100
text, text_part, text_thresh = '','','0.0'
with torch.autocast(device_type='cuda', dtype=torch.float16):
semantic=False
if mode == "Interactive":
labeled_array, num_features = label(np.asarray(image['mask'].convert('L')))
spatial_masks = torch.stack([torch.from_numpy(labeled_array == i+1) for i in range(num_features)])
if model_name == 'semantic-sam':
model = model_semsam
output, mask = inference_semsam_m2m_auto(model, image['image'], level, text, text_part, text_thresh, text_size, hole_scale, island_scale, semantic, label_mode=label_mode, alpha=alpha, anno_mode=anno_mode, *args, **kwargs)
elif model_name == 'sam':
model = model_sam
if mode == "Automatic": | output, mask = inference_sam_m2m_auto(model, image['image'], text_size, label_mode, alpha, anno_mode) | 5 | 2023-10-16 03:39:26+00:00 | 8k |
codefuse-ai/Test-Agent | chat/server/gradio_testgpt.py | [
{
"identifier": "LOGDIR",
"path": "chat/constants.py",
"snippet": "LOGDIR = os.getenv(\"LOGDIR\", \".\")"
},
{
"identifier": "WORKER_API_TIMEOUT",
"path": "chat/constants.py",
"snippet": "WORKER_API_TIMEOUT = int(os.getenv(\"FASTCHAT_WORKER_API_TIMEOUT\", 100))"
},
{
"identifier"... | import argparse
import datetime
import json
import os
import time
import uuid
import gradio as gr
import requests
from collections import defaultdict
from chat.constants import (
LOGDIR,
WORKER_API_TIMEOUT,
ErrorCode,
MODERATION_MSG,
CONVERSATION_LIMIT_MSG,
SERVER_ERROR_MSG,
INACTIVE_MSG,
INPUT_CHAR_LEN_LIMIT,
CONVERSATION_TURN_LIMIT,
SESSION_EXPIRATION_TIME,
)
from chat.model.model_adapter import get_conversation_template
from chat.model.model_registry import model_info
from chat.server.api_provider import (
anthropic_api_stream_iter,
openai_api_stream_iter,
palm_api_stream_iter,
init_palm_chat,
)
from chat.utils import (
build_logger,
violates_moderation,
get_window_url_params_js,
parse_gradio_auth_creds,
) | 3,906 | interactive=True,
show_label=False,
container=False,
)
chatbot = gr.Chatbot(
elem_id="chatbot",
label="Scroll down and start chatting",
visible=False,
height=550,
)
with gr.Row(visible=True) as button_fun_row:
gen_testcase_btn = gr.Button(value="单测生成")
assert_completion_btn = gr.Button(value="Assert补全")
with gr.Row():
with gr.Column(scale=20):
textbox = gr.Textbox(
show_label=False,
placeholder="Enter text and press ENTER",
visible=False,
container=False,
)
with gr.Column(scale=1, min_width=100):
send_btn = gr.Button(value="Send", visible=False)
with gr.Row(visible=True) as button_row:
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=True)
clear_btn = gr.Button(value="🗑️ Clear history", interactive=True)
with gr.Accordion("Parameters", open=False, visible=False) as parameter_row:
temperature = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.7,
step=0.1,
interactive=True,
label="Temperature",
)
top_p = gr.Slider(
minimum=0.0,
maximum=1.0,
value=1.0,
step=0.1,
interactive=True,
label="Top P",
)
max_output_tokens = gr.Slider(
minimum=16,
maximum=1024,
value=512,
step=64,
interactive=True,
label="Max output tokens",
)
# Register listeners
#btn_list = [regenerate_btn, clear_btn]
btn_list = []
regenerate_btn.click(regenerate, state, [state, chatbot, textbox] + btn_list).then(
bot_response,
[state, temperature, top_p, max_output_tokens],
[state, chatbot] + btn_list,
)
clear_btn.click(clear_history, None, [state, chatbot, textbox] + btn_list)
gen_testcase_btn.click(fn=gen_testcase, outputs=textbox)
assert_completion_btn.click(fn=assert_completion, outputs=textbox)
model_selector.change(clear_history, None, [state, chatbot, textbox] + btn_list)
textbox.submit(
add_text, [state, model_selector, textbox], [state, chatbot, textbox] + btn_list
).then(
bot_response,
[state, temperature, top_p, max_output_tokens],
[state, chatbot] + btn_list,
)
send_btn.click(
add_text, [state, model_selector, textbox], [state, chatbot, textbox] + btn_list
).then(
bot_response,
[state, temperature, top_p, max_output_tokens],
[state, chatbot] + btn_list,
)
return state, model_selector, chatbot, textbox, send_btn, button_row, parameter_row
def build_demo(models):
with gr.Blocks(
title="TestAgent",
theme=gr.themes.Base(),
css=block_css,
) as demo:
url_params = gr.JSON(visible=False)
(
state,
model_selector,
chatbot,
textbox,
send_btn,
button_row,
parameter_row,
) = build_single_model_ui(models, add_promotion_links=True)
if args.model_list_mode not in ["once", "reload"]:
raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
demo.load(
load_demo,
[url_params],
[
state,
model_selector,
chatbot,
textbox,
send_btn,
button_row,
parameter_row,
],
| """
The gradio demo server for chatting with a single model.
"""
logger = build_logger("gradio_web_server", "gradio_web_server.log")
headers = {"User-Agent": "FastChat Client"}
no_change_btn = gr.Button.update()
enable_btn = gr.Button.update(interactive=True)
disable_btn = gr.Button.update(interactive=False)
controller_url = None
enable_moderation = False
acknowledgment_md = """
**Acknowledgment:** We thank Kaggle, MBZUAI, and AnyScale for their sponsorship.
"""
ip_expiration_dict = defaultdict(lambda: 0)
# Information about custom OpenAI compatible API models.
# JSON file format:
# {
# "vicuna-7b": {
# "model_name": "vicuna-7b-v1.5",
# "api_base": "http://8.8.8.55:5555/v1",
# "api_key": "password"
# },
# }
openai_compatible_models_info = {}
class State:
def __init__(self, model_name):
self.conv = get_conversation_template(model_name)
self.conv_id = uuid.uuid4().hex
self.skip_next = False
self.model_name = model_name
if model_name == "palm-2":
# According to release note, "chat-bison@001" is PaLM 2 for chat.
# https://cloud.google.com/vertex-ai/docs/release-notes#May_10_2023
self.palm_chat = init_palm_chat("chat-bison@001")
def to_gradio_chatbot(self):
return self.conv.to_gradio_chatbot()
def dict(self):
base = self.conv.dict()
base.update(
{
"conv_id": self.conv_id,
"model_name": self.model_name,
}
)
return base
def set_global_vars(controller_url_, enable_moderation_):
global controller_url, enable_moderation
controller_url = controller_url_
enable_moderation = enable_moderation_
def get_conv_log_filename():
t = datetime.datetime.now()
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
return name
def get_model_list(
controller_url, register_openai_compatible_models, add_chatgpt, add_claude, add_palm
):
if controller_url:
ret = requests.post(controller_url + "/refresh_all_workers")
assert ret.status_code == 200
ret = requests.post(controller_url + "/list_models")
models = ret.json()["models"]
else:
models = []
# Add API providers
if register_openai_compatible_models:
global openai_compatible_models_info
openai_compatible_models_info = json.load(
open(register_openai_compatible_models)
)
models += list(openai_compatible_models_info.keys())
if add_chatgpt:
models += ["gpt-3.5-turbo", "gpt-4"]
if add_claude:
models += ["claude-2", "claude-instant-1"]
if add_palm:
models += ["palm-2"]
models = list(set(models))
priority = {k: f"___{i:02d}" for i, k in enumerate(model_info)}
models.sort(key=lambda x: priority.get(x, x))
logger.info(f"Models: {models}")
return models
def load_demo_single(models, url_params):
selected_model = models[0] if len(models) > 0 else ""
if "model" in url_params:
model = url_params["model"]
if model in models:
selected_model = model
dropdown_update = gr.Dropdown.update(
choices=models, value=selected_model, visible=True
)
state = None
return (
state,
dropdown_update,
gr.Chatbot.update(visible=True),
gr.Textbox.update(visible=True),
gr.Button.update(visible=True),
gr.Row.update(visible=True),
gr.Accordion.update(visible=True),
)
def load_demo(url_params, request: gr.Request):
global models
ip = request.client.host
logger.info(f"load_demo. ip: {ip}. params: {url_params}")
ip_expiration_dict[ip] = time.time() + SESSION_EXPIRATION_TIME
if args.model_list_mode == "reload":
models = get_model_list(
controller_url,
args.register_openai_compatible_models,
args.add_chatgpt,
args.add_claude,
args.add_palm,
)
return load_demo_single(models, url_params)
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
with open(get_conv_log_filename(), "a") as fout:
data = {
"tstamp": round(time.time(), 4),
"type": vote_type,
"model": model_selector,
"state": state.dict(),
"ip": request.client.host,
}
fout.write(json.dumps(data) + "\n")
def upvote_last_response(state, model_selector, request: gr.Request):
logger.info(f"upvote. ip: {request.client.host}")
vote_last_response(state, "upvote", model_selector, request)
return ("",) + (disable_btn,) * 3
def downvote_last_response(state, model_selector, request: gr.Request):
logger.info(f"downvote. ip: {request.client.host}")
vote_last_response(state, "downvote", model_selector, request)
return ("",) + (disable_btn,) * 3
def flag_last_response(state, model_selector, request: gr.Request):
logger.info(f"flag. ip: {request.client.host}")
vote_last_response(state, "flag", model_selector, request)
return ("",) + (disable_btn,) * 3
def regenerate(state, request: gr.Request):
logger.info(f"regenerate. ip: {request.client.host}")
state.conv.update_last_message(None)
return (state, state.to_gradio_chatbot(), "") + (disable_btn,) * 2
def clear_history(request: gr.Request):
logger.info(f"clear_history. ip: {request.client.host}")
state = None
return (state, [], "") + (disable_btn,) * 2
def gen_testcase():
return "为以下代码写单测:\n" + \
"```\n" + \
"def prime_and_fibonacci_less_than(n):\n" + \
" # Generating prime numbers\n" + \
" primes = []\n" + \
" for x in range(2, n):\n" + \
" for y in range(2, x):\n" + \
" if x % y == 0:\n" + \
" break\n" + \
" else:\n" + \
" primes.append(x)\n" + \
" \n" + \
" # Generating Fibonacci numbers\n" + \
" fibonacci = []\n" + \
" a, b = 0, 1\n" + \
" while a < n:\n" + \
" fibonacci.append(a)\n" + \
" a, b = b, a+b\n" + \
"\n" + \
" return {'Primes': primes, 'Fibonacci': fibonacci}\n" + \
"\n" + \
"# Testing the function\n" + \
"print(prime_and_fibonacci_less_than(20))\n" + \
"```"
def assert_completion():
return "下面是被测代码\n" + \
"```java\n" + \
"public class LongCollectorImpl implements LongCollector<A, R> {\n" + \
" private final Set<Collector.Characteristics> characteristics;\n" + \
"\n" + \
" @Override\n" + \
" public Set<Collector.Characteristics> characteristics() {\n" + \
" return characteristics;\n" + \
" }\n" + \
"}\n" + \
"```\n" + \
"下面代码是针对上面被测代码生成的用例,请补全用例,生成assert校验\n" + \
"```java\n" + \
"private static final Set<Collector.Characteristics> CHARACTERISTICS = emptySet();\n" + \
"private static final LongCollectorImpl<List<Long>, Long> COLLECTOR = new LongCollectorImpl<>(\n" + \
" SUPPLIER, ACCUMULATOR, COMBINER, FINISHER, CHARACTERISTICS);\n" + \
"\n" + \
"@Test\n" + \
"void characteristics() {\n" + \
" COLLECTOR.characteristics();\n" + \
"}\n" + \
"\n" + \
"```"
def add_text(state, model_selector, text, request: gr.Request):
ip = request.client.host
logger.info(f"add_text. ip: {ip}. len: {len(text)}")
if state is None:
state = State(model_selector)
if len(text) <= 0:
state.skip_next = True
return (state, state.to_gradio_chatbot(), "") + (no_change_btn,) * 5
if ip_expiration_dict[ip] < time.time():
logger.info(f"inactive. ip: {request.client.host}. text: {text}")
state.skip_next = True
return (state, state.to_gradio_chatbot(), INACTIVE_MSG) + (no_change_btn,) * 5
if enable_moderation:
flagged = violates_moderation(text)
if flagged:
logger.info(f"violate moderation. ip: {request.client.host}. text: {text}")
state.skip_next = True
return (state, state.to_gradio_chatbot(), MODERATION_MSG) + (
no_change_btn,
) * 5
conv = state.conv
if (len(conv.messages) - conv.offset) // 2 >= CONVERSATION_TURN_LIMIT:
logger.info(f"conversation turn limit. ip: {request.client.host}. text: {text}")
state.skip_next = True
return (state, state.to_gradio_chatbot(), CONVERSATION_LIMIT_MSG) + (
no_change_btn,
) * 5
text = text[:INPUT_CHAR_LEN_LIMIT] # Hard cut-off
conv.append_message(conv.roles[0], text)
conv.append_message(conv.roles[1], None)
return (state, state.to_gradio_chatbot(), "") + (disable_btn,) * 5
def post_process_code(code):
sep = "\n```"
if sep in code:
blocks = code.split(sep)
if len(blocks) % 2 == 1:
for i in range(1, len(blocks), 2):
blocks[i] = blocks[i].replace("\\_", "_")
code = sep.join(blocks)
return code
def model_worker_stream_iter(
conv,
model_name,
worker_addr,
prompt,
temperature,
repetition_penalty,
top_p,
max_new_tokens,
):
# Make requests
gen_params = {
"model": model_name,
"prompt": prompt,
"temperature": temperature,
"repetition_penalty": repetition_penalty,
"top_p": top_p,
"max_new_tokens": max_new_tokens,
"stop": conv.stop_str,
"stop_token_ids": conv.stop_token_ids,
"echo": False,
}
logger.info(f"==== request ====\n{gen_params}")
# Stream output
response = requests.post(
worker_addr + "/worker_generate_stream",
headers=headers,
json=gen_params,
stream=True,
timeout=WORKER_API_TIMEOUT,
)
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
if chunk:
data = json.loads(chunk.decode())
yield data
def bot_response(state, temperature, top_p, max_new_tokens, request: gr.Request):
logger.info(f"bot_response. ip: {request.client.host}")
start_tstamp = time.time()
temperature = float(temperature)
top_p = float(top_p)
max_new_tokens = int(max_new_tokens)
if state.skip_next:
# This generate call is skipped due to invalid inputs
state.skip_next = False
yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
return
conv, model_name = state.conv, state.model_name
if model_name == "gpt-3.5-turbo" or model_name == "gpt-4":
prompt = conv.to_openai_api_messages()
stream_iter = openai_api_stream_iter(
model_name, prompt, temperature, top_p, max_new_tokens
)
elif model_name == "claude-2" or model_name == "claude-instant-1":
prompt = conv.get_prompt()
stream_iter = anthropic_api_stream_iter(
model_name, prompt, temperature, top_p, max_new_tokens
)
elif model_name == "palm-2":
stream_iter = palm_api_stream_iter(
state.palm_chat, conv.messages[-2][1], temperature, top_p, max_new_tokens
)
elif model_name in openai_compatible_models_info:
model_info = openai_compatible_models_info[model_name]
prompt = conv.to_openai_api_messages()
stream_iter = openai_api_stream_iter(
model_info["model_name"],
prompt,
temperature,
top_p,
max_new_tokens,
api_base=model_info["api_base"],
api_key=model_info["api_key"],
)
else:
# Query worker address
ret = requests.post(
controller_url + "/get_worker_address", json={"model": model_name}
)
worker_addr = ret.json()["address"]
logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
# No available worker
if worker_addr == "":
conv.update_last_message(SERVER_ERROR_MSG)
yield (
state,
state.to_gradio_chatbot(),
disable_btn,
disable_btn,
disable_btn,
enable_btn,
enable_btn,
)
return
# Construct prompt.
# We need to call it here, so it will not be affected by "▌".
prompt = conv.get_prompt()
# Set repetition_penalty
if "t5" in model_name:
repetition_penalty = 1.2
else:
repetition_penalty = 1.0
stream_iter = model_worker_stream_iter(
conv,
model_name,
worker_addr,
prompt,
temperature,
repetition_penalty,
top_p,
max_new_tokens,
)
conv.update_last_message("▌")
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
try:
for i, data in enumerate(stream_iter):
if data["error_code"] == 0:
if i % 5 != 0: # reduce gradio's overhead
continue
output = data["text"].strip()
conv.update_last_message(output + "▌")
yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
else:
output = data["text"] + f"\n\n(error_code: {data['error_code']})"
conv.update_last_message(output)
yield (state, state.to_gradio_chatbot()) + (
disable_btn,
disable_btn,
disable_btn,
enable_btn,
enable_btn,
)
return
output = data["text"].strip()
if "vicuna" in model_name:
output = post_process_code(output)
conv.update_last_message(output)
yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
except requests.exceptions.RequestException as e:
conv.update_last_message(
f"{SERVER_ERROR_MSG}\n\n"
f"(error_code: {ErrorCode.GRADIO_REQUEST_ERROR}, {e})"
)
yield (state, state.to_gradio_chatbot()) + (
disable_btn,
disable_btn,
disable_btn,
enable_btn,
enable_btn,
)
return
except Exception as e:
conv.update_last_message(
f"{SERVER_ERROR_MSG}\n\n"
f"(error_code: {ErrorCode.GRADIO_STREAM_UNKNOWN_ERROR}, {e})"
)
yield (state, state.to_gradio_chatbot()) + (
disable_btn,
disable_btn,
disable_btn,
enable_btn,
enable_btn,
)
return
finish_tstamp = time.time()
logger.info(f"{output}")
with open(get_conv_log_filename(), "a") as fout:
data = {
"tstamp": round(finish_tstamp, 4),
"type": "chat",
"model": model_name,
"gen_params": {
"temperature": temperature,
"top_p": top_p,
"max_new_tokens": max_new_tokens,
},
"start": round(start_tstamp, 4),
"finish": round(finish_tstamp, 4),
"state": state.dict(),
"ip": request.client.host,
}
fout.write(json.dumps(data) + "\n")
block_css = """
#notice_markdown {
font-size: 104%
}
#notice_markdown th {
display: none;
}
#notice_markdown td {
padding-top: 6px;
padding-bottom: 6px;
}
#leaderboard_markdown {
font-size: 104%
}
#leaderboard_markdown td {
padding-top: 6px;
padding-bottom: 6px;
}
#leaderboard_dataframe td {
line-height: 0.1em;
}
footer {
display:none !important
}
"""
def get_model_description_md(models):
model_description_md = """
| | | |
| ---- | ---- | ---- |
"""
ct = 0
visited = set()
for i, name in enumerate(models):
if name in model_info:
minfo = model_info[name]
if minfo.simple_name in visited:
continue
visited.add(minfo.simple_name)
one_model_md = f"[{minfo.simple_name}]({minfo.link}): {minfo.description}"
else:
visited.add(name)
one_model_md = (
f"[{name}](): Add the description at chat/model/model_registry.py"
)
if ct % 3 == 0:
model_description_md += "|"
model_description_md += f" {one_model_md} |"
if ct % 3 == 2:
model_description_md += "\n"
ct += 1
return model_description_md
# TODO
def build_single_model_ui(models, add_promotion_links=False):
promotion = (
"""
- TestGPT-7B: 模型以CodeLlama-7B为基座,进行了测试领域下游任务的微调,包含多语言测试用例生成、测试用例Assert补全。 [[ModelScope]](https://modelscope.cn/models/codefuse-ai/TestGPT-7B/summary)
"""
if add_promotion_links
else ""
)
notice_markdown = f"""
# 🏔️ TestAgent 测试助理
{promotion}
### 请选择模型
"""
state = gr.State()
model_description_md = get_model_description_md(models)
gr.Markdown(notice_markdown + model_description_md, elem_id="notice_markdown")
fun = ["testcase", "assert"]
with gr.Row(elem_id="model_selector_row"):
model_selector = gr.Dropdown(
choices=models,
value=models[0] if len(models) > 0 else "",
interactive=True,
show_label=False,
container=False,
)
chatbot = gr.Chatbot(
elem_id="chatbot",
label="Scroll down and start chatting",
visible=False,
height=550,
)
with gr.Row(visible=True) as button_fun_row:
gen_testcase_btn = gr.Button(value="单测生成")
assert_completion_btn = gr.Button(value="Assert补全")
with gr.Row():
with gr.Column(scale=20):
textbox = gr.Textbox(
show_label=False,
placeholder="Enter text and press ENTER",
visible=False,
container=False,
)
with gr.Column(scale=1, min_width=100):
send_btn = gr.Button(value="Send", visible=False)
with gr.Row(visible=True) as button_row:
regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=True)
clear_btn = gr.Button(value="🗑️ Clear history", interactive=True)
with gr.Accordion("Parameters", open=False, visible=False) as parameter_row:
temperature = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.7,
step=0.1,
interactive=True,
label="Temperature",
)
top_p = gr.Slider(
minimum=0.0,
maximum=1.0,
value=1.0,
step=0.1,
interactive=True,
label="Top P",
)
max_output_tokens = gr.Slider(
minimum=16,
maximum=1024,
value=512,
step=64,
interactive=True,
label="Max output tokens",
)
# Register listeners
#btn_list = [regenerate_btn, clear_btn]
btn_list = []
regenerate_btn.click(regenerate, state, [state, chatbot, textbox] + btn_list).then(
bot_response,
[state, temperature, top_p, max_output_tokens],
[state, chatbot] + btn_list,
)
clear_btn.click(clear_history, None, [state, chatbot, textbox] + btn_list)
gen_testcase_btn.click(fn=gen_testcase, outputs=textbox)
assert_completion_btn.click(fn=assert_completion, outputs=textbox)
model_selector.change(clear_history, None, [state, chatbot, textbox] + btn_list)
textbox.submit(
add_text, [state, model_selector, textbox], [state, chatbot, textbox] + btn_list
).then(
bot_response,
[state, temperature, top_p, max_output_tokens],
[state, chatbot] + btn_list,
)
send_btn.click(
add_text, [state, model_selector, textbox], [state, chatbot, textbox] + btn_list
).then(
bot_response,
[state, temperature, top_p, max_output_tokens],
[state, chatbot] + btn_list,
)
return state, model_selector, chatbot, textbox, send_btn, button_row, parameter_row
def build_demo(models):
with gr.Blocks(
title="TestAgent",
theme=gr.themes.Base(),
css=block_css,
) as demo:
url_params = gr.JSON(visible=False)
(
state,
model_selector,
chatbot,
textbox,
send_btn,
button_row,
parameter_row,
) = build_single_model_ui(models, add_promotion_links=True)
if args.model_list_mode not in ["once", "reload"]:
raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
demo.load(
load_demo,
[url_params],
[
state,
model_selector,
chatbot,
textbox,
send_btn,
button_row,
parameter_row,
], | _js=get_window_url_params_js, | 16 | 2023-10-20 08:56:20+00:00 | 8k |
thuml/iTransformer | data_provider/data_factory.py | [
{
"identifier": "Dataset_ETT_hour",
"path": "data_provider/data_loader.py",
"snippet": "class Dataset_ETT_hour(Dataset):\n def __init__(self, root_path, flag='train', size=None,\n features='S', data_path='ETTh1.csv',\n target='OT', scale=True, timeenc=0, freq='h'):\n ... | from data_provider.data_loader import Dataset_ETT_hour, Dataset_ETT_minute, Dataset_Custom, Dataset_Solar, Dataset_PEMS, \
Dataset_Pred
from torch.utils.data import DataLoader | 5,696 |
data_dict = {
'ETTh1': Dataset_ETT_hour,
'ETTh2': Dataset_ETT_hour,
'ETTm1': Dataset_ETT_minute,
'ETTm2': Dataset_ETT_minute,
|
data_dict = {
'ETTh1': Dataset_ETT_hour,
'ETTh2': Dataset_ETT_hour,
'ETTm1': Dataset_ETT_minute,
'ETTm2': Dataset_ETT_minute, | 'Solar': Dataset_Solar, | 3 | 2023-10-19 03:23:15+00:00 | 8k |
kylesargent/ZeroNVS | threestudio/models/geometry/implicit_sdf.py | [
{
"identifier": "BaseImplicitGeometry",
"path": "threestudio/models/geometry/base.py",
"snippet": "class BaseImplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n isosurface: bool = True\n isosurface_method: str = \"mt\"\n ... | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import threestudio
import trimesh
from dataclasses import dataclass, field
from threestudio.models.geometry.base import BaseImplicitGeometry, contract_to_unisphere
from threestudio.models.mesh import Mesh
from threestudio.models.networks import get_encoding, get_mlp
from threestudio.utils.misc import broadcast, get_rank
from threestudio.utils.typing import *
from pysdf import SDF
from tqdm import tqdm | 7,184 | if self.cfg.sdf_bias != 0.0:
threestudio.warn(
"shape_init and sdf_bias are both specified, which may lead to unexpected results."
)
get_gt_sdf: Callable[[Float[Tensor, "N 3"]], Float[Tensor, "N 1"]]
assert isinstance(self.cfg.shape_init, str)
if self.cfg.shape_init == "ellipsoid":
assert (
isinstance(self.cfg.shape_init_params, Sized)
and len(self.cfg.shape_init_params) == 3
)
size = torch.as_tensor(self.cfg.shape_init_params).to(self.device)
def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
return ((points_rand / size) ** 2).sum(
dim=-1, keepdim=True
).sqrt() - 1.0 # pseudo signed distance of an ellipsoid
get_gt_sdf = func
elif self.cfg.shape_init == "sphere":
assert isinstance(self.cfg.shape_init_params, float)
radius = self.cfg.shape_init_params
def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius
get_gt_sdf = func
elif self.cfg.shape_init.startswith("mesh:"):
assert isinstance(self.cfg.shape_init_params, float)
mesh_path = self.cfg.shape_init[5:]
if not os.path.exists(mesh_path):
raise ValueError(f"Mesh file {mesh_path} does not exist.")
scene = trimesh.load(mesh_path)
if isinstance(scene, trimesh.Trimesh):
mesh = scene
elif isinstance(scene, trimesh.scene.Scene):
mesh = trimesh.Trimesh()
for obj in scene.geometry.values():
mesh = trimesh.util.concatenate([mesh, obj])
else:
raise ValueError(f"Unknown mesh type at {mesh_path}.")
# move to center
centroid = mesh.vertices.mean(0)
mesh.vertices = mesh.vertices - centroid
# align to up-z and front-x
dirs = ["+x", "+y", "+z", "-x", "-y", "-z"]
dir2vec = {
"+x": np.array([1, 0, 0]),
"+y": np.array([0, 1, 0]),
"+z": np.array([0, 0, 1]),
"-x": np.array([-1, 0, 0]),
"-y": np.array([0, -1, 0]),
"-z": np.array([0, 0, -1]),
}
if (
self.cfg.shape_init_mesh_up not in dirs
or self.cfg.shape_init_mesh_front not in dirs
):
raise ValueError(
f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}."
)
if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]:
raise ValueError(
"shape_init_mesh_up and shape_init_mesh_front must be orthogonal."
)
z_, x_ = (
dir2vec[self.cfg.shape_init_mesh_up],
dir2vec[self.cfg.shape_init_mesh_front],
)
y_ = np.cross(z_, x_)
std2mesh = np.stack([x_, y_, z_], axis=0).T
mesh2std = np.linalg.inv(std2mesh)
# scaling
scale = np.abs(mesh.vertices).max()
mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params
mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T
sdf = SDF(mesh.vertices, mesh.faces)
def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
# add a negative signed here
# as in pysdf the inside of the shape has positive signed distance
return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to(
points_rand
)[..., None]
get_gt_sdf = func
else:
raise ValueError(
f"Unknown shape initialization type: {self.cfg.shape_init}"
)
# Initialize SDF to a given shape when no weights are provided or force_shape_init is True
optim = torch.optim.Adam(self.parameters(), lr=1e-3)
for _ in tqdm(
range(1000),
desc=f"Initializing SDF to a(n) {self.cfg.shape_init}:",
disable=get_rank() != 0,
):
points_rand = (
torch.rand((10000, 3), dtype=torch.float32).to(self.device) * 2.0 - 1.0
)
sdf_gt = get_gt_sdf(points_rand)
sdf_pred = self.forward_sdf(points_rand)
loss = F.mse_loss(sdf_pred, sdf_gt)
optim.zero_grad()
loss.backward()
optim.step()
# explicit broadcast to ensure param consistency across ranks
for param in self.parameters():
|
@threestudio.register("implicit-sdf")
class ImplicitSDF(BaseImplicitGeometry):
@dataclass
class Config(BaseImplicitGeometry.Config):
n_input_dims: int = 3
n_feature_dims: int = 3
pos_encoding_config: dict = field(
default_factory=lambda: {
"otype": "HashGrid",
"n_levels": 16,
"n_features_per_level": 2,
"log2_hashmap_size": 19,
"base_resolution": 16,
"per_level_scale": 1.447269237440378,
}
)
mlp_network_config: dict = field(
default_factory=lambda: {
"otype": "VanillaMLP",
"activation": "ReLU",
"output_activation": "none",
"n_neurons": 64,
"n_hidden_layers": 1,
}
)
normal_type: Optional[
str
] = "finite_difference" # in ['pred', 'finite_difference', 'finite_difference_laplacian']
finite_difference_normal_eps: Union[
float, str
] = 0.01 # in [float, "progressive"]
shape_init: Optional[str] = None
shape_init_params: Optional[Any] = None
shape_init_mesh_up: str = "+z"
shape_init_mesh_front: str = "+x"
force_shape_init: bool = False
sdf_bias: Union[float, str] = 0.0
sdf_bias_params: Optional[Any] = None
# no need to removal outlier for SDF
isosurface_remove_outliers: bool = False
cfg: Config
def configure(self) -> None:
super().configure()
self.encoding = get_encoding(
self.cfg.n_input_dims, self.cfg.pos_encoding_config
)
self.sdf_network = get_mlp(
self.encoding.n_output_dims, 1, self.cfg.mlp_network_config
)
if self.cfg.n_feature_dims > 0:
self.feature_network = get_mlp(
self.encoding.n_output_dims,
self.cfg.n_feature_dims,
self.cfg.mlp_network_config,
)
if self.cfg.normal_type == "pred":
self.normal_network = get_mlp(
self.encoding.n_output_dims, 3, self.cfg.mlp_network_config
)
if self.cfg.isosurface_deformable_grid:
assert (
self.cfg.isosurface_method == "mt"
), "isosurface_deformable_grid only works with mt"
self.deformation_network = get_mlp(
self.encoding.n_output_dims, 3, self.cfg.mlp_network_config
)
self.finite_difference_normal_eps: Optional[float] = None
def initialize_shape(self) -> None:
if self.cfg.shape_init is None and not self.cfg.force_shape_init:
return
# do not initialize shape if weights are provided
if self.cfg.weights is not None and not self.cfg.force_shape_init:
return
if self.cfg.sdf_bias != 0.0:
threestudio.warn(
"shape_init and sdf_bias are both specified, which may lead to unexpected results."
)
get_gt_sdf: Callable[[Float[Tensor, "N 3"]], Float[Tensor, "N 1"]]
assert isinstance(self.cfg.shape_init, str)
if self.cfg.shape_init == "ellipsoid":
assert (
isinstance(self.cfg.shape_init_params, Sized)
and len(self.cfg.shape_init_params) == 3
)
size = torch.as_tensor(self.cfg.shape_init_params).to(self.device)
def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
return ((points_rand / size) ** 2).sum(
dim=-1, keepdim=True
).sqrt() - 1.0 # pseudo signed distance of an ellipsoid
get_gt_sdf = func
elif self.cfg.shape_init == "sphere":
assert isinstance(self.cfg.shape_init_params, float)
radius = self.cfg.shape_init_params
def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
return (points_rand**2).sum(dim=-1, keepdim=True).sqrt() - radius
get_gt_sdf = func
elif self.cfg.shape_init.startswith("mesh:"):
assert isinstance(self.cfg.shape_init_params, float)
mesh_path = self.cfg.shape_init[5:]
if not os.path.exists(mesh_path):
raise ValueError(f"Mesh file {mesh_path} does not exist.")
scene = trimesh.load(mesh_path)
if isinstance(scene, trimesh.Trimesh):
mesh = scene
elif isinstance(scene, trimesh.scene.Scene):
mesh = trimesh.Trimesh()
for obj in scene.geometry.values():
mesh = trimesh.util.concatenate([mesh, obj])
else:
raise ValueError(f"Unknown mesh type at {mesh_path}.")
# move to center
centroid = mesh.vertices.mean(0)
mesh.vertices = mesh.vertices - centroid
# align to up-z and front-x
dirs = ["+x", "+y", "+z", "-x", "-y", "-z"]
dir2vec = {
"+x": np.array([1, 0, 0]),
"+y": np.array([0, 1, 0]),
"+z": np.array([0, 0, 1]),
"-x": np.array([-1, 0, 0]),
"-y": np.array([0, -1, 0]),
"-z": np.array([0, 0, -1]),
}
if (
self.cfg.shape_init_mesh_up not in dirs
or self.cfg.shape_init_mesh_front not in dirs
):
raise ValueError(
f"shape_init_mesh_up and shape_init_mesh_front must be one of {dirs}."
)
if self.cfg.shape_init_mesh_up[1] == self.cfg.shape_init_mesh_front[1]:
raise ValueError(
"shape_init_mesh_up and shape_init_mesh_front must be orthogonal."
)
z_, x_ = (
dir2vec[self.cfg.shape_init_mesh_up],
dir2vec[self.cfg.shape_init_mesh_front],
)
y_ = np.cross(z_, x_)
std2mesh = np.stack([x_, y_, z_], axis=0).T
mesh2std = np.linalg.inv(std2mesh)
# scaling
scale = np.abs(mesh.vertices).max()
mesh.vertices = mesh.vertices / scale * self.cfg.shape_init_params
mesh.vertices = np.dot(mesh2std, mesh.vertices.T).T
sdf = SDF(mesh.vertices, mesh.faces)
def func(points_rand: Float[Tensor, "N 3"]) -> Float[Tensor, "N 1"]:
# add a negative signed here
# as in pysdf the inside of the shape has positive signed distance
return torch.from_numpy(-sdf(points_rand.cpu().numpy())).to(
points_rand
)[..., None]
get_gt_sdf = func
else:
raise ValueError(
f"Unknown shape initialization type: {self.cfg.shape_init}"
)
# Initialize SDF to a given shape when no weights are provided or force_shape_init is True
optim = torch.optim.Adam(self.parameters(), lr=1e-3)
for _ in tqdm(
range(1000),
desc=f"Initializing SDF to a(n) {self.cfg.shape_init}:",
disable=get_rank() != 0,
):
points_rand = (
torch.rand((10000, 3), dtype=torch.float32).to(self.device) * 2.0 - 1.0
)
sdf_gt = get_gt_sdf(points_rand)
sdf_pred = self.forward_sdf(points_rand)
loss = F.mse_loss(sdf_pred, sdf_gt)
optim.zero_grad()
loss.backward()
optim.step()
# explicit broadcast to ensure param consistency across ranks
for param in self.parameters(): | broadcast(param, src=0) | 5 | 2023-10-24 19:02:44+00:00 | 8k |
princeton-nlp/LLM-Shearing | llmshearing/train.py | [
{
"identifier": "DebugCallback",
"path": "llmshearing/callbacks/callbacks.py",
"snippet": "class DebugCallback(Callback):\n def batch_start(self, state: State, logger: Logger) -> None:\n for b in state.batch[\"input_ids\"]:\n print(b) "
},
{
"identifier": "DynamicLoadingCall... | import os
import sys
import warnings
import torch
from types import MethodType
from typing import Any, Dict
from composer import Logger, State, Trainer
from composer.callbacks.checkpoint_saver import CheckpointSaver
from composer.core import Evaluator, Event
from composer.loggers import FileLogger
from composer.optim import DecoupledAdamW
from composer.utils import dist, get_device, reproducibility
from llmfoundry.optim import (DecoupledAdaLRLion, DecoupledClipLion,
DecoupledLionW, DecoupledLionW_8bit)
from llmfoundry.utils.builders import (build_algorithm, build_callback,
build_logger, build_scheduler)
from llmfoundry.utils.config_utils import (log_config, pop_config,
update_batch_size_info)
from omegaconf import DictConfig
from omegaconf import OmegaConf as om
from torch import nn
from torch.optim.optimizer import Optimizer
from llmshearing.callbacks.callbacks import DebugCallback
from llmshearing.callbacks.dynamic_loading_callback import \
DynamicLoadingCallback
from llmshearing.callbacks.pruning_callback import PruningCallback
from llmshearing.datasets.load_text_dataloader import build_text_dataloader
from llmshearing.models.model_registry import COMPOSER_MODEL_REGISTRY
from llmshearing.datasets.state import _dataset_state_dict | 4,340 | optimizer_config: Dict[str, Any]) -> Optimizer:
"""
build optimizer that consists of three groups of parameters:
- main_model_params: parameters of the main model
- l0_module_params: parameters of the l0 module
- lagrange_params: parameters of the lagrange multipliers
"""
param_groups = {}
main_model_params = [p for n, p in model.named_parameters() if "l0_module" not in n]
l0_module_params = [p for n, p in model.named_parameters() if "l0_module" in n and "lambda" not in n]
lagrange_params = [p for n, p in model.named_parameters() if "l0_module" in n and "lambda" in n]
param_groups = [{"params": main_model_params, "lr": optimizer_config.lr}]
lag_lr = pop_config(optimizer_config, "lag_lr")
if len(l0_module_params) > 0:
param_groups.extend([{"params": l0_module_params, "lr": lag_lr}, {"params": lagrange_params, "lr": -(lag_lr)}])
for i, group in enumerate(param_groups):
print(f"Group {i}:", f"{len(group['params'])} tensors", f"{sum(p.numel() for p in group['params'])} params", f"{group['lr']:.2e} lr")
if name == 'decoupled_adamw':
return DecoupledAdamW(param_groups, **optimizer_config)
elif name == 'decoupled_lionw':
return DecoupledLionW(param_groups, **optimizer_config)
elif name == 'clip_lion':
return DecoupledClipLion(param_groups, **optimizer_config)
elif name == 'adalr_lion':
return DecoupledAdaLRLion(param_groups, **optimizer_config)
elif name == 'decoupled_lionw_8b':
return DecoupledLionW_8bit(param_groups, **optimizer_config)
else:
raise ValueError(f'Not sure how to build optimizer: {name}')
def main(cfg):
""" Main training function """
print("Start running ")
warnings.filterwarnings(
action='ignore',
category=UserWarning,
message=f'torch.distributed.*_base is a private function and will be deprecated.*'
)
cfg.dist_timeout = cfg.get('dist_timeout', 1800.0)
dist.initialize_dist(get_device(None), timeout=cfg.dist_timeout)
# Check for incompatibilities between the model and data loaders
validate_config(cfg)
# Filter deprecation warning from torch internal usage
warnings.filterwarnings(
action='ignore',
category=UserWarning,
message='torch.distributed.*_base is a private function and will be deprecated.*'
)
reproducibility.seed_all(cfg.seed)
# Run Name
if cfg.get('run_name') is None:
cfg.run_name = os.environ.get('COMPOSER_RUN_NAME', 'llm')
# Get batch size info
cfg = update_batch_size_info(cfg)
# Read FSDP Config as a dict
fsdp_config = cfg.get('fsdp_config', None)
fsdp_config = om.to_container(fsdp_config,
resolve=True) if fsdp_config else None
# Restrict model init_device to 'meta' and 'cpu',
# when multiple GPUs are available.
# Also 'meta' is only valid when using FSDP
init_device = cfg.model.get('init_device', 'cpu')
assert init_device in ['meta', 'cpu']
if fsdp_config is None and init_device == 'meta':
warnings.warn(
"Using `cfg.model.init_device='meta'` is only valid when using FSDP! " +\
"Reverting to `cfg.model.init_device='cpu'`.")
cfg.model.init_device = 'cpu'
# Loggers
loggers = [
build_logger(name, logger_cfg)
for name, logger_cfg in (cfg.get('loggers') or {}).items()
]
save_folder = cfg.save_folder.replace('{run_name}', cfg.run_name)
filename = f"{save_folder}/logs.txt"
count = 1
while os.path.exists(filename):
print(f"File {filename} already exists")
filename = f"{save_folder}/logs_{count}.txt"
count += 1
print(f"Logging to {filename}")
loggers.append(FileLogger(filename=filename,
buffer_size=1,
flush_interval=50))
# Build Model
print('Initializing model...')
if cfg.callbacks.data_loading.dynamic:
cfg.model.set_names = cfg.callbacks.data_loading.set_names
model = build_composer_model(cfg.model)
print(model)
print(cfg.model.l0_module)
state_dict = load_weights(cfg)
if state_dict is not None:
load_state_dict(model, state_dict)
cfg.n_params = sum(p.numel() for p in model.parameters())
print(f'{cfg.n_params=:.2e}')
if hasattr(model, 'num_fwd_flops'):
print(f'{model.num_fwd_flops=:.2e}')
# set names has to be part of the config
assert getattr(cfg.callbacks.data_loading, 'set_names', None) is not None, "please specify the set (domain) names in the config"
# Dataloaders
print('Building train loader...')
| # Copyright 2022 MosaicML Examples authors
# SPDX-License-Identifier: Apache-2.0
def is_one_hour(run_name: str):
""" Check if the run name is for one hour training. """
return run_name.startswith("ONE_HOUR")
def exit_batch_checkpoint(self, state: State, logger: Logger):
""" Exit the program after saving the checkpoint. """
if self.save_interval(state, Event.BATCH_CHECKPOINT) and self.last_checkpoint_batch != state.timestamp.batch:
self._save_checkpoint(
state,
logger,
)
print("Ending program at batch", state.timestamp.batch)
print(self.folder)
sys.exit()
def validate_config(cfg: DictConfig):
"""Validates compatible model and dataloader selection."""
loaders = [cfg.train_loader]
if 'eval_loader' in cfg:
loaders.append(cfg.eval_loader)
def build_composer_model(cfg: DictConfig):
""" build the composer model """
warnings.filterwarnings(
action='ignore',
message='Torchmetrics v0.9 introduced a new argument class property')
return COMPOSER_MODEL_REGISTRY[cfg.name](cfg)
def load_weights(cfg: DictConfig):
""" load weights """
if cfg.model.get('path', None):
state_dict = torch.load(cfg.model.path) # for loading pre-trained llama
if "state" in state_dict:
state_dict = state_dict["state"]["model"]
print("Loaded model from path: ", cfg.model.path)
return state_dict
return None
def load_state_dict(model: nn.Module, state_dict: Dict[str, Any]):
""" load state dict to the model """
result = model.load_state_dict(state_dict, strict=False)
print("Model load state dict result: ", result)
print("Having missing rotary_emb.inv_freq keys is normal")
def build_optimizer(model: torch.nn.Module, name: str,
optimizer_config: Dict[str, Any]) -> Optimizer:
"""
build optimizer that consists of three groups of parameters:
- main_model_params: parameters of the main model
- l0_module_params: parameters of the l0 module
- lagrange_params: parameters of the lagrange multipliers
"""
param_groups = {}
main_model_params = [p for n, p in model.named_parameters() if "l0_module" not in n]
l0_module_params = [p for n, p in model.named_parameters() if "l0_module" in n and "lambda" not in n]
lagrange_params = [p for n, p in model.named_parameters() if "l0_module" in n and "lambda" in n]
param_groups = [{"params": main_model_params, "lr": optimizer_config.lr}]
lag_lr = pop_config(optimizer_config, "lag_lr")
if len(l0_module_params) > 0:
param_groups.extend([{"params": l0_module_params, "lr": lag_lr}, {"params": lagrange_params, "lr": -(lag_lr)}])
for i, group in enumerate(param_groups):
print(f"Group {i}:", f"{len(group['params'])} tensors", f"{sum(p.numel() for p in group['params'])} params", f"{group['lr']:.2e} lr")
if name == 'decoupled_adamw':
return DecoupledAdamW(param_groups, **optimizer_config)
elif name == 'decoupled_lionw':
return DecoupledLionW(param_groups, **optimizer_config)
elif name == 'clip_lion':
return DecoupledClipLion(param_groups, **optimizer_config)
elif name == 'adalr_lion':
return DecoupledAdaLRLion(param_groups, **optimizer_config)
elif name == 'decoupled_lionw_8b':
return DecoupledLionW_8bit(param_groups, **optimizer_config)
else:
raise ValueError(f'Not sure how to build optimizer: {name}')
def main(cfg):
""" Main training function """
print("Start running ")
warnings.filterwarnings(
action='ignore',
category=UserWarning,
message=f'torch.distributed.*_base is a private function and will be deprecated.*'
)
cfg.dist_timeout = cfg.get('dist_timeout', 1800.0)
dist.initialize_dist(get_device(None), timeout=cfg.dist_timeout)
# Check for incompatibilities between the model and data loaders
validate_config(cfg)
# Filter deprecation warning from torch internal usage
warnings.filterwarnings(
action='ignore',
category=UserWarning,
message='torch.distributed.*_base is a private function and will be deprecated.*'
)
reproducibility.seed_all(cfg.seed)
# Run Name
if cfg.get('run_name') is None:
cfg.run_name = os.environ.get('COMPOSER_RUN_NAME', 'llm')
# Get batch size info
cfg = update_batch_size_info(cfg)
# Read FSDP Config as a dict
fsdp_config = cfg.get('fsdp_config', None)
fsdp_config = om.to_container(fsdp_config,
resolve=True) if fsdp_config else None
# Restrict model init_device to 'meta' and 'cpu',
# when multiple GPUs are available.
# Also 'meta' is only valid when using FSDP
init_device = cfg.model.get('init_device', 'cpu')
assert init_device in ['meta', 'cpu']
if fsdp_config is None and init_device == 'meta':
warnings.warn(
"Using `cfg.model.init_device='meta'` is only valid when using FSDP! " +\
"Reverting to `cfg.model.init_device='cpu'`.")
cfg.model.init_device = 'cpu'
# Loggers
loggers = [
build_logger(name, logger_cfg)
for name, logger_cfg in (cfg.get('loggers') or {}).items()
]
save_folder = cfg.save_folder.replace('{run_name}', cfg.run_name)
filename = f"{save_folder}/logs.txt"
count = 1
while os.path.exists(filename):
print(f"File {filename} already exists")
filename = f"{save_folder}/logs_{count}.txt"
count += 1
print(f"Logging to {filename}")
loggers.append(FileLogger(filename=filename,
buffer_size=1,
flush_interval=50))
# Build Model
print('Initializing model...')
if cfg.callbacks.data_loading.dynamic:
cfg.model.set_names = cfg.callbacks.data_loading.set_names
model = build_composer_model(cfg.model)
print(model)
print(cfg.model.l0_module)
state_dict = load_weights(cfg)
if state_dict is not None:
load_state_dict(model, state_dict)
cfg.n_params = sum(p.numel() for p in model.parameters())
print(f'{cfg.n_params=:.2e}')
if hasattr(model, 'num_fwd_flops'):
print(f'{model.num_fwd_flops=:.2e}')
# set names has to be part of the config
assert getattr(cfg.callbacks.data_loading, 'set_names', None) is not None, "please specify the set (domain) names in the config"
# Dataloaders
print('Building train loader...') | train_loader = build_text_dataloader(cfg.train_loader, | 3 | 2023-10-16 12:26:08+00:00 | 8k |
hugoycj/Instant-angelo | systems/base.py | [
{
"identifier": "parse_optimizer",
"path": "systems/utils.py",
"snippet": "def parse_optimizer(config, model):\n if hasattr(config, 'params'):\n params = [{'params': get_parameters(model, name), 'name': name, **args} for name, args in config.params.items()]\n rank_zero_debug('Specify op... | import pytorch_lightning as pl
import models
from systems.utils import parse_optimizer, parse_scheduler, update_module_step
from utils.mixins import SaverMixin
from utils.misc import config_to_primitive, get_rank | 4,188 |
class BaseSystem(pl.LightningModule, SaverMixin):
"""
Two ways to print to console:
1. self.print: correctly handle progress bar
2. rank_zero_info: use the logging module
"""
def __init__(self, config):
super().__init__()
self.config = config
self.rank = get_rank()
self.prepare()
self.model = models.make(self.config.model.name, self.config.model)
def prepare(self):
pass
def forward(self, batch):
raise NotImplementedError
def C(self, value):
if isinstance(value, int) or isinstance(value, float):
pass
else:
value = config_to_primitive(value)
if not isinstance(value, list):
raise TypeError('Scalar specification only supports list, got', type(value))
if len(value) == 3:
value = [0] + value
assert len(value) == 4
start_step, start_value, end_value, end_step = value
if isinstance(end_step, int):
current_step = self.global_step
value = start_value + (end_value - start_value) * max(min(1.0, (current_step - start_step) / (end_step - start_step)), 0.0)
elif isinstance(end_step, float):
current_step = self.current_epoch
value = start_value + (end_value - start_value) * max(min(1.0, (current_step - start_step) / (end_step - start_step)), 0.0)
return value
def preprocess_data(self, batch, stage):
pass
"""
Implementing on_after_batch_transfer of DataModule does the same.
But on_after_batch_transfer does not support DP.
"""
def on_train_batch_start(self, batch, batch_idx, unused=0):
self.dataset = self.trainer.datamodule.train_dataloader().dataset
self.preprocess_data(batch, 'train')
update_module_step(self.model, self.current_epoch, self.global_step)
def on_validation_batch_start(self, batch, batch_idx, dataloader_idx):
self.dataset = self.trainer.datamodule.val_dataloader().dataset
self.preprocess_data(batch, 'validation')
update_module_step(self.model, self.current_epoch, self.global_step)
def on_test_batch_start(self, batch, batch_idx, dataloader_idx):
self.dataset = self.trainer.datamodule.test_dataloader().dataset
self.preprocess_data(batch, 'test')
update_module_step(self.model, self.current_epoch, self.global_step)
def on_predict_batch_start(self, batch, batch_idx, dataloader_idx):
self.dataset = self.trainer.datamodule.predict_dataloader().dataset
self.preprocess_data(batch, 'predict')
update_module_step(self.model, self.current_epoch, self.global_step)
def training_step(self, batch, batch_idx):
raise NotImplementedError
"""
# aggregate outputs from different devices (DP)
def training_step_end(self, out):
pass
"""
"""
# aggregate outputs from different iterations
def training_epoch_end(self, out):
pass
"""
def validation_step(self, batch, batch_idx):
raise NotImplementedError
"""
# aggregate outputs from different devices when using DP
def validation_step_end(self, out):
pass
"""
def validation_epoch_end(self, out):
"""
Gather metrics from all devices, compute mean.
Purge repeated results using data index.
"""
raise NotImplementedError
def test_step(self, batch, batch_idx):
raise NotImplementedError
def test_epoch_end(self, out):
"""
Gather metrics from all devices, compute mean.
Purge repeated results using data index.
"""
raise NotImplementedError
def export(self):
raise NotImplementedError
def configure_optimizers(self):
|
class BaseSystem(pl.LightningModule, SaverMixin):
"""
Two ways to print to console:
1. self.print: correctly handle progress bar
2. rank_zero_info: use the logging module
"""
def __init__(self, config):
super().__init__()
self.config = config
self.rank = get_rank()
self.prepare()
self.model = models.make(self.config.model.name, self.config.model)
def prepare(self):
pass
def forward(self, batch):
raise NotImplementedError
def C(self, value):
if isinstance(value, int) or isinstance(value, float):
pass
else:
value = config_to_primitive(value)
if not isinstance(value, list):
raise TypeError('Scalar specification only supports list, got', type(value))
if len(value) == 3:
value = [0] + value
assert len(value) == 4
start_step, start_value, end_value, end_step = value
if isinstance(end_step, int):
current_step = self.global_step
value = start_value + (end_value - start_value) * max(min(1.0, (current_step - start_step) / (end_step - start_step)), 0.0)
elif isinstance(end_step, float):
current_step = self.current_epoch
value = start_value + (end_value - start_value) * max(min(1.0, (current_step - start_step) / (end_step - start_step)), 0.0)
return value
def preprocess_data(self, batch, stage):
pass
"""
Implementing on_after_batch_transfer of DataModule does the same.
But on_after_batch_transfer does not support DP.
"""
def on_train_batch_start(self, batch, batch_idx, unused=0):
self.dataset = self.trainer.datamodule.train_dataloader().dataset
self.preprocess_data(batch, 'train')
update_module_step(self.model, self.current_epoch, self.global_step)
def on_validation_batch_start(self, batch, batch_idx, dataloader_idx):
self.dataset = self.trainer.datamodule.val_dataloader().dataset
self.preprocess_data(batch, 'validation')
update_module_step(self.model, self.current_epoch, self.global_step)
def on_test_batch_start(self, batch, batch_idx, dataloader_idx):
self.dataset = self.trainer.datamodule.test_dataloader().dataset
self.preprocess_data(batch, 'test')
update_module_step(self.model, self.current_epoch, self.global_step)
def on_predict_batch_start(self, batch, batch_idx, dataloader_idx):
self.dataset = self.trainer.datamodule.predict_dataloader().dataset
self.preprocess_data(batch, 'predict')
update_module_step(self.model, self.current_epoch, self.global_step)
def training_step(self, batch, batch_idx):
raise NotImplementedError
"""
# aggregate outputs from different devices (DP)
def training_step_end(self, out):
pass
"""
"""
# aggregate outputs from different iterations
def training_epoch_end(self, out):
pass
"""
def validation_step(self, batch, batch_idx):
raise NotImplementedError
"""
# aggregate outputs from different devices when using DP
def validation_step_end(self, out):
pass
"""
def validation_epoch_end(self, out):
"""
Gather metrics from all devices, compute mean.
Purge repeated results using data index.
"""
raise NotImplementedError
def test_step(self, batch, batch_idx):
raise NotImplementedError
def test_epoch_end(self, out):
"""
Gather metrics from all devices, compute mean.
Purge repeated results using data index.
"""
raise NotImplementedError
def export(self):
raise NotImplementedError
def configure_optimizers(self): | optim = parse_optimizer(self.config.system.optimizer, self.model) | 0 | 2023-10-22 02:53:17+00:00 | 8k |
HKUDS/GraphGPT | graphgpt/train/train_light.py | [
{
"identifier": "GraphChatTrainer",
"path": "graphgpt/train/graphchat_trainer.py",
"snippet": "class GraphChatTrainer(Trainer):\n\n def _save(self, output_dir: Optional[str] = None, state_dict=None):\n if getattr(self.args, 'tune_graph_mlp_adapter', False):\n # Save the model\n ... | import os
import copy
import json
import logging
import pathlib
import torch
import transformers
import torch.nn as nn
from dataclasses import dataclass, field
from typing import Dict, Optional, Sequence, List
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from graphgpt.train.graphchat_trainer import GraphChatTrainer
from graphgpt import conversation as conversation_lib
from graphgpt.model import *
from PIL import Image
from torch_geometric.data import Data
from lightning.pytorch.strategies import FSDPStrategy
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
from transformers.models.llama.modeling_llama import LlamaDecoderLayer
from lightning.pytorch.loggers import WandbLogger
from lightning.pytorch import LightningModule, Trainer, seed_everything
from graphgpt.model.GraphLlama_pl import GraphGPT_pl
from lightning.pytorch.callbacks import ModelCheckpoint
from lightning.pytorch.callbacks.callback import Callback
from deepspeed import zero
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus | 5,665 | graph_type = copy.deepcopy(self.list_data_dict[i]['id']).split('_')[0]
graph_node_rep = self.graph_data_all[graph_type].x[graph_node_list] ##
cur_token_len = len(graph_node_rep) # FIXME: 14 is hardcoded patch size
sources = preprocess_graph(
copy.deepcopy([e["conversations"] for e in sources]),
self.graph_cfg, cur_token_len)
else:
sources = copy.deepcopy([e["conversations"] for e in sources])
data_dict = preprocess(
sources,
self.tokenizer)
if isinstance(i, int):
data_dict = dict(input_ids=data_dict["input_ids"][0],
labels=data_dict["labels"][0])
# image exist in the data
if 'graph' in self.list_data_dict[i]:
# data_dict['graph_node'] = graph_node_rep
# data_dict['graph_edge'] = graph_edge_index
# data_dict['target_node'] = target_node
data_dict['graph_data'] = Data(graph_node = graph_node_rep, edge_index=graph_edge_index, target_node = torch.tensor([target_node]))
elif self.graph_cfg['is_graph']:
# image does not exist in the data, but the model is multimodal
node_feas = self.graph_cfg['graph_processor'].node_feas
data_dict['graph_data'] = Data(graph_node = torch.zeros(3, node_feas), edge_index=torch.zeros(2, 3), target_node = torch.tensor([0]))
return data_dict
@dataclass
class DataCollatorForSupervisedDataset(object):
"""Collate examples for supervised fine-tuning."""
tokenizer: transformers.PreTrainedTokenizer
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
input_ids, labels = tuple([instance[key] for instance in instances]
for key in ("input_ids", "labels"))
input_ids = torch.nn.utils.rnn.pad_sequence(
input_ids,
batch_first=True,
padding_value=self.tokenizer.pad_token_id)
labels = torch.nn.utils.rnn.pad_sequence(labels,
batch_first=True,
padding_value=IGNORE_INDEX)
batch = dict(
input_ids=input_ids,
labels=labels,
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
)
if 'graph_data' in instances[0]:
# graph_node_reps = [instance['graph_node'] for instance in instances]
# edge_index_reps = [instance['graph_edge'] for instance in instances]
# target_node_reps = [instance['target_node'] for instance in instances]
graph_data_batch = [instance['graph_data'] for instance in instances]
# if all(x is not None and x.shape == images[0].shape for x in images):
# batch['images'] = torch.stack(images)
# else:
# batch['images'] = images
# batch['graph_node_reps'] = graph_node_reps
# batch['edge_index_reps'] = edge_index_reps
# batch['edge_index_reps'] = target_node_reps
batch['graph_data'] = graph_data_batch
return batch
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
data_args, training_args) -> Dict:
"""Make dataset and collator for supervised fine-tuning."""
dataset_cls = (LazySupervisedDataset
if data_args.lazy_preprocess else SupervisedDataset)
train_dataset = dataset_cls(tokenizer=tokenizer,
data_path=data_args.data_path,
graph_cfg=dict(
is_graph=data_args.is_graph,
sep_graph_conv_front=data_args.sep_graph_conv_front,
graph_token_len=data_args.graph_token_len,
graph_content=data_args.graph_content,
use_graph_start_end=getattr(data_args, 'use_graph_start_end', False)
),
graph_data_path = data_args.graph_data_path)
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
train_dataloader = DataLoader(train_dataset,
batch_size=training_args.per_device_train_batch_size,
num_workers=training_args.num_workers,
collate_fn=data_collator,
prefetch_factor=4,
pin_memory=True)
return train_dataloader, None
def train():
parser = transformers.HfArgumentParser(
(ModelArguments, DataArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
if isinstance(training_args.gpus, str):
training_args.gpus = [int(x) for x in training_args.gpus.split(',')]
batch_size = training_args.real_batch_size
devices = training_args.gpus
num_devices = len(devices)
gradient_accumulation_steps = max(1,batch_size // (training_args.per_device_train_batch_size*num_devices))
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=training_args.cache_dir,
model_max_length=training_args.model_max_length,
padding_side="right",
use_fast=False
)
if model_args.version == "v1":
tokenizer.pad_token = tokenizer.unk_token
conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1_1"]
else:
raise ValueError
| # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
#
# 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.
# TODO: import and use code from ../data/dataset.py
IGNORE_INDEX = -100
DEFAULT_PAD_TOKEN = "[PAD]"
DEFAULT_EOS_TOKEN = "</s>"
DEFAULT_BOS_TOKEN = "<s>"
DEFAULT_UNK_TOKEN = "<unk>"
DEFAULT_GRAPH_TOKEN = "<graph>"
DEFAULT_GRAPH_PATCH_TOKEN = "<g_patch>"
DEFAULT_G_START_TOKEN = "<g_start>"
DEFAULT_G_END_TOKEN = "<g_end>"
@dataclass
class ModelArguments:
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
version: Optional[str] = field(default="v0")
freeze_backbone: bool = field(default=False)
tune_graph_mlp_adapter: bool = field(default=False)
graph_tower: Optional[str] = field(default=None)
graph_select_layer: Optional[int] = field(default=-1) # default to the last layer
pretrain_graph_mlp_adapter: Optional[str] = field(default=None)
use_graph_start_end: bool = field(default=False)
model_save_name: Optional[str] = field(default="model_{epoch}-{step}")
@dataclass
class DataArguments:
data_path: str = field(default=None,
metadata={"help": "Path to the training data."})
lazy_preprocess: bool = False
is_graph: bool = False
sep_graph_conv_front: bool = False
graph_token_len: int = 0
graph_content: Optional[str] = field(default=None)
graph_data_path: Optional[str] = field(default=None)
image_aspect_ratio: str = 'square'
@dataclass
class TrainingArguments:
cache_dir: Optional[str] = field(default=None)
optim: str = field(default="adamw_torch")
remove_unused_columns: bool = field(default=False)
freeze_graph_mlp_adapter: bool = field(default=False)
force_fsdp: bool = field(default=False)
model_max_length: int = field(
default=512,
metadata={
"help":
"Maximum sequence length. Sequences will be right padded (and possibly truncated)."
},
)
double_quant: bool = field(
default=True,
metadata={"help": "Compress the quantization statistics through double quantization."}
)
quant_type: str = field(
default="nf4",
metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."}
)
bits: int = field(
default=16,
metadata={"help": "How many bits to use."}
)
strategy: str = field(
default='fsdp'
)
real_batch_size: int = field(default=1)
lora_enable: bool = False
lora_r: int = 64
lora_alpha: int = 16
lora_dropout: float = 0.05
lora_weight_path: str = ""
lora_bias: str = "none"
disable_tqdm: bool =False
gpus: Optional[str] = field(default='0,1')
resume: Optional[str] = field(default=None)
adam_epsilon: float = field(default=1e-8)
warmup_steps:int = field(default=1000)
num_workers:int = field(default=16)
bf16: bool = field(default=False)
fp16: bool = field(default=False)
output_dir: str = field(default='./checkpoints/graphchat-gt-graphmatch-7b')
num_train_epochs: int = field(default=3)
per_device_train_batch_size: int = field(default=1)
per_device_eval_batch_size: int = field(default=1)
gradient_accumulation_steps: int = field(default=1)
evaluation_strategy: str = field(default='no')
save_strategy: str = field(default='steps')
save_steps: int = field(default=2400)
save_total_limit: int = field(default=1)
learning_rate: float = field(default=2e-5)
weight_decay: float = field(default=0.)
warmup_ratio: float = field(default=0.03)
lr_scheduler_type: str = field(default='cosine')
logging_steps: int = field(default=1)
tf32: bool = field(default=True)
gradient_checkpointing: bool = field(default=True)
report_to: str = field(default='wandb')
class SaveGraphProjectorCallback(Callback):
def __init__(self, output_dir, keys_to_match):
self.output_dir = output_dir
self.keys_to_match = keys_to_match
def on_train_epoch_end(self, trainer, pl_module, unused=None):
# 准备保存模型权重
_state_dict = pl_module.state_dict()
weight_to_save = {}
for k, v in _state_dict.items():
if any(key_match in k for key_match in self.keys_to_match):
weight_to_save[k] = v
# 确保输出目录存在
os.makedirs(self.output_dir, exist_ok=True)
# 保存 graph projector 的权重
torch.save(weight_to_save, os.path.join(self.output_dir, 'graph_projector.bin'))
def maybe_zero_3(param, ignore_status=False, name=None):
if hasattr(param, "ds_id"):
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
if not ignore_status:
logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}")
with zero.GatheredParameters([param]):
param = param.data.detach().cpu().clone()
else:
param = param.detach().cpu().clone()
return param
# Borrowed from peft.utils.get_peft_model_state_dict
def get_peft_state_maybe_zero_3(named_params, bias):
if bias == "none":
to_return = {k: t for k, t in named_params if "lora_" in k}
elif bias == "all":
to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
elif bias == "lora_only":
to_return = {}
maybe_lora_bias = {}
lora_bias_names = set()
for k, t in named_params:
if "lora_" in k:
to_return[k] = t
bias_name = k.split("lora_")[0] + "bias"
lora_bias_names.add(bias_name)
elif "bias" in k:
maybe_lora_bias[k] = t
for k, t in maybe_lora_bias:
if bias_name in lora_bias_names:
to_return[bias_name] = t
else:
raise NotImplementedError
to_return = {k: maybe_zero_3(v, name=k) for k, v in to_return.items()}
return to_return
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
to_return = {k: t for k, t in named_params if "lora_" not in k}
if require_grad_only:
to_return = {k: t for k, t in to_return.items() if t.requires_grad}
to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()}
return to_return
def find_all_linear_names(model):
cls = torch.nn.Linear
lora_module_names = set()
for name, module in model.named_modules():
if isinstance(module, cls):
names = name.split('.')
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
if 'lm_head' in lora_module_names: # needed for 16-bit
lora_module_names.remove('lm_head')
return list(lora_module_names)
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer,
output_dir: str):
"""Collects the state dict and dump to disk."""
if trainer.deepspeed:
torch.cuda.synchronize()
trainer.save_model(output_dir)
return
state_dict = trainer.model.state_dict()
if trainer.args.should_save:
cpu_state_dict = {
key: value.cpu()
for key, value in state_dict.items()
}
del state_dict
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
def smart_tokenizer_and_embedding_resize(
special_tokens_dict: Dict,
tokenizer: transformers.PreTrainedTokenizer,
model: transformers.PreTrainedModel,
):
"""Resize tokenizer and embedding.
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
"""
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
model.resize_token_embeddings(len(tokenizer))
if num_new_tokens > 0:
input_embeddings = model.get_input_embeddings().weight.data
output_embeddings = model.get_output_embeddings().weight.data
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
dim=0, keepdim=True)
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
dim=0, keepdim=True)
input_embeddings[-num_new_tokens:] = input_embeddings_avg
output_embeddings[-num_new_tokens:] = output_embeddings_avg
def _tokenize_fn(strings: Sequence[str],
tokenizer: transformers.PreTrainedTokenizer) -> Dict:
"""Tokenize a list of strings."""
tokenized_list = [
tokenizer(
text,
return_tensors="pt",
padding="longest",
max_length=tokenizer.model_max_length,
truncation=True,
) for text in strings
]
input_ids = labels = [
tokenized.input_ids[0] for tokenized in tokenized_list
]
input_ids_lens = labels_lens = [
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
for tokenized in tokenized_list
]
return dict(
input_ids=input_ids,
labels=labels,
input_ids_lens=input_ids_lens,
labels_lens=labels_lens,
)
def _mask_targets(target, tokenized_lens, speakers):
# cur_idx = 0
cur_idx = tokenized_lens[0]
tokenized_lens = tokenized_lens[1:]
target[:cur_idx] = IGNORE_INDEX
for tokenized_len, speaker in zip(tokenized_lens, speakers):
if speaker == "human":
target[cur_idx+2:cur_idx + tokenized_len] = IGNORE_INDEX
cur_idx += tokenized_len
def _add_speaker_and_signal(header, source, get_conversation=True):
"""Add speaker and start/end signal on each round."""
BEGIN_SIGNAL = "### "
END_SIGNAL = "\n"
conversation = header
for sentence in source:
from_str = sentence["from"]
if from_str.lower() == "human":
from_str = conversation_lib.default_conversation.roles[0]
elif from_str.lower() == "gpt":
from_str = conversation_lib.default_conversation.roles[1]
else:
from_str = 'unknown'
sentence["value"] = (BEGIN_SIGNAL + from_str + ": " +
sentence["value"] + END_SIGNAL)
if get_conversation:
conversation += sentence["value"]
conversation += BEGIN_SIGNAL
return conversation
def preprocess_graph(
sources: Sequence[str],
graph_cfg: dict,
cur_token_len: int,
) -> Dict:
is_graph = graph_cfg['is_graph']
# image_token_len = multimodal_cfg['image_token_len']
graph_token_len = cur_token_len
if not is_graph:
return sources
for source in sources:
if graph_cfg['sep_graph_conv_front']:
assert DEFAULT_GRAPH_TOKEN in source[0]['value']
source[0]['value'] = source[0]['value'].replace(DEFAULT_GRAPH_TOKEN, '').strip()
source[0]['value'] = DEFAULT_GRAPH_TOKEN + conversation_lib.default_conversation.sep + conversation_lib.default_conversation.roles[0] + ": " + source[0]['value']
for sentence in source:
replace_token = DEFAULT_GRAPH_PATCH_TOKEN * graph_token_len
if graph_cfg['use_graph_start_end']:
replace_token = DEFAULT_G_START_TOKEN + replace_token + DEFAULT_G_END_TOKEN
sentence["value"] = sentence["value"].replace(DEFAULT_GRAPH_TOKEN, replace_token)
return sources
def preprocess_graph_LP(
sources: Sequence[str],
graph_cfg: dict,
cur_token_len_1: int,
cur_token_len_2: int,
) -> Dict:
is_graph = graph_cfg['is_graph']
# image_token_len = multimodal_cfg['image_token_len']
graph_token_len_1 = cur_token_len_1
graph_token_len_2 = cur_token_len_2
if not is_graph:
return sources
for source in sources:
if graph_cfg['sep_graph_conv_front']:
assert DEFAULT_GRAPH_TOKEN in source[0]['value']
source[0]['value'] = source[0]['value'].replace(DEFAULT_GRAPH_TOKEN, '').strip()
source[0]['value'] = DEFAULT_GRAPH_TOKEN + conversation_lib.default_conversation.sep + conversation_lib.default_conversation.roles[0] + ": " + source[0]['value']
for sentence in source:
replace_token_1 = DEFAULT_GRAPH_PATCH_TOKEN * graph_token_len_1
replace_token_2 = DEFAULT_GRAPH_PATCH_TOKEN * graph_token_len_2
if graph_cfg['use_graph_start_end']:
replace_token_1 = DEFAULT_G_START_TOKEN + replace_token_1 + DEFAULT_G_END_TOKEN
replace_token_2 = DEFAULT_G_START_TOKEN + replace_token_2 + DEFAULT_G_END_TOKEN
if DEFAULT_GRAPH_TOKEN in sentence["value"]:
first_index = sentence["value"].find(DEFAULT_GRAPH_TOKEN)
sentence["value"] = sentence["value"][:first_index] + replace_token_1 + sentence["value"][first_index+len(DEFAULT_GRAPH_TOKEN):]
# 替换第二个<graph>为B
second_index = sentence["value"].find(DEFAULT_GRAPH_TOKEN)
sentence["value"] = sentence["value"][:second_index] + replace_token_2 + sentence["value"][second_index+len(DEFAULT_GRAPH_TOKEN):]
# sentence["value"] = sentence["value"].replace(DEFAULT_GRAPH_TOKEN, replace_token)
# print(sources)
return sources
def preprocess_v1(
sources,
tokenizer: transformers.PreTrainedTokenizer,
) -> Dict:
conv = conversation_lib.default_conversation.copy()
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
# Apply prompt templates
conversations = []
for i, source in enumerate(sources):
if roles[source[0]["from"]] != conv.roles[0]:
# Skip the first one if it is not from human
source = source[1:]
conv.messages = []
for j, sentence in enumerate(source):
role = roles[sentence["from"]]
assert role == conv.roles[j % 2], f"{i}"
conv.append_message(role, sentence["value"])
conversations.append(conv.get_prompt())
# Tokenize conversations
input_ids = tokenizer(
conversations,
return_tensors="pt",
padding="longest",
max_length=tokenizer.model_max_length,
truncation=True,
).input_ids
targets = input_ids.clone()
assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
# Mask targets
sep = conv.sep + conv.roles[1] + ": "
for conversation, target in zip(conversations, targets):
total_len = int(target.ne(tokenizer.pad_token_id).sum())
rounds = conversation.split(conv.sep2)
cur_len = 1
target[:cur_len] = IGNORE_INDEX
for i, rou in enumerate(rounds):
if rou == "":
break
parts = rou.split(sep)
if len(parts) != 2:
break
parts[0] += sep
round_len = len(tokenizer(rou).input_ids)
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
cur_len += round_len
target[cur_len:] = IGNORE_INDEX
if cur_len < tokenizer.model_max_length:
if cur_len != total_len:
target[:] = IGNORE_INDEX
print(
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
f" (ignored)"
)
return dict(
input_ids=input_ids,
labels=targets,
)
def preprocess_mpt(
sources,
tokenizer: transformers.PreTrainedTokenizer,
) -> Dict:
conv = conversation_lib.default_conversation.copy()
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
# Apply prompt templates
conversations = []
for i, source in enumerate(sources):
if roles[source[0]["from"]] != conv.roles[0]:
# Skip the first one if it is not from human
source = source[1:]
conv.messages = []
for j, sentence in enumerate(source):
role = roles[sentence["from"]]
assert role == conv.roles[j % 2], f"{i}"
conv.append_message(role, sentence["value"])
conversations.append(conv.get_prompt())
# Tokenize conversations
input_ids = tokenizer(
conversations,
return_tensors="pt",
padding="longest",
max_length=tokenizer.model_max_length,
truncation=True,
).input_ids
targets = input_ids.clone()
assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
# Mask targets
sep = conv.sep + conv.roles[1]
for conversation, target in zip(conversations, targets):
total_len = int(target.ne(tokenizer.pad_token_id).sum())
rounds = conversation.split(conv.sep)
re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
for conv_idx in range(3, len(rounds), 2):
re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx+2])) # user + gpt
cur_len = 0
target[:cur_len] = IGNORE_INDEX
for i, rou in enumerate(re_rounds):
if rou == "":
break
parts = rou.split(sep)
if len(parts) != 2:
break
parts[0] += sep
round_len = len(tokenizer(rou).input_ids) + len(tokenizer(conv.sep).input_ids)
instruction_len = len(tokenizer(parts[0]).input_ids)
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
cur_len += round_len
target[cur_len:] = IGNORE_INDEX
if cur_len < tokenizer.model_max_length:
if cur_len != total_len:
target[:] = IGNORE_INDEX
print(
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
f" (ignored)"
)
return dict(
input_ids=input_ids,
labels=targets,
)
def preprocess(
sources: Sequence[str],
tokenizer: transformers.PreTrainedTokenizer,
) -> Dict:
"""
Given a list of sources, each is a conversation list. This transform:
1. Add signal '### ' at the beginning each sentence, with end signal '\n';
2. Concatenate conversations together;
3. Tokenize the concatenated conversation;
4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
"""
if conversation_lib.default_conversation.version == "v1":
return preprocess_v1(sources, tokenizer)
if conversation_lib.default_conversation.version == "mpt":
return preprocess_mpt(sources, tokenizer)
# add end signal and concatenate together
conversations = []
for source in sources:
header = f"{conversation_lib.default_conversation.system}\n\n"
conversation = _add_speaker_and_signal(header, source)
conversations.append(conversation)
# tokenize conversations
conversations_tokenized = _tokenize_fn(conversations, tokenizer)
input_ids = conversations_tokenized["input_ids"]
targets = copy.deepcopy(input_ids)
for target, source in zip(targets, sources):
tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source],
tokenizer)["input_ids_lens"]
speakers = [sentence["from"] for sentence in source]
_mask_targets(target, tokenized_lens, speakers)
return dict(input_ids=input_ids, labels=targets)
class SupervisedDataset(Dataset):
"""Dataset for supervised fine-tuning."""
def __init__(self, data_path: str,
tokenizer: transformers.PreTrainedTokenizer):
super(SupervisedDataset, self).__init__()
logging.warning("Loading data...")
list_data_dict = json.load(open(data_path, "r"))
logging.warning("Formatting inputs...")
sources = [example["conversations"] for example in list_data_dict]
data_dict = preprocess(sources, tokenizer)
self.input_ids = data_dict["input_ids"]
self.labels = data_dict["labels"]
def __len__(self):
return len(self.input_ids)
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
return dict(input_ids=self.input_ids[i], labels=self.labels[i])
class LazySupervisedDataset(Dataset):
"""Dataset for supervised fine-tuning."""
def __init__(self, data_path: str,
tokenizer: transformers.PreTrainedTokenizer,
graph_cfg: dict,
**kwargs,):
super(LazySupervisedDataset, self).__init__()
logging.warning("Loading data...")
list_data_dict = json.load(open(data_path, "r"))
logging.warning("Formatting inputs...Skip in lazy mode")
self.tokenizer = tokenizer
self.list_data_dict = list_data_dict
self.graph_cfg = graph_cfg
graph_data_path = kwargs.get('graph_data_path')
self.graph_data_all = torch.load(graph_data_path)
def __len__(self):
return len(self.list_data_dict)
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
sources = self.list_data_dict[i]
if isinstance(i, int):
sources = [sources]
assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
task_type = self.list_data_dict[i]['id'].split("_")[-1]
if task_type != 'LP':
if 'graph' in sources[0]:
graph_dict = self.list_data_dict[i]['graph']
graph_edge_index = torch.Tensor(copy.deepcopy(graph_dict['edge_index'])).long()
graph_node_list = copy.deepcopy(graph_dict['node_list'])
target_node = copy.deepcopy(graph_dict['node_idx'])
graph_type = copy.deepcopy(self.list_data_dict[i]['id']).split('_')[0]
graph_node_rep = self.graph_data_all[graph_type].x[graph_node_list] ##
cur_token_len = len(graph_node_rep) # FIXME: 14 is hardcoded patch size
sources = preprocess_graph(
copy.deepcopy([e["conversations"] for e in sources]),
self.graph_cfg, cur_token_len)
else:
sources = copy.deepcopy([e["conversations"] for e in sources])
else:
if 'graph' in sources[0]:
graph_dict = self.list_data_dict[i]['graph']
graph_edge_index_1 = torch.Tensor(copy.deepcopy(graph_dict['edge_index_1'])).long()
graph_node_list_1 = copy.deepcopy(graph_dict['node_list_1'])
target_node_1 = copy.deepcopy(graph_dict['node_idx_1'])
graph_type = copy.deepcopy(self.list_data_dict[i]['id']).split('_')[0]
graph_node_rep_1 = self.graph_data_all[graph_type].x[graph_node_list_1] ##
cur_token_len_1 = len(graph_node_rep_1) # FIXME: 14 is hardcoded patch size
graph_edge_index_2 = torch.Tensor(copy.deepcopy(graph_dict['edge_index_2'])).long()
graph_node_list_2 = copy.deepcopy(graph_dict['node_list_2'])
target_node_2 = copy.deepcopy(graph_dict['node_idx_2'])
graph_node_rep_2 = self.graph_data_all[graph_type].x[graph_node_list_2] ##
cur_token_len_2 = len(graph_node_rep_2) # FIXME: 14 is hardcoded patch size
sources = preprocess_graph_LP(
copy.deepcopy([e["conversations"] for e in sources]),
self.graph_cfg, cur_token_len_1, cur_token_len_2)
else:
sources = copy.deepcopy([e["conversations"] for e in sources])
data_dict = preprocess(
sources,
self.tokenizer)
if isinstance(i, int):
data_dict = dict(input_ids=data_dict["input_ids"][0],
labels=data_dict["labels"][0])
# image exist in the data
if task_type != 'LP':
if 'graph' in self.list_data_dict[i]:
# data_dict['graph_node'] = graph_node_rep
# data_dict['graph_edge'] = graph_edge_index
# data_dict['target_node'] = target_node
data_dict['graph_data'] = Data(graph_node = graph_node_rep, edge_index=graph_edge_index, target_node = torch.tensor([target_node]))
elif self.graph_cfg['is_graph']:
# image does not exist in the data, but the model is multimodal
node_feas = self.graph_cfg['graph_processor'].node_feas
data_dict['graph_data'] = Data(graph_node = torch.zeros(3, node_feas), edge_index=torch.zeros(2, 3), target_node = torch.tensor([0]))
else:
if 'graph' in self.list_data_dict[i]:
# data_dict['graph_node'] = graph_node_rep
# data_dict['graph_edge'] = graph_edge_index
# data_dict['target_node'] = target_node
data_dict['graph_data'] = {
'graph_1': Data(graph_node = graph_node_rep_1, edge_index=graph_edge_index_1, target_node = torch.tensor([target_node_1])),
'graph_2': Data(graph_node = graph_node_rep_2, edge_index=graph_edge_index_2, target_node = torch.tensor([target_node_2]))
}
elif self.graph_cfg['is_graph']:
# image does not exist in the data, but the model is multimodal
node_feas = self.graph_cfg['graph_processor'].node_feas
data_dict['graph_data'] = Data(graph_node = torch.zeros(3, node_feas), edge_index=torch.zeros(2, 3), target_node = torch.tensor([0]))
return data_dict
class LazySupervisedDataset_back(Dataset):
"""Dataset for supervised fine-tuning."""
def __init__(self, data_path: str,
tokenizer: transformers.PreTrainedTokenizer,
graph_cfg: dict,
**kwargs,):
super(LazySupervisedDataset, self).__init__()
logging.warning("Loading data...")
list_data_dict = json.load(open(data_path, "r"))
logging.warning("Formatting inputs...Skip in lazy mode")
self.tokenizer = tokenizer
self.list_data_dict = list_data_dict
self.graph_cfg = graph_cfg
graph_data_path = kwargs.get('graph_data_path')
self.graph_data_all = torch.load(graph_data_path)
def __len__(self):
return len(self.list_data_dict)
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
sources = self.list_data_dict[i]
if isinstance(i, int):
sources = [sources]
assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
if 'graph' in sources[0]:
graph_dict = self.list_data_dict[i]['graph']
graph_edge_index = torch.Tensor(copy.deepcopy(graph_dict['edge_index'])).long()
graph_node_list = copy.deepcopy(graph_dict['node_list'])
target_node = copy.deepcopy(graph_dict['node_idx'])
graph_type = copy.deepcopy(self.list_data_dict[i]['id']).split('_')[0]
graph_node_rep = self.graph_data_all[graph_type].x[graph_node_list] ##
cur_token_len = len(graph_node_rep) # FIXME: 14 is hardcoded patch size
sources = preprocess_graph(
copy.deepcopy([e["conversations"] for e in sources]),
self.graph_cfg, cur_token_len)
else:
sources = copy.deepcopy([e["conversations"] for e in sources])
data_dict = preprocess(
sources,
self.tokenizer)
if isinstance(i, int):
data_dict = dict(input_ids=data_dict["input_ids"][0],
labels=data_dict["labels"][0])
# image exist in the data
if 'graph' in self.list_data_dict[i]:
# data_dict['graph_node'] = graph_node_rep
# data_dict['graph_edge'] = graph_edge_index
# data_dict['target_node'] = target_node
data_dict['graph_data'] = Data(graph_node = graph_node_rep, edge_index=graph_edge_index, target_node = torch.tensor([target_node]))
elif self.graph_cfg['is_graph']:
# image does not exist in the data, but the model is multimodal
node_feas = self.graph_cfg['graph_processor'].node_feas
data_dict['graph_data'] = Data(graph_node = torch.zeros(3, node_feas), edge_index=torch.zeros(2, 3), target_node = torch.tensor([0]))
return data_dict
@dataclass
class DataCollatorForSupervisedDataset(object):
"""Collate examples for supervised fine-tuning."""
tokenizer: transformers.PreTrainedTokenizer
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
input_ids, labels = tuple([instance[key] for instance in instances]
for key in ("input_ids", "labels"))
input_ids = torch.nn.utils.rnn.pad_sequence(
input_ids,
batch_first=True,
padding_value=self.tokenizer.pad_token_id)
labels = torch.nn.utils.rnn.pad_sequence(labels,
batch_first=True,
padding_value=IGNORE_INDEX)
batch = dict(
input_ids=input_ids,
labels=labels,
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
)
if 'graph_data' in instances[0]:
# graph_node_reps = [instance['graph_node'] for instance in instances]
# edge_index_reps = [instance['graph_edge'] for instance in instances]
# target_node_reps = [instance['target_node'] for instance in instances]
graph_data_batch = [instance['graph_data'] for instance in instances]
# if all(x is not None and x.shape == images[0].shape for x in images):
# batch['images'] = torch.stack(images)
# else:
# batch['images'] = images
# batch['graph_node_reps'] = graph_node_reps
# batch['edge_index_reps'] = edge_index_reps
# batch['edge_index_reps'] = target_node_reps
batch['graph_data'] = graph_data_batch
return batch
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer,
data_args, training_args) -> Dict:
"""Make dataset and collator for supervised fine-tuning."""
dataset_cls = (LazySupervisedDataset
if data_args.lazy_preprocess else SupervisedDataset)
train_dataset = dataset_cls(tokenizer=tokenizer,
data_path=data_args.data_path,
graph_cfg=dict(
is_graph=data_args.is_graph,
sep_graph_conv_front=data_args.sep_graph_conv_front,
graph_token_len=data_args.graph_token_len,
graph_content=data_args.graph_content,
use_graph_start_end=getattr(data_args, 'use_graph_start_end', False)
),
graph_data_path = data_args.graph_data_path)
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
train_dataloader = DataLoader(train_dataset,
batch_size=training_args.per_device_train_batch_size,
num_workers=training_args.num_workers,
collate_fn=data_collator,
prefetch_factor=4,
pin_memory=True)
return train_dataloader, None
def train():
parser = transformers.HfArgumentParser(
(ModelArguments, DataArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
if isinstance(training_args.gpus, str):
training_args.gpus = [int(x) for x in training_args.gpus.split(',')]
batch_size = training_args.real_batch_size
devices = training_args.gpus
num_devices = len(devices)
gradient_accumulation_steps = max(1,batch_size // (training_args.per_device_train_batch_size*num_devices))
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
cache_dir=training_args.cache_dir,
model_max_length=training_args.model_max_length,
padding_side="right",
use_fast=False
)
if model_args.version == "v1":
tokenizer.pad_token = tokenizer.unk_token
conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1_1"]
else:
raise ValueError
| model = GraphGPT_pl(training_args, model_args, data_args, tokenizer) | 2 | 2023-10-15 05:13:24+00:00 | 8k |
hkchengrex/Cutie | gui/ritm/model/is_hrnet_model.py | [
{
"identifier": "serialize",
"path": "gui/ritm/utils/serialization.py",
"snippet": "def serialize(init):\n parameters = list(inspect.signature(init).parameters)\n\n @wraps(init)\n def new_init(self, *args, **kwargs):\n params = deepcopy(kwargs)\n for pname, value in zip(parameters... | import torch.nn as nn
from ..utils.serialization import serialize
from .is_model import ISModel
from .modeling.hrnet_ocr import HighResolutionNet
from ..model.modifiers import LRMult | 4,490 |
class HRNetModel(ISModel):
@serialize
def __init__(self,
width=48,
ocr_width=256,
small=False,
backbone_lr_mult=0.1,
norm_layer=nn.BatchNorm2d,
**kwargs):
super().__init__(norm_layer=norm_layer, **kwargs)
|
class HRNetModel(ISModel):
@serialize
def __init__(self,
width=48,
ocr_width=256,
small=False,
backbone_lr_mult=0.1,
norm_layer=nn.BatchNorm2d,
**kwargs):
super().__init__(norm_layer=norm_layer, **kwargs)
| self.feature_extractor = HighResolutionNet(width=width, | 2 | 2023-10-19 17:49:24+00:00 | 8k |
DeepGraphLearning/ULTRA | script/run_many.py | [
{
"identifier": "tasks",
"path": "ultra/tasks.py",
"snippet": "def edge_match(edge_index, query_index):\ndef negative_sampling(data, batch, num_negative, strict=True):\ndef all_negative(data, batch):\ndef strict_negative_mask(data, batch):\ndef compute_ranking(pred, target, mask=None):\ndef build_relati... | import os
import sys
import csv
import math
import time
import pprint
import argparse
import random
import torch
import torch_geometric as pyg
from torch import optim
from torch import nn
from torch.nn import functional as F
from torch import distributed as dist
from torch.utils import data as torch_data
from torch_geometric.data import Data
from ultra import tasks, util
from ultra.models import Ultra
from script.run import train_and_validate, test | 5,410 | torch.manual_seed(seed + util.get_rank())
torch.cuda.manual_seed(seed + util.get_rank())
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
if __name__ == "__main__":
seeds = [1024, 42, 1337, 512, 256]
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", help="yaml configuration file", required=True)
parser.add_argument("-d", "--datasets", help="target datasets", default='FB15k237Inductive:v1,NELLInductive:v4', type=str, required=True)
parser.add_argument("-reps", "--repeats", help="number of times to repeat each exp", default=1, type=int)
parser.add_argument("-ft", "--finetune", help="finetune the checkpoint on the specified datasets", action='store_true')
parser.add_argument("-tr", "--train", help="train the model from scratch", action='store_true')
args, unparsed = parser.parse_known_args()
datasets = args.datasets.split(",")
path = os.path.dirname(os.path.expanduser(__file__))
results_file = os.path.join(path, f"ultra_results_{time.strftime('%Y-%m-%d-%H-%M-%S')}.csv")
for graph in datasets:
ds, version = graph.split(":") if ":" in graph else (graph, None)
for i in range(args.repeats):
seed = seeds[i] if i < len(seeds) else random.randint(0, 10000)
print(f"Running on {graph}, iteration {i+1} / {args.repeats}, seed: {seed}")
# get dynamic arguments defined in the config file
vars = util.detect_variables(args.config)
parser = argparse.ArgumentParser()
for var in vars:
parser.add_argument("--%s" % var)
vars = parser.parse_known_args(unparsed)[0]
vars = {k: util.literal_eval(v) for k, v in vars._get_kwargs()}
if args.finetune:
epochs, batch_per_epoch = default_finetuning_config[ds]
elif args.train:
epochs, batch_per_epoch = default_train_config[ds]
else:
epochs, batch_per_epoch = 0, 'null'
vars['epochs'] = epochs
vars['bpe'] = batch_per_epoch
vars['dataset'] = ds
if version is not None:
vars['version'] = version
cfg = util.load_config(args.config, context=vars)
root_dir = os.path.expanduser(cfg.output_dir) # resetting the path to avoid inf nesting
os.chdir(root_dir)
working_dir = util.create_working_directory(cfg)
set_seed(seed)
# args, vars = util.parse_args()
# cfg = util.load_config(args.config, context=vars)
# working_dir = util.create_working_directory(cfg)
# torch.manual_seed(args.seed + util.get_rank())
logger = util.get_root_logger()
if util.get_rank() == 0:
logger.warning("Random seed: %d" % seed)
logger.warning("Config file: %s" % args.config)
logger.warning(pprint.pformat(cfg))
task_name = cfg.task["name"]
dataset = util.build_dataset(cfg)
device = util.get_device(cfg)
train_data, valid_data, test_data = dataset[0], dataset[1], dataset[2]
train_data = train_data.to(device)
valid_data = valid_data.to(device)
test_data = test_data.to(device)
model = Ultra(
rel_model_cfg=cfg.model.relation_model,
entity_model_cfg=cfg.model.entity_model,
)
if "checkpoint" in cfg and cfg.checkpoint is not None:
state = torch.load(cfg.checkpoint, map_location="cpu")
model.load_state_dict(state["model"])
#model = pyg.compile(model, dynamic=True)
model = model.to(device)
if task_name == "InductiveInference":
# filtering for inductive datasets
# Grail, MTDEA, HM datasets have validation sets based off the training graph
# ILPC, Ingram have validation sets from the inference graph
# filtering dataset should contain all true edges (base graph + (valid) + test)
if "ILPC" in cfg.dataset['class'] or "Ingram" in cfg.dataset['class']:
# add inference, valid, test as the validation and test filtering graphs
full_inference_edges = torch.cat([valid_data.edge_index, valid_data.target_edge_index, test_data.target_edge_index], dim=1)
full_inference_etypes = torch.cat([valid_data.edge_type, valid_data.target_edge_type, test_data.target_edge_type])
test_filtered_data = Data(edge_index=full_inference_edges, edge_type=full_inference_etypes, num_nodes=test_data.num_nodes)
val_filtered_data = test_filtered_data
else:
# test filtering graph: inference edges + test edges
full_inference_edges = torch.cat([test_data.edge_index, test_data.target_edge_index], dim=1)
full_inference_etypes = torch.cat([test_data.edge_type, test_data.target_edge_type])
test_filtered_data = Data(edge_index=full_inference_edges, edge_type=full_inference_etypes, num_nodes=test_data.num_nodes)
# validation filtering graph: train edges + validation edges
val_filtered_data = Data(
edge_index=torch.cat([train_data.edge_index, valid_data.target_edge_index], dim=1),
edge_type=torch.cat([train_data.edge_type, valid_data.target_edge_type])
)
#test_filtered_data = val_filtered_data = None
else:
# for transductive setting, use the whole graph for filtered ranking
filtered_data = Data(edge_index=dataset._data.target_edge_index, edge_type=dataset._data.target_edge_type, num_nodes=dataset[0].num_nodes)
val_filtered_data = test_filtered_data = filtered_data
val_filtered_data = val_filtered_data.to(device)
test_filtered_data = test_filtered_data.to(device)
train_and_validate(cfg, model, train_data, valid_data, filtered_data=val_filtered_data, device=device, logger=logger)
if util.get_rank() == 0:
logger.warning(separator)
logger.warning("Evaluate on valid")
|
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
default_finetuning_config = {
# graph: (num_epochs, batches_per_epoch), null means all triples in train set
# transductive datasets (17)
# standard ones (10)
"CoDExSmall": (1, 4000),
"CoDExMedium": (1, 4000),
"CoDExLarge": (1, 2000),
"FB15k237": (1, 'null'),
"WN18RR": (1, 'null'),
"YAGO310": (1, 2000),
"DBpedia100k": (1, 1000),
"AristoV4": (1, 2000),
"ConceptNet100k": (1, 2000),
"ATOMIC": (1, 200),
# tail-only datasets (2)
"NELL995": (1, 'null'), # not implemented yet
"Hetionet": (1, 4000),
# sparse datasets (5)
"WDsinger": (3, 'null'),
"FB15k237_10": (1, 'null'),
"FB15k237_20": (1, 'null'),
"FB15k237_50": (1, 1000),
"NELL23k": (3, 'null'),
# inductive datasets (42)
# GraIL datasets (12)
"FB15k237Inductive": (1, 'null'), # for all 4 datasets
"WN18RRInductive": (1, 'null'), # for all 4 datasets
"NELLInductive": (3, 'null'), # for all 4 datasets
# ILPC (2)
"ILPC2022SmallInductive": (3, 'null'),
"ILPC2022LargeInductive": (1, 1000),
# Ingram datasets (13)
"NLIngram": (3, 'null'), # for all 5 datasets
"FBIngram": (3, 'null'), # for all 4 datasets
"WKIngram": (3, 'null'), # for all 4 datasets
# MTDEA datasets (10)
"WikiTopicsMT1": (3, 'null'), # for all 2 test datasets
"WikiTopicsMT2": (3, 'null'), # for all 2 test datasets
"WikiTopicsMT3": (3, 'null'), # for all 2 test datasets
"WikiTopicsMT4": (3, 'null'), # for all 2 test datasets
"Metafam": (3, 'null'),
"FBNELL": (3, 'null'),
# Hamaguchi datasets (4)
"HM": (1, 100) # for all 4 datasets
}
default_train_config = {
# graph: (num_epochs, batches_per_epoch), null means all triples in train set
# transductive datasets (17)
# standard ones (10)
"CoDExSmall": (10, 1000),
"CoDExMedium": (10, 1000),
"CoDExLarge": (10, 1000),
"FB15k237": (10, 1000),
"WN18RR": (10, 1000),
"YAGO310": (10, 2000),
"DBpedia100k": (10, 1000),
"AristoV4": (10, 1000),
"ConceptNet100k": (10, 1000),
"ATOMIC": (10, 1000),
# tail-only datasets (2)
"NELL995": (10, 1000), # not implemented yet
"Hetionet": (10, 1000),
# sparse datasets (5)
"WDsinger": (10, 1000),
"FB15k237_10": (10, 1000),
"FB15k237_20": (10, 1000),
"FB15k237_50": (10, 1000),
"NELL23k": (10, 1000),
# inductive datasets (42)
# GraIL datasets (12)
"FB15k237Inductive": (10, 'null'), # for all 4 datasets
"WN18RRInductive": (10, 'null'), # for all 4 datasets
"NELLInductive": (10, 'null'), # for all 4 datasets
# ILPC (2)
"ILPC2022SmallInductive": (10, 'null'),
"ILPC2022LargeInductive": (10, 1000),
# Ingram datasets (13)
"NLIngram": (10, 'null'), # for all 5 datasets
"FBIngram": (10, 'null'), # for all 4 datasets
"WKIngram": (10, 'null'), # for all 4 datasets
# MTDEA datasets (10)
"WikiTopicsMT1": (10, 'null'), # for all 2 test datasets
"WikiTopicsMT2": (10, 'null'), # for all 2 test datasets
"WikiTopicsMT3": (10, 'null'), # for all 2 test datasets
"WikiTopicsMT4": (10, 'null'), # for all 2 test datasets
"Metafam": (10, 'null'),
"FBNELL": (10, 'null'),
# Hamaguchi datasets (4)
"HM": (10, 1000) # for all 4 datasets
}
separator = ">" * 30
line = "-" * 30
def set_seed(seed):
random.seed(seed + util.get_rank())
# np.random.seed(seed + util.get_rank())
torch.manual_seed(seed + util.get_rank())
torch.cuda.manual_seed(seed + util.get_rank())
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
if __name__ == "__main__":
seeds = [1024, 42, 1337, 512, 256]
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", help="yaml configuration file", required=True)
parser.add_argument("-d", "--datasets", help="target datasets", default='FB15k237Inductive:v1,NELLInductive:v4', type=str, required=True)
parser.add_argument("-reps", "--repeats", help="number of times to repeat each exp", default=1, type=int)
parser.add_argument("-ft", "--finetune", help="finetune the checkpoint on the specified datasets", action='store_true')
parser.add_argument("-tr", "--train", help="train the model from scratch", action='store_true')
args, unparsed = parser.parse_known_args()
datasets = args.datasets.split(",")
path = os.path.dirname(os.path.expanduser(__file__))
results_file = os.path.join(path, f"ultra_results_{time.strftime('%Y-%m-%d-%H-%M-%S')}.csv")
for graph in datasets:
ds, version = graph.split(":") if ":" in graph else (graph, None)
for i in range(args.repeats):
seed = seeds[i] if i < len(seeds) else random.randint(0, 10000)
print(f"Running on {graph}, iteration {i+1} / {args.repeats}, seed: {seed}")
# get dynamic arguments defined in the config file
vars = util.detect_variables(args.config)
parser = argparse.ArgumentParser()
for var in vars:
parser.add_argument("--%s" % var)
vars = parser.parse_known_args(unparsed)[0]
vars = {k: util.literal_eval(v) for k, v in vars._get_kwargs()}
if args.finetune:
epochs, batch_per_epoch = default_finetuning_config[ds]
elif args.train:
epochs, batch_per_epoch = default_train_config[ds]
else:
epochs, batch_per_epoch = 0, 'null'
vars['epochs'] = epochs
vars['bpe'] = batch_per_epoch
vars['dataset'] = ds
if version is not None:
vars['version'] = version
cfg = util.load_config(args.config, context=vars)
root_dir = os.path.expanduser(cfg.output_dir) # resetting the path to avoid inf nesting
os.chdir(root_dir)
working_dir = util.create_working_directory(cfg)
set_seed(seed)
# args, vars = util.parse_args()
# cfg = util.load_config(args.config, context=vars)
# working_dir = util.create_working_directory(cfg)
# torch.manual_seed(args.seed + util.get_rank())
logger = util.get_root_logger()
if util.get_rank() == 0:
logger.warning("Random seed: %d" % seed)
logger.warning("Config file: %s" % args.config)
logger.warning(pprint.pformat(cfg))
task_name = cfg.task["name"]
dataset = util.build_dataset(cfg)
device = util.get_device(cfg)
train_data, valid_data, test_data = dataset[0], dataset[1], dataset[2]
train_data = train_data.to(device)
valid_data = valid_data.to(device)
test_data = test_data.to(device)
model = Ultra(
rel_model_cfg=cfg.model.relation_model,
entity_model_cfg=cfg.model.entity_model,
)
if "checkpoint" in cfg and cfg.checkpoint is not None:
state = torch.load(cfg.checkpoint, map_location="cpu")
model.load_state_dict(state["model"])
#model = pyg.compile(model, dynamic=True)
model = model.to(device)
if task_name == "InductiveInference":
# filtering for inductive datasets
# Grail, MTDEA, HM datasets have validation sets based off the training graph
# ILPC, Ingram have validation sets from the inference graph
# filtering dataset should contain all true edges (base graph + (valid) + test)
if "ILPC" in cfg.dataset['class'] or "Ingram" in cfg.dataset['class']:
# add inference, valid, test as the validation and test filtering graphs
full_inference_edges = torch.cat([valid_data.edge_index, valid_data.target_edge_index, test_data.target_edge_index], dim=1)
full_inference_etypes = torch.cat([valid_data.edge_type, valid_data.target_edge_type, test_data.target_edge_type])
test_filtered_data = Data(edge_index=full_inference_edges, edge_type=full_inference_etypes, num_nodes=test_data.num_nodes)
val_filtered_data = test_filtered_data
else:
# test filtering graph: inference edges + test edges
full_inference_edges = torch.cat([test_data.edge_index, test_data.target_edge_index], dim=1)
full_inference_etypes = torch.cat([test_data.edge_type, test_data.target_edge_type])
test_filtered_data = Data(edge_index=full_inference_edges, edge_type=full_inference_etypes, num_nodes=test_data.num_nodes)
# validation filtering graph: train edges + validation edges
val_filtered_data = Data(
edge_index=torch.cat([train_data.edge_index, valid_data.target_edge_index], dim=1),
edge_type=torch.cat([train_data.edge_type, valid_data.target_edge_type])
)
#test_filtered_data = val_filtered_data = None
else:
# for transductive setting, use the whole graph for filtered ranking
filtered_data = Data(edge_index=dataset._data.target_edge_index, edge_type=dataset._data.target_edge_type, num_nodes=dataset[0].num_nodes)
val_filtered_data = test_filtered_data = filtered_data
val_filtered_data = val_filtered_data.to(device)
test_filtered_data = test_filtered_data.to(device)
train_and_validate(cfg, model, train_data, valid_data, filtered_data=val_filtered_data, device=device, logger=logger)
if util.get_rank() == 0:
logger.warning(separator)
logger.warning("Evaluate on valid") | test(cfg, model, valid_data, filtered_data=val_filtered_data, device=device, logger=logger) | 4 | 2023-10-23 17:06:10+00:00 | 8k |
ZhengyiLuo/PerpetualHumanoidControl | phc/run.py | [
{
"identifier": "set_np_formatting",
"path": "phc/utils/config.py",
"snippet": "def set_np_formatting():\n np.set_printoptions(edgeitems=30, infstr='inf', linewidth=4000, nanstr='nan', precision=2, suppress=False, threshold=10000, formatter=None)"
},
{
"identifier": "set_seed",
"path": "p... | import glob
import os
import sys
import pdb
import os.path as osp
import numpy as np
import copy
import torch
import wandb
import horovod.torch as hvd
from phc.utils.config import set_np_formatting, set_seed, get_args, parse_sim_params, load_cfg
from phc.utils.parse_task import parse_task
from rl_games.algos_torch import players
from rl_games.algos_torch import torch_ext
from rl_games.common import env_configurations, experiment, vecenv
from rl_games.common.algo_observer import AlgoObserver
from rl_games.torch_runner import Runner
from phc.utils.flags import flags
from learning import im_amp
from learning import im_amp_players
from learning import amp_agent
from learning import amp_players
from learning import amp_models
from learning import amp_network_builder
from learning import amp_network_mcp_builder
from learning import amp_network_pnn_builder
from env.tasks import humanoid_amp_task | 5,895 | return
def after_init(self, algo):
self.algo = algo
self.consecutive_successes = torch_ext.AverageMeter(1, self.algo.games_to_track).to(self.algo.ppo_device)
self.writer = self.algo.writer
return
def process_infos(self, infos, done_indices):
if isinstance(infos, dict):
if (self.use_successes == False) and 'consecutive_successes' in infos:
cons_successes = infos['consecutive_successes'].clone()
self.consecutive_successes.update(cons_successes.to(self.algo.ppo_device))
if self.use_successes and 'successes' in infos:
successes = infos['successes'].clone()
self.consecutive_successes.update(successes[done_indices].to(self.algo.ppo_device))
return
def after_clear_stats(self):
self.mean_scores.clear()
return
def after_print_stats(self, frame, epoch_num, total_time):
if self.consecutive_successes.current_size > 0:
mean_con_successes = self.consecutive_successes.get_mean()
self.writer.add_scalar('successes/consecutive_successes/mean', mean_con_successes, frame)
self.writer.add_scalar('successes/consecutive_successes/iter', mean_con_successes, epoch_num)
self.writer.add_scalar('successes/consecutive_successes/time', mean_con_successes, total_time)
return
class RLGPUEnv(vecenv.IVecEnv):
def __init__(self, config_name, num_actors, **kwargs):
self.env = env_configurations.configurations[config_name]['env_creator'](**kwargs)
self.use_global_obs = (self.env.num_states > 0)
self.full_state = {}
self.full_state["obs"] = self.reset()
if self.use_global_obs:
self.full_state["states"] = self.env.get_state()
return
def step(self, action):
next_obs, reward, is_done, info = self.env.step(action)
# todo: improve, return only dictinary
self.full_state["obs"] = next_obs
if self.use_global_obs:
self.full_state["states"] = self.env.get_state()
return self.full_state, reward, is_done, info
else:
return self.full_state["obs"], reward, is_done, info
def reset(self, env_ids=None):
self.full_state["obs"] = self.env.reset(env_ids)
if self.use_global_obs:
self.full_state["states"] = self.env.get_state()
return self.full_state
else:
return self.full_state["obs"]
def get_number_of_agents(self):
return self.env.get_number_of_agents()
def get_env_info(self):
info = {}
info['action_space'] = self.env.action_space
info['observation_space'] = self.env.observation_space
info['amp_observation_space'] = self.env.amp_observation_space
info['enc_amp_observation_space'] = self.env.enc_amp_observation_space
if isinstance(self.env.task, humanoid_amp_task.HumanoidAMPTask):
info['task_obs_size'] = self.env.task.get_task_obs_size()
else:
info['task_obs_size'] = 0
if self.use_global_obs:
info['state_space'] = self.env.state_space
print(info['action_space'], info['observation_space'], info['state_space'])
else:
print(info['action_space'], info['observation_space'])
return info
vecenv.register('RLGPU', lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs))
env_configurations.register('rlgpu', {'env_creator': lambda **kwargs: create_rlgpu_env(**kwargs), 'vecenv_type': 'RLGPU'})
def build_alg_runner(algo_observer):
runner = Runner(algo_observer)
runner.player_factory.register_builder('amp_discrete', lambda **kwargs: amp_players.AMPPlayerDiscrete(**kwargs))
runner.algo_factory.register_builder('amp', lambda **kwargs: amp_agent.AMPAgent(**kwargs))
runner.player_factory.register_builder('amp', lambda **kwargs: amp_players.AMPPlayerContinuous(**kwargs))
runner.model_builder.model_factory.register_builder('amp', lambda network, **kwargs: amp_models.ModelAMPContinuous(network))
runner.model_builder.network_factory.register_builder('amp', lambda **kwargs: amp_network_builder.AMPBuilder())
runner.model_builder.network_factory.register_builder('amp_mcp', lambda **kwargs: amp_network_mcp_builder.AMPMCPBuilder())
runner.model_builder.network_factory.register_builder('amp_pnn', lambda **kwargs: amp_network_pnn_builder.AMPPNNBuilder())
runner.algo_factory.register_builder('im_amp', lambda **kwargs: im_amp.IMAmpAgent(**kwargs))
runner.player_factory.register_builder('im_amp', lambda **kwargs: im_amp_players.IMAMPPlayerContinuous(**kwargs))
return runner
def main():
global args
global cfg
global cfg_train
set_np_formatting()
args = get_args()
cfg_env_name = args.cfg_env.split("/")[-1].split(".")[0]
args.logdir = args.network_path
cfg, cfg_train, logdir = load_cfg(args)
| # Copyright (c) 2018-2023, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
sys.path.append(os.getcwd())
args = None
cfg = None
cfg_train = None
def create_rlgpu_env(**kwargs):
use_horovod = cfg_train['params']['config'].get('multi_gpu', False)
if use_horovod:
rank = hvd.rank()
print("Horovod rank: ", rank)
cfg_train['params']['seed'] = cfg_train['params']['seed'] + rank
args.device = 'cuda'
args.device_id = rank
args.rl_device = 'cuda:' + str(rank)
cfg['rank'] = rank
cfg['rl_device'] = 'cuda:' + str(rank)
sim_params = parse_sim_params(args, cfg, cfg_train)
task, env = parse_task(args, cfg, cfg_train, sim_params)
print(env.num_envs)
print(env.num_actions)
print(env.num_obs)
print(env.num_states)
frames = kwargs.pop('frames', 1)
if frames > 1:
env = wrappers.FrameStack(env, frames, False)
return env
class RLGPUAlgoObserver(AlgoObserver):
def __init__(self, use_successes=True):
self.use_successes = use_successes
return
def after_init(self, algo):
self.algo = algo
self.consecutive_successes = torch_ext.AverageMeter(1, self.algo.games_to_track).to(self.algo.ppo_device)
self.writer = self.algo.writer
return
def process_infos(self, infos, done_indices):
if isinstance(infos, dict):
if (self.use_successes == False) and 'consecutive_successes' in infos:
cons_successes = infos['consecutive_successes'].clone()
self.consecutive_successes.update(cons_successes.to(self.algo.ppo_device))
if self.use_successes and 'successes' in infos:
successes = infos['successes'].clone()
self.consecutive_successes.update(successes[done_indices].to(self.algo.ppo_device))
return
def after_clear_stats(self):
self.mean_scores.clear()
return
def after_print_stats(self, frame, epoch_num, total_time):
if self.consecutive_successes.current_size > 0:
mean_con_successes = self.consecutive_successes.get_mean()
self.writer.add_scalar('successes/consecutive_successes/mean', mean_con_successes, frame)
self.writer.add_scalar('successes/consecutive_successes/iter', mean_con_successes, epoch_num)
self.writer.add_scalar('successes/consecutive_successes/time', mean_con_successes, total_time)
return
class RLGPUEnv(vecenv.IVecEnv):
def __init__(self, config_name, num_actors, **kwargs):
self.env = env_configurations.configurations[config_name]['env_creator'](**kwargs)
self.use_global_obs = (self.env.num_states > 0)
self.full_state = {}
self.full_state["obs"] = self.reset()
if self.use_global_obs:
self.full_state["states"] = self.env.get_state()
return
def step(self, action):
next_obs, reward, is_done, info = self.env.step(action)
# todo: improve, return only dictinary
self.full_state["obs"] = next_obs
if self.use_global_obs:
self.full_state["states"] = self.env.get_state()
return self.full_state, reward, is_done, info
else:
return self.full_state["obs"], reward, is_done, info
def reset(self, env_ids=None):
self.full_state["obs"] = self.env.reset(env_ids)
if self.use_global_obs:
self.full_state["states"] = self.env.get_state()
return self.full_state
else:
return self.full_state["obs"]
def get_number_of_agents(self):
return self.env.get_number_of_agents()
def get_env_info(self):
info = {}
info['action_space'] = self.env.action_space
info['observation_space'] = self.env.observation_space
info['amp_observation_space'] = self.env.amp_observation_space
info['enc_amp_observation_space'] = self.env.enc_amp_observation_space
if isinstance(self.env.task, humanoid_amp_task.HumanoidAMPTask):
info['task_obs_size'] = self.env.task.get_task_obs_size()
else:
info['task_obs_size'] = 0
if self.use_global_obs:
info['state_space'] = self.env.state_space
print(info['action_space'], info['observation_space'], info['state_space'])
else:
print(info['action_space'], info['observation_space'])
return info
vecenv.register('RLGPU', lambda config_name, num_actors, **kwargs: RLGPUEnv(config_name, num_actors, **kwargs))
env_configurations.register('rlgpu', {'env_creator': lambda **kwargs: create_rlgpu_env(**kwargs), 'vecenv_type': 'RLGPU'})
def build_alg_runner(algo_observer):
runner = Runner(algo_observer)
runner.player_factory.register_builder('amp_discrete', lambda **kwargs: amp_players.AMPPlayerDiscrete(**kwargs))
runner.algo_factory.register_builder('amp', lambda **kwargs: amp_agent.AMPAgent(**kwargs))
runner.player_factory.register_builder('amp', lambda **kwargs: amp_players.AMPPlayerContinuous(**kwargs))
runner.model_builder.model_factory.register_builder('amp', lambda network, **kwargs: amp_models.ModelAMPContinuous(network))
runner.model_builder.network_factory.register_builder('amp', lambda **kwargs: amp_network_builder.AMPBuilder())
runner.model_builder.network_factory.register_builder('amp_mcp', lambda **kwargs: amp_network_mcp_builder.AMPMCPBuilder())
runner.model_builder.network_factory.register_builder('amp_pnn', lambda **kwargs: amp_network_pnn_builder.AMPPNNBuilder())
runner.algo_factory.register_builder('im_amp', lambda **kwargs: im_amp.IMAmpAgent(**kwargs))
runner.player_factory.register_builder('im_amp', lambda **kwargs: im_amp_players.IMAMPPlayerContinuous(**kwargs))
return runner
def main():
global args
global cfg
global cfg_train
set_np_formatting()
args = get_args()
cfg_env_name = args.cfg_env.split("/")[-1].split(".")[0]
args.logdir = args.network_path
cfg, cfg_train, logdir = load_cfg(args) | flags.debug, flags.follow, flags.fixed, flags.divide_group, flags.no_collision_check, flags.fixed_path, flags.real_path, flags.small_terrain, flags.show_traj, flags.server_mode, flags.slow, flags.real_traj, flags.im_eval, flags.no_virtual_display, flags.render_o3d = \ | 6 | 2023-10-15 19:05:47+00:00 | 8k |
uni-medical/SAM-Med3D | segment_anything/modeling/sam3D.py | [
{
"identifier": "ImageEncoderViT3D",
"path": "segment_anything/modeling/image_encoder3D.py",
"snippet": "class ImageEncoderViT3D(nn.Module):\n def __init__(\n self,\n img_size: int = 256,\n patch_size: int = 16,\n in_chans: int = 1,\n embed_dim: int = 768,\n ... | import torch
from torch import nn
from torch.nn import functional as F
from typing import Any, Dict, List, Tuple
from .image_encoder3D import ImageEncoderViT3D
from .mask_decoder3D import MaskDecoder3D
from .prompt_encoder3D import PromptEncoder3D | 4,342 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
class Sam3D(nn.Module):
mask_threshold: float = 0.0
image_format: str = "L"
def __init__(
self,
| # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
class Sam3D(nn.Module):
mask_threshold: float = 0.0
image_format: str = "L"
def __init__(
self, | image_encoder: ImageEncoderViT3D, | 0 | 2023-10-23 15:41:07+00:00 | 8k |
MolecularAI/REINVENT4 | reinvent/runmodes/create_model/libinvent.py | [
{
"identifier": "DecoratorModel",
"path": "reinvent/models/libinvent/models/model.py",
"snippet": "class DecoratorModel:\n _model_type = \"Libinvent\"\n _version = 1\n\n def __init__(\n self,\n vocabulary,\n decorator,\n max_sequence_length=256,\n mode=ModelMo... | from reinvent.models.libinvent.models.model import DecoratorModel
from reinvent.models.libinvent.models.vocabulary import DecoratorVocabulary
from reinvent.models.libinvent.models.decorator import Decorator
from reinvent.chemistry.file_reader import FileReader
import sys | 3,824 | """Create a Lbinvent model from a list of SMILES strings"""
from __future__ import annotations
def create_model(
num_layers: int,
layer_size: int,
dropout: float,
max_sequence_length: int,
input_smiles_path: str,
output_model_path: str,
):
"""Create a Lbinvent model from scratch
Learn the vocabulary from SMILES.
:returns: a new Libinvent model
"""
reader = FileReader([], None)
# build vocabulary
scaffolds, decorators = zip(
*reader.read_library_design_data_file(input_smiles_path, num_fields=2)
)
| """Create a Lbinvent model from a list of SMILES strings"""
from __future__ import annotations
def create_model(
num_layers: int,
layer_size: int,
dropout: float,
max_sequence_length: int,
input_smiles_path: str,
output_model_path: str,
):
"""Create a Lbinvent model from scratch
Learn the vocabulary from SMILES.
:returns: a new Libinvent model
"""
reader = FileReader([], None)
# build vocabulary
scaffolds, decorators = zip(
*reader.read_library_design_data_file(input_smiles_path, num_fields=2)
)
| vocabulary = DecoratorVocabulary.from_lists(scaffolds, decorators) | 1 | 2023-10-20 06:43:16+00:00 | 8k |
lion-agi/lionagi | lionagi/core/sessions/sessions.py | [
{
"identifier": "Tool",
"path": "lionagi/schema/base_tool.py",
"snippet": "class Tool(BaseNode):\n # name: str = None\n func: Any\n content: Any = None\n parser: Any = None\n schema_: dict\n\n @field_serializer('func')\n def serialize_func(self, func):\n return func.__name__"... | import json
from typing import Any
from dotenv import load_dotenv
from lionagi.schema import DataLogger, Tool
from lionagi.utils import lcall, alcall
from lionagi.services import OpenAIService
from lionagi.endpoints import ChatCompletion
from lionagi.objs.tool_manager import ToolManager
from lionagi.configs.oai_configs import oai_schema
from lionagi.core.conversations.conversation import Conversation | 4,794 |
load_dotenv()
OAIService = OpenAIService()
class Session:
def __init__(
self, system, dir=None, llmconfig=oai_schema['chat']['config'],
service=OAIService
):
self.conversation = Conversation()
self.system = system
self.llmconfig = llmconfig
self.logger_ = DataLogger(dir=dir)
self.service = service
self.tool_manager = ToolManager()
def set_dir(self, dir):
self.logger_.dir = dir
def set_system(self, system):
self.conversation.change_system(system)
def set_llmconfig(self, llmconfig):
self.llmconfig = llmconfig
def set_service(self, service):
self.service = service
async def _output(self, invoke=True, out=True):
if invoke:
try:
# func, args = self.tool_manager._get_function_call(self.conversation.responses[-1]['content'])
# outs = await self.tool_manager.invoke(func, args)
# self.conversation.add_messages(response=outs)
tool_uses = json.loads(self.conversation.responses[-1].message_content)
if 'function_list' in tool_uses.keys():
func_calls = lcall(tool_uses['function_list'], self.tool_manager.get_function_call)
else:
func_calls = lcall(tool_uses['tool_uses'], self.tool_manager.get_function_call)
outs = await alcall(func_calls, self.tool_manager.invoke)
for out, f in zip(outs, func_calls):
response = {"function": f[0], "arguments": f[1], "output": out}
self.conversation.add_messages(response=response)
except:
pass
if out:
return self.conversation.responses[-1].message_content
def _is_invoked(self):
content = self.conversation.messages[-1].message_content
try:
if json.loads(content).keys() >= {'function', 'arguments', 'output'}:
return True
except:
return False
def register_tools(self, tools): #, update=False, new=False, prefix=None, postfix=None):
if not isinstance(tools, list):
tools=[tools]
self.tool_manager.register_tools(tools=tools) #, update=update, new=new, prefix=prefix, postfix=postfix)
# tools_schema = lcall(tools, lambda tool: tool.to_dict()['schema_'])
# if self.llmconfig['tools'] is None:
# self.llmconfig['tools'] = tools_schema
# else:
# self.llmconfig['tools'] += tools_schema
def _tool_parser(self, **kwargs):
# 1. single schema: dict
# 2. tool: Tool
# 3. name: str
# 4. list: 3 types of lists
def tool_check(tool):
if isinstance(tool, dict):
return tool
|
load_dotenv()
OAIService = OpenAIService()
class Session:
def __init__(
self, system, dir=None, llmconfig=oai_schema['chat']['config'],
service=OAIService
):
self.conversation = Conversation()
self.system = system
self.llmconfig = llmconfig
self.logger_ = DataLogger(dir=dir)
self.service = service
self.tool_manager = ToolManager()
def set_dir(self, dir):
self.logger_.dir = dir
def set_system(self, system):
self.conversation.change_system(system)
def set_llmconfig(self, llmconfig):
self.llmconfig = llmconfig
def set_service(self, service):
self.service = service
async def _output(self, invoke=True, out=True):
if invoke:
try:
# func, args = self.tool_manager._get_function_call(self.conversation.responses[-1]['content'])
# outs = await self.tool_manager.invoke(func, args)
# self.conversation.add_messages(response=outs)
tool_uses = json.loads(self.conversation.responses[-1].message_content)
if 'function_list' in tool_uses.keys():
func_calls = lcall(tool_uses['function_list'], self.tool_manager.get_function_call)
else:
func_calls = lcall(tool_uses['tool_uses'], self.tool_manager.get_function_call)
outs = await alcall(func_calls, self.tool_manager.invoke)
for out, f in zip(outs, func_calls):
response = {"function": f[0], "arguments": f[1], "output": out}
self.conversation.add_messages(response=response)
except:
pass
if out:
return self.conversation.responses[-1].message_content
def _is_invoked(self):
content = self.conversation.messages[-1].message_content
try:
if json.loads(content).keys() >= {'function', 'arguments', 'output'}:
return True
except:
return False
def register_tools(self, tools): #, update=False, new=False, prefix=None, postfix=None):
if not isinstance(tools, list):
tools=[tools]
self.tool_manager.register_tools(tools=tools) #, update=update, new=new, prefix=prefix, postfix=postfix)
# tools_schema = lcall(tools, lambda tool: tool.to_dict()['schema_'])
# if self.llmconfig['tools'] is None:
# self.llmconfig['tools'] = tools_schema
# else:
# self.llmconfig['tools'] += tools_schema
def _tool_parser(self, **kwargs):
# 1. single schema: dict
# 2. tool: Tool
# 3. name: str
# 4. list: 3 types of lists
def tool_check(tool):
if isinstance(tool, dict):
return tool | elif isinstance(tool, Tool): | 0 | 2023-10-17 03:10:02+00:00 | 8k |
ziqipang/LM4VisualEncoding | pointcloud_classification/models/Point_BERT.py | [
{
"identifier": "Group",
"path": "pointcloud_classification/models/dvae.py",
"snippet": "class Group(nn.Module):\n def __init__(self, num_group, group_size):\n super().__init__()\n self.num_group = num_group\n self.group_size = group_size\n # self.knn = KNN(k=self.group_si... | import torch
import torch.nn as nn
import torch.nn.functional as F
import timm
import numpy as np
import random
from pathlib import Path
from timm.models.layers import DropPath, trunc_normal_
from .dvae import Group
from .dvae import DiscreteVAE, Encoder
from .llama import LLaMATransformer
from .build import MODELS
from utils import misc
from utils.checkpoint import get_missing_parameters_message, get_unexpected_parameters_message
from utils.logger import * | 3,770 | x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = Attention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class TransformerEncoder(nn.Module):
""" Transformer Encoder without hierarchical structure
"""
def __init__(self, embed_dim=768, depth=4, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.):
super().__init__()
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate,
drop_path = drop_path_rate[i] if isinstance(drop_path_rate, list) else drop_path_rate
)
for i in range(depth)])
def forward(self, x, pos):
for _, block in enumerate(self.blocks):
x = block(x + pos)
return x
@MODELS.register_module()
class PointTransformer(nn.Module):
def __init__(self, config, **kwargs):
super().__init__()
self.config = config
self.trans_dim = config.trans_dim
self.depth = config.depth
self.drop_path_rate = config.drop_path_rate
self.cls_dim = config.cls_dim
self.num_heads = config.num_heads
self.group_size = config.group_size
self.num_group = config.num_group
# grouper
self.group_divider = Group(num_group = self.num_group, group_size = self.group_size)
# define the encoder
self.encoder_dims = config.encoder_dims
self.encoder = Encoder(encoder_channel = self.encoder_dims)
# bridge encoder and transformer
self.reduce_dim = nn.Linear(self.encoder_dims, self.trans_dim)
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.trans_dim))
self.cls_pos = nn.Parameter(torch.randn(1, 1, self.trans_dim))
self.pos_embed = nn.Sequential(
nn.Linear(3, 128),
nn.GELU(),
nn.Linear(128, self.trans_dim)
)
dpr = [x.item() for x in torch.linspace(0, self.drop_path_rate, self.depth)]
self.blocks = TransformerEncoder(
embed_dim = self.trans_dim,
depth = self.depth,
drop_path_rate = dpr,
num_heads = self.num_heads
)
self.norm = nn.LayerNorm(self.trans_dim)
self.cls_head_finetune = nn.Sequential(
nn.Linear(self.trans_dim * 2, 256),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(256, self.cls_dim)
)
if hasattr(config, 'use_llama') and config.use_llama:
llama_default_config = dict(config.llama_cfg)
|
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = Attention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class TransformerEncoder(nn.Module):
""" Transformer Encoder without hierarchical structure
"""
def __init__(self, embed_dim=768, depth=4, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.):
super().__init__()
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate,
drop_path = drop_path_rate[i] if isinstance(drop_path_rate, list) else drop_path_rate
)
for i in range(depth)])
def forward(self, x, pos):
for _, block in enumerate(self.blocks):
x = block(x + pos)
return x
@MODELS.register_module()
class PointTransformer(nn.Module):
def __init__(self, config, **kwargs):
super().__init__()
self.config = config
self.trans_dim = config.trans_dim
self.depth = config.depth
self.drop_path_rate = config.drop_path_rate
self.cls_dim = config.cls_dim
self.num_heads = config.num_heads
self.group_size = config.group_size
self.num_group = config.num_group
# grouper
self.group_divider = Group(num_group = self.num_group, group_size = self.group_size)
# define the encoder
self.encoder_dims = config.encoder_dims
self.encoder = Encoder(encoder_channel = self.encoder_dims)
# bridge encoder and transformer
self.reduce_dim = nn.Linear(self.encoder_dims, self.trans_dim)
self.cls_token = nn.Parameter(torch.zeros(1, 1, self.trans_dim))
self.cls_pos = nn.Parameter(torch.randn(1, 1, self.trans_dim))
self.pos_embed = nn.Sequential(
nn.Linear(3, 128),
nn.GELU(),
nn.Linear(128, self.trans_dim)
)
dpr = [x.item() for x in torch.linspace(0, self.drop_path_rate, self.depth)]
self.blocks = TransformerEncoder(
embed_dim = self.trans_dim,
depth = self.depth,
drop_path_rate = dpr,
num_heads = self.num_heads
)
self.norm = nn.LayerNorm(self.trans_dim)
self.cls_head_finetune = nn.Sequential(
nn.Linear(self.trans_dim * 2, 256),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(256, self.cls_dim)
)
if hasattr(config, 'use_llama') and config.use_llama:
llama_default_config = dict(config.llama_cfg) | self.llama = LLaMATransformer(llama_default_config) | 3 | 2023-10-19 15:40:57+00:00 | 8k |
stanford-oval/WikiChat | pipelines/chatbot.py | [
{
"identifier": "DialogueTurn",
"path": "pipelines/dialog_turn.py",
"snippet": "class DialogueTurn:\n def __init__(\n self,\n agent_utterance: str = None,\n user_utterance: str = None,\n pipeline: str = None,\n engine: str = None,\n generate_engine: str = Non... | from concurrent.futures import ThreadPoolExecutor
from typing import List
from .dialog_turn import DialogueTurn
from llm.llm_generate import llm_generate
from .claim_splitter import ClaimSplitter
from .refiner import Refiner
from .utils import is_everything_verified, extract_year
import time
import re
import requests
import logging
import numpy as np | 4,994 |
logger = logging.getLogger(__name__)
class Chatbot:
"""
A stateless chatbot. Stateless means that it does not store the history of the dialog in itself, but requires it as an input
"""
def __init__(self, args) -> None:
# Initialize everything, because we can change the pipeline on the fly using system_parameters
self.claim_splitter = ClaimSplitter(args.claim_prompt_template_file)
self.evi_num = args.evi_num
self.colbert_endpoint = args.colbert_endpoint
self.retrieval_num = args.retrieval_num
self.refiner = Refiner(prompt=args.refinement_prompt, args=args)
self.temperature = args.temperature
self.max_tokens = args.max_tokens
self.top_p = args.top_p
self.presence_penalty = args.presence_penalty
self.frequency_penalty = args.frequency_penalty
self.skip_verification = args.skip_verification
# default parameters, can be overridden:
self.engine = args.engine
self.generate_engine = args.generate_engine
self.draft_engine = args.draft_engine
self.do_refine=args.do_refine
self.fuse_claim_splitting = args.fuse_claim_splitting
def generate_next_turn(
self,
|
logger = logging.getLogger(__name__)
class Chatbot:
"""
A stateless chatbot. Stateless means that it does not store the history of the dialog in itself, but requires it as an input
"""
def __init__(self, args) -> None:
# Initialize everything, because we can change the pipeline on the fly using system_parameters
self.claim_splitter = ClaimSplitter(args.claim_prompt_template_file)
self.evi_num = args.evi_num
self.colbert_endpoint = args.colbert_endpoint
self.retrieval_num = args.retrieval_num
self.refiner = Refiner(prompt=args.refinement_prompt, args=args)
self.temperature = args.temperature
self.max_tokens = args.max_tokens
self.top_p = args.top_p
self.presence_penalty = args.presence_penalty
self.frequency_penalty = args.frequency_penalty
self.skip_verification = args.skip_verification
# default parameters, can be overridden:
self.engine = args.engine
self.generate_engine = args.generate_engine
self.draft_engine = args.draft_engine
self.do_refine=args.do_refine
self.fuse_claim_splitting = args.fuse_claim_splitting
def generate_next_turn(
self, | object_dlg_history: List[DialogueTurn], | 0 | 2023-10-19 18:17:25+00:00 | 8k |
SunOner/yolov8_aimbot | run.py | [
{
"identifier": "Config",
"path": "logic/config_watcher.py",
"snippet": "class Config():\n def __init__(self):\n self.config = configparser.ConfigParser()\n self.Read(verbose=False)\n \n def Read(self, verbose=False):\n self.config.read('./config.ini')\n self.config_... | from logic.config_watcher import Config
from logic.keyboard import *
from logic.capture import *
from logic.mouse import MouseThread
from ultralytics import YOLO
import math
import torch
import cv2
import time
import win32api, win32con, win32gui
import tkinter as tk | 4,481 | def spawn_debug_window():
if cfg.show_window:
print('An open debug window can affect performance.')
cv2.namedWindow(cfg.debug_window_name)
if cfg.debug_window_always_on_top:
debug_window_hwnd = win32gui.FindWindow(None, cfg.debug_window_name)
win32gui.SetWindowPos(debug_window_hwnd, win32con.HWND_TOPMOST, 100, 100, 200, 200, 0)
@torch.no_grad()
def init():
overlay = OverlayWindow() if cfg.show_overlay_detector else None
prev_frame_time, new_frame_time = 0, 0 if cfg.show_window and cfg.show_fps else None
try:
model = YOLO(f'models/{cfg.AI_model_path}', task='detect')
print_startup_messages()
except Exception as e:
print(e)
quit(0)
spawn_debug_window()
cfg_reload_prev_state = 0
shooting_queue = []
screen_center = torch.tensor([frames.screen_x_center, frames.screen_y_center], device='cuda:0')
while True:
cfg_reload_prev_state = process_hotkeys(cfg_reload_prev_state)
image = frames.get_new_frame()
result = perform_detection(model, image)
update_overlay_window(overlay)
if cfg.show_window:
annotated_frame = image
for frame in result:
if cfg.show_window and cfg.show_speed == True:
annotated_frame = speed(annotated_frame, frame.speed['preprocess'], frame.speed['inference'], frame.speed['postprocess'])
if len(frame.boxes):
if app_pause == 0:
boxes_array = frame.boxes.xywh
distances_sq = torch.sum((boxes_array[:, :2] - screen_center) ** 2, dim=1)
classes_np = frame.boxes.cls.cpu().numpy()
shooting_queue = [Target(*box[:4].cpu().numpy(), cls) for box, cls in zip(boxes_array, classes_np)]
if not cfg.disable_headshot:
sort_indices = np.lexsort((distances_sq.cpu().numpy(), classes_np != 7))
else:
class7_indices = torch.where(frame.boxes.cls == 7)[0]
if len(class7_indices) > 0:
class7_distances_sq = distances_sq[class7_indices]
sort_indices_class7 = torch.argsort(class7_distances_sq)
class7_indices = class7_indices[sort_indices_class7]
else:
sort_indices_class7 = torch.tensor([], dtype=torch.int64, device=cfg.AI_device)
other_indices = torch.where(frame.boxes.cls != 7)[0]
other_distances_sq = distances_sq[other_indices]
sort_indices_other = torch.argsort(other_distances_sq)
sort_indices = torch.cat((class7_indices, other_indices[sort_indices_other])).cpu().numpy()
shooting_queue = [shooting_queue[i] for i in sort_indices]
if shooting_queue:
target = shooting_queue[0]
mouse_worker.queue.put((target.x, target.y, target.w, target.h))
if cfg.show_window and cfg.show_target_line:
draw_target_line(annotated_frame=annotated_frame, screen_x_center=cfg.detection_window_width / 2, screen_y_center=cfg.detection_window_height / 2, target_x=target.x, target_y=target.y + cfg.body_y_offset / target.h)
if cfg.show_overlay_detector and cfg.show_overlay_boxes:
x1, y1 = target.x - target.w / 2, target.y - target.h / 2
x2, y2 = target.x + target.w / 2, target.y + target.h / 2
overlay.canvas.create_rectangle(x1.item(), y1.item(), x2.item(), y2.item(), width=2, outline='green')
if cfg.show_overlay_detector and cfg.show_overlay_line:
overlay.canvas.create_line(cfg.detection_window_width / 2, cfg.detection_window_height / 2, target.x, target.y + cfg.body_y_offset / target.h, width=2, fill='red')
shooting_queue.clear()
else: pass
if cfg.show_window and cfg.show_boxes:
draw_helpers(annotated_frame=annotated_frame, boxes=frame.boxes)
else:
mouse_worker.queue.put(None)
if cfg.show_window and cfg.show_fps:
new_frame_time = time.time()
fps = 1/(new_frame_time-prev_frame_time)
prev_frame_time = new_frame_time
cv2.putText(annotated_frame, f'FPS: {str(int(fps))}', (10, 80) if cfg.show_speed else (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1, cv2.LINE_AA)
if win32api.GetAsyncKeyState(Keyboard.KEY_CODES.get(cfg.hotkey_exit)) & 0xFF:
if cfg.show_window:
cv2.destroyWindow(cfg.debug_window_name)
frames.Quit()
break
if cfg.show_window:
try:
if cfg.debug_window_scale_percent != 100:
height = int(cfg.detection_window_height * cfg.debug_window_scale_percent / 100)
width = int(cfg.detection_window_width * cfg.debug_window_scale_percent / 100)
dim = (width, height)
cv2.resizeWindow(cfg.debug_window_name, dim)
resised = cv2.resize(annotated_frame, dim, cv2.INTER_NEAREST)
cv2.imshow(cfg.debug_window_name, resised)
else:
cv2.imshow(cfg.debug_window_name, annotated_frame)
except: exit(0)
if cfg.show_window and cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == "__main__":
frames = Capture()
| cfg = Config()
if cfg.show_overlay_detector:
class Target:
def __init__(self, x, y, w, h, cls):
self.x = x
self.y = y if cls == 7 else (y - cfg.body_y_offset * h)
self.w = w
self.h = h
self.distance = math.sqrt((x - frames.screen_x_center)**2 + (y - frames.screen_y_center)**2)
self.cls = cls
class OverlayWindow:
def __init__(self):
self.overlay_detector = tk.Tk()
self.overlay_detector.geometry(f'{cfg.detection_window_width}x{cfg.detection_window_height}+{frames.Calculate_screen_offset()[0]}+{frames.Calculate_screen_offset()[1]}')
self.overlay_detector.lift()
self.overlay_detector.wm_attributes("-topmost", True)
self.overlay_detector.wm_attributes("-disabled", True)
self.overlay_detector.wm_attributes("-transparentcolor", "white")
self.overlay_detector.title('new.txt')
self.overlay_detector.overrideredirect(True)
self.canvas = tk.Canvas(self.overlay_detector, bg='white', height=cfg.detection_window_height, width=cfg.detection_window_width)
self.canvas.pack()
def perform_detection(model, image):
clss = [0, 1]
if cfg.hideout_targets:
clss += 5, 6
if cfg.disable_headshot == False:
clss.append(7)
return model.predict(
source=image,
stream=True,
cfg='logic/game.yaml',
imgsz=cfg.AI_image_size,
stream_buffer=False,
visualize=False,
augment=True,
agnostic_nms=False,
save=False,
conf=cfg.AI_conf,
iou=cfg.AI_iou,
device=cfg.AI_device,
half=False,
max_det=10,
vid_stride=False,
classes=clss,
verbose=False,
show_boxes=False,
show_labels=False,
show_conf=False,
show=False)
def print_startup_messages():
print('Aimbot is started. Enjoy!\n'
f'[{cfg.hotkey_targeting}] - Aiming at the target\n'
f'[{cfg.hotkey_exit}] - EXIT\n'
f'[{cfg.hotkey_pause}] - PAUSE AIM\n'
f'[{cfg.hotkey_reload_config}] - Reload config')
def process_hotkeys(cfg_reload_prev_state):
global app_pause
app_pause = win32api.GetKeyState(Keyboard.KEY_CODES[cfg.hotkey_pause])
app_reload_cfg = win32api.GetKeyState(Keyboard.KEY_CODES[cfg.hotkey_reload_config])
if app_reload_cfg != cfg_reload_prev_state:
if app_reload_cfg in (1, 0):
cfg.Read(verbose=True)
frames.reload_capture()
mouse_worker.Update_settings()
cfg_reload_prev_state = app_reload_cfg
return cfg_reload_prev_state
def update_overlay_window(overlay):
if cfg.show_overlay_detector:
overlay.overlay_detector.update()
overlay.canvas.delete("all")
def spawn_debug_window():
if cfg.show_window:
print('An open debug window can affect performance.')
cv2.namedWindow(cfg.debug_window_name)
if cfg.debug_window_always_on_top:
debug_window_hwnd = win32gui.FindWindow(None, cfg.debug_window_name)
win32gui.SetWindowPos(debug_window_hwnd, win32con.HWND_TOPMOST, 100, 100, 200, 200, 0)
@torch.no_grad()
def init():
overlay = OverlayWindow() if cfg.show_overlay_detector else None
prev_frame_time, new_frame_time = 0, 0 if cfg.show_window and cfg.show_fps else None
try:
model = YOLO(f'models/{cfg.AI_model_path}', task='detect')
print_startup_messages()
except Exception as e:
print(e)
quit(0)
spawn_debug_window()
cfg_reload_prev_state = 0
shooting_queue = []
screen_center = torch.tensor([frames.screen_x_center, frames.screen_y_center], device='cuda:0')
while True:
cfg_reload_prev_state = process_hotkeys(cfg_reload_prev_state)
image = frames.get_new_frame()
result = perform_detection(model, image)
update_overlay_window(overlay)
if cfg.show_window:
annotated_frame = image
for frame in result:
if cfg.show_window and cfg.show_speed == True:
annotated_frame = speed(annotated_frame, frame.speed['preprocess'], frame.speed['inference'], frame.speed['postprocess'])
if len(frame.boxes):
if app_pause == 0:
boxes_array = frame.boxes.xywh
distances_sq = torch.sum((boxes_array[:, :2] - screen_center) ** 2, dim=1)
classes_np = frame.boxes.cls.cpu().numpy()
shooting_queue = [Target(*box[:4].cpu().numpy(), cls) for box, cls in zip(boxes_array, classes_np)]
if not cfg.disable_headshot:
sort_indices = np.lexsort((distances_sq.cpu().numpy(), classes_np != 7))
else:
class7_indices = torch.where(frame.boxes.cls == 7)[0]
if len(class7_indices) > 0:
class7_distances_sq = distances_sq[class7_indices]
sort_indices_class7 = torch.argsort(class7_distances_sq)
class7_indices = class7_indices[sort_indices_class7]
else:
sort_indices_class7 = torch.tensor([], dtype=torch.int64, device=cfg.AI_device)
other_indices = torch.where(frame.boxes.cls != 7)[0]
other_distances_sq = distances_sq[other_indices]
sort_indices_other = torch.argsort(other_distances_sq)
sort_indices = torch.cat((class7_indices, other_indices[sort_indices_other])).cpu().numpy()
shooting_queue = [shooting_queue[i] for i in sort_indices]
if shooting_queue:
target = shooting_queue[0]
mouse_worker.queue.put((target.x, target.y, target.w, target.h))
if cfg.show_window and cfg.show_target_line:
draw_target_line(annotated_frame=annotated_frame, screen_x_center=cfg.detection_window_width / 2, screen_y_center=cfg.detection_window_height / 2, target_x=target.x, target_y=target.y + cfg.body_y_offset / target.h)
if cfg.show_overlay_detector and cfg.show_overlay_boxes:
x1, y1 = target.x - target.w / 2, target.y - target.h / 2
x2, y2 = target.x + target.w / 2, target.y + target.h / 2
overlay.canvas.create_rectangle(x1.item(), y1.item(), x2.item(), y2.item(), width=2, outline='green')
if cfg.show_overlay_detector and cfg.show_overlay_line:
overlay.canvas.create_line(cfg.detection_window_width / 2, cfg.detection_window_height / 2, target.x, target.y + cfg.body_y_offset / target.h, width=2, fill='red')
shooting_queue.clear()
else: pass
if cfg.show_window and cfg.show_boxes:
draw_helpers(annotated_frame=annotated_frame, boxes=frame.boxes)
else:
mouse_worker.queue.put(None)
if cfg.show_window and cfg.show_fps:
new_frame_time = time.time()
fps = 1/(new_frame_time-prev_frame_time)
prev_frame_time = new_frame_time
cv2.putText(annotated_frame, f'FPS: {str(int(fps))}', (10, 80) if cfg.show_speed else (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1, cv2.LINE_AA)
if win32api.GetAsyncKeyState(Keyboard.KEY_CODES.get(cfg.hotkey_exit)) & 0xFF:
if cfg.show_window:
cv2.destroyWindow(cfg.debug_window_name)
frames.Quit()
break
if cfg.show_window:
try:
if cfg.debug_window_scale_percent != 100:
height = int(cfg.detection_window_height * cfg.debug_window_scale_percent / 100)
width = int(cfg.detection_window_width * cfg.debug_window_scale_percent / 100)
dim = (width, height)
cv2.resizeWindow(cfg.debug_window_name, dim)
resised = cv2.resize(annotated_frame, dim, cv2.INTER_NEAREST)
cv2.imshow(cfg.debug_window_name, resised)
else:
cv2.imshow(cfg.debug_window_name, annotated_frame)
except: exit(0)
if cfg.show_window and cv2.waitKey(1) & 0xFF == ord('q'):
break
if __name__ == "__main__":
frames = Capture() | mouse_worker = MouseThread() | 1 | 2023-10-16 11:32:57+00:00 | 8k |
jhejna/cpl | scripts/create_comparison_dataset.py | [
{
"identifier": "ReplayBuffer",
"path": "research/datasets/replay_buffer/buffer.py",
"snippet": "class ReplayBuffer(torch.utils.data.IterableDataset):\n \"\"\"\n Generic Replay Buffer Class.\n\n This class adheres to the following conventions to support multiprocessing:\n 1. Variables/functi... | import argparse
import collections
import io
import os
import numpy as np
from research.datasets import ReplayBuffer
from research.utils import utils
from research.utils.config import Config | 6,454 |
if __name__ == "__main__":
# This is a short script that generates a pairwise preference dataset from a ReplayBuffer
parser = argparse.ArgumentParser()
parser.add_argument("--path", type=str, required=True, help="Path to the ReplayBuffer")
parser.add_argument("--output", type=str, required=True, help="Output path for the dataset")
parser.add_argument("--size", type=int, default=20000, help="How many data points to sample")
parser.add_argument("--segment-size", type=int, default=64, help="How large to make segments")
parser.add_argument("--checkpoint", type=str, required=True, help="Path to oracle model")
args = parser.parse_args()
# Get the model
config_path = os.path.dirname(args.checkpoint) if args.checkpoint.endswith(".pt") else args.checkpoint
config = Config.load(config_path)
config["checkpoint"] = None # Set checkpoint to None, we don't actually need to load it.
config = config.parse()
env_fn = config.get_train_env_fn()
if env_fn is None:
env_fn = config.get_eval_env_fn()
env = env_fn()
# Load the data
assert os.path.exists(args.path)
replay_buffer = ReplayBuffer(
env.observation_space, env.action_space, distributed=False, path=args.path, sample_fn="sample_sequence"
)
data = []
scores = collections.defaultdict(list)
batch_size = 256
remaining_data_points = args.size
# sample num segments...
while remaining_data_points > 0:
sample_size = min(batch_size, remaining_data_points)
batch = replay_buffer.sample(
batch_size=sample_size,
sample_by_timesteps=True,
seq_length=args.segment_size,
pad=0,
seq_keys=("obs", "action", "reward", "state", "timestep"),
)
del batch["mask"]
data.append(batch)
remaining_data_points -= sample_size
assert remaining_data_points == 0, "Must have zero remaining segments"
|
if __name__ == "__main__":
# This is a short script that generates a pairwise preference dataset from a ReplayBuffer
parser = argparse.ArgumentParser()
parser.add_argument("--path", type=str, required=True, help="Path to the ReplayBuffer")
parser.add_argument("--output", type=str, required=True, help="Output path for the dataset")
parser.add_argument("--size", type=int, default=20000, help="How many data points to sample")
parser.add_argument("--segment-size", type=int, default=64, help="How large to make segments")
parser.add_argument("--checkpoint", type=str, required=True, help="Path to oracle model")
args = parser.parse_args()
# Get the model
config_path = os.path.dirname(args.checkpoint) if args.checkpoint.endswith(".pt") else args.checkpoint
config = Config.load(config_path)
config["checkpoint"] = None # Set checkpoint to None, we don't actually need to load it.
config = config.parse()
env_fn = config.get_train_env_fn()
if env_fn is None:
env_fn = config.get_eval_env_fn()
env = env_fn()
# Load the data
assert os.path.exists(args.path)
replay_buffer = ReplayBuffer(
env.observation_space, env.action_space, distributed=False, path=args.path, sample_fn="sample_sequence"
)
data = []
scores = collections.defaultdict(list)
batch_size = 256
remaining_data_points = args.size
# sample num segments...
while remaining_data_points > 0:
sample_size = min(batch_size, remaining_data_points)
batch = replay_buffer.sample(
batch_size=sample_size,
sample_by_timesteps=True,
seq_length=args.segment_size,
pad=0,
seq_keys=("obs", "action", "reward", "state", "timestep"),
)
del batch["mask"]
data.append(batch)
remaining_data_points -= sample_size
assert remaining_data_points == 0, "Must have zero remaining segments"
| data = utils.concatenate(*data, dim=0) | 1 | 2023-10-19 17:25:45+00:00 | 8k |
nbasyl/LLM-FP4 | lm_eval/models/huggingface.py | [
{
"identifier": "utils",
"path": "lm_eval/utils.py",
"snippet": "class ExitCodeError(Exception):\nclass MultiChoice:\nclass Reorderer:\ndef sh(x):\ndef escaped_split(text, sep_char, maxsplit=-1):\ndef simple_parse_args_string(args_string):\ndef join_iters(iters):\ndef chunks(iter, n=0, fn=None):\ndef gr... | import math
import torch
import torch.nn.functional as F
import transformers
import peft
from peft import __version__ as PEFT_VERSION
from pathlib import Path
from typing import List, Mapping, NewType, Optional, Tuple, Union
from tqdm import tqdm
from transformers import BatchEncoding
from lm_eval import utils
from lm_eval.base import BaseLM
from auto_gptq import AutoGPTQForCausalLM | 3,676 |
TokenSequence = Union[List[int], torch.LongTensor, torch.Tensor, BatchEncoding]
_DeviceMapping = NewType("DeviceMapping", Mapping[str, Union[int, str, torch.device]])
def _get_accelerate_args(
device_map_option: Optional[str] = "auto",
max_memory_per_gpu: Optional[Union[int, str]] = None,
max_cpu_memory: Optional[Union[int, str]] = None,
offload_folder: Optional[str] = "./offload",
) -> dict:
"""Returns the kwargs needed to apply `accelerate` in `AutoModel.from_pretrained`."""
max_memory = {}
if max_memory_per_gpu is not None:
max_memory_per_gpu_map = {
device_idx: max_memory_per_gpu
for device_idx in range(torch.cuda.device_count())
}
max_memory.update(max_memory_per_gpu_map)
if max_cpu_memory is not None:
max_memory["cpu"] = max_cpu_memory
args = {}
if max_memory:
args["max_memory"] = max_memory
args["device_map"] = device_map_option
args["offload_folder"] = offload_folder
return args
def _get_dtype(
dtype: Union[str, torch.dtype], config: Optional[transformers.AutoConfig] = None
) -> torch.dtype:
"""Converts `dtype` from `str` to torch.dtype when possible."""
if dtype is None and config is not None:
_torch_dtype = config.torch_dtype
elif isinstance(dtype, str) and dtype != "auto":
# Convert `str` args torch dtype: `float16` -> `torch.float16`
_torch_dtype = getattr(torch, dtype)
else:
_torch_dtype = dtype
return _torch_dtype
|
TokenSequence = Union[List[int], torch.LongTensor, torch.Tensor, BatchEncoding]
_DeviceMapping = NewType("DeviceMapping", Mapping[str, Union[int, str, torch.device]])
def _get_accelerate_args(
device_map_option: Optional[str] = "auto",
max_memory_per_gpu: Optional[Union[int, str]] = None,
max_cpu_memory: Optional[Union[int, str]] = None,
offload_folder: Optional[str] = "./offload",
) -> dict:
"""Returns the kwargs needed to apply `accelerate` in `AutoModel.from_pretrained`."""
max_memory = {}
if max_memory_per_gpu is not None:
max_memory_per_gpu_map = {
device_idx: max_memory_per_gpu
for device_idx in range(torch.cuda.device_count())
}
max_memory.update(max_memory_per_gpu_map)
if max_cpu_memory is not None:
max_memory["cpu"] = max_cpu_memory
args = {}
if max_memory:
args["max_memory"] = max_memory
args["device_map"] = device_map_option
args["offload_folder"] = offload_folder
return args
def _get_dtype(
dtype: Union[str, torch.dtype], config: Optional[transformers.AutoConfig] = None
) -> torch.dtype:
"""Converts `dtype` from `str` to torch.dtype when possible."""
if dtype is None and config is not None:
_torch_dtype = config.torch_dtype
elif isinstance(dtype, str) and dtype != "auto":
# Convert `str` args torch dtype: `float16` -> `torch.float16`
_torch_dtype = getattr(torch, dtype)
else:
_torch_dtype = dtype
return _torch_dtype
| class HuggingFaceAutoLM(BaseLM): | 1 | 2023-10-15 06:05:13+00:00 | 8k |
alextamkin/generative-elicitation | pool_based_agent.py | [
{
"identifier": "BaseActiveLearningAgent",
"path": "base_active_learning_agent.py",
"snippet": "class BaseActiveLearningAgent(ABC):\n \n def __init__(self, target_specification_file, engine, openai_cache_file=None, **kwargs):\n self.get_gold_domain_info(target_specification_file)\n s... | import textwrap
import numpy as np
import random
import json
from base_active_learning_agent import BaseActiveLearningAgent
from utils import query_api, load_openai_cache, async_query_api
from tqdm import tqdm
from sentence_transformers import SentenceTransformer
from sklearn.cluster import KMeans | 4,654 | super().__init__(target_specification_file, engine, openai_cache_file, **kwargs)
# either specified in `target_specification_file` or in args
if pool_data_path is not None:
self.pool_data_path = pool_data_path
if pool_al_sampling_type is not None:
self.pool_al_sampling_type = pool_al_sampling_type
self.pool_al_examples = self.load_pool_examples(self.pool_data_path)
self.previous_samples = []
if self.pool_al_sampling_type == "diversity":
self.num_clusters = pool_diversity_num_clusters
print("Loading sentence transformer model...")
model = SentenceTransformer('all-MiniLM-L6-v2')
print("Embedding pool examples...")
# embed everything
self.pool_al_examples_embeddings = model.encode(self.pool_al_examples)
kmeans = KMeans(n_clusters=self.num_clusters, random_state=0).fit(self.pool_al_examples_embeddings)
# get centroids of clusters
centroids = kmeans.cluster_centers_
# get closest example to each centroid
self.all_samples = []
# round robin
self.curr_centroid_idx = 0
for centroid_idx, centroid in enumerate(centroids):
# closest_example_idx = np.argmin(np.linalg.norm(self.pool_al_examples_embeddings - centroid, axis=1))
cluster_samples = np.where(kmeans.labels_ == centroid_idx)[0]
# sort by distance (smallest to largest)
cluster_samples = cluster_samples[np.argsort(np.linalg.norm(self.pool_al_examples_embeddings[cluster_samples] - centroid, axis=1))]
self.all_samples.append([self.pool_al_examples[pool_sample] for pool_sample in cluster_samples])
all_samples = []
for sample in self.all_samples: all_samples.extend(sample)
assert set(all_samples) == set(self.pool_al_examples)
if self.pool_al_sampling_type == "uncertainty_logits":
self.engine_selection = "text-davinci-003"
self.openai_cache_selection_file = f"{self.engine_selection}-cache.jsonl"
self.openai_cache_selection = load_openai_cache(self.openai_cache_selection_file)
def load_pool_examples(self, pool_fp):
# csv_reader = csv.DictReader(open(pool_fp, 'r'), delimiter='\t')
pool_examples = []
for row in open(pool_fp):
pool_examples.append(json.loads(row)["nl_desc"])
return pool_examples
def format_edge_cases(self, edge_cases):
return '\n'.join([f"{idx+1}. {edge_case[0]} -> {edge_case[1]}" for idx, edge_case in enumerate(edge_cases)])
def format_al_json_samples(self, edge_cases):
return json.dumps([{"sample": sample.strip()} for sample in edge_cases])
@staticmethod
def strip_edge_case(edge_case):
# Strip label
edge_case = edge_case.split(" -> ")[0]
# Strip beginning dashes
if edge_case.startswith("- "):
edge_case = edge_case[2:]
return edge_case
def get_hypothesis_prompt(self):
pass
def get_query_prompt(self):
return f"pool_{self.pool_al_sampling_type}"
def generate_active_query(self):
'''Generates the next active learning query.'''
if self.pool_al_sampling_type == "uncertainty_tokens":
sample = self.generate_active_query_uncertainty_tokens(batch_size=10)
elif self.pool_al_sampling_type == "uncertainty_logits":
sample = self.generate_active_query_uncertainty_logits()
elif self.pool_al_sampling_type == "diversity":
sample = self.generate_active_query_diversity()
elif self.pool_al_sampling_type == "random":
sample = self.generate_active_query_random()
else:
raise NotImplementedError
self.previous_samples.append(sample)
self.pool_al_examples.remove(sample)
print(sample)
print("===")
return self.example_edge_case_question_format.replace("[edge case]", sample)
def generate_active_query_diversity(self):
# make people go through a fixed number (k turns)
# if len(self.previous_samples) >= len(self.all_samples):
# return self.generate_active_query_random()
next_sample = self.all_samples[self.curr_centroid_idx].pop(0)
self.curr_centroid_idx = (self.curr_centroid_idx + 1) % self.num_clusters
return next_sample
def generate_active_query_random(self):
random_sample = random.choice(self.pool_al_examples)
return random_sample
def generate_active_query_uncertainty_tokens(self, batch_size):
'''Samples the most uncertain edge case for the oracle.'''
"""
TODO old code... remove
"""
most_uncertain_edge_case = None
max_uncertainty = 0
for possible_next_edge_case_idx in tqdm(range(0, len(self.pool_al_examples), batch_size)):
next_edge_cases = self.pool_al_examples[possible_next_edge_case_idx:possible_next_edge_case_idx+batch_size]
al_template = textwrap.dedent('''\
{pool_al_prompt}
{previous_examples}
{pool_al_prompt2}
{next_edge_cases}
Return a json list of the form [{{"sample": sample, "pred label": yes/no, "pred prob": probability of predicted label for the sample}}]. Please stick to this format and return nothing else.'''
).format(
pool_al_prompt=self.pool_al_prompt[0],
previous_examples=self.format_edge_cases([
[self.previous_samples[idx], item[1]] for idx, item in enumerate(self.interaction_history)
]),
pool_al_prompt2=self.pool_al_prompt[1],
next_edge_cases=self.format_al_json_samples(next_edge_cases),
)
|
IMPLEMENTATION = "system" #["Python regex", "system"]
class PoolBasedAgent(BaseActiveLearningAgent):
"""Active learning agent that generates edge cases to identify the target regex."""
def __init__(self, target_specification_file, engine, openai_cache_file=None, pool_data_path=None, pool_al_sampling_type=None, pool_diversity_num_clusters=None, **kwargs):
super().__init__(target_specification_file, engine, openai_cache_file, **kwargs)
# either specified in `target_specification_file` or in args
if pool_data_path is not None:
self.pool_data_path = pool_data_path
if pool_al_sampling_type is not None:
self.pool_al_sampling_type = pool_al_sampling_type
self.pool_al_examples = self.load_pool_examples(self.pool_data_path)
self.previous_samples = []
if self.pool_al_sampling_type == "diversity":
self.num_clusters = pool_diversity_num_clusters
print("Loading sentence transformer model...")
model = SentenceTransformer('all-MiniLM-L6-v2')
print("Embedding pool examples...")
# embed everything
self.pool_al_examples_embeddings = model.encode(self.pool_al_examples)
kmeans = KMeans(n_clusters=self.num_clusters, random_state=0).fit(self.pool_al_examples_embeddings)
# get centroids of clusters
centroids = kmeans.cluster_centers_
# get closest example to each centroid
self.all_samples = []
# round robin
self.curr_centroid_idx = 0
for centroid_idx, centroid in enumerate(centroids):
# closest_example_idx = np.argmin(np.linalg.norm(self.pool_al_examples_embeddings - centroid, axis=1))
cluster_samples = np.where(kmeans.labels_ == centroid_idx)[0]
# sort by distance (smallest to largest)
cluster_samples = cluster_samples[np.argsort(np.linalg.norm(self.pool_al_examples_embeddings[cluster_samples] - centroid, axis=1))]
self.all_samples.append([self.pool_al_examples[pool_sample] for pool_sample in cluster_samples])
all_samples = []
for sample in self.all_samples: all_samples.extend(sample)
assert set(all_samples) == set(self.pool_al_examples)
if self.pool_al_sampling_type == "uncertainty_logits":
self.engine_selection = "text-davinci-003"
self.openai_cache_selection_file = f"{self.engine_selection}-cache.jsonl"
self.openai_cache_selection = load_openai_cache(self.openai_cache_selection_file)
def load_pool_examples(self, pool_fp):
# csv_reader = csv.DictReader(open(pool_fp, 'r'), delimiter='\t')
pool_examples = []
for row in open(pool_fp):
pool_examples.append(json.loads(row)["nl_desc"])
return pool_examples
def format_edge_cases(self, edge_cases):
return '\n'.join([f"{idx+1}. {edge_case[0]} -> {edge_case[1]}" for idx, edge_case in enumerate(edge_cases)])
def format_al_json_samples(self, edge_cases):
return json.dumps([{"sample": sample.strip()} for sample in edge_cases])
@staticmethod
def strip_edge_case(edge_case):
# Strip label
edge_case = edge_case.split(" -> ")[0]
# Strip beginning dashes
if edge_case.startswith("- "):
edge_case = edge_case[2:]
return edge_case
def get_hypothesis_prompt(self):
pass
def get_query_prompt(self):
return f"pool_{self.pool_al_sampling_type}"
def generate_active_query(self):
'''Generates the next active learning query.'''
if self.pool_al_sampling_type == "uncertainty_tokens":
sample = self.generate_active_query_uncertainty_tokens(batch_size=10)
elif self.pool_al_sampling_type == "uncertainty_logits":
sample = self.generate_active_query_uncertainty_logits()
elif self.pool_al_sampling_type == "diversity":
sample = self.generate_active_query_diversity()
elif self.pool_al_sampling_type == "random":
sample = self.generate_active_query_random()
else:
raise NotImplementedError
self.previous_samples.append(sample)
self.pool_al_examples.remove(sample)
print(sample)
print("===")
return self.example_edge_case_question_format.replace("[edge case]", sample)
def generate_active_query_diversity(self):
# make people go through a fixed number (k turns)
# if len(self.previous_samples) >= len(self.all_samples):
# return self.generate_active_query_random()
next_sample = self.all_samples[self.curr_centroid_idx].pop(0)
self.curr_centroid_idx = (self.curr_centroid_idx + 1) % self.num_clusters
return next_sample
def generate_active_query_random(self):
random_sample = random.choice(self.pool_al_examples)
return random_sample
def generate_active_query_uncertainty_tokens(self, batch_size):
'''Samples the most uncertain edge case for the oracle.'''
"""
TODO old code... remove
"""
most_uncertain_edge_case = None
max_uncertainty = 0
for possible_next_edge_case_idx in tqdm(range(0, len(self.pool_al_examples), batch_size)):
next_edge_cases = self.pool_al_examples[possible_next_edge_case_idx:possible_next_edge_case_idx+batch_size]
al_template = textwrap.dedent('''\
{pool_al_prompt}
{previous_examples}
{pool_al_prompt2}
{next_edge_cases}
Return a json list of the form [{{"sample": sample, "pred label": yes/no, "pred prob": probability of predicted label for the sample}}]. Please stick to this format and return nothing else.'''
).format(
pool_al_prompt=self.pool_al_prompt[0],
previous_examples=self.format_edge_cases([
[self.previous_samples[idx], item[1]] for idx, item in enumerate(self.interaction_history)
]),
pool_al_prompt2=self.pool_al_prompt[1],
next_edge_cases=self.format_al_json_samples(next_edge_cases),
) | response, _ = query_api( | 1 | 2023-10-16 18:43:47+00:00 | 8k |
bcmi/libcom | libcom/shadow_generation/source/PostProcessModel.py | [
{
"identifier": "ControlLDM",
"path": "libcom/shadow_generation/source/cldm/cldm.py",
"snippet": "class ControlLDM(LatentDiffusion):\n\n def __init__(self, control_stage_config, control_key, only_mid_control, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.control_model = i... | from torch import nn
from .cldm.cldm import ControlLDM
from .cldm.model import create_model, load_state_dict
from torch.utils.data import DataLoader
from .cldm.logger import PostProcessLogger
from PIL import Image
from libcom.shadow_generation.source.ldm.modules.diffusionmodules.openaimodel import (ResBlock, TimestepEmbedSequential, AttentionBlock,
Upsample, SpatialTransformer, Downsample)
from libcom.shadow_generation.source.ldm.modules.diffusionmodules.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from libcom.shadow_generation.source.ldm.util import exists
import torch
import pytorch_lightning as pl
import os
import cv2
import numpy as np | 5,841 | # from share import *
class Post_Process_Net(nn.Module):
def __init__(
self,
image_size,
in_channels,
model_channels,
out_channels,
num_res_blocks,
attention_resolutions,
dropout=0,
channel_mult=(1, 2, 4, 8),
conv_resample=True,
dims=2,
num_classes=None,
use_checkpoint=False,
use_fp16=False,
num_heads=-1,
num_head_channels=-1,
num_heads_upsample=-1,
use_scale_shift_norm=False,
resblock_updown=False,
use_new_attention_order=False,
use_spatial_transformer=False, # custom transformer support
transformer_depth=1, # custom transformer support
context_dim=None, # custom transformer support
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
legacy=True,
disable_self_attentions=None,
num_attention_blocks=None,
disable_middle_self_attn=False,
use_linear_in_transformer=False,
):
super().__init__()
self.image_size = image_size
self.in_channels = in_channels
self.model_channels = model_channels
self.out_channels = out_channels
if isinstance(num_res_blocks, int):
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
else:
if len(num_res_blocks) != len(channel_mult):
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
"as a list/tuple (per-level) with the same length as channel_mult")
self.num_res_blocks = num_res_blocks
if disable_self_attentions is not None:
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
assert len(disable_self_attentions) == len(channel_mult)
if num_attention_blocks is not None:
assert len(num_attention_blocks) == len(self.num_res_blocks)
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
f"attention will still not be set.")
self.attention_resolutions = attention_resolutions
self.dropout = dropout
self.channel_mult = channel_mult
self.conv_resample = conv_resample
self.num_classes = num_classes
self.use_checkpoint = use_checkpoint
self.dtype = torch.float16 if use_fp16 else torch.float32
self.num_heads = num_heads
self.num_head_channels = num_head_channels
self.num_heads_upsample = num_heads_upsample
self.predict_codebook_ids = n_embed is not None
time_embed_dim = model_channels * 4
self.time_embed = nn.Sequential(
linear(model_channels, time_embed_dim),
nn.SiLU(),
linear(time_embed_dim, time_embed_dim),
)
if self.num_classes is not None:
if isinstance(self.num_classes, int):
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
elif self.num_classes == "continuous":
print("setting up linear c_adm embedding layer")
self.label_emb = nn.Linear(1, time_embed_dim)
else:
raise ValueError()
self.input_blocks = nn.ModuleList(
[
| # from share import *
class Post_Process_Net(nn.Module):
def __init__(
self,
image_size,
in_channels,
model_channels,
out_channels,
num_res_blocks,
attention_resolutions,
dropout=0,
channel_mult=(1, 2, 4, 8),
conv_resample=True,
dims=2,
num_classes=None,
use_checkpoint=False,
use_fp16=False,
num_heads=-1,
num_head_channels=-1,
num_heads_upsample=-1,
use_scale_shift_norm=False,
resblock_updown=False,
use_new_attention_order=False,
use_spatial_transformer=False, # custom transformer support
transformer_depth=1, # custom transformer support
context_dim=None, # custom transformer support
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
legacy=True,
disable_self_attentions=None,
num_attention_blocks=None,
disable_middle_self_attn=False,
use_linear_in_transformer=False,
):
super().__init__()
self.image_size = image_size
self.in_channels = in_channels
self.model_channels = model_channels
self.out_channels = out_channels
if isinstance(num_res_blocks, int):
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
else:
if len(num_res_blocks) != len(channel_mult):
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
"as a list/tuple (per-level) with the same length as channel_mult")
self.num_res_blocks = num_res_blocks
if disable_self_attentions is not None:
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
assert len(disable_self_attentions) == len(channel_mult)
if num_attention_blocks is not None:
assert len(num_attention_blocks) == len(self.num_res_blocks)
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
f"attention will still not be set.")
self.attention_resolutions = attention_resolutions
self.dropout = dropout
self.channel_mult = channel_mult
self.conv_resample = conv_resample
self.num_classes = num_classes
self.use_checkpoint = use_checkpoint
self.dtype = torch.float16 if use_fp16 else torch.float32
self.num_heads = num_heads
self.num_head_channels = num_head_channels
self.num_heads_upsample = num_heads_upsample
self.predict_codebook_ids = n_embed is not None
time_embed_dim = model_channels * 4
self.time_embed = nn.Sequential(
linear(model_channels, time_embed_dim),
nn.SiLU(),
linear(time_embed_dim, time_embed_dim),
)
if self.num_classes is not None:
if isinstance(self.num_classes, int):
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
elif self.num_classes == "continuous":
print("setting up linear c_adm embedding layer")
self.label_emb = nn.Linear(1, time_embed_dim)
else:
raise ValueError()
self.input_blocks = nn.ModuleList(
[ | TimestepEmbedSequential( | 4 | 2023-10-19 05:08:12+00:00 | 8k |
facebookresearch/motif | rl_baseline/sample-factory/sample_factory/algorithms/appo/learner.py | [
{
"identifier": "encoders_nle",
"path": "rl_baseline/encoders_nle.py",
"snippet": "NUM_CHARS = 256\nPAD_CHAR = 0\n H = math.floor((H + 2*P - D*(K-1) - 1)/S + 1)\n W = math.floor((W + 2*P - D*(K-1) - 1)/S + 1)\n K = self.k_dim # number of input filters\n F = 3 # filt... | import csv
import glob
import os
import re
import shutil
import signal
import threading
import time
import numpy as np
import psutil
import torch
import torch.nn.functional as F
import gym
from collections import OrderedDict, deque
from os.path import join
from queue import Empty, Queue, Full
from threading import Thread
from typing import Tuple
from torch.nn.utils.rnn import PackedSequence, invert_permutation
from torch.multiprocessing import Process, Event as MultiprocessingEvent
from sample_factory.utils import Queue as MpQueue
from faster_fifo import Queue as MpQueue
from rl_baseline import encoders_nle
from rlaif.reward_model import create_reward_model
from sample_factory.algorithms.appo.appo_utils import TaskType, list_of_dicts_to_dict_of_lists, memory_stats, cuda_envvars_for_policy, \
TensorBatcher, iter_dicts_recursively, copy_dict_structure, ObjectPool
from sample_factory.algorithms.appo.model import create_actor_critic
from sample_factory.algorithms.appo.model_utils import create_encoder, normalize_obs
from sample_factory.algorithms.appo.aux_losses import CPCA
from sample_factory.algorithms.appo.population_based_training import PbtTask
from sample_factory.algorithms.utils.action_distributions import get_action_distribution, is_continuous_action_space
from sample_factory.algorithms.utils.algo_utils import calculate_gae, EPS
from sample_factory.algorithms.utils.pytorch_utils import to_scalar
from sample_factory.utils.decay import LinearDecay
from sample_factory.utils.timing import Timing
from sample_factory.utils.utils import log, AttrDict, experiment_dir, ensure_dir_exists, join_or_kill, safe_get, safe_put | 3,846 | if self.aux_loss_module is not None:
stats.aux_loss = var.aux_loss
stats.adv_min = var.adv.min()
stats.adv_max = var.adv.max()
stats.adv_std = var.adv_std
stats.max_abs_logprob = torch.abs(var.mb.action_logits).max()
if hasattr(var.action_distribution, 'summaries'):
stats.update(var.action_distribution.summaries())
if var.epoch == self.cfg.ppo_epochs - 1 and var.batch_num == len(var.minibatches) - 1:
# we collect these stats only for the last PPO batch, or every time if we're only doing one batch, IMPALA-style
ratio_mean = torch.abs(1.0 - var.ratio).mean().detach()
ratio_min = var.ratio.min().detach()
ratio_max = var.ratio.max().detach()
# log.debug('Learner %d ratio mean min max %.4f %.4f %.4f', self.policy_id, ratio_mean.cpu().item(), ratio_min.cpu().item(), ratio_max.cpu().item())
value_delta = torch.abs(var.values - var.old_values)
value_delta_avg, value_delta_max = value_delta.mean(), value_delta.max()
# calculate KL-divergence with the behaviour policy action distribution
old_action_distribution = get_action_distribution(
self.actor_critic.action_space, var.mb.action_logits,
)
kl_old = var.action_distribution.kl_divergence(old_action_distribution)
kl_old_mean = kl_old.mean()
stats.kl_divergence = kl_old_mean
stats.value_delta = value_delta_avg
stats.value_delta_max = value_delta_max
stats.fraction_clipped = ((var.ratio < var.clip_ratio_low).float() + (var.ratio > var.clip_ratio_high).float()).mean()
stats.ratio_mean = ratio_mean
stats.ratio_min = ratio_min
stats.ratio_max = ratio_max
stats.num_sgd_steps = var.num_sgd_steps
# this caused numerical issues on some versions of PyTorch with second moment reaching infinity
adam_max_second_moment = 0.0
for key, tensor_state in self.optimizer.state.items():
adam_max_second_moment = max(tensor_state['exp_avg_sq'].max().item(), adam_max_second_moment)
stats.adam_max_second_moment = adam_max_second_moment
version_diff = (var.curr_policy_version - var.mb.policy_version)[var.mb.policy_id == self.policy_id]
stats.version_diff_avg = version_diff.mean()
stats.version_diff_min = version_diff.min()
stats.version_diff_max = version_diff.max()
for key, value in stats.items():
stats[key] = to_scalar(value)
return stats
def _update_pbt(self):
"""To be called from the training loop, same thread that updates the model!"""
with self.pbt_mutex:
if self.load_policy_id is not None:
assert self.cfg.with_pbt
log.debug('Learner %d loads policy from %d', self.policy_id, self.load_policy_id)
self.load_from_checkpoint(self.load_policy_id)
self.load_policy_id = None
if self.new_cfg is not None:
for key, value in self.new_cfg.items():
if self.cfg[key] != value:
log.debug('Learner %d replacing cfg parameter %r with new value %r', self.policy_id, key, value)
self.cfg[key] = value
for param_group in self.optimizer.param_groups:
param_group['lr'] = self.cfg.learning_rate
param_group['betas'] = (self.cfg.adam_beta1, self.cfg.adam_beta2)
log.debug('Updated optimizer lr to value %.7f, betas: %r', param_group['lr'], param_group['betas'])
self.new_cfg = None
@staticmethod
def load_checkpoint(checkpoints, device, checkpoint_num=0):
if len(checkpoints) <= 0:
log.warning('No checkpoints found')
return None
else:
if checkpoint_num == 0:
checkpoints = sorted(checkpoints, key=lambda x: (int(re.search(r'_(\d+)\.pth', x).group(1)), x))
latest_checkpoint = checkpoints[-1]
else:
file_id = f"_{checkpoint_num}.pth"
filtered_list = [file_name for file_name in checkpoints if file_id in file_name]
assert len(filtered_list) > 0
latest_checkpoint = filtered_list[0]
# extra safety mechanism to recover from spurious filesystem errors
num_attempts = 3
for attempt in range(num_attempts):
try:
log.warning('Loading state from checkpoint %s...', latest_checkpoint)
checkpoint_dict = torch.load(latest_checkpoint, map_location=device)
return checkpoint_dict
except Exception:
log.exception(f'Could not load from checkpoint, attempt {attempt}')
def _load_state(self, checkpoint_dict, load_progress=True):
if load_progress:
self.train_step = checkpoint_dict['train_step']
self.env_steps = checkpoint_dict['env_steps']
self.actor_critic.load_state_dict(checkpoint_dict['model'])
self.optimizer.load_state_dict(checkpoint_dict['optimizer'])
if self.aux_loss_module is not None:
self.aux_loss_module.load_state_dict(checkpoint_dict['aux_loss_module'])
log.info('Loaded experiment state at training iteration %d, env step %d', self.train_step, self.env_steps)
def init_model(self, timing):
# Load the reward model
if self.cfg.llm_reward > 0.:
checkpoints = self.get_checkpoints(join(self.cfg.reward_dir, f'checkpoint_p0'))
assert len(checkpoints) > 0
checkpoint_dict = self.load_checkpoint(checkpoints, self.device, checkpoint_num=self.cfg.checkpoint_num)
# TODO: don't save/load actor and critic weights that are not used anyways. This would avoid importing gym here.
reward_action_space = checkpoint_dict['model']['action_parameterization.distribution_linear.bias'].shape[0]
| #Copyright (c) Meta Platforms, Inc. and affiliates.
torch.autograd.set_detect_anomaly(True)
if os.name == 'nt':
else:
# noinspection PyPep8Naming
def _build_pack_info_from_dones(dones: torch.Tensor, T: int) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Create the indexing info needed to make the PackedSequence based on the dones.
PackedSequences are PyTorch's way of supporting a single RNN forward
call where each input in the batch can have an arbitrary sequence length
They work as follows: Given the sequences [c], [x, y, z], [a, b],
we generate data [x, a, c, y, b, z] and batch_sizes [3, 2, 1]. The
data is a flattened out version of the input sequences (the ordering in
data is determined by sequence length). batch_sizes tells you that
for each index, how many sequences have a length of (index + 1) or greater.
This method will generate the new index ordering such that you can
construct the data for a PackedSequence from a (N*T, ...) tensor
via x.index_select(0, select_inds)
"""
num_samples = len(dones)
rollout_boundaries = dones.clone().detach()
rollout_boundaries[T - 1::T] = 1 # end of each rollout is the boundary
rollout_boundaries = rollout_boundaries.nonzero(as_tuple=False).squeeze(dim=1) + 1
first_len = rollout_boundaries[0].unsqueeze(0)
if len(rollout_boundaries) <= 1:
log.debug('Only one rollout boundary. This can happen if batch size is 1, probably not during the real training.')
rollout_lengths = first_len
else:
rollout_lengths = rollout_boundaries[1:] - rollout_boundaries[:-1]
rollout_lengths = torch.cat([first_len, rollout_lengths])
rollout_starts_orig = rollout_boundaries - rollout_lengths
# done=True for the last step in the episode, so done flags rolled 1 step to the right will indicate
# first frames in the episodes
is_new_episode = dones.clone().detach().view((-1, T))
is_new_episode = is_new_episode.roll(1, 1)
# roll() is cyclical, so done=True in the last position in the rollout will roll to 0th position
# we want to avoid it here. (note to self: is there a function that does two of these things at once?)
is_new_episode[:, 0] = 0
is_new_episode = is_new_episode.view((-1, ))
lengths, sorted_indices = torch.sort(rollout_lengths, descending=True)
# We will want these on the CPU for torch.unique_consecutive,
# so move now.
cpu_lengths = lengths.to(device='cpu', non_blocking=True)
# We need to keep the original unpermuted rollout_starts, because the permutation is later applied
# internally in the RNN implementation.
# From modules/rnn.py:
# Each batch of the hidden state should match the input sequence that
# the user believes he/she is passing in.
# hx = self.permute_hidden(hx, sorted_indices)
rollout_starts_sorted = rollout_starts_orig.index_select(0, sorted_indices)
select_inds = torch.empty(num_samples, device=dones.device, dtype=torch.int64)
max_length = int(cpu_lengths[0].item())
# batch_sizes is *always* on the CPU
batch_sizes = torch.empty((max_length,), device='cpu', dtype=torch.int64)
offset = 0
prev_len = 0
num_valid_for_length = lengths.size(0)
unique_lengths = torch.unique_consecutive(cpu_lengths)
# Iterate over all unique lengths in reverse as they sorted
# in decreasing order
for i in range(len(unique_lengths) - 1, -1, -1):
valids = lengths[0:num_valid_for_length] > prev_len
num_valid_for_length = int(valids.float().sum().item())
next_len = int(unique_lengths[i])
batch_sizes[prev_len:next_len] = num_valid_for_length
new_inds = (
rollout_starts_sorted[0:num_valid_for_length].view(1, num_valid_for_length)
+ torch.arange(prev_len, next_len, device=rollout_starts_sorted.device).view(next_len - prev_len, 1)
).view(-1)
# for a set of sequences [1, 2, 3], [4, 5], [6, 7], [8]
# these indices will be 1,4,6,8,2,5,7,3
# (all first steps in all trajectories, then all second steps, etc.)
select_inds[offset:offset + new_inds.numel()] = new_inds
offset += new_inds.numel()
prev_len = next_len
# Make sure we have an index for all elements
assert offset == num_samples
assert is_new_episode.shape[0] == num_samples
return rollout_starts_orig, is_new_episode, select_inds, batch_sizes, sorted_indices
def build_rnn_inputs(x, dones_cpu, rnn_states, T: int):
"""
Create a PackedSequence input for an RNN such that each
set of steps that are part of the same episode are all part of
a batch in the PackedSequence.
Use the returned select_inds and build_core_out_from_seq to invert this.
:param x: A (N*T, -1) tensor of the data to build the PackedSequence out of
:param dones_cpu: A (N*T) tensor where dones[i] == 1.0 indicates an episode is done, a CPU-bound tensor
:param rnn_states: A (N*T, -1) tensor of the rnn_hidden_states
:param T: The length of the rollout
:return: tuple(x_seq, rnn_states, select_inds)
WHERE
x_seq is the PackedSequence version of x to pass to the RNN
rnn_states are the corresponding rnn state, zeroed on the episode boundary
inverted_select_inds can be passed to build_core_out_from_seq so the RNN output can be retrieved
"""
rollout_starts, is_new_episode, select_inds, batch_sizes, sorted_indices = _build_pack_info_from_dones(dones_cpu, T)
inverted_select_inds = invert_permutation(select_inds)
def device(t):
return t.to(device=x.device)
select_inds = device(select_inds)
inverted_select_inds = device(inverted_select_inds)
sorted_indices = device(sorted_indices)
rollout_starts = device(rollout_starts)
is_new_episode = device(is_new_episode)
x_seq = PackedSequence(x.index_select(0, select_inds), batch_sizes, sorted_indices)
# We zero-out rnn states for timesteps at the beginning of the episode.
# rollout_starts are indices of all starts of sequences
# (which can be due to episode boundary or just boundary of a rollout)
# (1 - is_new_episode.view(-1, 1)).index_select(0, rollout_starts) gives us a zero for every beginning of
# the sequence that is actually also a start of a new episode, and by multiplying this RNN state by zero
# we ensure no information transfer across episode boundaries.
rnn_states = rnn_states.index_select(0, rollout_starts)
is_same_episode = (1 - is_new_episode.view(-1, 1)).index_select(0, rollout_starts)
rnn_states = rnn_states * is_same_episode
return x_seq, rnn_states, inverted_select_inds
def build_core_out_from_seq(x_seq: PackedSequence, inverted_select_inds):
return x_seq.data.index_select(0, inverted_select_inds)
class LearnerWorker:
def __init__(
self, worker_idx, policy_id, cfg, obs_space, action_space, report_queue, policy_worker_queues, shared_buffers,
policy_lock, resume_experience_collection_cv,
):
log.info('Initializing the learner %d for policy %d', worker_idx, policy_id)
self.worker_idx = worker_idx
self.policy_id = policy_id
self.cfg = cfg
# PBT-related stuff
self.should_save_model = True # set to true if we need to save the model to disk on the next training iteration
self.load_policy_id = None # non-None when we need to replace our parameters with another policy's parameters
self.pbt_mutex = None # deferred initialization
self.new_cfg = None # non-None when we need to update the learning hyperparameters
self.terminate = False
self.num_batches_processed = 0
self.obs_space = obs_space
self.action_space = action_space
self.shared_buffers = shared_buffers
# deferred initialization
self.rollout_tensors = None
self.policy_versions = None
self.stop_experience_collection = None
self.stop_experience_collection_num_msgs = self.resume_experience_collection_num_msgs = 0
self.device = None
self.actor_critic = None
self.aux_loss_module = None
self.optimizer = None
self.policy_lock = policy_lock
self.resume_experience_collection_cv = resume_experience_collection_cv
self.task_queue = MpQueue()
self.report_queue = report_queue
self.initialized_event = MultiprocessingEvent()
self.initialized_event.clear()
self.model_saved_event = MultiprocessingEvent()
self.model_saved_event.clear()
# queues corresponding to policy workers using the same policy
# we send weight updates via these queues
self.policy_worker_queues = policy_worker_queues
self.experience_buffer_queue = None # deferred initialization
self.tensor_batch_pool = self.tensor_batcher = None
self.with_training = True # set to False for debugging no-training regime
self.train_in_background = self.cfg.train_in_background_thread # set to False for debugging
self.training_thread = None
self.train_thread_initialized = None
self.is_training = False
self.train_step = self.env_steps = 0
self.cycle_count = 1
# decay rate at which summaries are collected
# save summaries every 20 seconds in the beginning, but decay to every 4 minutes in the limit, because we
# do not need frequent summaries for longer experiments
self.summary_rate_decay_seconds = LinearDecay([(0, 20), (100000, 120), (1000000, 240)])
self.last_summary_time = 0
self.last_saved_time = self.last_milestone_time = 0
self.discarded_experience_over_time = deque([], maxlen=30)
self.discarded_experience_timer = time.time()
self.num_discarded_rollouts = 0
self.process = Process(target=self._run, daemon=True)
if is_continuous_action_space(self.action_space) and self.cfg.exploration_loss == 'symmetric_kl':
raise NotImplementedError('KL-divergence exploration loss is not supported with '
'continuous action spaces. Use entropy exploration loss')
self.exploration_loss_func = None # deferred initialization
try:
reward_csv_file = f'{cfg.reward_dir}/reward_metrics/train_norm_quantiles.csv'
with open(reward_csv_file, 'r', newline='') as file:
csv_reader = csv.reader(file)
reward_quantile_info = list(csv_reader)
except:
raise FileNotFoundError('Reward quantiles file not found.')
if cfg.eps_threshold_quantile != '0.0':
quantile_index = np.where(np.array(reward_quantile_info[0]).astype(float) == cfg.eps_threshold_quantile)[0][0]
self.rew_eps_threshold = float(reward_quantile_info[-1][quantile_index])
else:
self.rew_eps_threshold = -1000
def start_process(self):
self.process.start()
def deferred_initialization(self):
self.rollout_tensors = self.shared_buffers.tensors
self.policy_versions = self.shared_buffers.policy_versions
self.stop_experience_collection = self.shared_buffers.stop_experience_collection
self.pbt_mutex = threading.Lock()
self.experience_buffer_queue = Queue()
self.tensor_batch_pool = ObjectPool()
self.tensor_batcher = TensorBatcher(self.tensor_batch_pool)
self.training_thread = Thread(target=self._train_loop) if self.train_in_background else None
self.train_thread_initialized = threading.Event()
if self.cfg.exploration_loss_coeff == 0.0:
self.exploration_loss_func = lambda action_distr, valids: 0.0
elif self.cfg.exploration_loss == 'entropy':
self.exploration_loss_func = self.entropy_exploration_loss
elif self.cfg.exploration_loss == 'symmetric_kl':
self.exploration_loss_func = self.symmetric_kl_exploration_loss
else:
raise NotImplementedError(f'{self.cfg.exploration_loss} not supported!')
def _init(self):
log.info('Waiting for the learner to initialize...')
self.train_thread_initialized.wait()
log.info('Learner %d initialized', self.worker_idx)
self.initialized_event.set()
def _terminate(self):
self.terminate = True
def _broadcast_model_weights(self):
state_dict = self.actor_critic.state_dict()
policy_version = self.train_step
log.debug('Broadcast model weights for model version %d', policy_version)
model_state = (policy_version, state_dict)
for q in self.policy_worker_queues:
q.put((TaskType.INIT_MODEL, model_state))
def _calculate_gae(self, buffer):
"""
Calculate advantages using Generalized Advantage Estimation.
This is leftover the from previous version of the algorithm.
Perhaps should be re-implemented in PyTorch tensors, similar to V-trace for uniformity.
"""
rewards = np.stack(buffer.rewards).squeeze() # [E, T]
dones = np.stack(buffer.dones).squeeze() # [E, T]
values_arr = np.stack(buffer.values).squeeze() # [E, T]
# calculating fake values for the last step in the rollout
# this will make sure that advantage of the very last action is always zero
values = []
for i in range(len(values_arr)):
last_value, last_reward = values_arr[i][-1], rewards[i, -1]
next_value = (last_value - last_reward) / self.cfg.gamma
values.append(list(values_arr[i]))
values[i].append(float(next_value)) # [T] -> [T+1]
# calculating returns and GAE
rewards = rewards.transpose((1, 0)) # [E, T] -> [T, E]
dones = dones.transpose((1, 0)) # [E, T] -> [T, E]
values = np.asarray(values).transpose((1, 0)) # [E, T+1] -> [T+1, E]
advantages, returns = calculate_gae(rewards, dones, values, self.cfg.gamma, self.cfg.gae_lambda)
# transpose tensors back to [E, T] before creating a single experience buffer
buffer.advantages = advantages.transpose((1, 0)) # [T, E] -> [E, T]
buffer.returns = returns.transpose((1, 0)) # [T, E] -> [E, T]
buffer.returns = buffer.returns[:, :, np.newaxis] # [E, T] -> [E, T, 1]
buffer.advantages = [torch.tensor(buffer.advantages).reshape(-1)]
buffer.returns = [torch.tensor(buffer.returns).reshape(-1)]
return buffer
def _prepare_train_buffer(self, rollouts, macro_batch_size, timing):
trajectories = [AttrDict(r['t']) for r in rollouts]
with timing.add_time('buffers'):
buffer = AttrDict()
# by the end of this loop the buffer is a dictionary containing lists of numpy arrays
for i, t in enumerate(trajectories):
for key, x in t.items():
if key not in buffer:
buffer[key] = []
buffer[key].append(x)
# convert lists of dict observations to a single dictionary of lists
for key, x in buffer.items():
if isinstance(x[0], (dict, OrderedDict)):
buffer[key] = list_of_dicts_to_dict_of_lists(x)
if not self.cfg.with_vtrace:
with timing.add_time('calc_gae'):
buffer = self._calculate_gae(buffer)
with timing.add_time('batching'):
# concatenate rollouts from different workers into a single batch efficiently
# that is, if we already have memory for the buffers allocated, we can just copy the data into
# existing cached tensors instead of creating new ones. This is a performance optimization.
use_pinned_memory = self.cfg.device == 'gpu'
buffer = self.tensor_batcher.cat(buffer, macro_batch_size, use_pinned_memory, timing)
with timing.add_time('buff_ready'):
self.shared_buffers.free_trajectory_buffers([r.traj_buffer_idx for r in rollouts])
with timing.add_time('tensors_gpu_float'):
device_buffer = self._copy_train_data_to_device(buffer)
with timing.add_time('squeeze'):
# will squeeze actions only in simple categorical case
tensors_to_squeeze = [
'actions', 'log_prob_actions', 'policy_version', 'policy_id', 'values',
'rewards', 'dones', 'rewards_cpu', 'dones_cpu',
]
for tensor_name in tensors_to_squeeze:
device_buffer[tensor_name].squeeze_()
# we no longer need the cached buffer, and can put it back into the pool
self.tensor_batch_pool.put(buffer)
return device_buffer
def _macro_batch_size(self, batch_size):
return self.cfg.num_batches_per_iteration * batch_size
def _process_macro_batch(self, rollouts, batch_size, timing):
macro_batch_size = self._macro_batch_size(batch_size)
assert macro_batch_size % self.cfg.rollout == 0
assert self.cfg.rollout % self.cfg.recurrence == 0
assert macro_batch_size % self.cfg.recurrence == 0
samples = env_steps = 0
for rollout in rollouts:
samples += rollout['length']
env_steps += rollout['env_steps']
with timing.add_time('prepare'):
buffer = self._prepare_train_buffer(rollouts, macro_batch_size, timing)
self.experience_buffer_queue.put((buffer, batch_size, samples, env_steps))
if not self.cfg.benchmark and self.cfg.train_in_background_thread:
# in PyTorch 1.4.0 there is an intense memory spike when the very first batch is being processed
# we wait here until this is over so we can continue queueing more batches onto a GPU without having
# a risk to run out of GPU memory
while self.num_batches_processed < 1:
# log.debug('Waiting for the first batch to be processed')
time.sleep(0.5)
def _process_rollouts(self, rollouts, timing):
# batch_size can potentially change through PBT, so we should keep it the same and pass it around
# using function arguments, instead of using global self.cfg
batch_size = self.cfg.batch_size
rollouts_in_macro_batch = self._macro_batch_size(batch_size) // self.cfg.rollout
if len(rollouts) < rollouts_in_macro_batch:
return rollouts
to_discard = 0
to_process = []
policy_version = self.train_step
for r in rollouts:
mask = r.t['policy_id'] == self.policy_id
if np.any(mask):
rollout_newest_version = r.t['policy_version'][mask].max().item()
else:
log.error(
'Learner %d got a rollout without any transitions produced by policy %d. This must be a bug.',
self.policy_id, self.policy_id,
)
log.error('Rollout policy ids: %r', r.t['policy_id'])
rollout_newest_version = policy_version - self.cfg.max_policy_lag
if policy_version - rollout_newest_version >= self.cfg.max_policy_lag:
# the entire rollout is too old, discard it!
to_discard += 1
self.shared_buffers.free_trajectory_buffers([r.traj_buffer_idx])
else:
# There is some experience in the rollout that we can learn from.
# Old experience (older than max policy lag), experience from other policies (in case of policy
# change on episode boundary), and experience from inactive agents (policy id = -1) will be masked
# out during loss calculations.
to_process.append(r)
if to_discard > 0:
log.warning(
'Discarding %d old rollouts, cut by policy lag threshold %d (learner %d)',
to_discard, self.cfg.max_policy_lag, self.policy_id,
)
rollouts = to_process
self.num_discarded_rollouts += to_discard
if len(rollouts) >= rollouts_in_macro_batch:
# process newest rollouts
rollouts_to_process = rollouts[:rollouts_in_macro_batch]
rollouts = rollouts[rollouts_in_macro_batch:]
self._process_macro_batch(rollouts_to_process, batch_size, timing)
# log.info('Unprocessed rollouts: %d (%d samples)', len(rollouts), len(rollouts) * self.cfg.rollout)
return rollouts
def _get_minibatches(self, batch_size, experience_size):
"""Generating minibatches for training."""
assert self.cfg.rollout % self.cfg.recurrence == 0
assert experience_size % batch_size == 0, f'experience size: {experience_size}, batch size: {batch_size}'
if self.cfg.num_batches_per_iteration == 1:
return [None] # single minibatch is actually the entire buffer, we don't need indices
# indices that will start the mini-trajectories from the same episode (for bptt)
indices = np.arange(0, experience_size, self.cfg.recurrence)
indices = np.random.permutation(indices)
# complete indices of mini trajectories, e.g. with recurrence==4: [4, 16] -> [4, 5, 6, 7, 16, 17, 18, 19]
indices = [np.arange(i, i + self.cfg.recurrence) for i in indices]
indices = np.concatenate(indices)
assert len(indices) == experience_size
num_minibatches = experience_size // batch_size
minibatches = np.split(indices, num_minibatches)
return minibatches
@staticmethod
def _get_minibatch(buffer, indices):
if indices is None:
# handle the case of a single batch, where the entire buffer is a minibatch
return buffer
mb = AttrDict()
for item, x in buffer.items():
if isinstance(x, (dict, OrderedDict)):
mb[item] = AttrDict()
for key, x_elem in x.items():
mb[item][key] = x_elem[indices]
else:
mb[item] = x[indices]
return mb
def _should_save_summaries(self):
summaries_every_seconds = self.summary_rate_decay_seconds.at(self.train_step)
if time.time() - self.last_summary_time < summaries_every_seconds:
return False
return True
def _after_optimizer_step(self):
"""A hook to be called after each optimizer step."""
self.train_step += 1
self._maybe_save()
def _maybe_save(self):
if self.env_steps > self.cfg.save_every_steps * self.cycle_count:
# Keep a separate condition for updating cycle_counts
self._save()
self.model_saved_event.set()
self.cycle_count += 1
@staticmethod
def checkpoint_dir(cfg, policy_id):
checkpoint_dir = join(experiment_dir(cfg=cfg), f'checkpoint_p{policy_id}')
return ensure_dir_exists(checkpoint_dir)
@staticmethod
def get_checkpoints(checkpoints_dir):
checkpoints = glob.glob(join(checkpoints_dir, 'checkpoint_*'))
return sorted(checkpoints)
def _get_checkpoint_dict(self):
checkpoint = {
'train_step': self.train_step,
'env_steps': self.env_steps,
'model': self.actor_critic.state_dict(),
'optimizer': self.optimizer.state_dict(),
}
if self.aux_loss_module is not None:
checkpoint['aux_loss_module'] = self.aux_loss_module.state_dict()
return checkpoint
def _save(self):
checkpoint = self._get_checkpoint_dict()
assert checkpoint is not None
checkpoint_dir = self.checkpoint_dir(self.cfg, self.policy_id)
tmp_filepath = join(checkpoint_dir, 'temp_checkpoint.pth')
checkpoint_name = f'checkpoint_{self.train_step:09d}_{self.env_steps}.pth'
filepath = join(checkpoint_dir, checkpoint_name)
log.info('Saving %s...', tmp_filepath)
torch.save(checkpoint, tmp_filepath)
log.info('Renaming %s to %s', tmp_filepath, filepath)
os.rename(tmp_filepath, filepath)
while len(self.get_checkpoints(checkpoint_dir)) > self.cfg.keep_checkpoints:
oldest_checkpoint = self.get_checkpoints(checkpoint_dir)[0]
if os.path.isfile(oldest_checkpoint):
log.debug('Removing %s', oldest_checkpoint)
os.remove(oldest_checkpoint)
if self.cfg.save_milestones_sec > 0:
# milestones enabled
if time.time() - self.last_milestone_time >= self.cfg.save_milestones_sec:
milestones_dir = ensure_dir_exists(join(checkpoint_dir, 'milestones'))
milestone_path = join(milestones_dir, f'{checkpoint_name}.milestone')
log.debug('Saving a milestone %s', milestone_path)
shutil.copy(filepath, milestone_path)
self.last_milestone_time = time.time()
@staticmethod
def _policy_loss(ratio, adv, clip_ratio_low, clip_ratio_high, valids):
clipped_ratio = torch.clamp(ratio, clip_ratio_low, clip_ratio_high)
loss_unclipped = ratio * adv
loss_clipped = clipped_ratio * adv
loss = torch.min(loss_unclipped, loss_clipped)
loss = torch.masked_select(loss, valids)
loss = -loss.mean()
return loss
def _value_loss(self, new_values, old_values, target, clip_value, valids):
value_clipped = old_values + torch.clamp(new_values - old_values, -clip_value, clip_value)
value_original_loss = (new_values - target).pow(2)
value_clipped_loss = (value_clipped - target).pow(2)
value_loss = torch.max(value_original_loss, value_clipped_loss)
value_loss = torch.masked_select(value_loss, valids)
value_loss = value_loss.mean()
value_loss *= self.cfg.value_loss_coeff
return value_loss
def entropy_exploration_loss(self, action_distribution, valids):
entropy = action_distribution.entropy()
entropy = torch.masked_select(entropy, valids)
entropy_loss = -self.cfg.exploration_loss_coeff * entropy.mean()
return entropy_loss
def symmetric_kl_exploration_loss(self, action_distribution, valids):
kl_prior = action_distribution.symmetric_kl_with_uniform_prior()
kl_prior = torch.masked_select(kl_prior, valids).mean()
if not torch.isfinite(kl_prior):
kl_prior = torch.zeros(kl_prior.shape)
kl_prior = torch.clamp(kl_prior, max=30)
kl_prior_loss = self.cfg.exploration_loss_coeff * kl_prior
return kl_prior_loss
def _prepare_observations(self, obs_tensors, gpu_buffer_obs):
for d, gpu_d, k, v, _ in iter_dicts_recursively(obs_tensors, gpu_buffer_obs):
device, dtype = self.actor_critic.device_and_type_for_input_tensor(k)
tensor = v.detach().to(device, copy=True).type(dtype)
gpu_d[k] = tensor
def _copy_train_data_to_device(self, buffer):
device_buffer = copy_dict_structure(buffer)
for key, item in buffer.items():
if key == 'obs':
self._prepare_observations(item, device_buffer['obs'])
else:
device_tensor = item.detach().to(self.device, copy=True, non_blocking=True)
device_buffer[key] = device_tensor.float()
device_buffer['dones_cpu'] = buffer.dones.to('cpu', copy=True, non_blocking=True).float()
device_buffer['rewards_cpu'] = buffer.rewards.to('cpu', copy=True, non_blocking=True).float()
return device_buffer
def _train(self, gpu_buffer, batch_size, experience_size, timing):
with torch.no_grad():
policy_version_before_train = self.train_step
early_stopping_tolerance = 1e-6
early_stop = False
prev_epoch_actor_loss = 1e9
epoch_actor_losses = []
# V-trace parameters
# noinspection PyArgumentList
rho_hat = torch.Tensor([self.cfg.vtrace_rho])
# noinspection PyArgumentList
c_hat = torch.Tensor([self.cfg.vtrace_c])
clip_ratio_high = 1.0 + self.cfg.ppo_clip_ratio # e.g. 1.1
# this still works with e.g. clip_ratio = 2, while PPO's 1-r would give negative ratio
clip_ratio_low = 1.0 / clip_ratio_high
clip_value = self.cfg.ppo_clip_value
gamma = self.cfg.gamma
recurrence = self.cfg.recurrence
if self.cfg.with_vtrace:
assert recurrence == self.cfg.rollout and recurrence > 1, \
'V-trace requires to recurrence and rollout to be equal'
num_sgd_steps = 0
stats_and_summaries = None
if not self.with_training:
return stats_and_summaries
for epoch in range(self.cfg.ppo_epochs):
with timing.add_time('epoch_init'):
if early_stop or self.terminate:
break
summary_this_epoch = force_summaries = False
minibatches = self._get_minibatches(batch_size, experience_size)
for batch_num in range(len(minibatches)):
with timing.add_time('minibatch_init'):
indices = minibatches[batch_num]
# current minibatch consisting of short trajectory segments with length == recurrence
mb = self._get_minibatch(gpu_buffer, indices)
# calculate policy head outside of recurrent loop
with timing.add_time('forward_head'):
head_outputs = self.actor_critic.forward_head(mb.obs)
if self.cfg.llm_reward > 0.:
# Don't normalize 'obs' since normalization happens in-place when calling self.actor_critic.forward_head
r_head_outputs = self.reward_model.forward_head(mb.obs, normalize=False)
# initial rnn states
with timing.add_time('bptt_initial'):
if self.cfg.use_rnn:
head_output_seq, rnn_states, inverted_select_inds = build_rnn_inputs(
head_outputs, mb.dones_cpu, mb.rnn_states, recurrence,
)
else:
rnn_states = mb.rnn_states[::recurrence]
# calculate RNN outputs for each timestep in a loop
with timing.add_time('bptt'):
if self.cfg.use_rnn:
with timing.add_time('bptt_forward_core'):
core_output_seq, _ = self.actor_critic.forward_core(head_output_seq, rnn_states)
core_outputs = build_core_out_from_seq(core_output_seq, inverted_select_inds)
else:
core_outputs, _ = self.actor_critic.forward_core(head_outputs, rnn_states)
if self.cfg.llm_reward > 0.:
r_core_outputs, _ = self.reward_model.forward_core(r_head_outputs, torch.zeros_like(rnn_states))
num_trajectories = head_outputs.size(0) // recurrence
with timing.add_time('tail'):
assert core_outputs.shape[0] == head_outputs.shape[0]
# calculate policy tail outside of recurrent loop
result = self.actor_critic.forward_tail(core_outputs, with_action_distribution=True)
action_distribution = result.action_distribution
log_prob_actions = action_distribution.log_prob(mb.actions)
ratio = torch.exp(log_prob_actions - mb.log_prob_actions) # pi / pi_old
# super large/small values can cause numerical problems and are probably noise anyway
ratio = torch.clamp(ratio, 0.05, 20.0)
values = result.values.squeeze()
with torch.no_grad(): # these computations are not the part of the computation graph
# ignore experience from other agents (i.e. on episode boundary) and from inactive agents
valids = mb.policy_id == self.policy_id
# ignore experience that was older than the threshold even before training started
valids = valids & (policy_version_before_train - mb.policy_version < self.cfg.max_policy_lag)
if self.cfg.with_vtrace:
ratios_cpu = ratio.cpu()
values_cpu = values.cpu()
dones_cpu = mb.dones_cpu
if self.cfg.llm_reward > 0.:
llm_reward = self.reward_model.reward_fn(r_core_outputs)
llm_rewards_cpu = llm_reward.detach().cpu().squeeze()
if self.cfg.rew_norm:
llm_rewards_cpu = (llm_rewards_cpu - self.reward_model.mean) / (self.reward_model.var)**(1/2)
llm_rewards_cpu = (llm_rewards_cpu > self.rew_eps_threshold) * llm_rewards_cpu
msg_count = mb.obs['msg_count'].squeeze().cpu()
msg_count_coeff = 1 / (msg_count ** (self.cfg.beta_count_exponent))
else:
llm_rewards_cpu = torch.zeros_like(mb.rewards_cpu)
msg_count_coeff = 0.0
rewards_cpu = (self.cfg.extrinsic_reward * mb.rewards_cpu
+ self.cfg.llm_reward * llm_rewards_cpu * msg_count_coeff)
vtrace_rho = torch.min(rho_hat, ratios_cpu)
vtrace_c = torch.min(c_hat, ratios_cpu)
vs = torch.zeros((num_trajectories * recurrence))
adv = torch.zeros((num_trajectories * recurrence))
next_values = (values_cpu[recurrence - 1::recurrence] - rewards_cpu[recurrence - 1::recurrence]) / gamma
next_vs = next_values
with timing.add_time('vtrace'):
for i in reversed(range(self.cfg.recurrence)):
rewards = rewards_cpu[i::recurrence]
dones = dones_cpu[i::recurrence]
not_done = 1.0 - dones
not_done_times_gamma = not_done * gamma
curr_values = values_cpu[i::recurrence]
curr_vtrace_rho = vtrace_rho[i::recurrence]
curr_vtrace_c = vtrace_c[i::recurrence]
delta_s = curr_vtrace_rho * (rewards + not_done_times_gamma * next_values - curr_values)
adv[i::recurrence] = curr_vtrace_rho * (rewards + not_done_times_gamma * next_vs - curr_values)
next_vs = curr_values + delta_s + not_done_times_gamma * curr_vtrace_c * (next_vs - next_values)
vs[i::recurrence] = next_vs
next_values = curr_values
targets = vs
else:
raise NotImplementedError
adv_mean = adv.mean()
adv_std = adv.std()
adv = (adv - adv_mean) / max(1e-3, adv_std) # normalize advantage
adv = adv.to(self.device)
with timing.add_time('losses'):
policy_loss = self._policy_loss(ratio, adv, clip_ratio_low, clip_ratio_high, valids)
exploration_loss = self.exploration_loss_func(action_distribution, valids)
actor_loss = policy_loss + exploration_loss
epoch_actor_losses.append(actor_loss.item())
targets = targets.to(self.device)
old_values = mb.values
value_loss = self._value_loss(values, old_values, targets, clip_value, valids)
critic_loss = value_loss
loss = actor_loss + critic_loss
if self.aux_loss_module is not None:
with timing.add_time('aux_loss'):
aux_loss = self.aux_loss_module(
mb.actions.view(num_trajectories, recurrence, -1),
(1.0 - mb.dones).view(num_trajectories, recurrence, 1),
valids.view(num_trajectories, recurrence, -1),
head_outputs.view(num_trajectories, recurrence, -1),
core_outputs.view(num_trajectories, recurrence, -1),
)
loss = loss + aux_loss
high_loss = 30.0
if abs(to_scalar(policy_loss)) > high_loss or abs(to_scalar(value_loss)) > high_loss or abs(to_scalar(exploration_loss)) > high_loss:
log.warning(
'High loss value: %.4f %.4f %.4f %.4f (recommended to adjust the --reward_scale parameter)',
to_scalar(loss), to_scalar(policy_loss), to_scalar(value_loss), to_scalar(exploration_loss),
)
force_summaries = True
# update the weights
with timing.add_time('update'):
# following advice from https://youtu.be/9mS1fIYj1So set grad to None instead of optimizer.zero_grad()
for p in self.actor_critic.parameters():
p.grad = None
if self.aux_loss_module is not None:
for p in self.aux_loss_module.parameters():
p.grad = None
loss.backward()
if self.cfg.max_grad_norm > 0.0:
with timing.add_time('clip'):
torch.nn.utils.clip_grad_norm_(self.actor_critic.parameters(), self.cfg.max_grad_norm)
if self.aux_loss_module is not None:
torch.nn.utils.clip_grad_norm_(self.aux_loss_module.parameters(), self.cfg.max_grad_norm)
curr_policy_version = self.train_step # policy version before the weight update
with self.policy_lock:
self.optimizer.step()
num_sgd_steps += 1
with torch.no_grad():
with timing.add_time('after_optimizer'):
self._after_optimizer_step()
# collect and report summaries
with_summaries = self._should_save_summaries() or force_summaries
if with_summaries and not summary_this_epoch:
stats_and_summaries = self._record_summaries(AttrDict(locals()))
summary_this_epoch = True
force_summaries = False
# end of an epoch
# this will force policy update on the inference worker (policy worker)
self.policy_versions[self.policy_id] = self.train_step
new_epoch_actor_loss = np.mean(epoch_actor_losses)
loss_delta_abs = abs(prev_epoch_actor_loss - new_epoch_actor_loss)
if loss_delta_abs < early_stopping_tolerance:
early_stop = True
log.debug(
'Early stopping after %d epochs (%d sgd steps), loss delta %.7f',
epoch + 1, num_sgd_steps, loss_delta_abs,
)
break
prev_epoch_actor_loss = new_epoch_actor_loss
epoch_actor_losses = []
return stats_and_summaries
def _record_summaries(self, train_loop_vars):
var = train_loop_vars
self.last_summary_time = time.time()
stats = AttrDict()
stats.valids_fraction = var.valids.float().mean()
stats.same_policy_fraction = (var.mb.policy_id == self.policy_id).float().mean()
grad_norm = sum(
p.grad.data.norm(2).item() ** 2
for p in self.actor_critic.parameters()
if p.grad is not None
) ** 0.5
stats.grad_norm = grad_norm
stats.loss = var.loss
stats.value = var.result.values.mean()
stats.entropy = var.action_distribution.entropy().mean()
stats.policy_loss = var.policy_loss
stats.value_loss = var.value_loss
stats.exploration_loss = var.exploration_loss
if self.aux_loss_module is not None:
stats.aux_loss = var.aux_loss
stats.adv_min = var.adv.min()
stats.adv_max = var.adv.max()
stats.adv_std = var.adv_std
stats.max_abs_logprob = torch.abs(var.mb.action_logits).max()
if hasattr(var.action_distribution, 'summaries'):
stats.update(var.action_distribution.summaries())
if var.epoch == self.cfg.ppo_epochs - 1 and var.batch_num == len(var.minibatches) - 1:
# we collect these stats only for the last PPO batch, or every time if we're only doing one batch, IMPALA-style
ratio_mean = torch.abs(1.0 - var.ratio).mean().detach()
ratio_min = var.ratio.min().detach()
ratio_max = var.ratio.max().detach()
# log.debug('Learner %d ratio mean min max %.4f %.4f %.4f', self.policy_id, ratio_mean.cpu().item(), ratio_min.cpu().item(), ratio_max.cpu().item())
value_delta = torch.abs(var.values - var.old_values)
value_delta_avg, value_delta_max = value_delta.mean(), value_delta.max()
# calculate KL-divergence with the behaviour policy action distribution
old_action_distribution = get_action_distribution(
self.actor_critic.action_space, var.mb.action_logits,
)
kl_old = var.action_distribution.kl_divergence(old_action_distribution)
kl_old_mean = kl_old.mean()
stats.kl_divergence = kl_old_mean
stats.value_delta = value_delta_avg
stats.value_delta_max = value_delta_max
stats.fraction_clipped = ((var.ratio < var.clip_ratio_low).float() + (var.ratio > var.clip_ratio_high).float()).mean()
stats.ratio_mean = ratio_mean
stats.ratio_min = ratio_min
stats.ratio_max = ratio_max
stats.num_sgd_steps = var.num_sgd_steps
# this caused numerical issues on some versions of PyTorch with second moment reaching infinity
adam_max_second_moment = 0.0
for key, tensor_state in self.optimizer.state.items():
adam_max_second_moment = max(tensor_state['exp_avg_sq'].max().item(), adam_max_second_moment)
stats.adam_max_second_moment = adam_max_second_moment
version_diff = (var.curr_policy_version - var.mb.policy_version)[var.mb.policy_id == self.policy_id]
stats.version_diff_avg = version_diff.mean()
stats.version_diff_min = version_diff.min()
stats.version_diff_max = version_diff.max()
for key, value in stats.items():
stats[key] = to_scalar(value)
return stats
def _update_pbt(self):
"""To be called from the training loop, same thread that updates the model!"""
with self.pbt_mutex:
if self.load_policy_id is not None:
assert self.cfg.with_pbt
log.debug('Learner %d loads policy from %d', self.policy_id, self.load_policy_id)
self.load_from_checkpoint(self.load_policy_id)
self.load_policy_id = None
if self.new_cfg is not None:
for key, value in self.new_cfg.items():
if self.cfg[key] != value:
log.debug('Learner %d replacing cfg parameter %r with new value %r', self.policy_id, key, value)
self.cfg[key] = value
for param_group in self.optimizer.param_groups:
param_group['lr'] = self.cfg.learning_rate
param_group['betas'] = (self.cfg.adam_beta1, self.cfg.adam_beta2)
log.debug('Updated optimizer lr to value %.7f, betas: %r', param_group['lr'], param_group['betas'])
self.new_cfg = None
@staticmethod
def load_checkpoint(checkpoints, device, checkpoint_num=0):
if len(checkpoints) <= 0:
log.warning('No checkpoints found')
return None
else:
if checkpoint_num == 0:
checkpoints = sorted(checkpoints, key=lambda x: (int(re.search(r'_(\d+)\.pth', x).group(1)), x))
latest_checkpoint = checkpoints[-1]
else:
file_id = f"_{checkpoint_num}.pth"
filtered_list = [file_name for file_name in checkpoints if file_id in file_name]
assert len(filtered_list) > 0
latest_checkpoint = filtered_list[0]
# extra safety mechanism to recover from spurious filesystem errors
num_attempts = 3
for attempt in range(num_attempts):
try:
log.warning('Loading state from checkpoint %s...', latest_checkpoint)
checkpoint_dict = torch.load(latest_checkpoint, map_location=device)
return checkpoint_dict
except Exception:
log.exception(f'Could not load from checkpoint, attempt {attempt}')
def _load_state(self, checkpoint_dict, load_progress=True):
if load_progress:
self.train_step = checkpoint_dict['train_step']
self.env_steps = checkpoint_dict['env_steps']
self.actor_critic.load_state_dict(checkpoint_dict['model'])
self.optimizer.load_state_dict(checkpoint_dict['optimizer'])
if self.aux_loss_module is not None:
self.aux_loss_module.load_state_dict(checkpoint_dict['aux_loss_module'])
log.info('Loaded experiment state at training iteration %d, env step %d', self.train_step, self.env_steps)
def init_model(self, timing):
# Load the reward model
if self.cfg.llm_reward > 0.:
checkpoints = self.get_checkpoints(join(self.cfg.reward_dir, f'checkpoint_p0'))
assert len(checkpoints) > 0
checkpoint_dict = self.load_checkpoint(checkpoints, self.device, checkpoint_num=self.cfg.checkpoint_num)
# TODO: don't save/load actor and critic weights that are not used anyways. This would avoid importing gym here.
reward_action_space = checkpoint_dict['model']['action_parameterization.distribution_linear.bias'].shape[0] | self.reward_model = create_reward_model(self.cfg, self.obs_space, gym.spaces.Discrete(reward_action_space), timing=timing) | 1 | 2023-10-24 17:45:26+00:00 | 8k |
pgorecki/lato | examples/example3/lagom_integration.py | [
{
"identifier": "Application",
"path": "lato/application.py",
"snippet": "class Application(ApplicationModule):\n dependency_provider_class = SimpleDependencyProvider\n\n def __init__(self, name=__name__, dependency_provider=None, **kwargs):\n super().__init__(name)\n self.dependency... | import uuid
import lagom.exceptions
from lagom import Container
from lato import Application, DependencyProvider, TransactionContext
from lato.dependency_provider import as_type | 3,635 |
class CorrelationId(uuid.UUID):
pass
class Name(str):
pass
class Session:
...
class Repository:
def __init__(self, session: Session):
self.session = session
class Engine:
def __init__(self, url):
self.url = url
def create_sesson(self):
return Session()
application_container = Container()
application_container[Name] = "Foo"
application_container[Engine] = Engine("sqlite:///:memory:")
class LagomDependencyProvider(DependencyProvider):
allow_names = False
def __init__(self, lagom_container):
self.container = lagom_container
def has_dependency(self, identifier: str | type) -> bool:
if type(identifier) is str:
return False
return identifier in self.container.defined_types
def register_dependency(self, identifier, dependency):
if type(identifier) is str:
raise ValueError(
f"Lagom container does not support string identifiers: {identifier}"
)
try:
self.container[identifier] = dependency
except lagom.exceptions.DuplicateDefinition:
pass
def get_dependency(self, identifier):
if type(identifier) is str:
raise ValueError(
f"Lagom container does not support string identifiers: {identifier}"
)
return self.container[identifier]
def copy(self, *args, **kwargs) -> DependencyProvider:
dp = LagomDependencyProvider(self.container.clone())
dp.update(*args, **kwargs)
return dp
dp1 = LagomDependencyProvider(application_container)
# make a copy
dp2 = dp1.copy()
# make sure that the original and the copy are the same
assert dp1[Name] == dp2[Name] == "Foo"
assert dp1[Engine] is dp2[Engine]
# create a copy with overriden value
dp3 = dp1.copy(name=as_type("Bar", Name)) # not yet implemented
# make sure that the original was not overriden
assert dp3[Name] == "Bar" and dp1[Name] == "Foo"
|
class CorrelationId(uuid.UUID):
pass
class Name(str):
pass
class Session:
...
class Repository:
def __init__(self, session: Session):
self.session = session
class Engine:
def __init__(self, url):
self.url = url
def create_sesson(self):
return Session()
application_container = Container()
application_container[Name] = "Foo"
application_container[Engine] = Engine("sqlite:///:memory:")
class LagomDependencyProvider(DependencyProvider):
allow_names = False
def __init__(self, lagom_container):
self.container = lagom_container
def has_dependency(self, identifier: str | type) -> bool:
if type(identifier) is str:
return False
return identifier in self.container.defined_types
def register_dependency(self, identifier, dependency):
if type(identifier) is str:
raise ValueError(
f"Lagom container does not support string identifiers: {identifier}"
)
try:
self.container[identifier] = dependency
except lagom.exceptions.DuplicateDefinition:
pass
def get_dependency(self, identifier):
if type(identifier) is str:
raise ValueError(
f"Lagom container does not support string identifiers: {identifier}"
)
return self.container[identifier]
def copy(self, *args, **kwargs) -> DependencyProvider:
dp = LagomDependencyProvider(self.container.clone())
dp.update(*args, **kwargs)
return dp
dp1 = LagomDependencyProvider(application_container)
# make a copy
dp2 = dp1.copy()
# make sure that the original and the copy are the same
assert dp1[Name] == dp2[Name] == "Foo"
assert dp1[Engine] is dp2[Engine]
# create a copy with overriden value
dp3 = dp1.copy(name=as_type("Bar", Name)) # not yet implemented
# make sure that the original was not overriden
assert dp3[Name] == "Bar" and dp1[Name] == "Foo"
| app = Application(dependency_provider=LagomDependencyProvider(application_container)) | 0 | 2023-10-21 11:33:05+00:00 | 8k |
NVIDIA/trt-llm-rag-windows | app.py | [
{
"identifier": "TrtLlmAPI",
"path": "trt_llama_api.py",
"snippet": "class TrtLlmAPI(CustomLLM):\n model_path: Optional[str] = Field(\n description=\"The path to the trt engine.\"\n )\n temperature: float = Field(description=\"The temperature to use for sampling.\")\n max_new_tokens: ... | import time
import gradio as gr
import argparse
from trt_llama_api import TrtLlmAPI #llama_index does not currently support TRT-LLM. The trt_llama_api.py file defines a llama_index compatible interface for TRT-LLM.
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from llama_index import LangchainEmbedding, ServiceContext
from llama_index.llms.llama_utils import messages_to_prompt, completion_to_prompt
from llama_index import set_global_service_context
from faiss_vector_storage import FaissEmbeddingStorage | 3,669 | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# 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.
# Create an argument parser
parser = argparse.ArgumentParser(description='NVIDIA Chatbot Parameters')
# Add arguments
parser.add_argument('--trt_engine_path', type=str, required=True,
help="Path to the TensorRT engine.", default="")
parser.add_argument('--trt_engine_name', type=str, required=True,
help="Name of the TensorRT engine.", default="")
parser.add_argument('--tokenizer_dir_path', type=str, required=True,
help="Directory path for the tokenizer.", default="")
parser.add_argument('--embedded_model', type=str,
help="Name or path of the embedded model. Defaults to 'sentence-transformers/all-MiniLM-L6-v2' if "
"not provided.",
default='sentence-transformers/all-MiniLM-L6-v2')
parser.add_argument('--data_dir', type=str, required=False,
help="Directory path for data.", default="./dataset")
parser.add_argument('--verbose', type=bool, required=False,
help="Enable verbose logging.", default=False)
# Parse the arguments
args = parser.parse_args()
# Use the provided arguments
trt_engine_path = args.trt_engine_path
trt_engine_name = args.trt_engine_name
tokenizer_dir_path = args.tokenizer_dir_path
embedded_model = args.embedded_model
data_dir = args.data_dir
verbose = args.verbose
# create trt_llm engine object
llm = TrtLlmAPI(
model_path=trt_engine_path,
engine_name=trt_engine_name,
tokenizer_dir=tokenizer_dir_path,
temperature=0.1,
max_new_tokens=1024,
context_window=3900,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
verbose=False
)
# create embeddings model object
embed_model = LangchainEmbedding(HuggingFaceEmbeddings(model_name=embedded_model))
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)
set_global_service_context(service_context)
# load the vectorstore index
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# 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.
# Create an argument parser
parser = argparse.ArgumentParser(description='NVIDIA Chatbot Parameters')
# Add arguments
parser.add_argument('--trt_engine_path', type=str, required=True,
help="Path to the TensorRT engine.", default="")
parser.add_argument('--trt_engine_name', type=str, required=True,
help="Name of the TensorRT engine.", default="")
parser.add_argument('--tokenizer_dir_path', type=str, required=True,
help="Directory path for the tokenizer.", default="")
parser.add_argument('--embedded_model', type=str,
help="Name or path of the embedded model. Defaults to 'sentence-transformers/all-MiniLM-L6-v2' if "
"not provided.",
default='sentence-transformers/all-MiniLM-L6-v2')
parser.add_argument('--data_dir', type=str, required=False,
help="Directory path for data.", default="./dataset")
parser.add_argument('--verbose', type=bool, required=False,
help="Enable verbose logging.", default=False)
# Parse the arguments
args = parser.parse_args()
# Use the provided arguments
trt_engine_path = args.trt_engine_path
trt_engine_name = args.trt_engine_name
tokenizer_dir_path = args.tokenizer_dir_path
embedded_model = args.embedded_model
data_dir = args.data_dir
verbose = args.verbose
# create trt_llm engine object
llm = TrtLlmAPI(
model_path=trt_engine_path,
engine_name=trt_engine_name,
tokenizer_dir=tokenizer_dir_path,
temperature=0.1,
max_new_tokens=1024,
context_window=3900,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
verbose=False
)
# create embeddings model object
embed_model = LangchainEmbedding(HuggingFaceEmbeddings(model_name=embedded_model))
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)
set_global_service_context(service_context)
# load the vectorstore index | faiss_storage = FaissEmbeddingStorage(data_dir=data_dir) | 1 | 2023-10-18 12:57:53+00:00 | 8k |
instadeepai/flashbax | flashbax/buffers/prioritised_trajectory_buffer_test.py | [
{
"identifier": "prioritised_trajectory_buffer",
"path": "flashbax/buffers/prioritised_trajectory_buffer.py",
"snippet": "SET_BATCH_FN = {\n \"tpu\": sum_tree.set_batch_bincount,\n \"gpu\": sum_tree.set_batch_bincount,\n \"cpu\": sum_tree.set_batch_scan,\n}\nclass PrioritisedTrajectoryBufferSta... | from copy import deepcopy
from typing import List
from flashbax.buffers import prioritised_trajectory_buffer, sum_tree, trajectory_buffer
from flashbax.buffers.conftest import get_fake_batch
from flashbax.conftest import _DEVICE_COUNT_MOCK
import chex
import jax
import jax.numpy as jnp
import numpy as np
import pytest | 3,879 |
# Check correct the shape prefix is correct.
chex.assert_trees_all_equal_dtypes(
fake_transition, batch1.experience, batch2.experience
)
@pytest.mark.parametrize("sample_period", [1, 2, 3, 4, 5])
def test_prioritised_sample_with_period(
fake_transition: chex.ArrayTree,
min_length: int,
max_length: int,
add_batch_size: int,
sample_sequence_length: int,
rng_key: chex.PRNGKey,
sample_batch_size: int,
sample_period: int,
device: str,
) -> None:
"""Test the random sampling with different periods."""
# Choose period based on the degree of overlap tested
assert sample_sequence_length >= sample_period
rng_key1, rng_key2 = jax.random.split(rng_key)
# Initialise the buffer
state = prioritised_trajectory_buffer.prioritised_init(
fake_transition, add_batch_size, max_length, sample_period
)
# Create a batch but specifically ensure that sequences in different add_batch rows
# are distinct - this is simply for testing purposes in order to verify periodicity
fake_batch_sequence = jax.tree_map(
lambda x: jnp.stack([x + i * (max_length - 1) for i in range(add_batch_size)]),
get_fake_batch(fake_transition, max_length - 1),
)
assert np.prod(fake_batch_sequence["reward"].shape) == np.prod(
jnp.unique(fake_batch_sequence["reward"]).shape
)
# Add the fake sequence to the buffer
state = prioritised_trajectory_buffer.prioritised_add(
state, fake_batch_sequence, sample_sequence_length, sample_period, device
)
assert trajectory_buffer.can_sample(state, min_length)
# Sample from the buffer
batch1 = prioritised_trajectory_buffer.prioritised_sample(
state, rng_key1, sample_batch_size, sample_sequence_length, sample_period
)
# Check correct the shape prefix is correct.
chex.assert_tree_shape_prefix(
batch1.experience, (sample_batch_size, sample_sequence_length)
)
# Check that the initial value in each sequence is always in a position that is a
# multiple of the sample period or zero.
# We check each sequence compared to every other sequence.
for i in range(sample_batch_size):
equal = batch1.experience["reward"][i][0] == batch1.experience["reward"] # type: ignore
pos = jnp.argmax(equal, axis=1)
test = (pos % sample_period == 0).astype(jnp.int32) + (pos == 0).astype(
jnp.int32
)
assert jnp.all(test.astype(jnp.bool_))
def test_adjust_priorities(
fake_transition: chex.ArrayTree,
min_length: int,
max_length: int,
rng_key: chex.PRNGKey,
add_batch_size: int,
sample_sequence_length: int,
sample_batch_size: int,
sample_period: int,
priority_exponent: float,
device: str,
) -> None:
"""Test the adjustment of priorities in the buffer."""
rng_key1, rng_key2 = jax.random.split(rng_key)
state = prioritised_trajectory_buffer.prioritised_init(
fake_transition,
add_batch_size,
max_length,
sample_period,
)
# Fill buffer to the point that we can sample.
fake_batch_sequence = get_fake_batch_sequence(
fake_transition, add_batch_size, min_length + 10
)
state = prioritised_trajectory_buffer.prioritised_add(
state, fake_batch_sequence, sample_sequence_length, sample_period, device
)
# Sample from the buffer.
batch = prioritised_trajectory_buffer.prioritised_sample(
state, rng_key1, sample_batch_size, sample_sequence_length, sample_period
)
# Create fake new priorities, and apply the adjustment.
new_priorities = jnp.ones_like(batch.priorities) + 10007
state = prioritised_trajectory_buffer.set_priorities(
state, batch.indices, new_priorities, priority_exponent, device
)
# Check that this results in the correct changes to the state.
assert (
state.priority_state.max_recorded_priority
== jnp.max(new_priorities) ** priority_exponent
)
assert (
| # Copyright 2023 InstaDeep Ltd. 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.
@pytest.fixture()
def sample_sequence_length() -> int:
return 5
@pytest.fixture()
def add_sequence_length() -> int:
return 7
@pytest.fixture()
def sample_period() -> int:
return 3
@pytest.fixture()
def priority_exponent() -> float:
return 0.6
@pytest.fixture()
def device() -> str:
return "tpu"
@pytest.fixture()
def prioritised_state(
fake_transition: chex.ArrayTree,
max_length: int,
add_batch_size: int,
sample_period: int,
) -> prioritised_trajectory_buffer.PrioritisedTrajectoryBufferState:
"""Initialise the trajectory buffer state."""
return prioritised_trajectory_buffer.prioritised_init(
fake_transition,
add_batch_size,
max_length,
sample_period,
)
def get_fake_batch_sequence(
fake_transition: chex.ArrayTree, batch_size: int, sequence_length: int
) -> chex.ArrayTree:
return get_fake_batch(get_fake_batch(fake_transition, sequence_length), batch_size)
def test_add_and_can_sample_prioritised(
prioritised_state: prioritised_trajectory_buffer.PrioritisedTrajectoryBufferState,
fake_transition: chex.ArrayTree,
min_length: int,
max_length: int,
add_batch_size: int,
add_sequence_length: int,
sample_sequence_length: int,
sample_period: int,
device: str,
) -> None:
"""Check the `add` function by filling the buffer all
the way to the max_length and checking that it produces the expected behaviour .
"""
fake_batch_sequence = get_fake_batch_sequence(
fake_transition, add_batch_size, add_sequence_length
)
init_state = deepcopy(prioritised_state) # Save for later checks.
n_batches_to_fill = int(np.ceil(max_length / add_sequence_length))
n_batches_to_sample = int(np.ceil(min_length / add_sequence_length))
for i in range(n_batches_to_fill):
assert not prioritised_state.is_full
prioritised_state = prioritised_trajectory_buffer.prioritised_add(
prioritised_state,
fake_batch_sequence,
sample_sequence_length,
sample_period,
device,
)
num_added_timesteps = (i + 1) * add_sequence_length
assert prioritised_state.current_index == (num_added_timesteps % max_length)
# Check that the `can_sample` function behavior is correct.
is_ready_to_sample = trajectory_buffer.can_sample(prioritised_state, min_length)
if i < (n_batches_to_sample - 1):
assert not is_ready_to_sample
else:
assert is_ready_to_sample
assert prioritised_state.is_full
# Check that the trajectorys have been updated.
with pytest.raises(AssertionError):
chex.assert_trees_all_close(prioritised_state.experience, init_state.experience)
def test_prioritised_sample(
prioritised_state: prioritised_trajectory_buffer.PrioritisedTrajectoryBufferState,
fake_transition: chex.ArrayTree,
min_length: int,
add_batch_size: int,
sample_sequence_length: int,
rng_key: chex.PRNGKey,
sample_batch_size: int,
sample_period: int,
device: str,
) -> None:
"""Test the random sampling from the buffer."""
rng_key1, rng_key2 = jax.random.split(rng_key)
# Fill buffer to the point that we can sample
fake_batch_sequence = get_fake_batch_sequence(
fake_transition, add_batch_size, min_length + 10
)
prioritised_state = prioritised_trajectory_buffer.prioritised_add(
prioritised_state,
fake_batch_sequence,
sample_sequence_length,
sample_period,
device,
)
assert trajectory_buffer.can_sample(prioritised_state, min_length)
# Sample from the buffer with different keys and check it gives us different batches.
batch1 = prioritised_trajectory_buffer.prioritised_sample(
prioritised_state,
rng_key1,
sample_batch_size,
sample_sequence_length,
sample_period,
)
batch2 = prioritised_trajectory_buffer.prioritised_sample(
prioritised_state,
rng_key2,
sample_batch_size,
sample_sequence_length,
sample_period,
)
# Check that the trajectorys have been updated.
with pytest.raises(AssertionError):
chex.assert_trees_all_close(batch1, batch2)
assert (batch1.priorities > 0).all()
assert (batch2.priorities > 0).all()
# Check correct the shape prefix is correct.
chex.assert_trees_all_equal_dtypes(
fake_transition, batch1.experience, batch2.experience
)
@pytest.mark.parametrize("sample_period", [1, 2, 3, 4, 5])
def test_prioritised_sample_with_period(
fake_transition: chex.ArrayTree,
min_length: int,
max_length: int,
add_batch_size: int,
sample_sequence_length: int,
rng_key: chex.PRNGKey,
sample_batch_size: int,
sample_period: int,
device: str,
) -> None:
"""Test the random sampling with different periods."""
# Choose period based on the degree of overlap tested
assert sample_sequence_length >= sample_period
rng_key1, rng_key2 = jax.random.split(rng_key)
# Initialise the buffer
state = prioritised_trajectory_buffer.prioritised_init(
fake_transition, add_batch_size, max_length, sample_period
)
# Create a batch but specifically ensure that sequences in different add_batch rows
# are distinct - this is simply for testing purposes in order to verify periodicity
fake_batch_sequence = jax.tree_map(
lambda x: jnp.stack([x + i * (max_length - 1) for i in range(add_batch_size)]),
get_fake_batch(fake_transition, max_length - 1),
)
assert np.prod(fake_batch_sequence["reward"].shape) == np.prod(
jnp.unique(fake_batch_sequence["reward"]).shape
)
# Add the fake sequence to the buffer
state = prioritised_trajectory_buffer.prioritised_add(
state, fake_batch_sequence, sample_sequence_length, sample_period, device
)
assert trajectory_buffer.can_sample(state, min_length)
# Sample from the buffer
batch1 = prioritised_trajectory_buffer.prioritised_sample(
state, rng_key1, sample_batch_size, sample_sequence_length, sample_period
)
# Check correct the shape prefix is correct.
chex.assert_tree_shape_prefix(
batch1.experience, (sample_batch_size, sample_sequence_length)
)
# Check that the initial value in each sequence is always in a position that is a
# multiple of the sample period or zero.
# We check each sequence compared to every other sequence.
for i in range(sample_batch_size):
equal = batch1.experience["reward"][i][0] == batch1.experience["reward"] # type: ignore
pos = jnp.argmax(equal, axis=1)
test = (pos % sample_period == 0).astype(jnp.int32) + (pos == 0).astype(
jnp.int32
)
assert jnp.all(test.astype(jnp.bool_))
def test_adjust_priorities(
fake_transition: chex.ArrayTree,
min_length: int,
max_length: int,
rng_key: chex.PRNGKey,
add_batch_size: int,
sample_sequence_length: int,
sample_batch_size: int,
sample_period: int,
priority_exponent: float,
device: str,
) -> None:
"""Test the adjustment of priorities in the buffer."""
rng_key1, rng_key2 = jax.random.split(rng_key)
state = prioritised_trajectory_buffer.prioritised_init(
fake_transition,
add_batch_size,
max_length,
sample_period,
)
# Fill buffer to the point that we can sample.
fake_batch_sequence = get_fake_batch_sequence(
fake_transition, add_batch_size, min_length + 10
)
state = prioritised_trajectory_buffer.prioritised_add(
state, fake_batch_sequence, sample_sequence_length, sample_period, device
)
# Sample from the buffer.
batch = prioritised_trajectory_buffer.prioritised_sample(
state, rng_key1, sample_batch_size, sample_sequence_length, sample_period
)
# Create fake new priorities, and apply the adjustment.
new_priorities = jnp.ones_like(batch.priorities) + 10007
state = prioritised_trajectory_buffer.set_priorities(
state, batch.indices, new_priorities, priority_exponent, device
)
# Check that this results in the correct changes to the state.
assert (
state.priority_state.max_recorded_priority
== jnp.max(new_priorities) ** priority_exponent
)
assert ( | sum_tree.get(state.priority_state, batch.indices) | 1 | 2023-10-17 10:57:14+00:00 | 8k |
TheDuckAI/DuckTrack | ducktrack/app.py | [
{
"identifier": "close_obs",
"path": "ducktrack/obs_client.py",
"snippet": "def close_obs(obs_process: subprocess.Popen):\n if obs_process:\n obs_process.terminate()\n try:\n obs_process.wait(timeout=5)\n except subprocess.TimeoutExpired:\n obs_process.kill(... | import os
import sys
from platform import system
from PyQt6.QtCore import QTimer, pyqtSlot
from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog,
QFormLayout, QLabel, QLineEdit, QMenu,
QMessageBox, QPushButton, QSystemTrayIcon,
QTextEdit, QVBoxLayout, QWidget)
from .obs_client import close_obs, is_obs_running, open_obs
from .playback import Player, get_latest_recording
from .recorder import Recorder
from .util import get_recordings_dir, open_file | 3,919 | self.setWindowTitle("Recording Details")
layout = QVBoxLayout(self)
self.form_layout = QFormLayout()
self.title_label = QLabel("Title:")
self.title_input = QLineEdit(self)
self.form_layout.addRow(self.title_label, self.title_input)
self.description_label = QLabel("Description:")
self.description_input = QTextEdit(self)
self.form_layout.addRow(self.description_label, self.description_input)
layout.addLayout(self.form_layout)
self.submit_button = QPushButton("Save", self)
self.submit_button.clicked.connect(self.accept)
layout.addWidget(self.submit_button)
def get_values(self):
return self.title_input.text(), self.description_input.toPlainText()
class MainInterface(QWidget):
def __init__(self, app: QApplication):
super().__init__()
self.tray = QSystemTrayIcon(QIcon(resource_path("assets/duck.png")))
self.tray.show()
self.app = app
self.init_tray()
self.init_window()
if not is_obs_running():
self.obs_process = open_obs()
def init_window(self):
self.setWindowTitle("DuckTrack")
layout = QVBoxLayout(self)
self.toggle_record_button = QPushButton("Start Recording", self)
self.toggle_record_button.clicked.connect(self.toggle_record)
layout.addWidget(self.toggle_record_button)
self.toggle_pause_button = QPushButton("Pause Recording", self)
self.toggle_pause_button.clicked.connect(self.toggle_pause)
self.toggle_pause_button.setEnabled(False)
layout.addWidget(self.toggle_pause_button)
self.show_recordings_button = QPushButton("Show Recordings", self)
self.show_recordings_button.clicked.connect(lambda: open_file(get_recordings_dir()))
layout.addWidget(self.show_recordings_button)
self.play_latest_button = QPushButton("Play Latest Recording", self)
self.play_latest_button.clicked.connect(self.play_latest_recording)
layout.addWidget(self.play_latest_button)
self.play_custom_button = QPushButton("Play Custom Recording", self)
self.play_custom_button.clicked.connect(self.play_custom_recording)
layout.addWidget(self.play_custom_button)
self.replay_recording_button = QPushButton("Replay Recording", self)
self.replay_recording_button.clicked.connect(self.replay_recording)
self.replay_recording_button.setEnabled(False)
layout.addWidget(self.replay_recording_button)
self.quit_button = QPushButton("Quit", self)
self.quit_button.clicked.connect(self.quit)
layout.addWidget(self.quit_button)
self.natural_scrolling_checkbox = QCheckBox("Natural Scrolling", self, checked=system() == "Darwin")
layout.addWidget(self.natural_scrolling_checkbox)
self.natural_scrolling_checkbox.stateChanged.connect(self.toggle_natural_scrolling)
self.setLayout(layout)
def init_tray(self):
self.menu = QMenu()
self.tray.setContextMenu(self.menu)
self.toggle_record_action = QAction("Start Recording")
self.toggle_record_action.triggered.connect(self.toggle_record)
self.menu.addAction(self.toggle_record_action)
self.toggle_pause_action = QAction("Pause Recording")
self.toggle_pause_action.triggered.connect(self.toggle_pause)
self.toggle_pause_action.setVisible(False)
self.menu.addAction(self.toggle_pause_action)
self.show_recordings_action = QAction("Show Recordings")
self.show_recordings_action.triggered.connect(lambda: open_file(get_recordings_dir()))
self.menu.addAction(self.show_recordings_action)
self.play_latest_action = QAction("Play Latest Recording")
self.play_latest_action.triggered.connect(self.play_latest_recording)
self.menu.addAction(self.play_latest_action)
self.play_custom_action = QAction("Play Custom Recording")
self.play_custom_action.triggered.connect(self.play_custom_recording)
self.menu.addAction(self.play_custom_action)
self.replay_recording_action = QAction("Replay Recording")
self.replay_recording_action.triggered.connect(self.replay_recording)
self.menu.addAction(self.replay_recording_action)
self.replay_recording_action.setVisible(False)
self.quit_action = QAction("Quit")
self.quit_action.triggered.connect(self.quit)
self.menu.addAction(self.quit_action)
self.menu.addSeparator()
self.natural_scrolling_option = QAction("Natural Scrolling", checkable=True, checked=system() == "Darwin")
self.natural_scrolling_option.triggered.connect(self.toggle_natural_scrolling)
self.menu.addAction(self.natural_scrolling_option)
@pyqtSlot()
def replay_recording(self):
|
class TitleDescriptionDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Recording Details")
layout = QVBoxLayout(self)
self.form_layout = QFormLayout()
self.title_label = QLabel("Title:")
self.title_input = QLineEdit(self)
self.form_layout.addRow(self.title_label, self.title_input)
self.description_label = QLabel("Description:")
self.description_input = QTextEdit(self)
self.form_layout.addRow(self.description_label, self.description_input)
layout.addLayout(self.form_layout)
self.submit_button = QPushButton("Save", self)
self.submit_button.clicked.connect(self.accept)
layout.addWidget(self.submit_button)
def get_values(self):
return self.title_input.text(), self.description_input.toPlainText()
class MainInterface(QWidget):
def __init__(self, app: QApplication):
super().__init__()
self.tray = QSystemTrayIcon(QIcon(resource_path("assets/duck.png")))
self.tray.show()
self.app = app
self.init_tray()
self.init_window()
if not is_obs_running():
self.obs_process = open_obs()
def init_window(self):
self.setWindowTitle("DuckTrack")
layout = QVBoxLayout(self)
self.toggle_record_button = QPushButton("Start Recording", self)
self.toggle_record_button.clicked.connect(self.toggle_record)
layout.addWidget(self.toggle_record_button)
self.toggle_pause_button = QPushButton("Pause Recording", self)
self.toggle_pause_button.clicked.connect(self.toggle_pause)
self.toggle_pause_button.setEnabled(False)
layout.addWidget(self.toggle_pause_button)
self.show_recordings_button = QPushButton("Show Recordings", self)
self.show_recordings_button.clicked.connect(lambda: open_file(get_recordings_dir()))
layout.addWidget(self.show_recordings_button)
self.play_latest_button = QPushButton("Play Latest Recording", self)
self.play_latest_button.clicked.connect(self.play_latest_recording)
layout.addWidget(self.play_latest_button)
self.play_custom_button = QPushButton("Play Custom Recording", self)
self.play_custom_button.clicked.connect(self.play_custom_recording)
layout.addWidget(self.play_custom_button)
self.replay_recording_button = QPushButton("Replay Recording", self)
self.replay_recording_button.clicked.connect(self.replay_recording)
self.replay_recording_button.setEnabled(False)
layout.addWidget(self.replay_recording_button)
self.quit_button = QPushButton("Quit", self)
self.quit_button.clicked.connect(self.quit)
layout.addWidget(self.quit_button)
self.natural_scrolling_checkbox = QCheckBox("Natural Scrolling", self, checked=system() == "Darwin")
layout.addWidget(self.natural_scrolling_checkbox)
self.natural_scrolling_checkbox.stateChanged.connect(self.toggle_natural_scrolling)
self.setLayout(layout)
def init_tray(self):
self.menu = QMenu()
self.tray.setContextMenu(self.menu)
self.toggle_record_action = QAction("Start Recording")
self.toggle_record_action.triggered.connect(self.toggle_record)
self.menu.addAction(self.toggle_record_action)
self.toggle_pause_action = QAction("Pause Recording")
self.toggle_pause_action.triggered.connect(self.toggle_pause)
self.toggle_pause_action.setVisible(False)
self.menu.addAction(self.toggle_pause_action)
self.show_recordings_action = QAction("Show Recordings")
self.show_recordings_action.triggered.connect(lambda: open_file(get_recordings_dir()))
self.menu.addAction(self.show_recordings_action)
self.play_latest_action = QAction("Play Latest Recording")
self.play_latest_action.triggered.connect(self.play_latest_recording)
self.menu.addAction(self.play_latest_action)
self.play_custom_action = QAction("Play Custom Recording")
self.play_custom_action.triggered.connect(self.play_custom_recording)
self.menu.addAction(self.play_custom_action)
self.replay_recording_action = QAction("Replay Recording")
self.replay_recording_action.triggered.connect(self.replay_recording)
self.menu.addAction(self.replay_recording_action)
self.replay_recording_action.setVisible(False)
self.quit_action = QAction("Quit")
self.quit_action.triggered.connect(self.quit)
self.menu.addAction(self.quit_action)
self.menu.addSeparator()
self.natural_scrolling_option = QAction("Natural Scrolling", checkable=True, checked=system() == "Darwin")
self.natural_scrolling_option.triggered.connect(self.toggle_natural_scrolling)
self.menu.addAction(self.natural_scrolling_option)
@pyqtSlot()
def replay_recording(self): | player = Player() | 3 | 2023-10-18 19:34:19+00:00 | 8k |
e4s2023/E4S2023 | swap_face_fine/face_vid2vid/modules/generator.py | [
{
"identifier": "ResBlock2d",
"path": "swap_face_fine/face_vid2vid/modules/util.py",
"snippet": "class ResBlock2d(nn.Module):\n \"\"\"\n Res block, preserve spatial resolution.\n \"\"\"\n\n def __init__(self, in_features, kernel_size, padding):\n super(ResBlock2d, self).__init__()\n ... | import torch
import torch.nn.functional as F
from torch import nn
from swap_face_fine.face_vid2vid.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from swap_face_fine.face_vid2vid.modules.dense_motion import DenseMotionNetwork | 4,015 |
class OcclusionAwareGenerator(nn.Module):
"""
Generator follows NVIDIA architecture.
"""
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_params=None, estimate_jacobian=False):
super(OcclusionAwareGenerator, self).__init__()
if dense_motion_params is not None:
self.dense_motion_network = DenseMotionNetwork(num_kp=num_kp, feature_channel=feature_channel,
estimate_occlusion_map=estimate_occlusion_map,
**dense_motion_params)
else:
self.dense_motion_network = None
self.first = SameBlock2d(image_channel, block_expansion, kernel_size=(7, 7), padding=(3, 3))
down_blocks = []
for i in range(num_down_blocks):
in_features = min(max_features, block_expansion * (2 ** i))
out_features = min(max_features, block_expansion * (2 ** (i + 1)))
down_blocks.append(DownBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
self.down_blocks = nn.ModuleList(down_blocks)
self.second = nn.Conv2d(in_channels=out_features, out_channels=max_features, kernel_size=1, stride=1)
self.reshape_channel = reshape_channel
self.reshape_depth = reshape_depth
self.resblocks_3d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_3d.add_module('3dr' + str(i), ResBlock3d(reshape_channel, kernel_size=3, padding=1))
out_features = block_expansion * (2 ** (num_down_blocks))
self.third = SameBlock2d(max_features, out_features, kernel_size=(3, 3), padding=(1, 1), lrelu=True)
self.fourth = nn.Conv2d(in_channels=out_features, out_channels=out_features, kernel_size=1, stride=1)
self.resblocks_2d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_2d.add_module('2dr' + str(i), ResBlock2d(out_features, kernel_size=3, padding=1))
up_blocks = []
for i in range(num_down_blocks):
in_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i)))
out_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i - 1)))
|
class OcclusionAwareGenerator(nn.Module):
"""
Generator follows NVIDIA architecture.
"""
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_params=None, estimate_jacobian=False):
super(OcclusionAwareGenerator, self).__init__()
if dense_motion_params is not None:
self.dense_motion_network = DenseMotionNetwork(num_kp=num_kp, feature_channel=feature_channel,
estimate_occlusion_map=estimate_occlusion_map,
**dense_motion_params)
else:
self.dense_motion_network = None
self.first = SameBlock2d(image_channel, block_expansion, kernel_size=(7, 7), padding=(3, 3))
down_blocks = []
for i in range(num_down_blocks):
in_features = min(max_features, block_expansion * (2 ** i))
out_features = min(max_features, block_expansion * (2 ** (i + 1)))
down_blocks.append(DownBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
self.down_blocks = nn.ModuleList(down_blocks)
self.second = nn.Conv2d(in_channels=out_features, out_channels=max_features, kernel_size=1, stride=1)
self.reshape_channel = reshape_channel
self.reshape_depth = reshape_depth
self.resblocks_3d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_3d.add_module('3dr' + str(i), ResBlock3d(reshape_channel, kernel_size=3, padding=1))
out_features = block_expansion * (2 ** (num_down_blocks))
self.third = SameBlock2d(max_features, out_features, kernel_size=(3, 3), padding=(1, 1), lrelu=True)
self.fourth = nn.Conv2d(in_channels=out_features, out_channels=out_features, kernel_size=1, stride=1)
self.resblocks_2d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_2d.add_module('2dr' + str(i), ResBlock2d(out_features, kernel_size=3, padding=1))
up_blocks = []
for i in range(num_down_blocks):
in_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i)))
out_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i - 1))) | up_blocks.append(UpBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1))) | 2 | 2023-10-15 12:15:01+00:00 | 8k |
lancopku/label-words-are-anchors | icl/analysis/compress_top.py | [
{
"identifier": "LMForwardAPI",
"path": "icl/lm_apis/lm_api_base.py",
"snippet": "class LMForwardAPI(nn.Module):\n def __init__(self, model, model_name, tokenizer, label_dict: Dict[int, str], device='cuda:0'):\n super().__init__()\n self._use_past_key_values = False\n self._past_... | import pickle
import random
import warnings
import os
import numpy as np
import torch
import torch.nn.functional as F
from dataclasses import dataclass, field
from typing import List
from transformers.hf_argparser import HfArgumentParser
from sklearn.metrics import accuracy_score
from .prefixier import Prefixer
from ..lm_apis.lm_api_base import LMForwardAPI
from ..util_classes.context_solver import ContextSolver
from ..util_classes.predictor_classes import Predictor
from ..utils.data_wrapper import wrap_dataset, tokenize_dataset, wrap_dataset_with_instruct, \
remove_str_columns
from ..utils.load_huggingface_dataset import load_huggingface_dataset_train_and_test
from ..utils.random_utils import set_seed
from ..utils.other import load_args, set_gpu, sample_two_set_with_shot_per_class
from transformers import Trainer, TrainingArguments, PreTrainedModel, AutoModelForCausalLM, \
AutoTokenizer, DataCollatorWithPadding
from ..utils.load_local import get_model_layer_num
from ..util_classes.arg_classes import CompressTopArgs
from ..utils.prepare_model_and_tokenizer import load_model_and_tokenizer, get_label_id_dict_for_args | 5,943 |
class TruncatingDataCollator(DataCollatorWithPadding):
def __init__(self, tokenizer, max_length: int, padding=True, pad_to_multiple_of=None):
super().__init__(tokenizer=tokenizer, padding=padding,
pad_to_multiple_of=pad_to_multiple_of)
self.max_length = max_length
def __call__(self, features: List[dict]):
batch = super().__call__(features)
for key, value in batch.items():
if isinstance(value, torch.Tensor) and len(value.shape) == 2:
batch[key] = value[:, :self.max_length]
return batch
def get_label(y):
return y.predictions[0].argmax(-1)
def get_logits(y):
if y.predictions[2].shape[-1] > 30000:
return y.predictions[2]
else:
return y.predictions[3]
def get_topk(y, k):
logits = get_logits(y)
indices = np.argpartition(logits, -k,axis=1)[:,-k:]
return indices
def jaccard(a,b):
scores = []
for single_a, single_b in zip(a,b):
set_a = set(single_a)
set_b = set(single_b)
score = len(set_a.intersection(set_b))/len(set_a.union(set_b))
scores.append(score)
return np.array(scores).mean()
def compress(args: CompressTopArgs):
if os.path.exists(args.save_file_name):
return
# set_gpu(args.gpu)
if args.sample_from == 'test':
dataset = load_huggingface_dataset_train_and_test(args.task_name)
else:
raise NotImplementedError(f"sample_from: {args.sample_from}")
model, tokenizer = load_model_and_tokenizer(args)
args.label_id_dict = get_label_id_dict_for_args(args, tokenizer)
model = LMForwardAPI(model=model, model_name=args.model_name, tokenizer=tokenizer,
device='cuda:0',
label_dict=args.label_dict)
|
class TruncatingDataCollator(DataCollatorWithPadding):
def __init__(self, tokenizer, max_length: int, padding=True, pad_to_multiple_of=None):
super().__init__(tokenizer=tokenizer, padding=padding,
pad_to_multiple_of=pad_to_multiple_of)
self.max_length = max_length
def __call__(self, features: List[dict]):
batch = super().__call__(features)
for key, value in batch.items():
if isinstance(value, torch.Tensor) and len(value.shape) == 2:
batch[key] = value[:, :self.max_length]
return batch
def get_label(y):
return y.predictions[0].argmax(-1)
def get_logits(y):
if y.predictions[2].shape[-1] > 30000:
return y.predictions[2]
else:
return y.predictions[3]
def get_topk(y, k):
logits = get_logits(y)
indices = np.argpartition(logits, -k,axis=1)[:,-k:]
return indices
def jaccard(a,b):
scores = []
for single_a, single_b in zip(a,b):
set_a = set(single_a)
set_b = set(single_b)
score = len(set_a.intersection(set_b))/len(set_a.union(set_b))
scores.append(score)
return np.array(scores).mean()
def compress(args: CompressTopArgs):
if os.path.exists(args.save_file_name):
return
# set_gpu(args.gpu)
if args.sample_from == 'test':
dataset = load_huggingface_dataset_train_and_test(args.task_name)
else:
raise NotImplementedError(f"sample_from: {args.sample_from}")
model, tokenizer = load_model_and_tokenizer(args)
args.label_id_dict = get_label_id_dict_for_args(args, tokenizer)
model = LMForwardAPI(model=model, model_name=args.model_name, tokenizer=tokenizer,
device='cuda:0',
label_dict=args.label_dict)
| set_seed(args.seeds[0]) | 8 | 2023-10-17 11:40:03+00:00 | 8k |
Aggify/aggify | aggify/aggify.py | [
{
"identifier": "F",
"path": "aggify/compiler.py",
"snippet": "class F:\n def __init__(self, field: Union[str, Dict[str, list]]):\n if isinstance(field, str):\n self.field = f\"${field.replace('__', '.')}\"\n else:\n self.field = field\n\n def to_dict(self):\n ... | import functools
from typing import Any, Dict, Type, Union, List, TypeVar, Callable, Tuple
from mongoengine import Document, EmbeddedDocument, fields as mongoengine_fields
from mongoengine.base import TopLevelDocumentMetaclass
from aggify.compiler import F, Match, Q, Operators, Cond # noqa keep
from aggify.exceptions import (
AggifyValueError,
AnnotationError,
InvalidField,
InvalidEmbeddedField,
OutStageError,
InvalidArgument,
InvalidProjection,
InvalidAnnotateExpression,
)
from aggify.types import QueryParams, CollectionType
from aggify.utilty import (
to_mongo_positive_index,
validate_field_existence,
replace_values_recursive,
convert_match_query,
check_field_already_exists,
get_db_field,
copy_class,
) | 5,804 |
class Aggify:
def __init__(self, base_model: Type[Document]):
"""
Initializes the Aggify class.
Args:
base_model: The base model class.
"""
# Create a separate copy of the main class for safety and flexibility
self.base_model = copy_class(base_model)
self.pipelines: List[Dict[str, Union[dict, Any]]] = []
self.start = None
self.stop = None
self.q = None
def __iter__(self):
# Return a generator or iterator for the data you want to represent as a list
return iter(self.pipelines)
@last_out_stage_check
def project(self, **kwargs: QueryParams) -> "Aggify":
"""
Adjusts the base model's fields based on the given keyword arguments.
Fields to be retained are set to 1 in kwargs.
Fields to be deleted are set to 0 in kwargs, except for _id which is controlled by the delete_id flag.
Args:
**kwargs: Fields to be retained or removed.
For example: {"field1": 1, "field2": 0}
_id field behavior: {"id": 0} means delete _id.
Returns:
Aggify: Returns an instance of the Aggify class for potential method chaining.
"""
filtered_kwargs = dict(kwargs)
filtered_kwargs.pop("id", None)
if all([i in filtered_kwargs.values() for i in [0, 1]]):
raise InvalidProjection()
# Extract fields to keep and check if _id should be deleted
to_keep_values = {"id"}
projection = {}
# Add missing fields to the base model
for key, value in kwargs.items():
if value == 1:
to_keep_values.add(key)
elif key not in self.base_model._fields and isinstance( # noqa
kwargs[key], (str, dict)
):
to_keep_values.add(key)
self.base_model._fields[key] = mongoengine_fields.IntField() # noqa
projection[get_db_field(self.base_model, key)] = value # noqa
if value == 0:
del self.base_model._fields[key] # noqa
# Remove fields from the base model, except the ones in to_keep_values and possibly _id
if to_keep_values != {"id"}:
keys_for_deletion = self.base_model._fields.keys() - to_keep_values # noqa
for key in keys_for_deletion:
del self.base_model._fields[key] # noqa
# Append the projection stage to the pipelines
self.pipelines.append({"$project": projection})
# Return the instance for method chaining
return self
@last_out_stage_check
def group(self, expression: Union[str, Dict, List, None] = "id") -> "Aggify":
if isinstance(expression, list):
expression = {
field: f"${self.get_field_name_recursively(field)}"
for field in expression
}
if expression and not isinstance(expression, dict):
try:
expression = "$" + self.get_field_name_recursively(expression)
except InvalidField:
pass
self.pipelines.append({"$group": {"_id": expression}})
return self
@last_out_stage_check
def order_by(self, *order_fields: Union[str, List[str]]) -> "Aggify":
sort_dict = {
get_db_field(self.base_model, field.replace("-", "")): -1
if field.startswith("-")
else 1
for field in order_fields
}
self.pipelines.append({"$sort": sort_dict})
return self
@last_out_stage_check
def raw(self, raw_query: dict) -> "Aggify":
self.pipelines.append(raw_query)
self.pipelines = self.__combine_sequential_matches()
return self
@last_out_stage_check
def add_fields(self, **fields) -> "Aggify": # noqa
"""Generates a MongoDB addFields pipeline stage.
Args:
fields: A dictionary of field expressions and values.
Returns:
A MongoDB add_fields pipeline stage.
"""
add_fields_stage = {"$addFields": {}}
for field, expression in fields.items():
field = field.replace("__", ".")
if isinstance(expression, str):
add_fields_stage["$addFields"][field] = {"$literal": expression}
elif isinstance(expression, F):
add_fields_stage["$addFields"][field] = expression.to_dict()
elif isinstance(expression, (list, dict)):
add_fields_stage["$addFields"][field] = expression
|
AggifyType = TypeVar("AggifyType", bound=Callable[..., "Aggify"])
def last_out_stage_check(method: AggifyType) -> AggifyType:
"""Check if the last stage is $out or not
This decorator check if the last stage is $out or not
MongoDB does not allow adding aggregation pipeline stage after $out stage
"""
@functools.wraps(method)
def decorator(*args, **kwargs):
try:
if bool(args[0].pipelines[-1].get("$out")):
raise OutStageError(method.__name__)
except IndexError:
return method(*args, **kwargs)
else:
return method(*args, **kwargs)
return decorator
class Aggify:
def __init__(self, base_model: Type[Document]):
"""
Initializes the Aggify class.
Args:
base_model: The base model class.
"""
# Create a separate copy of the main class for safety and flexibility
self.base_model = copy_class(base_model)
self.pipelines: List[Dict[str, Union[dict, Any]]] = []
self.start = None
self.stop = None
self.q = None
def __iter__(self):
# Return a generator or iterator for the data you want to represent as a list
return iter(self.pipelines)
@last_out_stage_check
def project(self, **kwargs: QueryParams) -> "Aggify":
"""
Adjusts the base model's fields based on the given keyword arguments.
Fields to be retained are set to 1 in kwargs.
Fields to be deleted are set to 0 in kwargs, except for _id which is controlled by the delete_id flag.
Args:
**kwargs: Fields to be retained or removed.
For example: {"field1": 1, "field2": 0}
_id field behavior: {"id": 0} means delete _id.
Returns:
Aggify: Returns an instance of the Aggify class for potential method chaining.
"""
filtered_kwargs = dict(kwargs)
filtered_kwargs.pop("id", None)
if all([i in filtered_kwargs.values() for i in [0, 1]]):
raise InvalidProjection()
# Extract fields to keep and check if _id should be deleted
to_keep_values = {"id"}
projection = {}
# Add missing fields to the base model
for key, value in kwargs.items():
if value == 1:
to_keep_values.add(key)
elif key not in self.base_model._fields and isinstance( # noqa
kwargs[key], (str, dict)
):
to_keep_values.add(key)
self.base_model._fields[key] = mongoengine_fields.IntField() # noqa
projection[get_db_field(self.base_model, key)] = value # noqa
if value == 0:
del self.base_model._fields[key] # noqa
# Remove fields from the base model, except the ones in to_keep_values and possibly _id
if to_keep_values != {"id"}:
keys_for_deletion = self.base_model._fields.keys() - to_keep_values # noqa
for key in keys_for_deletion:
del self.base_model._fields[key] # noqa
# Append the projection stage to the pipelines
self.pipelines.append({"$project": projection})
# Return the instance for method chaining
return self
@last_out_stage_check
def group(self, expression: Union[str, Dict, List, None] = "id") -> "Aggify":
if isinstance(expression, list):
expression = {
field: f"${self.get_field_name_recursively(field)}"
for field in expression
}
if expression and not isinstance(expression, dict):
try:
expression = "$" + self.get_field_name_recursively(expression)
except InvalidField:
pass
self.pipelines.append({"$group": {"_id": expression}})
return self
@last_out_stage_check
def order_by(self, *order_fields: Union[str, List[str]]) -> "Aggify":
sort_dict = {
get_db_field(self.base_model, field.replace("-", "")): -1
if field.startswith("-")
else 1
for field in order_fields
}
self.pipelines.append({"$sort": sort_dict})
return self
@last_out_stage_check
def raw(self, raw_query: dict) -> "Aggify":
self.pipelines.append(raw_query)
self.pipelines = self.__combine_sequential_matches()
return self
@last_out_stage_check
def add_fields(self, **fields) -> "Aggify": # noqa
"""Generates a MongoDB addFields pipeline stage.
Args:
fields: A dictionary of field expressions and values.
Returns:
A MongoDB add_fields pipeline stage.
"""
add_fields_stage = {"$addFields": {}}
for field, expression in fields.items():
field = field.replace("__", ".")
if isinstance(expression, str):
add_fields_stage["$addFields"][field] = {"$literal": expression}
elif isinstance(expression, F):
add_fields_stage["$addFields"][field] = expression.to_dict()
elif isinstance(expression, (list, dict)):
add_fields_stage["$addFields"][field] = expression | elif isinstance(expression, Cond): | 4 | 2023-10-22 07:53:28+00:00 | 8k |
sotopia-lab/sotopia | sotopia/samplers/uniform_sampler.py | [
{
"identifier": "BaseAgent",
"path": "sotopia/agents/base_agent.py",
"snippet": "class BaseAgent(Generic[ObsType, ActType], MessengerMixin):\n def __init__(\n self,\n agent_name: str | None = None,\n uuid_str: str | None = None,\n agent_profile: AgentProfile | None = None,... | import random
from typing import Any, Generator, Type, TypeVar, cast
from sotopia.agents.base_agent import BaseAgent
from sotopia.database import AgentProfile, EnvironmentProfile
from sotopia.envs.parallel import ParallelSotopiaEnv
from .base_sampler import BaseSampler, EnvAgentCombo | 5,981 |
ObsType = TypeVar("ObsType")
ActType = TypeVar("ActType")
class UniformSampler(BaseSampler[ObsType, ActType]):
def sample(
self,
agent_classes: Type[BaseAgent[ObsType, ActType]]
| list[Type[BaseAgent[ObsType, ActType]]],
n_agent: int = 2,
replacement: bool = True,
size: int = 1,
env_params: dict[str, Any] = {},
agents_params: list[dict[str, Any]] = [{}, {}],
) -> Generator[EnvAgentCombo[ObsType, ActType], None, None]:
"""
Sample an environment and `n_agent` agents.
Runtime checks:
1. If `agent_classes` is a list, it should have length `n_agent`.
2. `agents_params` should also be a list of length `n_agent`.
Note: Currently, uniform sampling without replacement is not supported.
This is due to the difficulty of sequentially sampling environment and agents.
In theory, we can reject samples that have been sampled before, but this is not efficient.
Please open an issue if you need this feature.
"""
assert (
not isinstance(agent_classes, list)
or len(agent_classes) == n_agent
), f"agent_classes should be a list of length {n_agent} or a single agent class"
if not isinstance(agent_classes, list):
agent_classes = [agent_classes] * n_agent
assert (
len(agents_params) == n_agent
), f"agents_params should be a list of length {n_agent}"
assert (
replacement
), "Uniform sampling without replacement is not supported yet"
for _ in range(size):
if self.env_candidates:
env_profile = random.choice(self.env_candidates)
if isinstance(env_profile, str):
env_profile = EnvironmentProfile.get(env_profile)
else:
env_profile_id = random.choice(
list(EnvironmentProfile.all_pks())
)
env_profile = EnvironmentProfile.get(env_profile_id)
|
ObsType = TypeVar("ObsType")
ActType = TypeVar("ActType")
class UniformSampler(BaseSampler[ObsType, ActType]):
def sample(
self,
agent_classes: Type[BaseAgent[ObsType, ActType]]
| list[Type[BaseAgent[ObsType, ActType]]],
n_agent: int = 2,
replacement: bool = True,
size: int = 1,
env_params: dict[str, Any] = {},
agents_params: list[dict[str, Any]] = [{}, {}],
) -> Generator[EnvAgentCombo[ObsType, ActType], None, None]:
"""
Sample an environment and `n_agent` agents.
Runtime checks:
1. If `agent_classes` is a list, it should have length `n_agent`.
2. `agents_params` should also be a list of length `n_agent`.
Note: Currently, uniform sampling without replacement is not supported.
This is due to the difficulty of sequentially sampling environment and agents.
In theory, we can reject samples that have been sampled before, but this is not efficient.
Please open an issue if you need this feature.
"""
assert (
not isinstance(agent_classes, list)
or len(agent_classes) == n_agent
), f"agent_classes should be a list of length {n_agent} or a single agent class"
if not isinstance(agent_classes, list):
agent_classes = [agent_classes] * n_agent
assert (
len(agents_params) == n_agent
), f"agents_params should be a list of length {n_agent}"
assert (
replacement
), "Uniform sampling without replacement is not supported yet"
for _ in range(size):
if self.env_candidates:
env_profile = random.choice(self.env_candidates)
if isinstance(env_profile, str):
env_profile = EnvironmentProfile.get(env_profile)
else:
env_profile_id = random.choice(
list(EnvironmentProfile.all_pks())
)
env_profile = EnvironmentProfile.get(env_profile_id) | env = ParallelSotopiaEnv(env_profile=env_profile, **env_params) | 3 | 2023-10-23 19:47:26+00:00 | 8k |
Zai-Kun/reverse-engineered-chatgpt | re_gpt/sync_chatgpt.py | [
{
"identifier": "BACKUP_ARKOSE_TOKEN_GENERATOR",
"path": "re_gpt/async_chatgpt.py",
"snippet": "BACKUP_ARKOSE_TOKEN_GENERATOR = \"https://arkose-token-generator.zaieem.repl.co/token\""
},
{
"identifier": "CHATGPT_API",
"path": "re_gpt/async_chatgpt.py",
"snippet": "CHATGPT_API = \"https:... | import ctypes
import inspect
import time
import uuid
from queue import Queue
from threading import Thread
from typing import Callable, Generator, Optional
from curl_cffi.requests import Session
from .async_chatgpt import (
BACKUP_ARKOSE_TOKEN_GENERATOR,
CHATGPT_API,
USER_AGENT,
AsyncChatGPT,
AsyncConversation,
MODELS,
)
from .errors import (
BackendError,
InvalidSessionToken,
RetryError,
TokenNotProvided,
UnexpectedResponseError,
InvalidModelName,
)
from .utils import sync_get_binary_path, get_model_slug | 6,893 | auth_token: Optional[str] = None,
):
"""
Initializes an instance of the class.
Args:
proxies (Optional[dict]): A dictionary of proxy settings. Defaults to None.
session_token (Optional[str]): A session token. Defaults to None.
exit_callback_function (Optional[callable]): A function to be called on exit. Defaults to None.
auth_token (Optional[str]): An authentication token. Defaults to None.
"""
super().__init__(
proxies=proxies,
session_token=session_token,
exit_callback_function=exit_callback_function,
auth_token=auth_token,
)
def __enter__(self):
self.session = Session(
impersonate="chrome110", timeout=99999, proxies=self.proxies
)
if self.generate_arkose_token:
self.binary_path = sync_get_binary_path(self.session)
if self.binary_path:
self.arkose = ctypes.CDLL(self.binary_path)
self.arkose.GetToken.restype = ctypes.c_char_p
self.tried_downloading_binary = True
if not self.auth_token:
if self.session_token is None:
raise TokenNotProvided
self.auth_token = self.fetch_auth_token()
return self
def __exit__(self, *args):
try:
if self.exit_callback_function and callable(self.exit_callback_function):
if not inspect.iscoroutinefunction(self.exit_callback_function):
self.exit_callback_function(self)
finally:
self.session.close()
def get_conversation(self, conversation_id: str) -> SyncConversation:
"""
Makes an instance of class Conversation and return it.
Args:
conversation_id (str): The ID of the conversation to fetch.
Returns:
Conversation: Conversation object.
"""
return SyncConversation(self, conversation_id)
def create_new_conversation(
self, model: Optional[str] = "gpt-3.5"
) -> SyncConversation:
if model not in MODELS:
raise InvalidModelName(model, MODELS)
return SyncConversation(self, model=model)
def delete_conversation(self, conversation_id: str) -> dict:
"""
Delete a conversation.
Args:
conversation_id (str): Unique identifier for the conversation.
Returns:
dict: Server response json.
"""
url = CHATGPT_API.format(f"conversation/{conversation_id}")
response = self.session.patch(
url=url, headers=self.build_request_headers(), json={"is_visible": False}
)
return response.json()
def fetch_auth_token(self) -> str:
"""
Fetch the authentication token for the session.
Raises:
InvalidSessionToken: If the session token is invalid.
Returns: authentication token.
"""
url = "https://chat.openai.com/api/auth/session"
cookies = {"__Secure-next-auth.session-token": self.session_token}
headers = {
"User-Agent": USER_AGENT,
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5",
"Alt-Used": "chat.openai.com",
"Connection": "keep-alive",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"Sec-GPC": "1",
"Cookie": "; ".join(
[
f"{cookie_key}={cookie_value}"
for cookie_key, cookie_value in cookies.items()
]
),
}
response = self.session.get(url=url, headers=headers)
response_json = response.json()
if "accessToken" in response_json:
return response_json["accessToken"]
|
class SyncConversation(AsyncConversation):
def __init__(self, chatgpt, conversation_id: Optional[str] = None, model=None):
super().__init__(chatgpt, conversation_id, model)
def fetch_chat(self) -> dict:
"""
Fetches the chat of the conversation from the API.
Returns:
dict: The JSON response from the API containing the chat if the conversation_id is not none, else returns an empty dict.
Raises:
UnexpectedResponseError: If the response is not a valid JSON object or if the response json is not in the expected format
"""
if not self.conversation_id:
return {}
url = CHATGPT_API.format(f"conversation/{self.conversation_id}")
response = self.chatgpt.session.get(
url=url, headers=self.chatgpt.build_request_headers()
)
error = None
try:
chat = response.json()
self.parent_id = list(chat.get("mapping", {}))[-1]
model_slug = get_model_slug(chat)
self.model = [
key for key, value in MODELS.items() if value["slug"] == model_slug
][0]
except Exception as e:
error = e
if error is not None:
raise UnexpectedResponseError(error, response.text)
return chat
def chat(self, user_input: str) -> Generator[dict, None, None]:
"""
As the name implies, chat with ChatGPT.
Args:
user_input (str): The user's input message.
Yields:
dict: A dictionary representing assistant responses.
Returns:
Generator[dict, None]: A generator object that yields assistant responses.
Raises:
UnexpectedResponseError: If the response is not a valid JSON object or if the response json is not in the expected format
"""
payload = self.build_message_payload(user_input)
server_response = (
"" # To store what the server returned for debugging in case of an error
)
error = None
try:
full_message = None
while True:
response = self.send_message(payload=payload)
for chunk in response:
decoded_chunk = chunk.decode()
server_response += decoded_chunk
for line in decoded_chunk.splitlines():
if not line.startswith("data: "):
continue
raw_json_data = line[6:]
if not (decoded_json := self.decode_raw_json(raw_json_data)):
continue
if (
"message" in decoded_json
and decoded_json["message"]["author"]["role"] == "assistant"
):
processed_response = self.filter_response(decoded_json)
if full_message:
prev_resp_len = len(
full_message["message"]["content"]["parts"][0]
)
processed_response["content"] = processed_response[
"content"
][prev_resp_len::]
yield processed_response
full_message = decoded_json
self.conversation_id = full_message["conversation_id"]
self.parent_id = full_message["message"]["id"]
if (
full_message["message"]["metadata"]["finish_details"]["type"]
== "max_tokens"
):
payload = self.build_message_continuation_payload()
else:
break
except Exception as e:
error = e
# raising the error outside the 'except' block to prevent the 'During handling of the above exception, another exception occurred' error
if error is not None:
raise UnexpectedResponseError(error, server_response)
def send_message(self, payload: dict) -> Generator[bytes, None, None]:
"""
Send a message payload to the server and receive the response.
Args:
payload (dict): Payload containing message information.
Yields:
bytes: Chunk of data received as a response.
"""
response_queue = Queue()
def perform_request():
def content_callback(chunk):
response_queue.put(chunk)
url = CHATGPT_API.format("conversation")
response = self.chatgpt.session.post(
url=url,
headers=self.chatgpt.build_request_headers(),
json=payload,
content_callback=content_callback,
)
response_queue.put(None)
Thread(target=perform_request).start()
while True:
chunk = response_queue.get()
if chunk is None:
break
yield chunk
def build_message_payload(self, user_input: str) -> dict:
"""
Build a payload for sending a user message.
Returns:
dict: Payload containing message information.
"""
if self.conversation_id and (self.parent_id is None or self.model is None):
self.fetch_chat() # it will automatically fetch the chat and set the parent id
payload = {
"conversation_mode": {"conversation_mode": {"kind": "primary_assistant"}},
"conversation_id": self.conversation_id,
"action": "next",
"arkose_token": self.arkose_token_generator()
if self.chatgpt.generate_arkose_token
or MODELS[self.model]["needs_arkose_token"]
else None,
"force_paragen": False,
"history_and_training_disabled": False,
"messages": [
{
"author": {"role": "user"},
"content": {"content_type": "text", "parts": [user_input]},
"id": str(uuid.uuid4()),
"metadata": {},
}
],
"model": MODELS[self.model]["slug"],
"parent_message_id": str(uuid.uuid4())
if not self.parent_id
else self.parent_id,
}
return payload
def build_message_continuation_payload(self) -> dict:
"""
Build a payload for continuing ChatGPT's cut off response.
Returns:
dict: Payload containing message information for continuation.
"""
payload = {
"conversation_mode": {"conversation_mode": {"kind": "primary_assistant"}},
"action": "continue",
"arkose_token": self.arkose_token_generator()
if self.chatgpt.generate_arkose_token
or MODELS[self.model]["needs_arkose_token"]
else None,
"conversation_id": self.conversation_id,
"force_paragen": False,
"history_and_training_disabled": False,
"model": MODELS[self.model]["slug"],
"parent_message_id": self.parent_id,
"timezone_offset_min": -300,
}
return payload
def arkose_token_generator(self) -> str:
"""
Generate an Arkose token.
Returns:
str: Arkose token.
"""
if not self.chatgpt.tried_downloading_binary:
self.chatgpt.binary_path = sync_get_binary_path(self.chatgpt.session)
if self.chatgpt.binary_path:
self.chatgpt.arkose = ctypes.CDLL(self.chatgpt.binary_path)
self.chatgpt.arkose.GetToken.restype = ctypes.c_char_p
self.chatgpt.tried_downloading_binary = True
if self.chatgpt.binary_path:
try:
result = self.chatgpt.arkose.GetToken()
return ctypes.string_at(result).decode("utf-8")
except:
pass
for _ in range(5):
response = self.chatgpt.session.get(BACKUP_ARKOSE_TOKEN_GENERATOR)
if response.text == "null":
raise BackendError(error_code=505)
try:
return response.json()["token"]
except:
time.sleep(0.7)
raise RetryError(website=BACKUP_ARKOSE_TOKEN_GENERATOR)
def delete(self) -> None:
"""
Deletes the conversation.
"""
if self.conversation_id:
self.chatgpt.delete_conversation(self.conversation_id)
self.conversation_id = None
self.parent_id = None
class SyncChatGPT(AsyncChatGPT):
def __init__(
self,
proxies: Optional[dict] = None,
session_token: Optional[str] = None,
exit_callback_function: Optional[Callable] = None,
auth_token: Optional[str] = None,
):
"""
Initializes an instance of the class.
Args:
proxies (Optional[dict]): A dictionary of proxy settings. Defaults to None.
session_token (Optional[str]): A session token. Defaults to None.
exit_callback_function (Optional[callable]): A function to be called on exit. Defaults to None.
auth_token (Optional[str]): An authentication token. Defaults to None.
"""
super().__init__(
proxies=proxies,
session_token=session_token,
exit_callback_function=exit_callback_function,
auth_token=auth_token,
)
def __enter__(self):
self.session = Session(
impersonate="chrome110", timeout=99999, proxies=self.proxies
)
if self.generate_arkose_token:
self.binary_path = sync_get_binary_path(self.session)
if self.binary_path:
self.arkose = ctypes.CDLL(self.binary_path)
self.arkose.GetToken.restype = ctypes.c_char_p
self.tried_downloading_binary = True
if not self.auth_token:
if self.session_token is None:
raise TokenNotProvided
self.auth_token = self.fetch_auth_token()
return self
def __exit__(self, *args):
try:
if self.exit_callback_function and callable(self.exit_callback_function):
if not inspect.iscoroutinefunction(self.exit_callback_function):
self.exit_callback_function(self)
finally:
self.session.close()
def get_conversation(self, conversation_id: str) -> SyncConversation:
"""
Makes an instance of class Conversation and return it.
Args:
conversation_id (str): The ID of the conversation to fetch.
Returns:
Conversation: Conversation object.
"""
return SyncConversation(self, conversation_id)
def create_new_conversation(
self, model: Optional[str] = "gpt-3.5"
) -> SyncConversation:
if model not in MODELS:
raise InvalidModelName(model, MODELS)
return SyncConversation(self, model=model)
def delete_conversation(self, conversation_id: str) -> dict:
"""
Delete a conversation.
Args:
conversation_id (str): Unique identifier for the conversation.
Returns:
dict: Server response json.
"""
url = CHATGPT_API.format(f"conversation/{conversation_id}")
response = self.session.patch(
url=url, headers=self.build_request_headers(), json={"is_visible": False}
)
return response.json()
def fetch_auth_token(self) -> str:
"""
Fetch the authentication token for the session.
Raises:
InvalidSessionToken: If the session token is invalid.
Returns: authentication token.
"""
url = "https://chat.openai.com/api/auth/session"
cookies = {"__Secure-next-auth.session-token": self.session_token}
headers = {
"User-Agent": USER_AGENT,
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5",
"Alt-Used": "chat.openai.com",
"Connection": "keep-alive",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"Sec-GPC": "1",
"Cookie": "; ".join(
[
f"{cookie_key}={cookie_value}"
for cookie_key, cookie_value in cookies.items()
]
),
}
response = self.session.get(url=url, headers=headers)
response_json = response.json()
if "accessToken" in response_json:
return response_json["accessToken"]
| raise InvalidSessionToken | 7 | 2023-10-17 08:34:04+00:00 | 8k |
qualabs/video-headline | player/views.py | [
{
"identifier": "Media",
"path": "video/models/media.py",
"snippet": "class Media(models.Model):\n '''\n Constants to represent the `state`s of the Video\n '''\n\n class State:\n WAITING_FILE = 'waiting_file'\n QUEUING_FAILED = 'queuing_failed'\n QUEUED = 'queued'\n ... | from base64 import b64decode
from django.conf import settings
from django.http import Http404
from django.utils.safestring import mark_safe
from django.views.generic.base import TemplateView
from video.models import Media, LiveVideo
import re | 3,714 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class EmbedView(TemplateView):
template_name = "player/index.html"
def validate_domain(self, channel_allowed_domains, referer_domain):
allowed_domains = settings.ALLOWED_DOMAINS + channel_allowed_domains
if len(channel_allowed_domains) == 0:
return True
for allowed_domain in allowed_domains:
secondary = allowed_domain
allowed_domain = re.escape(allowed_domain).replace('\\*', '[a-zA-Z0-9_-]+')
allowed_domain = re.compile(allowed_domain)
if allowed_domain.match(str(referer_domain)):
return True
return False
def get_context_data(self, **kwargs):
context = super(EmbedView, self).get_context_data(**kwargs)
poster_url, video, video_url, mime_type = self.get_video_data(kwargs.get('video_id'))
channel = video.channel
organization = video.organization
if not organization.traffic_enabled:
context['error'] = True
context['message'] = 'The content is not available.'
return context
referer = self.request.META.get('HTTP_REFERER')
referer_domain = None
if referer:
regex_domain = r'^(?:https?:\/\/)?(?:[^@\/\n]+@)?([^:\/?\n]+)'
referer_domain = re.match(regex_domain, referer).group(1)
adTagUrl = mark_safe(
video.ads_vast_url or channel.ads_vast_url or ''
) if video.enable_ads else mark_safe('')
if video.autoplay == 'c':
autoplay = channel.autoplay
else:
autoplay = video.autoplay == 'y'
if not autoplay:
autoplay = ''
if self.validate_domain(channel.allowed_domains, referer_domain):
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class EmbedView(TemplateView):
template_name = "player/index.html"
def validate_domain(self, channel_allowed_domains, referer_domain):
allowed_domains = settings.ALLOWED_DOMAINS + channel_allowed_domains
if len(channel_allowed_domains) == 0:
return True
for allowed_domain in allowed_domains:
secondary = allowed_domain
allowed_domain = re.escape(allowed_domain).replace('\\*', '[a-zA-Z0-9_-]+')
allowed_domain = re.compile(allowed_domain)
if allowed_domain.match(str(referer_domain)):
return True
return False
def get_context_data(self, **kwargs):
context = super(EmbedView, self).get_context_data(**kwargs)
poster_url, video, video_url, mime_type = self.get_video_data(kwargs.get('video_id'))
channel = video.channel
organization = video.organization
if not organization.traffic_enabled:
context['error'] = True
context['message'] = 'The content is not available.'
return context
referer = self.request.META.get('HTTP_REFERER')
referer_domain = None
if referer:
regex_domain = r'^(?:https?:\/\/)?(?:[^@\/\n]+@)?([^:\/?\n]+)'
referer_domain = re.match(regex_domain, referer).group(1)
adTagUrl = mark_safe(
video.ads_vast_url or channel.ads_vast_url or ''
) if video.enable_ads else mark_safe('')
if video.autoplay == 'c':
autoplay = channel.autoplay
else:
autoplay = video.autoplay == 'y'
if not autoplay:
autoplay = ''
if self.validate_domain(channel.allowed_domains, referer_domain): | if video.state not in [LiveVideo.State.ON, Media.State.FINISHED]: | 1 | 2023-10-17 19:44:32+00:00 | 8k |
Qualcomm-AI-research/geometric-algebra-transformer | tests/gatr/layers/test_linear.py | [
{
"identifier": "EquiLinear",
"path": "gatr/layers/linear.py",
"snippet": "class EquiLinear(nn.Module):\n \"\"\"Pin-equivariant linear layer.\n\n The forward pass maps multivector inputs with shape (..., in_channels, 16) to multivector\n outputs with shape (..., out_channels, 16) as\n\n ```\... | import pytest
import torch
from gatr.layers.linear import EquiLinear
from tests.helpers import BATCH_DIMS, TOLERANCES, check_pin_equivariance | 6,511 | out_s_channels=out_s_channels,
initialization=initialization,
)
# Some initialization schemes ar enot implemented when data is all-scalar. That's fine.
except NotImplementedError as exc:
print(exc)
return
# Inputs
inputs_mv = torch.randn(*batch_dims, in_mv_channels, 16)
inputs_s = torch.randn(*batch_dims, in_s_channels) if in_s_channels is not None else None
# Compute outputs
outputs_mv, outputs_s = layer(inputs_mv, scalars=inputs_s)
# Compute mean and variance of MV outputs
mv_mean = outputs_mv[...].cpu().detach().to(torch.float64).mean(dim=(0, 1))
mv_var = outputs_mv[...].cpu().detach().to(torch.float64).var(dim=(0, 1))
print("Output multivector means and std by components:")
for i, (mean_, var_) in enumerate(zip(mv_mean, mv_var)):
print(f" Component {i}: mean = {mean_:.2f}, std = {var_**0.5:.2f}")
# Check that the mean and variance agree with expectations
if initialization == "default":
target_mean = torch.zeros_like(mv_mean)
target_var = torch.ones_like(mv_var) / 3.0 # Factor 3 comes from heuristics
elif initialization == "small":
target_mean = torch.zeros_like(mv_mean)
target_var = 0.01 * torch.ones_like(mv_var) / 3.0
elif initialization == "unit_scalar":
target_mean = torch.zeros_like(mv_mean)
target_mean[0] = 1.0
target_var = 0.01 * torch.ones_like(mv_var) / 3.0
else:
raise ValueError(initialization)
assert torch.all(mv_mean > target_mean - 0.3)
assert torch.all(mv_mean < target_mean + 0.3)
assert torch.all(mv_var > target_var / var_tolerance)
assert torch.all(mv_var < target_var * var_tolerance)
# Same for scalar outputs
if out_s_channels is not None:
s_mean = outputs_s[...].cpu().detach().to(torch.float64).mean().item()
s_var = outputs_s[...].cpu().detach().to(torch.float64).var().item()
print(f"Output scalar: mean = {s_mean:.2f}, std = {s_var**0.5:.2f}")
assert -0.3 < s_mean < 0.3
if initialization in {"default", "unit_scalar"}:
assert 1.0 / 3.0 / var_tolerance < s_var < 1.0 / 3.0 * var_tolerance
else:
assert 0.01 / 3.0 / var_tolerance < s_var < 0.01 / 3.0 * var_tolerance
@pytest.mark.parametrize("rescaling", [0.0, -2.0, 100.0])
@pytest.mark.parametrize("batch_dims", BATCH_DIMS)
@pytest.mark.parametrize("in_mv_channels", [9, 1])
@pytest.mark.parametrize("out_mv_channels", [7, 1])
@pytest.mark.parametrize("in_s_channels", [None, 3])
@pytest.mark.parametrize("out_s_channels", [None, 4])
def test_linear_layer_linearity(
batch_dims, in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, rescaling
):
"""Tests that the EquiLinear layer indeed describes a linear map (when the bias is deactivated).
Checks that `f(x + rescaling * y) = f(x) + rescaling * f(y)` for random inputs `x`, `y` and
linear layer `f(x)`.
"""
layer = EquiLinear(
in_mv_channels,
out_mv_channels,
in_s_channels=in_s_channels,
out_s_channels=out_s_channels,
bias=False,
)
# Inputs
x_mv = torch.randn(*batch_dims, in_mv_channels, 16)
y_mv = torch.randn(*batch_dims, in_mv_channels, 16)
xy_mv = x_mv + rescaling * y_mv
if in_s_channels:
x_s = torch.randn(*batch_dims, in_s_channels)
y_s = torch.randn(*batch_dims, in_s_channels)
xy_s = x_s + rescaling * y_s
else:
x_s, y_s, xy_s = None, None, None
# Compute outputs
o_xy_mv, o_xy_s = layer(xy_mv, scalars=xy_s)
o_x_mv, o_x_s = layer(x_mv, scalars=x_s)
o_y_mv, o_y_s = layer(y_mv, scalars=y_s)
# Check equality
torch.testing.assert_close(o_xy_mv, o_x_mv + rescaling * o_y_mv, **TOLERANCES)
if out_s_channels is not None:
torch.testing.assert_close(o_xy_s, o_x_s + rescaling * o_y_s, **TOLERANCES)
@pytest.mark.parametrize("batch_dims", BATCH_DIMS)
@pytest.mark.parametrize("in_mv_channels", [9, 1])
@pytest.mark.parametrize("out_mv_channels", [7, 1])
@pytest.mark.parametrize("bias", [False, True])
@pytest.mark.parametrize("in_s_channels", [None, 3])
@pytest.mark.parametrize("out_s_channels", [None, 4])
def test_linear_layer_equivariance(
batch_dims, in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, bias
):
"""Tests the equi_linear() primitive for equivariance."""
layer = EquiLinear(
in_mv_channels,
out_mv_channels,
in_s_channels=in_s_channels,
out_s_channels=out_s_channels,
bias=bias,
)
data_dims = tuple(list(batch_dims) + [in_mv_channels])
scalars = None if in_s_channels is None else torch.randn(*batch_dims, in_s_channels)
| # Copyright (c) 2023 Qualcomm Technologies, Inc.
# All rights reserved.
@pytest.mark.parametrize("batch_dims", [(100,)])
@pytest.mark.parametrize("in_mv_channels, out_mv_channels", [(200, 5), (16, 16), (5, 200)])
@pytest.mark.parametrize(
"in_s_channels, out_s_channels", [(None, None), (None, 100), (100, None), (32, 32)]
)
@pytest.mark.parametrize("initialization", ["default", "small", "unit_scalar"])
def test_linear_layer_initialization(
initialization,
batch_dims,
in_mv_channels,
out_mv_channels,
in_s_channels,
out_s_channels,
var_tolerance=10.0,
):
"""Tests the initialization of `EquiLinear`.
The goal is that independent of the channel size, inputs with variance 1 are mapped to outputs
with, very roughly, variance 1.
"""
# Create layer
try:
layer = EquiLinear(
in_mv_channels,
out_mv_channels,
in_s_channels=in_s_channels,
out_s_channels=out_s_channels,
initialization=initialization,
)
# Some initialization schemes ar enot implemented when data is all-scalar. That's fine.
except NotImplementedError as exc:
print(exc)
return
# Inputs
inputs_mv = torch.randn(*batch_dims, in_mv_channels, 16)
inputs_s = torch.randn(*batch_dims, in_s_channels) if in_s_channels is not None else None
# Compute outputs
outputs_mv, outputs_s = layer(inputs_mv, scalars=inputs_s)
# Compute mean and variance of MV outputs
mv_mean = outputs_mv[...].cpu().detach().to(torch.float64).mean(dim=(0, 1))
mv_var = outputs_mv[...].cpu().detach().to(torch.float64).var(dim=(0, 1))
print("Output multivector means and std by components:")
for i, (mean_, var_) in enumerate(zip(mv_mean, mv_var)):
print(f" Component {i}: mean = {mean_:.2f}, std = {var_**0.5:.2f}")
# Check that the mean and variance agree with expectations
if initialization == "default":
target_mean = torch.zeros_like(mv_mean)
target_var = torch.ones_like(mv_var) / 3.0 # Factor 3 comes from heuristics
elif initialization == "small":
target_mean = torch.zeros_like(mv_mean)
target_var = 0.01 * torch.ones_like(mv_var) / 3.0
elif initialization == "unit_scalar":
target_mean = torch.zeros_like(mv_mean)
target_mean[0] = 1.0
target_var = 0.01 * torch.ones_like(mv_var) / 3.0
else:
raise ValueError(initialization)
assert torch.all(mv_mean > target_mean - 0.3)
assert torch.all(mv_mean < target_mean + 0.3)
assert torch.all(mv_var > target_var / var_tolerance)
assert torch.all(mv_var < target_var * var_tolerance)
# Same for scalar outputs
if out_s_channels is not None:
s_mean = outputs_s[...].cpu().detach().to(torch.float64).mean().item()
s_var = outputs_s[...].cpu().detach().to(torch.float64).var().item()
print(f"Output scalar: mean = {s_mean:.2f}, std = {s_var**0.5:.2f}")
assert -0.3 < s_mean < 0.3
if initialization in {"default", "unit_scalar"}:
assert 1.0 / 3.0 / var_tolerance < s_var < 1.0 / 3.0 * var_tolerance
else:
assert 0.01 / 3.0 / var_tolerance < s_var < 0.01 / 3.0 * var_tolerance
@pytest.mark.parametrize("rescaling", [0.0, -2.0, 100.0])
@pytest.mark.parametrize("batch_dims", BATCH_DIMS)
@pytest.mark.parametrize("in_mv_channels", [9, 1])
@pytest.mark.parametrize("out_mv_channels", [7, 1])
@pytest.mark.parametrize("in_s_channels", [None, 3])
@pytest.mark.parametrize("out_s_channels", [None, 4])
def test_linear_layer_linearity(
batch_dims, in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, rescaling
):
"""Tests that the EquiLinear layer indeed describes a linear map (when the bias is deactivated).
Checks that `f(x + rescaling * y) = f(x) + rescaling * f(y)` for random inputs `x`, `y` and
linear layer `f(x)`.
"""
layer = EquiLinear(
in_mv_channels,
out_mv_channels,
in_s_channels=in_s_channels,
out_s_channels=out_s_channels,
bias=False,
)
# Inputs
x_mv = torch.randn(*batch_dims, in_mv_channels, 16)
y_mv = torch.randn(*batch_dims, in_mv_channels, 16)
xy_mv = x_mv + rescaling * y_mv
if in_s_channels:
x_s = torch.randn(*batch_dims, in_s_channels)
y_s = torch.randn(*batch_dims, in_s_channels)
xy_s = x_s + rescaling * y_s
else:
x_s, y_s, xy_s = None, None, None
# Compute outputs
o_xy_mv, o_xy_s = layer(xy_mv, scalars=xy_s)
o_x_mv, o_x_s = layer(x_mv, scalars=x_s)
o_y_mv, o_y_s = layer(y_mv, scalars=y_s)
# Check equality
torch.testing.assert_close(o_xy_mv, o_x_mv + rescaling * o_y_mv, **TOLERANCES)
if out_s_channels is not None:
torch.testing.assert_close(o_xy_s, o_x_s + rescaling * o_y_s, **TOLERANCES)
@pytest.mark.parametrize("batch_dims", BATCH_DIMS)
@pytest.mark.parametrize("in_mv_channels", [9, 1])
@pytest.mark.parametrize("out_mv_channels", [7, 1])
@pytest.mark.parametrize("bias", [False, True])
@pytest.mark.parametrize("in_s_channels", [None, 3])
@pytest.mark.parametrize("out_s_channels", [None, 4])
def test_linear_layer_equivariance(
batch_dims, in_mv_channels, out_mv_channels, in_s_channels, out_s_channels, bias
):
"""Tests the equi_linear() primitive for equivariance."""
layer = EquiLinear(
in_mv_channels,
out_mv_channels,
in_s_channels=in_s_channels,
out_s_channels=out_s_channels,
bias=bias,
)
data_dims = tuple(list(batch_dims) + [in_mv_channels])
scalars = None if in_s_channels is None else torch.randn(*batch_dims, in_s_channels) | check_pin_equivariance( | 3 | 2023-10-23 15:58:36+00:00 | 8k |
StanislavPetrovV/Wolfenstein-3D-Clone | engine.py | [
{
"identifier": "Player",
"path": "player.py",
"snippet": "class Player(Camera):\n def __init__(self, eng, position=PLAYER_POS, yaw=0, pitch=0):\n self.app = eng.app\n self.eng = eng\n self.sound = eng.sound\n self.play = eng.sound.play\n super().__init__(position, ... | from player import Player, PlayerAttribs
from scene import Scene
from shader_program import ShaderProgram
from path_finding import PathFinder
from ray_casting import RayCasting
from level_map import LevelMap
from textures import Textures
from sound import Sound
import pygame as pg | 5,796 |
class Engine:
def __init__(self, app):
self.app = app
self.ctx = app.ctx
self.num_level = 0
self.textures = Textures(self)
self.sound = Sound()
self.player_attribs = PlayerAttribs()
self.player: Player = None
|
class Engine:
def __init__(self, app):
self.app = app
self.ctx = app.ctx
self.num_level = 0
self.textures = Textures(self)
self.sound = Sound()
self.player_attribs = PlayerAttribs()
self.player: Player = None | self.shader_program: ShaderProgram = None | 3 | 2023-10-22 08:41:55+00:00 | 8k |
amazon-science/cceval | eval.py | [
{
"identifier": "compute_metric_stmt",
"path": "eval_metric.py",
"snippet": "def compute_metric_stmt(args):\n with open(f\"{args.output_dir}/prediction.jsonl\", \"r\") as f_pred:\n samples = []\n for l in f_pred.readlines():\n samples.append(json.loads(l))\n\n examples = {... | import argparse
import json
import logging
import os
import numpy as np
import torch
import custom_generate
from accelerate import Accelerator
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.utils.data import DataLoader, SequentialSampler
from tqdm import tqdm
from transformers import (
AutoTokenizer,
AutoModelForCausalLM
)
from eval_metric import compute_metric_stmt
from eval_utils import compute_mean_logp | 4,319 | generated_texts = tokenizer.batch_decode(batch_pred, skip_special_tokens=True)
mean_logp = compute_mean_logp(batch_scores, batch_pred, tokenizer.pad_token_id)
return batch_task_id.tolist(), generated_texts, mean_logp
all_preds = []
all_task_ids = []
with torch.no_grad():
for idx, batch in tqdm(enumerate(dataloader), total=len(dataloader)):
completions = None
completion_scores = None
for seq_idx in range(args.num_return_sequences):
batch_task_id, generated_texts, mean_logp = generate_completions(batch)
if seq_idx == 0:
all_task_ids.extend(batch_task_id)
batch_size = len(batch_task_id)
completions = [[] for _ in range(batch_size)]
completion_scores = [[] for _ in range(batch_size)]
for j in range(batch_size):
completions[j].append(generated_texts[j])
completion_scores[j].append(mean_logp[j])
if args.num_return_sequences == 1:
all_preds.extend([c[0] for c in completions])
else:
for c, cs in zip(completions, completion_scores):
max_score = max(cs)
max_index = cs.index(max_score)
all_preds.append(c[max_index])
with open(f"{args.output_dir}/prediction.jsonl", "w", encoding="utf-8") as f_pred:
id_processed = set()
for idx, p in zip(all_task_ids, all_preds):
if index2taskid[idx] not in id_processed:
f_pred.write(json.dumps({"task_id": index2taskid[idx], "pred": p}) + "\n")
id_processed.add(index2taskid[idx])
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# model inference args
parser.add_argument("--language", type=str, required=True, help="language name")
parser.add_argument("--model_name_or_path", default=None, type=str, help="Pre-trained Model Path")
parser.add_argument(
"--model_type",
type=str,
default="codelm",
choices=["codelm", "codelm_cfc"],
help="Model type to be loaded"
)
parser.add_argument("--prompt_file", type=str, default=None, help="file with a list of prompts")
parser.add_argument("--gen_length", type=int, default=50, help="max length of generated token sequence")
parser.add_argument("--max_seq_length", type=int, default=2048, help="max length of prompt")
parser.add_argument(
"--cfc_seq_length",
type=int,
default=512,
help="For model_type=codelm_cfc: Text sequence length corresponding to the retrieved nodes"
)
parser.add_argument(
"--min_cfc_score",
type=float,
default=float('-inf'),
help="For model_type=codelm_cfc: min score of a chunk to be considered as CFC chunk"
)
parser.add_argument("--batch_size", type=int, default=32, help="batch size for code completion")
parser.add_argument("--stop_token", type=str, default=None, help="Token at which text generation is stopped")
parser.add_argument("--cache_dir", type=str, default=None)
parser.add_argument(
"--temperature",
type=float,
default=0.2,
help="temperature of 1.0 has no effect, lower tend toward greedy sampling"
)
parser.add_argument("--output_dir", type=str, default="output_dir", help="output directory to save predictions")
parser.add_argument("--top_k", type=int, default=0)
parser.add_argument("--top_p", type=float, default=0.95)
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
parser.add_argument("--num_return_sequences", type=int, default=1, help="The number of samples to generate.")
parser.add_argument("--repetition_penalty", type=float, default=1.0, help="The parameter for repetition penalty.")
parser.add_argument(
"--preprocessing_num_workers",
type=int,
default=1,
help="The number of processes to use for the preprocessing."
)
parser.add_argument(
"--overwrite_cache",
type=bool,
default=False,
help="Overwrite the cached training and evaluation sets"
)
parser.add_argument("--dtype", type=str, default='bf16')
parser.add_argument("--do_sample", action="store_true", help="whether we do sampling or greedy/beam-search")
parser.add_argument("--num_beams", type=int, default=1, help="num of beam for beam-search")
# compute metric args
parser.add_argument(
"--ts_lib",
type=str,
default="build/python-lang-parser.so",
help="tree-sitter lib for tokenize code"
)
# only compute metric
parser.add_argument("--only_compute_metric", action="store_true", help="only compute metric")
args = parser.parse_args()
set_seed(args.seed, device_specific=False)
if args.num_return_sequences > 1:
assert args.do_sample, "sampling must be set to True when num_return_sequences > 1"
accelerator = Accelerator()
if not args.only_compute_metric:
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, trust_remote_code=True)
tokenized_datasets, index2taskid = build_datasets(args, tokenizer)
model_inference(tokenized_datasets, index2taskid, tokenizer)
# check if the process is the main process
if accelerator.is_main_process:
| # Copyright Amazon.com, Inc. or its affiliates. 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.
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
COMMENT_SYMBOL = {
"python": "#",
"java": "//",
"csharp": "//",
"typescript": "//"
}
def custom_data_collator(features):
first = features[0]
batch = {}
for k, v in first.items():
if v is not None and not isinstance(v, str):
if isinstance(v, torch.Tensor):
batch[k] = torch.stack([f[k] for f in features])
elif isinstance(v, np.ndarray):
batch[k] = torch.tensor(np.stack([f[k] for f in features]))
else:
batch[k] = torch.tensor([f[k] for f in features])
if v is not None and isinstance(v, str):
batch[k] = [f[k] for f in features]
return batch
def build_datasets(args, tokenizer):
# Initialize the model and tokenizer
# when generating, we will use the logits of right-most token to predict the next token
# so the padding should be on the left
tokenizer.padding_side = "left"
tokenizer.pad_token = tokenizer.eos_token if tokenizer.eos_token else tokenizer.bos_token
# load the files into Dataset
raw_datasets = load_dataset("json", data_files=args.prompt_file, cache_dir=args.cache_dir)
raw_datasets = raw_datasets["train"]
raw_datasets = raw_datasets.map(lambda example, idx: {'index': idx, **example}, with_indices=True)
index2taskid = {idx: md["task_id"] for idx, md in zip(raw_datasets["index"], raw_datasets["metadata"])}
column_names = raw_datasets.column_names
# Prompt composition
def prepare_features(examples):
tokenizer.truncation_side = "left"
tokenized_inputs = tokenizer(
examples["prompt"],
padding="max_length",
truncation=True,
max_length=args.max_seq_length - args.gen_length
)
features = {k: t for k, t in tokenized_inputs.items()}
features["index"] = examples["index"]
return features
def prepare_features_cfc(examples):
max_prompt_length = args.max_seq_length - args.gen_length
use_key = "list"
crossfile_context = []
if use_key == "text":
crossfile_context = [ex["text"] for ex in examples["crossfile_context"]]
else:
ls_sym = COMMENT_SYMBOL[args.language]
num_chunk_inc_prompt = []
augmented_prompt = 0
for cfc_chunks in examples["crossfile_context"]:
cfc_chunks = cfc_chunks["list"] # a list of dict
cfc_text = ""
if cfc_chunks:
# at least 1 relevant cfc_chunk found
init_cfc_text = f"{ls_sym} Here are some relevant code fragments from other files of the repo:\n\n"
cfc_length = len(tokenizer.tokenize(init_cfc_text))
num_chunk_inc = 0
for cfc_idx, cfc_chunk in enumerate(cfc_chunks):
if cfc_chunk["score"] > args.min_cfc_score:
add_text = f"{ls_sym} the below code fragment is found in {cfc_chunk['filename']}" + "\n"
cfc_lines = cfc_chunk["retrieved_chunk"].split('\n')
add_text += "\n".join([f"{ls_sym} {cl}" for cl in cfc_lines if cl]) + "\n\n"
# check if adding chunk exceeds max length budget for CFC
add_text_len = len(tokenizer.tokenize(add_text))
if cfc_length + add_text_len <= args.cfc_seq_length:
cfc_text += add_text
cfc_length += add_text_len
num_chunk_inc += 1
else:
break
num_chunk_inc_prompt.append(num_chunk_inc)
if num_chunk_inc > 0:
cfc_text = init_cfc_text + cfc_text
augmented_prompt += 1
crossfile_context.append(cfc_text)
logger.info(
f"{augmented_prompt} out of {len(examples['crossfile_context'])} prompts are augmented with cross-file context.")
tokenizer.truncation_side = "right"
crossfile_features = tokenizer(
crossfile_context,
truncation=True,
max_length=args.cfc_seq_length
)
features = {"input_ids": [], "attention_mask": []}
tokenizer.truncation_side = "left"
for idx, prompt in enumerate(examples["prompt"]):
allowed_prompt_length = max_prompt_length - len(crossfile_features["input_ids"][idx])
prompt_feats = tokenizer(
[prompt],
truncation=True,
max_length=allowed_prompt_length
)
for k, v in prompt_feats.items():
features[k].append(crossfile_features[k][idx] + prompt_feats[k][0])
# pad to max_seq_length
tokenizer.padding_side = "left"
features = tokenizer.pad(features, padding="max_length", max_length=args.max_seq_length - args.gen_length)
features["index"] = examples["index"]
return features
if args.model_type in ["codelm", "seq2seqlm"]:
tokenized_datasets = raw_datasets.map(
prepare_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on dataset",
)
elif args.model_type == "codelm_cfc":
tokenized_datasets = raw_datasets.map(
prepare_features_cfc,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on dataset",
)
else:
raise NotImplementedError("prepare feature functions not implemented for new model type")
return tokenized_datasets, index2taskid
def model_inference(tokenized_datasets, index2taskid, tokenizer):
if args.dtype == 'fp16':
dtype = torch.float16
elif args.dtype == 'fp32':
dtype = torch.float32
elif args.dtype == 'bf16':
dtype = torch.bfloat16
elif args.dtype == 'int8':
dtype = torch.int8
else:
assert False, f'{args.dtype=} not implemented'
if args.model_type in ["codelm", "codelm_cfc"]:
model = AutoModelForCausalLM.from_pretrained(
args.model_name_or_path,
torch_dtype=dtype,
trust_remote_code=True,
revision="main"
)
else:
raise ValueError("Unknown model type")
total_samples_cnt = len(tokenized_datasets)
logger.info(f"total samples: {total_samples_cnt}")
data_sampler = SequentialSampler(tokenized_datasets)
dataloader = DataLoader(
tokenized_datasets,
sampler=data_sampler,
collate_fn=custom_data_collator,
batch_size=args.batch_size
)
model = accelerator.prepare_model(model)
dataloader = accelerator.prepare_data_loader(dataloader)
if not os.path.isdir(args.output_dir):
os.mkdir(args.output_dir)
tokenizer.pad_token = tokenizer.eos_token if tokenizer.eos_token else tokenizer.bos_token
prompt_length = args.max_seq_length - args.gen_length
@torch.no_grad()
def generate_completions(batch):
output_dict = custom_generate.generate(
accelerator.unwrap_model(model),
input_ids=batch["input_ids"],
attention_mask=batch["attention_mask"],
max_length=args.max_seq_length,
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
do_sample=args.do_sample,
num_beams=args.num_beams,
num_return_sequences=1,
pad_token_id=tokenizer.pad_token_id,
return_dict_in_generate=True,
output_scores=True
)
batch_task_id = batch["index"]
batch_pred = accelerator.pad_across_processes(
output_dict.sequences, dim=1, pad_index=tokenizer.pad_token_id
)
scores = torch.stack(output_dict.scores, dim=1)
batch_scores = accelerator.pad_across_processes(
scores, dim=1, pad_index=tokenizer.pad_token_id
)
# batch_scores.shape = (batch_size x num_gpus x num_return_sequences, max_length)
batch_task_id, batch_pred, batch_scores = accelerator.gather((batch_task_id, batch_pred, batch_scores))
batch_pred = batch_pred[:, prompt_length:]
generated_texts = tokenizer.batch_decode(batch_pred, skip_special_tokens=True)
mean_logp = compute_mean_logp(batch_scores, batch_pred, tokenizer.pad_token_id)
return batch_task_id.tolist(), generated_texts, mean_logp
all_preds = []
all_task_ids = []
with torch.no_grad():
for idx, batch in tqdm(enumerate(dataloader), total=len(dataloader)):
completions = None
completion_scores = None
for seq_idx in range(args.num_return_sequences):
batch_task_id, generated_texts, mean_logp = generate_completions(batch)
if seq_idx == 0:
all_task_ids.extend(batch_task_id)
batch_size = len(batch_task_id)
completions = [[] for _ in range(batch_size)]
completion_scores = [[] for _ in range(batch_size)]
for j in range(batch_size):
completions[j].append(generated_texts[j])
completion_scores[j].append(mean_logp[j])
if args.num_return_sequences == 1:
all_preds.extend([c[0] for c in completions])
else:
for c, cs in zip(completions, completion_scores):
max_score = max(cs)
max_index = cs.index(max_score)
all_preds.append(c[max_index])
with open(f"{args.output_dir}/prediction.jsonl", "w", encoding="utf-8") as f_pred:
id_processed = set()
for idx, p in zip(all_task_ids, all_preds):
if index2taskid[idx] not in id_processed:
f_pred.write(json.dumps({"task_id": index2taskid[idx], "pred": p}) + "\n")
id_processed.add(index2taskid[idx])
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# model inference args
parser.add_argument("--language", type=str, required=True, help="language name")
parser.add_argument("--model_name_or_path", default=None, type=str, help="Pre-trained Model Path")
parser.add_argument(
"--model_type",
type=str,
default="codelm",
choices=["codelm", "codelm_cfc"],
help="Model type to be loaded"
)
parser.add_argument("--prompt_file", type=str, default=None, help="file with a list of prompts")
parser.add_argument("--gen_length", type=int, default=50, help="max length of generated token sequence")
parser.add_argument("--max_seq_length", type=int, default=2048, help="max length of prompt")
parser.add_argument(
"--cfc_seq_length",
type=int,
default=512,
help="For model_type=codelm_cfc: Text sequence length corresponding to the retrieved nodes"
)
parser.add_argument(
"--min_cfc_score",
type=float,
default=float('-inf'),
help="For model_type=codelm_cfc: min score of a chunk to be considered as CFC chunk"
)
parser.add_argument("--batch_size", type=int, default=32, help="batch size for code completion")
parser.add_argument("--stop_token", type=str, default=None, help="Token at which text generation is stopped")
parser.add_argument("--cache_dir", type=str, default=None)
parser.add_argument(
"--temperature",
type=float,
default=0.2,
help="temperature of 1.0 has no effect, lower tend toward greedy sampling"
)
parser.add_argument("--output_dir", type=str, default="output_dir", help="output directory to save predictions")
parser.add_argument("--top_k", type=int, default=0)
parser.add_argument("--top_p", type=float, default=0.95)
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
parser.add_argument("--num_return_sequences", type=int, default=1, help="The number of samples to generate.")
parser.add_argument("--repetition_penalty", type=float, default=1.0, help="The parameter for repetition penalty.")
parser.add_argument(
"--preprocessing_num_workers",
type=int,
default=1,
help="The number of processes to use for the preprocessing."
)
parser.add_argument(
"--overwrite_cache",
type=bool,
default=False,
help="Overwrite the cached training and evaluation sets"
)
parser.add_argument("--dtype", type=str, default='bf16')
parser.add_argument("--do_sample", action="store_true", help="whether we do sampling or greedy/beam-search")
parser.add_argument("--num_beams", type=int, default=1, help="num of beam for beam-search")
# compute metric args
parser.add_argument(
"--ts_lib",
type=str,
default="build/python-lang-parser.so",
help="tree-sitter lib for tokenize code"
)
# only compute metric
parser.add_argument("--only_compute_metric", action="store_true", help="only compute metric")
args = parser.parse_args()
set_seed(args.seed, device_specific=False)
if args.num_return_sequences > 1:
assert args.do_sample, "sampling must be set to True when num_return_sequences > 1"
accelerator = Accelerator()
if not args.only_compute_metric:
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, trust_remote_code=True)
tokenized_datasets, index2taskid = build_datasets(args, tokenizer)
model_inference(tokenized_datasets, index2taskid, tokenizer)
# check if the process is the main process
if accelerator.is_main_process: | compute_metric_stmt(args) | 0 | 2023-10-16 04:23:03+00:00 | 8k |
uukuguy/multi_loras | multi_loras/slora/models/peft/lora_adapter.py | [
{
"identifier": "get_lora_config_json",
"path": "multi_loras/slora/mprophet/lora_config.py",
"snippet": "def get_lora_config_json(name):\n if \"alpaca-lora-7b\" in name:\n config = {\"base_model_name_or_path\": \"decapoda-research/llama-7b-hf\",\n \"bias\": \"none\",\n ... | import re
import torch
import os
from ...mprophet.lora_config import get_lora_config_json
from .layer_weights.hf_load_utils import load_hf_weights
from .layer_weights.lora_layer_weight import LoraLayerWeight
from ...utils.model_load import hf_load_config | 5,710 |
def get_lora_config(lora_dir, dummy):
if dummy:
return get_lora_config_json(lora_dir), lora_dir
else:
lora_dir = re.sub(r'-(\d+)$', '', lora_dir)
|
def get_lora_config(lora_dir, dummy):
if dummy:
return get_lora_config_json(lora_dir), lora_dir
else:
lora_dir = re.sub(r'-(\d+)$', '', lora_dir) | return hf_load_config(lora_dir) | 3 | 2023-10-16 02:39:47+00:00 | 8k |
MobileLLM/AutoDroid | droidbot/device_state.py | [
{
"identifier": "md5",
"path": "droidbot/utils.py",
"snippet": "def md5(input_str):\n import hashlib\n return hashlib.md5(input_str.encode('utf-8')).hexdigest()"
},
{
"identifier": "TouchEvent",
"path": "droidbot/input_event.py",
"snippet": "class TouchEvent(UIEvent):\n \"\"\"\n... | import copy
import math
import os
import pdb
import tools
import hashlib
import networkx as nx
import numpy as np
import json
import json
import json
import hashlib
import shutil
import hashlib
import re
import matplotlib.pyplot as plt
import re
from .utils import md5
from .input_event import TouchEvent, LongTouchEvent, ScrollEvent, SetTextEvent, KeyEvent, UIEvent
from treelib import Tree
from datetime import datetime
from xmlrpc.client import ServerProxy
from xmlrpc.client import ServerProxy
from PIL import Image | 5,770 |
# for view_id in enabled_view_ids:
# if view_id in touch_exclude_view_ids:
# continue
# children = self.__safe_dict_get(self.views[view_id], 'children')
# if children and len(children) > 0:
# continue
# possible_events.append(TouchEvent(view=self.views[view_id]))
# For old Android navigation bars
# possible_events.append(KeyEvent(name="MENU"))
self.possible_events = possible_events
return [] + possible_events
def _get_self_ancestors_property(self, view, key, default=None):
all_views = [view] + [self.views[i] for i in self.get_all_ancestors(view)]
for v in all_views:
value = self.__safe_dict_get(v, key)
if value:
return value
return default
def _merge_text(self, view_text, content_description):
text = ''
if view_text:
view_text = view_text.replace('\n', ' ')
view_text = f'{view_text[:20]}...' if len(view_text) > 20 else view_text
text += view_text
text += ' '
if content_description:
content_description = content_description.replace('\n', ' ')
content_description = f'{content_description[:20]}...' if len(content_description) > 20 else content_description
text += content_description
return text
def _remove_view_ids(self, views):
removed_views = []
for view_desc in views:
view_desc_without_id = tools.get_view_without_id(view_desc)
removed_views.append(view_desc_without_id)
return removed_views
def get_described_actions_bk(self, prefix=''):
"""
Get a text description of current state
"""
# import pdb;pdb.set_trace()
enabled_view_ids = []
for view_dict in self.views:
# exclude navigation bar if exists
if self.__safe_dict_get(view_dict, 'visible') and \
self.__safe_dict_get(view_dict, 'resource_id') not in \
['android:id/navigationBarBackground',
'android:id/statusBarBackground']:
enabled_view_ids.append(view_dict['temp_id'])
text_frame = "<p id=@ class='&'>#</p>"
btn_frame = "<button id=@ class='&' checked=$>#</button>"
input_frame = "<input id=@ class='&' >#</input>"
scroll_down_frame = "<div id=@ class='scroller'>scroll down</div>"
scroll_up_frame = "<div id=@ class='scroller'>scroll up</div>"
view_descs = []
available_actions = []
for view_id in enabled_view_ids:
view = self.views[view_id]
clickable = self._get_self_ancestors_property(view, 'clickable')
scrollable = self.__safe_dict_get(view, 'scrollable')
checkable = self._get_self_ancestors_property(view, 'checkable')
long_clickable = self._get_self_ancestors_property(view, 'long_clickable')
editable = self.__safe_dict_get(view, 'editable')
actionable = clickable or scrollable or checkable or long_clickable or editable
checked = self.__safe_dict_get(view, 'checked', default=False)
selected = self.__safe_dict_get(view, 'selected', default=False)
content_description = self.__safe_dict_get(view, 'content_description', default='')
view_text = self.__safe_dict_get(view, 'text', default='')
view_class = self.__safe_dict_get(view, 'class').split('.')[-1]
if not content_description and not view_text and not scrollable: # actionable?
continue
# text = self._merge_text(view_text, content_description)
# view_status = ''
if editable:
# view_status += 'editable '
view_desc = input_frame.replace('@', str(len(view_descs))).replace('#', view_text)
if content_description:
view_desc = view_desc.replace('&', content_description)
else:
view_desc = view_desc.replace(" class='&'", "")
view_descs.append(view_desc)
available_actions.append(SetTextEvent(view=view, text='HelloWorld'))
elif (clickable or checkable or long_clickable):
view_desc = btn_frame.replace('@', str(len(view_descs))).replace('#', view_text).replace('$', str(checked or selected))
# import pdb;pdb.set_trace()
if content_description:
view_desc = view_desc.replace('&', content_description)
else:
view_desc = view_desc.replace(" class='&'", "")
view_descs.append(view_desc)
available_actions.append(TouchEvent(view=view))
elif scrollable:
view_descs.append(scroll_up_frame.replace('@', str(len(view_descs))))#.replace('&', view_class).replace('#', text))
available_actions.append(ScrollEvent(view=view, direction='UP'))
view_descs.append(scroll_down_frame.replace('@', str(len(view_descs))))#.replace('&', view_class).replace('#', text))
available_actions.append(ScrollEvent(view=view, direction='DOWN'))
else:
view_desc = text_frame.replace('@', str(len(view_descs))).replace('#', view_text)
if content_description:
view_desc = view_desc.replace('&', content_description)
else:
view_desc = view_desc.replace(" class='&'", "")
view_descs.append(view_desc)
available_actions.append(TouchEvent(view=view))
view_descs.append(f"<button id={len(view_descs)} class='ImageButton'>go back</button>")
|
class DeviceState(object):
"""
the state of the current device
"""
def __init__(self, device, views, foreground_activity, activity_stack, background_services,
tag=None, screenshot_path=None):
self.device = device
self.foreground_activity = foreground_activity
self.activity_stack = activity_stack if isinstance(activity_stack, list) else []
self.background_services = background_services
if tag is None:
tag = datetime.now().strftime("%Y-%m-%d_%H%M%S")
self.tag = tag
self.screenshot_path = screenshot_path
self.views = self.__parse_views(views)
self.bk_views = copy.deepcopy(self.views)
self.view_graph = self._build_view_graph()
# self._adjust_view_clickability()
self.view_tree = {}
self.__assemble_view_tree(self.view_tree, self.views)
self.__generate_view_strs()
self.state_str = self.__get_hashed_state_str()
self.structure_str = self.__get_content_free_state_str()
self.search_content = self.__get_search_content()
self.possible_events = None
self.width = device.get_width(refresh=True)
self.height = device.get_height(refresh=False)
self._save_important_view_ids()
@property
def activity_short_name(self):
return self.foreground_activity.split('.')[-1]
def _save_important_view_ids(self):
_, _, _, important_view_ids = self.get_described_actions(remove_time_and_ip=False)
ids_path = self.device.output_dir +'/states_view_ids'
if not os.path.exists(ids_path):
os.mkdir(ids_path)
# if not isinstance(current_state, str):
# current_state_str = current_state.state_str
# else:
# current_state_str = current_state
important_view_id_path = self.device.output_dir +'/states_view_ids/'+ self.state_str + '.txt'
f = open(important_view_id_path, 'w')
f.write(str(important_view_ids))
f.close()
def __get_hashed_state_str(self):
state, _, _, _ = self.get_described_actions(remove_time_and_ip=True)
hashed_string = tools.hash_string(state)
return hashed_string
def to_dict(self):
state = {'tag': self.tag,
'state_str': self.state_str,
'state_str_content_free': self.structure_str,
'foreground_activity': self.foreground_activity,
'activity_stack': self.activity_stack,
'background_services': self.background_services,
'width': self.width,
'height': self.height,
'views': self.views}
return state
def to_json(self):
return json.dumps(self.to_dict(), indent=2)
def __parse_views(self, raw_views):
views = []
if not raw_views or len(raw_views) == 0:
return views
for view_dict in raw_views:
# # Simplify resource_id
# resource_id = view_dict['resource_id']
# if resource_id is not None and ":" in resource_id:
# resource_id = resource_id[(resource_id.find(":") + 1):]
# view_dict['resource_id'] = resource_id
views.append(view_dict)
return views
def __assemble_view_tree(self, root_view, views):
if not len(self.view_tree): # bootstrap
self.view_tree = copy.deepcopy(views[0])
self.__assemble_view_tree(self.view_tree, views)
else:
children = list(enumerate(root_view["children"]))
if not len(children):
return
for i, j in children:
root_view["children"][i] = copy.deepcopy(self.views[j])
self.__assemble_view_tree(root_view["children"][i], views)
def __generate_view_strs(self):
for view_dict in self.views:
self.__get_view_str(view_dict)
# self.__get_view_structure(view_dict)
@staticmethod
def __calculate_depth(views):
root_view = None
for view in views:
if DeviceState.__safe_dict_get(view, 'parent') == -1:
root_view = view
break
DeviceState.__assign_depth(views, root_view, 0)
@staticmethod
def __assign_depth(views, view_dict, depth):
view_dict['depth'] = depth
for view_id in DeviceState.__safe_dict_get(view_dict, 'children', []):
DeviceState.__assign_depth(views, views[view_id], depth + 1)
def __get_state_str(self):
state_str_raw = self.__get_state_str_raw()
return md5(state_str_raw)
def __get_state_str_raw(self):
if self.device.humanoid is not None:
proxy = ServerProxy("http://%s/" % self.device.humanoid)
return proxy.render_view_tree(json.dumps({
"view_tree": self.view_tree,
"screen_res": [self.device.display_info["width"],
self.device.display_info["height"]]
}))
else:
view_signatures = set()
for view in self.views:
view_signature = DeviceState.__get_view_signature(view)
if view_signature:
view_signatures.add(view_signature)
return "%s{%s}" % (self.foreground_activity, ",".join(sorted(view_signatures)))
def __get_content_free_state_str(self):
if self.device.humanoid is not None:
proxy = ServerProxy("http://%s/" % self.device.humanoid)
state_str = proxy.render_content_free_view_tree(json.dumps({
"view_tree": self.view_tree,
"screen_res": [self.device.display_info["width"],
self.device.display_info["height"]]
}))
else:
view_signatures = set()
for view in self.views:
view_signature = DeviceState.__get_content_free_view_signature(view)
if view_signature:
view_signatures.add(view_signature)
state_str = "%s{%s}" % (self.foreground_activity, ",".join(sorted(view_signatures)))
return hashlib.md5(state_str.encode('utf-8')).hexdigest()
def __get_search_content(self):
"""
get a text for searching the state
:return: str
"""
words = [",".join(self.__get_property_from_all_views("resource_id")),
",".join(self.__get_property_from_all_views("text"))]
return "\n".join(words)
def __get_property_from_all_views(self, property_name):
"""
get the values of a property from all views
:return: a list of property values
"""
property_values = set()
for view in self.views:
property_value = DeviceState.__safe_dict_get(view, property_name, None)
if property_value:
property_values.add(property_value)
return property_values
def save2dir(self, output_dir=None):
try:
if output_dir is None:
if self.device.output_dir is None:
return
else:
output_dir = os.path.join(self.device.output_dir, "states")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
dest_state_json_path = "%s/state_%s.json" % (output_dir, self.tag)
if self.device.adapters[self.device.minicap]:
dest_screenshot_path = "%s/screen_%s.jpg" % (output_dir, self.tag)
else:
dest_screenshot_path = "%s/screen_%s.png" % (output_dir, self.tag)
state_json_file = open(dest_state_json_path, "w")
state_json_file.write(self.to_json())
state_json_file.close()
shutil.copyfile(self.screenshot_path, dest_screenshot_path)
self.screenshot_path = dest_screenshot_path
# from PIL.Image import Image
# if isinstance(self.screenshot_path, Image):
# self.screenshot_path.save(dest_screenshot_path)
except Exception as e:
self.device.logger.warning(e)
def save_view_img(self, view_dict, output_dir=None):
try:
if output_dir is None:
if self.device.output_dir is None:
return
else:
output_dir = os.path.join(self.device.output_dir, "views")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
view_str = view_dict['view_str']
if self.device.adapters[self.device.minicap]:
view_file_path = "%s/view_%s.jpg" % (output_dir, view_str)
else:
view_file_path = "%s/view_%s.png" % (output_dir, view_str)
if os.path.exists(view_file_path):
return
# Load the original image:
view_bound = view_dict['bounds']
original_img = Image.open(self.screenshot_path)
# view bound should be in original image bound
view_img = original_img.crop((min(original_img.width - 1, max(0, view_bound[0][0])),
min(original_img.height - 1, max(0, view_bound[0][1])),
min(original_img.width, max(0, view_bound[1][0])),
min(original_img.height, max(0, view_bound[1][1]))))
view_img.convert("RGB").save(view_file_path)
except Exception as e:
self.device.logger.warning(e)
def is_different_from(self, another_state):
"""
compare this state with another
@param another_state: DeviceState
@return: boolean, true if this state is different from other_state
"""
return self.state_str != another_state.state_str
@staticmethod
def __get_view_signature(view_dict):
"""
get the signature of the given view
@param view_dict: dict, an element of list DeviceState.views
@return:
"""
if 'signature' in view_dict:
return view_dict['signature']
view_text = DeviceState.__safe_dict_get(view_dict, 'text', "None")
if view_text is None or len(view_text) > 50:
view_text = "None"
signature = "[class]%s[resource_id]%s[text]%s[%s,%s,%s]" % \
(DeviceState.__safe_dict_get(view_dict, 'class', "None"),
DeviceState.__safe_dict_get(view_dict, 'resource_id', "None"),
view_text,
DeviceState.__key_if_true(view_dict, 'enabled'),
DeviceState.__key_if_true(view_dict, 'checked'),
DeviceState.__key_if_true(view_dict, 'selected'))
view_dict['signature'] = signature
return signature
@staticmethod
def __get_content_free_view_signature(view_dict):
"""
get the content-free signature of the given view
@param view_dict: dict, an element of list DeviceState.views
@return:
"""
if 'content_free_signature' in view_dict:
return view_dict['content_free_signature']
content_free_signature = "[class]%s[resource_id]%s" % \
(DeviceState.__safe_dict_get(view_dict, 'class', "None"),
DeviceState.__safe_dict_get(view_dict, 'resource_id', "None"))
view_dict['content_free_signature'] = content_free_signature
return content_free_signature
def __get_view_str(self, view_dict):
"""
get a string which can represent the given view
@param view_dict: dict, an element of list DeviceState.views
@return:
"""
if 'view_str' in view_dict:
return view_dict['view_str']
view_signature = DeviceState.__get_view_signature(view_dict)
parent_strs = []
for parent_id in self.get_all_ancestors(view_dict):
parent_strs.append(DeviceState.__get_view_signature(self.views[parent_id]))
parent_strs.reverse()
child_strs = []
for child_id in self.get_all_children(view_dict):
child_strs.append(DeviceState.__get_view_signature(self.views[child_id]))
child_strs.sort()
view_str = "Activity:%s\nSelf:%s\nParents:%s\nChildren:%s" % \
(self.foreground_activity, view_signature, "//".join(parent_strs), "||".join(child_strs))
view_str = hashlib.md5(view_str.encode('utf-8')).hexdigest()
view_dict['view_str'] = view_str
return view_str
def __get_view_structure(self, view_dict):
"""
get the structure of the given view
:param view_dict: dict, an element of list DeviceState.views
:return: dict, representing the view structure
"""
if 'view_structure' in view_dict:
return view_dict['view_structure']
width = DeviceState.get_view_width(view_dict)
height = DeviceState.get_view_height(view_dict)
class_name = DeviceState.__safe_dict_get(view_dict, 'class', "None")
children = {}
root_x = view_dict['bounds'][0][0]
root_y = view_dict['bounds'][0][1]
child_view_ids = self.__safe_dict_get(view_dict, 'children')
if child_view_ids:
for child_view_id in child_view_ids:
child_view = self.views[child_view_id]
child_x = child_view['bounds'][0][0]
child_y = child_view['bounds'][0][1]
relative_x, relative_y = child_x - root_x, child_y - root_y
children["(%d,%d)" % (relative_x, relative_y)] = self.__get_view_structure(child_view)
view_structure = {
"%s(%d*%d)" % (class_name, width, height): children
}
view_dict['view_structure'] = view_structure
return view_structure
@staticmethod
def __key_if_true(view_dict, key):
return key if (key in view_dict and view_dict[key]) else ""
@staticmethod
def __safe_dict_get(view_dict, key, default=None):
return_itm = view_dict[key] if (key in view_dict) else default
if return_itm == None:
return_itm = ''
return return_itm
@staticmethod
def get_view_center(view_dict):
"""
return the center point in a view
@param view_dict: dict, an element of DeviceState.views
@return: a pair of int
"""
bounds = view_dict['bounds']
return (bounds[0][0] + bounds[1][0]) / 2, (bounds[0][1] + bounds[1][1]) / 2
@staticmethod
def get_view_width(view_dict):
"""
return the width of a view
@param view_dict: dict, an element of DeviceState.views
@return: int
"""
bounds = view_dict['bounds']
return int(math.fabs(bounds[0][0] - bounds[1][0]))
@staticmethod
def get_view_height(view_dict):
"""
return the height of a view
@param view_dict: dict, an element of DeviceState.views
@return: int
"""
bounds = view_dict['bounds']
return int(math.fabs(bounds[0][1] - bounds[1][1]))
def get_all_ancestors(self, view_dict):
"""
Get temp view ids of the given view's ancestors
:param view_dict: dict, an element of DeviceState.views
:return: list of int, each int is an ancestor node id
"""
result = []
parent_id = self.__safe_dict_get(view_dict, 'parent', -1)
if 0 <= parent_id < len(self.views):
result.append(parent_id)
result += self.get_all_ancestors(self.views[parent_id])
return result
def get_all_children(self, view_dict):
"""
Get temp view ids of the given view's children
:param view_dict: dict, an element of DeviceState.views
:return: set of int, each int is a child node id
"""
children = self.__safe_dict_get(view_dict, 'children')
if not children:
return set()
children = set(children)
for child in children:
children_of_child = self.get_all_children(self.views[child])
children.union(children_of_child)
return children
def get_app_activity_depth(self, app):
"""
Get the depth of the app's activity in the activity stack
:param app: App
:return: the depth of app's activity, -1 for not found
"""
depth = 0
for activity_str in self.activity_stack:
if app.package_name in activity_str:
return depth
depth += 1
return -1
def get_possible_input(self):
"""
Get a list of possible input events for this state
:return: list of InputEvent
"""
if self.possible_events:
return [] + self.possible_events
possible_events = []
enabled_view_ids = []
touch_exclude_view_ids = set()
for view_dict in self.views:
# exclude navigation bar if exists
if self.__safe_dict_get(view_dict, 'enabled') and \
self.__safe_dict_get(view_dict, 'visible') and \
self.__safe_dict_get(view_dict, 'resource_id') not in \
['android:id/navigationBarBackground',
'android:id/statusBarBackground']:
enabled_view_ids.append(view_dict['temp_id'])
# enabled_view_ids.reverse()
for view_id in enabled_view_ids:
if self.__safe_dict_get(self.views[view_id], 'clickable'):
possible_events.append(TouchEvent(view=self.views[view_id]))
touch_exclude_view_ids.add(view_id)
touch_exclude_view_ids.union(self.get_all_children(self.views[view_id]))
for view_id in enabled_view_ids:
if self.__safe_dict_get(self.views[view_id], 'scrollable'):
possible_events.append(ScrollEvent(view=self.views[view_id], direction="UP"))
possible_events.append(ScrollEvent(view=self.views[view_id], direction="DOWN"))
possible_events.append(ScrollEvent(view=self.views[view_id], direction="LEFT"))
possible_events.append(ScrollEvent(view=self.views[view_id], direction="RIGHT"))
for view_id in enabled_view_ids:
if self.__safe_dict_get(self.views[view_id], 'checkable'):
possible_events.append(TouchEvent(view=self.views[view_id]))
touch_exclude_view_ids.add(view_id)
touch_exclude_view_ids.union(self.get_all_children(self.views[view_id]))
for view_id in enabled_view_ids:
if self.__safe_dict_get(self.views[view_id], 'long_clickable'):
possible_events.append(LongTouchEvent(view=self.views[view_id]))
for view_id in enabled_view_ids:
if self.__safe_dict_get(self.views[view_id], 'editable'):
possible_events.append(SetTextEvent(view=self.views[view_id], text="HelloWorld"))
touch_exclude_view_ids.add(view_id)
# TODO figure out what event can be sent to editable views
pass
# for view_id in enabled_view_ids:
# if view_id in touch_exclude_view_ids:
# continue
# children = self.__safe_dict_get(self.views[view_id], 'children')
# if children and len(children) > 0:
# continue
# possible_events.append(TouchEvent(view=self.views[view_id]))
# For old Android navigation bars
# possible_events.append(KeyEvent(name="MENU"))
self.possible_events = possible_events
return [] + possible_events
def _get_self_ancestors_property(self, view, key, default=None):
all_views = [view] + [self.views[i] for i in self.get_all_ancestors(view)]
for v in all_views:
value = self.__safe_dict_get(v, key)
if value:
return value
return default
def _merge_text(self, view_text, content_description):
text = ''
if view_text:
view_text = view_text.replace('\n', ' ')
view_text = f'{view_text[:20]}...' if len(view_text) > 20 else view_text
text += view_text
text += ' '
if content_description:
content_description = content_description.replace('\n', ' ')
content_description = f'{content_description[:20]}...' if len(content_description) > 20 else content_description
text += content_description
return text
def _remove_view_ids(self, views):
removed_views = []
for view_desc in views:
view_desc_without_id = tools.get_view_without_id(view_desc)
removed_views.append(view_desc_without_id)
return removed_views
def get_described_actions_bk(self, prefix=''):
"""
Get a text description of current state
"""
# import pdb;pdb.set_trace()
enabled_view_ids = []
for view_dict in self.views:
# exclude navigation bar if exists
if self.__safe_dict_get(view_dict, 'visible') and \
self.__safe_dict_get(view_dict, 'resource_id') not in \
['android:id/navigationBarBackground',
'android:id/statusBarBackground']:
enabled_view_ids.append(view_dict['temp_id'])
text_frame = "<p id=@ class='&'>#</p>"
btn_frame = "<button id=@ class='&' checked=$>#</button>"
input_frame = "<input id=@ class='&' >#</input>"
scroll_down_frame = "<div id=@ class='scroller'>scroll down</div>"
scroll_up_frame = "<div id=@ class='scroller'>scroll up</div>"
view_descs = []
available_actions = []
for view_id in enabled_view_ids:
view = self.views[view_id]
clickable = self._get_self_ancestors_property(view, 'clickable')
scrollable = self.__safe_dict_get(view, 'scrollable')
checkable = self._get_self_ancestors_property(view, 'checkable')
long_clickable = self._get_self_ancestors_property(view, 'long_clickable')
editable = self.__safe_dict_get(view, 'editable')
actionable = clickable or scrollable or checkable or long_clickable or editable
checked = self.__safe_dict_get(view, 'checked', default=False)
selected = self.__safe_dict_get(view, 'selected', default=False)
content_description = self.__safe_dict_get(view, 'content_description', default='')
view_text = self.__safe_dict_get(view, 'text', default='')
view_class = self.__safe_dict_get(view, 'class').split('.')[-1]
if not content_description and not view_text and not scrollable: # actionable?
continue
# text = self._merge_text(view_text, content_description)
# view_status = ''
if editable:
# view_status += 'editable '
view_desc = input_frame.replace('@', str(len(view_descs))).replace('#', view_text)
if content_description:
view_desc = view_desc.replace('&', content_description)
else:
view_desc = view_desc.replace(" class='&'", "")
view_descs.append(view_desc)
available_actions.append(SetTextEvent(view=view, text='HelloWorld'))
elif (clickable or checkable or long_clickable):
view_desc = btn_frame.replace('@', str(len(view_descs))).replace('#', view_text).replace('$', str(checked or selected))
# import pdb;pdb.set_trace()
if content_description:
view_desc = view_desc.replace('&', content_description)
else:
view_desc = view_desc.replace(" class='&'", "")
view_descs.append(view_desc)
available_actions.append(TouchEvent(view=view))
elif scrollable:
view_descs.append(scroll_up_frame.replace('@', str(len(view_descs))))#.replace('&', view_class).replace('#', text))
available_actions.append(ScrollEvent(view=view, direction='UP'))
view_descs.append(scroll_down_frame.replace('@', str(len(view_descs))))#.replace('&', view_class).replace('#', text))
available_actions.append(ScrollEvent(view=view, direction='DOWN'))
else:
view_desc = text_frame.replace('@', str(len(view_descs))).replace('#', view_text)
if content_description:
view_desc = view_desc.replace('&', content_description)
else:
view_desc = view_desc.replace(" class='&'", "")
view_descs.append(view_desc)
available_actions.append(TouchEvent(view=view))
view_descs.append(f"<button id={len(view_descs)} class='ImageButton'>go back</button>") | available_actions.append(KeyEvent(name='BACK')) | 5 | 2023-10-23 03:32:58+00:00 | 8k |
aws/res | tasks/tools/clean_tool.py | [
{
"identifier": "BuildTool",
"path": "tasks/tools/build_tool.py",
"snippet": "class BuildTool:\n \"\"\"\n IDEA Project Build Tool\n Handles building of individual projects under <PROJECT_ROOT>/source/idea/*\n\n Works based on standard idea directory structure:\n <PROJECT_ROOT>/\n + sou... | import os
import shutil
import tasks.idea as idea
from tasks.tools.build_tool import BuildTool
from tasks.tools.package_tool import PackageTool
from invoke import Context
from typing import Optional | 3,620 | # Copyright Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
# and limitations under the License.
class CleanTool:
def __init__(self, c: Context, app_name: str):
self.c = c
if app_name is None:
raise idea.exceptions.invalid_params('app_name is required')
self.app_name = app_name
self.build_tool: Optional[BuildTool] = None
| # Copyright Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
# and limitations under the License.
class CleanTool:
def __init__(self, c: Context, app_name: str):
self.c = c
if app_name is None:
raise idea.exceptions.invalid_params('app_name is required')
self.app_name = app_name
self.build_tool: Optional[BuildTool] = None | self.package_tool: Optional[PackageTool] = None | 1 | 2023-10-20 17:11:30+00:00 | 8k |
Agora-X/Bing-Chat-API | src/bing_chat/chathub.py | [
{
"identifier": "DELIMITER",
"path": "src/bing_chat/constants.py",
"snippet": "DELIMITER = \"\\x1e\""
},
{
"identifier": "HEADERS",
"path": "src/bing_chat/constants.py",
"snippet": "HEADERS = {\n \"accept\": \"application/json\",\n \"accept-language\": \"en-US;q=0.9\",\n \"accep... | import asyncio
import json
import os
import ssl
import sys
import aiohttp
import certifi
import httpx
import urllib.parse
from time import time
from typing import Generator
from typing import List
from typing import Union
from BingImageCreator import ImageGenAsync
from .constants import DELIMITER
from .constants import HEADERS
from .constants import HEADERS_INIT_CONVER
from .conversation import Conversation
from .conversation_style import CONVERSATION_STYLE_TYPE
from .request import ChatHubRequest
from .utilities import append_identifier
from .utilities import get_ran_hex
from .utilities import guess_locale | 4,399 |
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations(certifi.where())
class ChatHub:
def __init__(
self,
conversation: Conversation,
proxy: str = None,
cookies: Union[List[dict], None] = None,
) -> None:
self.aio_session = None
self.request: ChatHubRequest
self.loop: bool
self.task: asyncio.Task
self.request = ChatHubRequest(
conversation_signature=conversation.struct["conversationSignature"],
encrypted_conversation_signature=conversation.struct["encryptedConversationSignature"],
client_id=conversation.struct["clientId"],
conversation_id=conversation.struct["conversationId"],
)
self.cookies = cookies
self.proxy: str = proxy
proxy = (
proxy
or os.environ.get("all_proxy")
or os.environ.get("ALL_PROXY")
or os.environ.get("https_proxy")
or os.environ.get("HTTPS_PROXY")
or None
)
if proxy is not None and proxy.startswith("socks5h://"):
proxy = "socks5://" + proxy[len("socks5h://") :]
self.session = httpx.AsyncClient(
proxies=proxy,
timeout=900,
headers=HEADERS_INIT_CONVER,
)
async def get_conversation(
self,
conversation_id: str = None,
conversation_signature: str = None,
encrypted_conversation_signature: str = None,
client_id: str = None,
) -> dict:
conversation_id = conversation_id or self.request.conversation_id
conversation_signature = (
conversation_signature or self.request.conversation_signature
)
encrypted_conversation_signature = (
encrypted_conversation_signature or self.request.encrypted_conversation_signature
)
client_id = client_id or self.request.client_id
url = f"https://sydney.bing.com/sydney/GetConversation?conversationId={conversation_id}&source=cib&participantId={client_id}&conversationSignature={conversation_signature}&encryptedConversationSignature={encrypted_conversation_signature}&traceId={get_ran_hex()}"
response = await self.session.get(url)
return response.json()
async def get_activity(self) -> dict:
url = "https://www.bing.com/turing/conversation/chats"
headers = HEADERS_INIT_CONVER.copy()
if self.cookies is not None:
for cookie in self.cookies:
if cookie["name"] == "_U":
headers["Cookie"] = f"SUID=A; _U={cookie['value']};"
break
response = await self.session.get(url, headers=headers)
return response.json()
async def ask_stream(
self,
prompt: str,
wss_link: str = None,
conversation_style: CONVERSATION_STYLE_TYPE = None,
raw: bool = False,
webpage_context: Union[str, None] = None,
search_result: bool = False,
locale: str = guess_locale(),
) -> Generator[bool, Union[dict, str], None]:
""" """
if self.request.encrypted_conversation_signature is not None:
wss_link = wss_link or "wss://sydney.bing.com/sydney/ChatHub"
wss_link += f"?sec_access_token={urllib.parse.quote(self.request.encrypted_conversation_signature)}"
cookies = {}
if self.cookies is not None:
for cookie in self.cookies:
cookies[cookie["name"]] = cookie["value"]
self.aio_session = aiohttp.ClientSession(cookies=cookies)
# Check if websocket is closed
wss = await self.aio_session.ws_connect(
wss_link or "wss://sydney.bing.com/sydney/ChatHub",
ssl=ssl_context,
headers=HEADERS,
proxy=self.proxy,
)
await self._initial_handshake(wss)
# Construct a ChatHub request
self.request.update(
prompt=prompt,
conversation_style=conversation_style,
webpage_context=webpage_context,
search_result=search_result,
locale=locale,
)
# Send request
await wss.send_str(append_identifier(self.request.struct))
draw = False
resp_txt = ""
result_text = ""
resp_txt_no_link = ""
retry_count = 5
while not wss.closed:
msg = await wss.receive_str()
if not msg:
retry_count -= 1
if retry_count == 0:
raise Exception("No response from server")
continue
if isinstance(msg, str):
|
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations(certifi.where())
class ChatHub:
def __init__(
self,
conversation: Conversation,
proxy: str = None,
cookies: Union[List[dict], None] = None,
) -> None:
self.aio_session = None
self.request: ChatHubRequest
self.loop: bool
self.task: asyncio.Task
self.request = ChatHubRequest(
conversation_signature=conversation.struct["conversationSignature"],
encrypted_conversation_signature=conversation.struct["encryptedConversationSignature"],
client_id=conversation.struct["clientId"],
conversation_id=conversation.struct["conversationId"],
)
self.cookies = cookies
self.proxy: str = proxy
proxy = (
proxy
or os.environ.get("all_proxy")
or os.environ.get("ALL_PROXY")
or os.environ.get("https_proxy")
or os.environ.get("HTTPS_PROXY")
or None
)
if proxy is not None and proxy.startswith("socks5h://"):
proxy = "socks5://" + proxy[len("socks5h://") :]
self.session = httpx.AsyncClient(
proxies=proxy,
timeout=900,
headers=HEADERS_INIT_CONVER,
)
async def get_conversation(
self,
conversation_id: str = None,
conversation_signature: str = None,
encrypted_conversation_signature: str = None,
client_id: str = None,
) -> dict:
conversation_id = conversation_id or self.request.conversation_id
conversation_signature = (
conversation_signature or self.request.conversation_signature
)
encrypted_conversation_signature = (
encrypted_conversation_signature or self.request.encrypted_conversation_signature
)
client_id = client_id or self.request.client_id
url = f"https://sydney.bing.com/sydney/GetConversation?conversationId={conversation_id}&source=cib&participantId={client_id}&conversationSignature={conversation_signature}&encryptedConversationSignature={encrypted_conversation_signature}&traceId={get_ran_hex()}"
response = await self.session.get(url)
return response.json()
async def get_activity(self) -> dict:
url = "https://www.bing.com/turing/conversation/chats"
headers = HEADERS_INIT_CONVER.copy()
if self.cookies is not None:
for cookie in self.cookies:
if cookie["name"] == "_U":
headers["Cookie"] = f"SUID=A; _U={cookie['value']};"
break
response = await self.session.get(url, headers=headers)
return response.json()
async def ask_stream(
self,
prompt: str,
wss_link: str = None,
conversation_style: CONVERSATION_STYLE_TYPE = None,
raw: bool = False,
webpage_context: Union[str, None] = None,
search_result: bool = False,
locale: str = guess_locale(),
) -> Generator[bool, Union[dict, str], None]:
""" """
if self.request.encrypted_conversation_signature is not None:
wss_link = wss_link or "wss://sydney.bing.com/sydney/ChatHub"
wss_link += f"?sec_access_token={urllib.parse.quote(self.request.encrypted_conversation_signature)}"
cookies = {}
if self.cookies is not None:
for cookie in self.cookies:
cookies[cookie["name"]] = cookie["value"]
self.aio_session = aiohttp.ClientSession(cookies=cookies)
# Check if websocket is closed
wss = await self.aio_session.ws_connect(
wss_link or "wss://sydney.bing.com/sydney/ChatHub",
ssl=ssl_context,
headers=HEADERS,
proxy=self.proxy,
)
await self._initial_handshake(wss)
# Construct a ChatHub request
self.request.update(
prompt=prompt,
conversation_style=conversation_style,
webpage_context=webpage_context,
search_result=search_result,
locale=locale,
)
# Send request
await wss.send_str(append_identifier(self.request.struct))
draw = False
resp_txt = ""
result_text = ""
resp_txt_no_link = ""
retry_count = 5
while not wss.closed:
msg = await wss.receive_str()
if not msg:
retry_count -= 1
if retry_count == 0:
raise Exception("No response from server")
continue
if isinstance(msg, str): | objects = msg.split(DELIMITER) | 0 | 2023-10-19 19:17:05+00:00 | 8k |
f0uriest/interpax | interpax/_spline.py | [
{
"identifier": "errorif",
"path": "interpax/utils.py",
"snippet": "def errorif(cond, err=ValueError, msg=\"\"):\n \"\"\"Raise an error if condition is met.\n\n Similar to assert but allows wider range of Error types, rather than\n just AssertionError.\n \"\"\"\n if cond:\n raise e... | from collections import OrderedDict
from functools import partial
from typing import Union
from jax import jit
from .utils import errorif, isbool
import equinox as eqx
import jax
import jax.numpy as jnp
import numpy as np | 3,888 | if fxyz is None:
fxyz = approx_df(z, fxy, method, 2, **kwargs)
assert (
fx.shape
== fy.shape
== fz.shape
== fxy.shape
== fxz.shape
== fyz.shape
== fxyz.shape
== f.shape
)
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
j = jnp.clip(jnp.searchsorted(y, yq, side="right"), 1, len(y) - 1)
k = jnp.clip(jnp.searchsorted(z, zq, side="right"), 1, len(z) - 1)
dx = x[i] - x[i - 1]
deltax = xq - x[i - 1]
dxi = jnp.where(dx == 0, 0, 1 / dx)
tx = deltax * dxi
dy = y[j] - y[j - 1]
deltay = yq - y[j - 1]
dyi = jnp.where(dy == 0, 0, 1 / dy)
ty = deltay * dyi
dz = z[k] - z[k - 1]
deltaz = zq - z[k - 1]
dzi = jnp.where(dz == 0, 0, 1 / dz)
tz = deltaz * dzi
fs = OrderedDict()
fs["f"] = f
fs["fx"] = fx
fs["fy"] = fy
fs["fz"] = fz
fs["fxy"] = fxy
fs["fxz"] = fxz
fs["fyz"] = fyz
fs["fxyz"] = fxyz
fsq = OrderedDict()
for ff in fs.keys():
for kk in [0, 1]:
for jj in [0, 1]:
for ii in [0, 1]:
s = ff + str(ii) + str(jj) + str(kk)
fsq[s] = fs[ff][i - 1 + ii, j - 1 + jj, k - 1 + kk]
if "x" in ff:
fsq[s] = (dx * fsq[s].T).T
if "y" in ff:
fsq[s] = (dy * fsq[s].T).T
if "z" in ff:
fsq[s] = (dz * fsq[s].T).T
F = jnp.stack([foo for foo in fsq.values()], axis=0).T
coef = jnp.vectorize(jnp.matmul, signature="(n,n),(n)->(n)")(A_TRICUBIC, F).T
coef = jnp.moveaxis(coef.reshape((4, 4, 4, *coef.shape[1:]), order="F"), 3, 0)
ttx = _get_t_der(tx, derivative_x, dxi)
tty = _get_t_der(ty, derivative_y, dyi)
ttz = _get_t_der(tz, derivative_z, dzi)
fq = jnp.einsum("lijk...,li,lj,lk->l...", coef, ttx, tty, ttz)
fq = _extrap(xq, fq, x, lowx, highx)
fq = _extrap(yq, fq, y, lowy, highy)
fq = _extrap(zq, fq, z, lowz, highz)
return fq.reshape(outshape)
@partial(jit, static_argnames=("axis"))
def _make_periodic(xq: jax.Array, x: jax.Array, period: float, axis: int, *arrs):
"""Make arrays periodic along a specified axis."""
period = abs(period)
xq = xq % period
x = x % period
i = jnp.argsort(x)
x = x[i]
x = jnp.concatenate([x[-1:] - period, x, x[:1] + period])
arrs = list(arrs)
for k in range(len(arrs)):
if arrs[k] is not None:
arrs[k] = jnp.take(arrs[k], i, axis, mode="wrap")
arrs[k] = jnp.concatenate(
[
jnp.take(arrs[k], jnp.array([-1]), axis),
arrs[k],
jnp.take(arrs[k], jnp.array([0]), axis),
],
axis=axis,
)
return (xq, x, *arrs)
@jit
def _get_t_der(t: jax.Array, derivative: int, dxi: jax.Array):
"""Get arrays of [1,t,t^2,t^3] for cubic interpolation."""
t0 = jnp.zeros_like(t)
t1 = jnp.ones_like(t)
dxi = jnp.atleast_1d(dxi)[:, None]
# derivatives of monomials
d0 = lambda: jnp.array([t1, t, t**2, t**3]).T * dxi**0
d1 = lambda: jnp.array([t0, t1, 2 * t, 3 * t**2]).T * dxi
d2 = lambda: jnp.array([t0, t0, 2 * t1, 6 * t]).T * dxi**2
d3 = lambda: jnp.array([t0, t0, t0, 6 * t1]).T * dxi**3
d4 = lambda: jnp.array([t0, t0, t0, t0]).T * (dxi * 0)
return jax.lax.switch(derivative, [d0, d1, d2, d3, d4])
def _parse_ndarg(arg, n):
try:
k = len(arg)
except TypeError:
arg = tuple(arg for _ in range(n))
k = n
assert k == n, "got too many args"
return arg
def _parse_extrap(extrap, n):
| """Functions for interpolating splines that are JAX differentiable."""
CUBIC_METHODS = ("cubic", "cubic2", "cardinal", "catmull-rom")
OTHER_METHODS = ("nearest", "linear")
METHODS_1D = CUBIC_METHODS + OTHER_METHODS + ("monotonic", "monotonic-0")
METHODS_2D = CUBIC_METHODS + OTHER_METHODS
METHODS_3D = CUBIC_METHODS + OTHER_METHODS
class Interpolator1D(eqx.Module):
"""Convenience class for representing a 1D interpolated function.
Parameters
----------
x : ndarray, shape(Nx,)
coordinates of known function values ("knots")
f : ndarray, shape(Nx,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
- ``'monotonic'``: C1 cubic splines that attempt to preserve monotonicity in the
data, and will not introduce new extrema in the interpolated points
- ``'monotonic-0'``: same as ``'monotonic'`` but with 0 first derivatives at
both endpoints
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as a 2 element array or tuple to specify different conditions
for xq<x[0] and x[-1]<xq
period : float > 0, None
periodicity of the function. If given, function is assumed to be periodic
on the interval [0,period]. None denotes no periodicity
Notes
-----
This class is registered as a PyTree in JAX (it is actually an equinox.Module)
so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)
"""
x: jax.Array
f: jax.Array
derivs: dict
method: str
extrap: Union[bool, float, tuple]
period: Union[None, float]
axis: int
def __init__(
self,
x: jax.Array,
f: jax.Array,
method: str = "cubic",
extrap: Union[bool, float, tuple] = False,
period: Union[None, float] = None,
**kwargs,
):
x, f = map(jnp.asarray, (x, f))
axis = kwargs.get("axis", 0)
fx = kwargs.pop("fx", None)
errorif(
(len(x) != f.shape[axis]) or (jnp.ndim(x) != 1),
ValueError,
"x and f must be arrays of equal length",
)
errorif(method not in METHODS_1D, ValueError, f"unknown method {method}")
self.x = x
self.f = f
self.axis = axis
self.method = method
self.extrap = extrap
self.period = period
if fx is None:
fx = approx_df(x, f, method, axis, **kwargs)
self.derivs = {"fx": fx}
def __call__(self, xq: jax.Array, dx: int = 0):
"""Evaluate the interpolated function or its derivatives.
Parameters
----------
xq : ndarray, shape(Nq,)
Query points where interpolation is desired
dx : int >= 0
Derivative to take.
Returns
-------
fq : ndarray, shape(Nq, ...)
Interpolated values.
"""
return interp1d(
xq,
self.x,
self.f,
self.method,
dx,
self.extrap,
self.period,
**self.derivs,
)
class Interpolator2D(eqx.Module):
"""Convenience class for representing a 2D interpolated function.
Parameters
----------
x : ndarray, shape(Nx,)
x coordinates of known function values ("knots")
y : ndarray, shape(Ny,)
y coordinates of known function values ("knots")
f : ndarray, shape(Nx,Ny,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as an array or tuple to specify different conditions
[[xlow, xhigh],[ylow,yhigh]]
period : float > 0, None, array-like, shape(2,)
periodicity of the function in x, y directions. None denotes no periodicity,
otherwise function is assumed to be periodic on the interval [0,period]. Use a
single value for the same in both directions.
Notes
-----
This class is registered as a PyTree in JAX (it is actually an equinox.Module)
so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)
"""
x: jax.Array
y: jax.Array
f: jax.Array
derivs: dict
method: str
extrap: Union[bool, float, tuple]
period: Union[None, float, tuple]
axis: int
def __init__(
self,
x: jax.Array,
y: jax.Array,
f: jax.Array,
method: str = "cubic",
extrap: Union[bool, float, tuple] = False,
period: Union[None, float, tuple] = None,
**kwargs,
):
x, y, f = map(jnp.asarray, (x, y, f))
axis = kwargs.get("axis", 0)
fx = kwargs.pop("fx", None)
fy = kwargs.pop("fy", None)
fxy = kwargs.pop("fxy", None)
errorif(
(len(x) != f.shape[0]) or (x.ndim != 1),
ValueError,
"x and f must be arrays of equal length",
)
errorif(
(len(y) != f.shape[1]) or (y.ndim != 1),
ValueError,
"y and f must be arrays of equal length",
)
errorif(method not in METHODS_2D, ValueError, f"unknown method {method}")
self.x = x
self.y = y
self.f = f
self.axis = axis
self.method = method
self.extrap = extrap
self.period = period
if fx is None:
fx = approx_df(x, f, method, 0, **kwargs)
if fy is None:
fy = approx_df(y, f, method, 1, **kwargs)
if fxy is None:
fxy = approx_df(y, fx, method, 1, **kwargs)
self.derivs = {"fx": fx, "fy": fy, "fxy": fxy}
def __call__(self, xq: jax.Array, yq: jax.Array, dx: int = 0, dy: int = 0):
"""Evaluate the interpolated function or its derivatives.
Parameters
----------
xq, yq : ndarray, shape(Nq,)
x, y query points where interpolation is desired
dx, dy : int >= 0
Derivative to take in x, y directions.
Returns
-------
fq : ndarray, shape(Nq, ...)
Interpolated values.
"""
return interp2d(
xq,
yq,
self.x,
self.y,
self.f,
self.method,
(dx, dy),
self.extrap,
self.period,
**self.derivs,
)
class Interpolator3D(eqx.Module):
"""Convenience class for representing a 3D interpolated function.
Parameters
----------
x : ndarray, shape(Nx,)
x coordinates of known function values ("knots")
y : ndarray, shape(Ny,)
y coordinates of known function values ("knots")
z : ndarray, shape(Nz,)
z coordinates of known function values ("knots")
f : ndarray, shape(Nx,Ny,Nz,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as an array or tuple to specify different conditions
[[xlow, xhigh],[ylow,yhigh]]
period : float > 0, None, array-like, shape(2,)
periodicity of the function in x, y, z directions. None denotes no periodicity,
otherwise function is assumed to be periodic on the interval [0,period]. Use a
single value for the same in both directions.
Notes
-----
This class is registered as a PyTree in JAX (it is actually an equinox.Module)
so should be compatible with standard JAX transformations (jit, grad, vmap, etc.)
"""
x: jax.Array
y: jax.Array
z: jax.Array
f: jax.Array
derivs: dict
method: str
extrap: Union[bool, float, tuple]
period: Union[None, float, tuple]
axis: int
def __init__(
self,
x: jax.Array,
y: jax.Array,
z: jax.Array,
f: jax.Array,
method: str = "cubic",
extrap: Union[bool, float, tuple] = False,
period: Union[None, float, tuple] = None,
**kwargs,
):
x, y, z, f = map(jnp.asarray, (x, y, z, f))
axis = kwargs.get("axis", 0)
errorif(
(len(x) != f.shape[0]) or (x.ndim != 1),
ValueError,
"x and f must be arrays of equal length",
)
errorif(
(len(y) != f.shape[1]) or (y.ndim != 1),
ValueError,
"y and f must be arrays of equal length",
)
errorif(
(len(z) != f.shape[2]) or (z.ndim != 1),
ValueError,
"z and f must be arrays of equal length",
)
errorif(method not in METHODS_3D, ValueError, f"unknown method {method}")
fx = kwargs.pop("fx", None)
fy = kwargs.pop("fy", None)
fz = kwargs.pop("fz", None)
fxy = kwargs.pop("fxy", None)
fxz = kwargs.pop("fxz", None)
fyz = kwargs.pop("fyz", None)
fxyz = kwargs.pop("fxyz", None)
self.x = x
self.y = y
self.z = z
self.f = f
self.axis = axis
self.method = method
self.extrap = extrap
self.period = period
if fx is None:
fx = approx_df(x, f, method, 0, **kwargs)
if fy is None:
fy = approx_df(y, f, method, 1, **kwargs)
if fz is None:
fz = approx_df(z, f, method, 2, **kwargs)
if fxy is None:
fxy = approx_df(y, fx, method, 1, **kwargs)
if fxz is None:
fxz = approx_df(z, fx, method, 2, **kwargs)
if fyz is None:
fyz = approx_df(z, fy, method, 2, **kwargs)
if fxyz is None:
fxyz = approx_df(z, fxy, method, 2, **kwargs)
self.derivs = {
"fx": fx,
"fy": fy,
"fz": fz,
"fxy": fxy,
"fxz": fxz,
"fyz": fyz,
"fxyz": fxyz,
}
def __call__(
self,
xq: jax.Array,
yq: jax.Array,
zq: jax.Array,
dx: int = 0,
dy: int = 0,
dz: int = 0,
):
"""Evaluate the interpolated function or its derivatives.
Parameters
----------
xq, yq, zq : ndarray, shape(Nq,)
x, y, z query points where interpolation is desired
dx, dy, dz : int >= 0
Derivative to take in x, y, z directions.
Returns
-------
fq : ndarray, shape(Nq, ...)
Interpolated values.
"""
return interp3d(
xq,
yq,
zq,
self.x,
self.y,
self.z,
self.f,
self.method,
(dx, dy, dz),
self.extrap,
self.period,
**self.derivs,
)
@partial(jit, static_argnames="method")
def interp1d(
xq: jax.Array,
x: jax.Array,
f: jax.Array,
method: str = "cubic",
derivative: int = 0,
extrap: Union[bool, float, tuple] = False,
period: Union[None, float] = None,
**kwargs,
):
"""Interpolate a 1d function.
Parameters
----------
xq : ndarray, shape(Nq,)
query points where interpolation is desired
x : ndarray, shape(Nx,)
coordinates of known function values ("knots")
f : ndarray, shape(Nx,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
- ``'monotonic'``: C1 cubic splines that attempt to preserve monotonicity in the
data, and will not introduce new extrema in the interpolated points
- ``'monotonic-0'``: same as ``'monotonic'`` but with 0 first derivatives at
both endpoints
derivative : int >= 0
derivative order to calculate
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as a 2 element array or tuple to specify different conditions
for xq<x[0] and x[-1]<xq
period : float > 0, None
periodicity of the function. If given, function is assumed to be periodic
on the interval [0,period]. None denotes no periodicity
Returns
-------
fq : ndarray, shape(Nq,...)
function value at query points
Notes
-----
For repeated interpolation given the same x, f data, recommend using Interpolator1D
which caches the calculation of the derivatives and spline coefficients.
"""
xq, x, f = map(jnp.asarray, (xq, x, f))
axis = kwargs.get("axis", 0)
fx = kwargs.pop("fx", None)
outshape = xq.shape + f.shape[1:]
# Promote scalar query points to 1D array.
# Note this is done after the computation of outshape
# to make jax.grad work in the scalar case.
xq = jnp.atleast_1d(xq)
errorif(
(len(x) != f.shape[axis]) or (jnp.ndim(x) != 1),
ValueError,
"x and f must be arrays of equal length",
)
errorif(method not in METHODS_1D, ValueError, f"unknown method {method}")
lowx, highx = _parse_extrap(extrap, 1)
if period is not None:
xq, x, f, fx = _make_periodic(xq, x, period, axis, f, fx)
lowx = highx = True
if method == "nearest":
def derivative0():
i = jnp.argmin(jnp.abs(xq[:, np.newaxis] - x[np.newaxis]), axis=1)
return f[i]
def derivative1():
return jnp.zeros((xq.size, *f.shape[1:]))
fq = jax.lax.switch(derivative, [derivative0, derivative1])
elif method == "linear":
def derivative0():
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
df = jnp.take(f, i, axis) - jnp.take(f, i - 1, axis)
dx = x[i] - x[i - 1]
dxi = jnp.where(dx == 0, 0, 1 / dx)
delta = xq - x[i - 1]
fq = jnp.where(
(dx == 0),
jnp.take(f, i, axis).T,
jnp.take(f, i - 1, axis).T + (delta * dxi * df.T),
).T
return fq
def derivative1():
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
df = jnp.take(f, i, axis) - jnp.take(f, i - 1, axis)
dx = x[i] - x[i - 1]
dxi = jnp.where(dx == 0, 0, 1 / dx)
return (df.T * dxi).T
def derivative2():
return jnp.zeros((xq.size, *f.shape[1:]))
fq = jax.lax.switch(derivative, [derivative0, derivative1, derivative2])
elif method in (CUBIC_METHODS + ("monotonic", "monotonic-0")):
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
if fx is None:
fx = approx_df(x, f, method, axis, **kwargs)
assert fx.shape == f.shape
dx = x[i] - x[i - 1]
delta = xq - x[i - 1]
dxi = jnp.where(dx == 0, 0, 1 / dx)
t = delta * dxi
f0 = jnp.take(f, i - 1, axis)
f1 = jnp.take(f, i, axis)
fx0 = (jnp.take(fx, i - 1, axis).T * dx).T
fx1 = (jnp.take(fx, i, axis).T * dx).T
F = jnp.stack([f0, f1, fx0, fx1], axis=0).T
coef = jnp.vectorize(jnp.matmul, signature="(n,n),(n)->(n)")(A_CUBIC, F).T
ttx = _get_t_der(t, derivative, dxi)
fq = jnp.einsum("ji...,ij->i...", coef, ttx)
fq = _extrap(xq, fq, x, lowx, highx)
return fq.reshape(outshape)
@partial(jit, static_argnames="method")
def interp2d( # noqa: C901 - FIXME: break this up into simpler pieces
xq: jax.Array,
yq: jax.Array,
x: jax.Array,
y: jax.Array,
f: jax.Array,
method: str = "cubic",
derivative: int = 0,
extrap: Union[bool, float, tuple] = False,
period: Union[None, float, tuple] = None,
**kwargs,
):
"""Interpolate a 2d function.
Parameters
----------
xq : ndarray, shape(Nq,)
x query points where interpolation is desired
yq : ndarray, shape(Nq,)
y query points where interpolation is desired
x : ndarray, shape(Nx,)
x coordinates of known function values ("knots")
y : ndarray, shape(Ny,)
y coordinates of known function values ("knots")
f : ndarray, shape(Nx,Ny,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
derivative : int >= 0 or array-like, shape(2,)
derivative order to calculate in x, y. Use a single value for the same in both
directions.
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as an array or tuple to specify different conditions
[[xlow, xhigh],[ylow,yhigh]]
period : float > 0, None, array-like, shape(2,)
periodicity of the function in x, y directions. None denotes no periodicity,
otherwise function is assumed to be periodic on the interval [0,period]. Use a
single value for the same in both directions.
Returns
-------
fq : ndarray, shape(Nq,...)
function value at query points
Notes
-----
For repeated interpolation given the same x, y, f data, recommend using
Interpolator2D which caches the calculation of the derivatives and spline
coefficients.
"""
xq, yq, x, y, f = map(jnp.asarray, (xq, yq, x, y, f))
fx = kwargs.pop("fx", None)
fy = kwargs.pop("fy", None)
fxy = kwargs.pop("fxy", None)
xq, yq = jnp.broadcast_arrays(xq, yq)
outshape = xq.shape + f.shape[2:]
# Promote scalar query points to 1D array.
# Note this is done after the computation of outshape
# to make jax.grad work in the scalar case.
xq, yq = map(jnp.atleast_1d, (xq, yq))
errorif(
(len(x) != f.shape[0]) or (x.ndim != 1),
ValueError,
"x and f must be arrays of equal length",
)
errorif(
(len(y) != f.shape[1]) or (y.ndim != 1),
ValueError,
"y and f must be arrays of equal length",
)
errorif(method not in METHODS_2D, ValueError, f"unknown method {method}")
periodx, periody = _parse_ndarg(period, 2)
derivative_x, derivative_y = _parse_ndarg(derivative, 2)
lowx, highx, lowy, highy = _parse_extrap(extrap, 2)
if periodx is not None:
xq, x, f, fx, fy, fxy = _make_periodic(xq, x, periodx, 0, f, fx, fy, fxy)
lowx = highx = True
if periody is not None:
yq, y, f, fx, fy, fxy = _make_periodic(yq, y, periody, 1, f, fx, fy, fxy)
lowy = highy = True
if method == "nearest":
def derivative0():
# because of the regular spaced grid we know that the nearest point
# will be one of the 4 neighbors on the grid, so we first find those
# and then take the nearest one among them.
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
j = jnp.clip(jnp.searchsorted(y, yq, side="right"), 1, len(y) - 1)
neighbors_x = jnp.array(
[[x[i], x[i - 1], x[i], x[i - 1]], [y[j], y[j], y[j - 1], y[j - 1]]]
)
neighbors_f = jnp.array(
[f[i, j].T, f[i - 1, j].T, f[i, j - 1].T, f[i - 1, j - 1].T]
)
xyq = jnp.array([xq, yq])
dist = jnp.linalg.norm(neighbors_x - xyq[:, None, :], axis=0)
idx = jnp.argmin(dist, axis=0)
return jax.vmap(lambda a, b: jnp.take(a, b, axis=-1))(neighbors_f.T, idx)
def derivative1():
return jnp.zeros((xq.size, *f.shape[2:]))
fq = jax.lax.cond(
(derivative_x == 0) & (derivative_y == 0), derivative0, derivative1
)
elif method == "linear":
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
j = jnp.clip(jnp.searchsorted(y, yq, side="right"), 1, len(y) - 1)
f00 = f[i - 1, j - 1]
f01 = f[i - 1, j]
f10 = f[i, j - 1]
f11 = f[i, j]
x0 = x[i - 1]
x1 = x[i]
y0 = y[j - 1]
y1 = y[j]
dx = x1 - x0
dxi = jnp.where(dx == 0, 0, 1 / dx)
dy = y1 - y0
dyi = jnp.where(dy == 0, 0, 1 / dy)
dx0 = lambda: jnp.array([x1 - xq, xq - x0])
dx1 = lambda: jnp.array([-jnp.ones_like(xq), jnp.ones_like(xq)])
dx2 = lambda: jnp.zeros((2, xq.size))
dy0 = lambda: jnp.array([y1 - yq, yq - y0])
dy1 = lambda: jnp.array([-jnp.ones_like(yq), jnp.ones_like(yq)])
dy2 = lambda: jnp.zeros((2, yq.size))
tx = jax.lax.switch(derivative_x, [dx0, dx1, dx2])
ty = jax.lax.switch(derivative_y, [dy0, dy1, dy2])
F = jnp.array([[f00, f01], [f10, f11]])
fq = (dxi * dyi * jnp.einsum("ijk...,ik,jk->k...", F, tx, ty).T).T
elif method in CUBIC_METHODS:
if fx is None:
fx = approx_df(x, f, method, 0, **kwargs)
if fy is None:
fy = approx_df(y, f, method, 1, **kwargs)
if fxy is None:
fxy = approx_df(y, fx, method, 1, **kwargs)
assert fx.shape == fy.shape == fxy.shape == f.shape
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
j = jnp.clip(jnp.searchsorted(y, yq, side="right"), 1, len(y) - 1)
dx = x[i] - x[i - 1]
deltax = xq - x[i - 1]
dxi = jnp.where(dx == 0, 0, 1 / dx)
tx = deltax * dxi
dy = y[j] - y[j - 1]
deltay = yq - y[j - 1]
dyi = jnp.where(dy == 0, 0, 1 / dy)
ty = deltay * dyi
fs = OrderedDict()
fs["f"] = f
fs["fx"] = fx
fs["fy"] = fy
fs["fxy"] = fxy
fsq = OrderedDict()
for ff in fs.keys():
for jj in [0, 1]:
for ii in [0, 1]:
s = ff + str(ii) + str(jj)
fsq[s] = fs[ff][i - 1 + ii, j - 1 + jj]
if "x" in ff:
fsq[s] = (dx * fsq[s].T).T
if "y" in ff:
fsq[s] = (dy * fsq[s].T).T
F = jnp.stack([foo for foo in fsq.values()], axis=0).T
coef = jnp.vectorize(jnp.matmul, signature="(n,n),(n)->(n)")(A_BICUBIC, F).T
coef = jnp.moveaxis(coef.reshape((4, 4, *coef.shape[1:]), order="F"), 2, 0)
ttx = _get_t_der(tx, derivative_x, dxi)
tty = _get_t_der(ty, derivative_y, dyi)
fq = jnp.einsum("ijk...,ij,ik->i...", coef, ttx, tty)
fq = _extrap(xq, fq, x, lowx, highx)
fq = _extrap(yq, fq, y, lowy, highy)
return fq.reshape(outshape)
@partial(jit, static_argnames="method")
def interp3d( # noqa: C901 - FIXME: break this up into simpler pieces
xq: jax.Array,
yq: jax.Array,
zq: jax.Array,
x: jax.Array,
y: jax.Array,
z: jax.Array,
f: jax.Array,
method: str = "cubic",
derivative: int = 0,
extrap: Union[bool, float, tuple] = False,
period: Union[None, float, tuple] = None,
**kwargs,
):
"""Interpolate a 3d function.
Parameters
----------
xq : ndarray, shape(Nq,)
x query points where interpolation is desired
yq : ndarray, shape(Nq,)
y query points where interpolation is desired
zq : ndarray, shape(Nq,)
z query points where interpolation is desired
x : ndarray, shape(Nx,)
x coordinates of known function values ("knots")
y : ndarray, shape(Ny,)
y coordinates of known function values ("knots")
z : ndarray, shape(Nz,)
z coordinates of known function values ("knots")
f : ndarray, shape(Nx,Ny,Nz,...)
function values to interpolate
method : str
method of interpolation
- ``'nearest'``: nearest neighbor interpolation
- ``'linear'``: linear interpolation
- ``'cubic'``: C1 cubic splines (aka local splines)
- ``'cubic2'``: C2 cubic splines (aka natural splines)
- ``'catmull-rom'``: C1 cubic centripetal "tension" splines
- ``'cardinal'``: C1 cubic general tension splines. If used, can also pass
keyword parameter ``c`` in float[0,1] to specify tension
derivative : int >= 0, array-like, shape(3,)
derivative order to calculate in x,y,z directions. Use a single value for the
same in all directions.
extrap : bool, float, array-like
whether to extrapolate values beyond knots (True) or return nan (False),
or a specified value to return for query points outside the bounds. Can
also be passed as an array or tuple to specify different conditions for
[[xlow, xhigh],[ylow,yhigh],[zlow,zhigh]]
period : float > 0, None, array-like, shape(3,)
periodicity of the function in x, y, z directions. None denotes no periodicity,
otherwise function is assumed to be periodic on the interval [0,period]. Use a
single value for the same in all directions.
Returns
-------
fq : ndarray, shape(Nq,...)
function value at query points
Notes
-----
For repeated interpolation given the same x, y, z, f data, recommend using
Interpolator3D which caches the calculation of the derivatives and spline
coefficients.
"""
xq, yq, zq, x, y, z, f = map(jnp.asarray, (xq, yq, zq, x, y, z, f))
errorif(
(len(x) != f.shape[0]) or (x.ndim != 1),
ValueError,
"x and f must be arrays of equal length",
)
errorif(
(len(y) != f.shape[1]) or (y.ndim != 1),
ValueError,
"y and f must be arrays of equal length",
)
errorif(
(len(z) != f.shape[2]) or (z.ndim != 1),
ValueError,
"z and f must be arrays of equal length",
)
errorif(method not in METHODS_3D, ValueError, f"unknown method {method}")
xq, yq, zq = jnp.broadcast_arrays(xq, yq, zq)
outshape = xq.shape + f.shape[3:]
# Promote scalar query points to 1D array.
# Note this is done after the computation of outshape
# to make jax.grad work in the scalar case.
xq, yq, zq = map(jnp.atleast_1d, (xq, yq, zq))
fx = kwargs.pop("fx", None)
fy = kwargs.pop("fy", None)
fz = kwargs.pop("fz", None)
fxy = kwargs.pop("fxy", None)
fxz = kwargs.pop("fxz", None)
fyz = kwargs.pop("fyz", None)
fxyz = kwargs.pop("fxyz", None)
periodx, periody, periodz = _parse_ndarg(period, 3)
derivative_x, derivative_y, derivative_z = _parse_ndarg(derivative, 3)
lowx, highx, lowy, highy, lowz, highz = _parse_extrap(extrap, 3)
if periodx is not None:
xq, x, f, fx, fy, fz, fxy, fxz, fyz, fxyz = _make_periodic(
xq, x, periodx, 0, f, fx, fy, fz, fxy, fxz, fyz, fxyz
)
lowx = highx = True
if periody is not None:
yq, y, f, fx, fy, fz, fxy, fxz, fyz, fxyz = _make_periodic(
yq, y, periody, 1, f, fx, fy, fz, fxy, fxz, fyz, fxyz
)
lowy = highy = True
if periodz is not None:
zq, z, f, fx, fy, fz, fxy, fxz, fyz, fxyz = _make_periodic(
zq, z, periodz, 2, f, fx, fy, fz, fxy, fxz, fyz, fxyz
)
lowz = highz = True
if method == "nearest":
def derivative0():
# because of the regular spaced grid we know that the nearest point
# will be one of the 8 neighbors on the grid, so we first find those
# and then take the nearest one among them.
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
j = jnp.clip(jnp.searchsorted(y, yq, side="right"), 1, len(y) - 1)
k = jnp.clip(jnp.searchsorted(z, zq, side="right"), 1, len(z) - 1)
neighbors_x = jnp.array(
[
[x[i], x[i - 1], x[i], x[i - 1], x[i], x[i - 1], x[i], x[i - 1]],
[y[j], y[j], y[j - 1], y[j - 1], y[j], y[j], y[j - 1], y[j - 1]],
[z[k], z[k], z[k], z[k], z[k - 1], z[k - 1], z[k - 1], z[k - 1]],
]
)
neighbors_f = jnp.array(
[
f[i, j, k].T,
f[i - 1, j, k].T,
f[i, j - 1, k].T,
f[i - 1, j - 1, k].T,
f[i, j, k - 1].T,
f[i - 1, j, k - 1].T,
f[i, j - 1, k - 1].T,
f[i - 1, j - 1, k - 1].T,
]
)
xyzq = jnp.array([xq, yq, zq])
dist = jnp.linalg.norm(neighbors_x - xyzq[:, None, :], axis=0)
idx = jnp.argmin(dist, axis=0)
return jax.vmap(lambda a, b: jnp.take(a, b, axis=-1))(neighbors_f.T, idx)
def derivative1():
return jnp.zeros((xq.size, *f.shape[3:]))
fq = jax.lax.cond(
(derivative_x == 0) & (derivative_y == 0) & (derivative_z == 0),
derivative0,
derivative1,
)
elif method == "linear":
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
j = jnp.clip(jnp.searchsorted(y, yq, side="right"), 1, len(y) - 1)
k = jnp.clip(jnp.searchsorted(z, zq, side="right"), 1, len(z) - 1)
f000 = f[i - 1, j - 1, k - 1]
f001 = f[i - 1, j - 1, k]
f010 = f[i - 1, j, k - 1]
f100 = f[i, j - 1, k - 1]
f110 = f[i, j, k - 1]
f011 = f[i - 1, j, k]
f101 = f[i, j - 1, k]
f111 = f[i, j, k]
x0 = x[i - 1]
x1 = x[i]
y0 = y[j - 1]
y1 = y[j]
z0 = z[k - 1]
z1 = z[k]
dx = x1 - x0
dxi = jnp.where(dx == 0, 0, 1 / dx)
dy = y1 - y0
dyi = jnp.where(dy == 0, 0, 1 / dy)
dz = z1 - z0
dzi = jnp.where(dz == 0, 0, 1 / dz)
dx0 = lambda: jnp.array([x1 - xq, xq - x0])
dx1 = lambda: jnp.array([-jnp.ones_like(xq), jnp.ones_like(xq)])
dx2 = lambda: jnp.zeros((2, xq.size))
dy0 = lambda: jnp.array([y1 - yq, yq - y0])
dy1 = lambda: jnp.array([-jnp.ones_like(yq), jnp.ones_like(yq)])
dy2 = lambda: jnp.zeros((2, yq.size))
dz0 = lambda: jnp.array([z1 - zq, zq - z0])
dz1 = lambda: jnp.array([-jnp.ones_like(zq), jnp.ones_like(zq)])
dz2 = lambda: jnp.zeros((2, zq.size))
tx = jax.lax.switch(derivative_x, [dx0, dx1, dx2])
ty = jax.lax.switch(derivative_y, [dy0, dy1, dy2])
tz = jax.lax.switch(derivative_z, [dz0, dz1, dz2])
F = jnp.array([[[f000, f001], [f010, f011]], [[f100, f101], [f110, f111]]])
fq = (dxi * dyi * dzi * jnp.einsum("lijk...,lk,ik,jk->k...", F, tx, ty, tz).T).T
elif method in CUBIC_METHODS:
if fx is None:
fx = approx_df(x, f, method, 0, **kwargs)
if fy is None:
fy = approx_df(y, f, method, 1, **kwargs)
if fz is None:
fz = approx_df(z, f, method, 2, **kwargs)
if fxy is None:
fxy = approx_df(y, fx, method, 1, **kwargs)
if fxz is None:
fxz = approx_df(z, fx, method, 2, **kwargs)
if fyz is None:
fyz = approx_df(z, fy, method, 2, **kwargs)
if fxyz is None:
fxyz = approx_df(z, fxy, method, 2, **kwargs)
assert (
fx.shape
== fy.shape
== fz.shape
== fxy.shape
== fxz.shape
== fyz.shape
== fxyz.shape
== f.shape
)
i = jnp.clip(jnp.searchsorted(x, xq, side="right"), 1, len(x) - 1)
j = jnp.clip(jnp.searchsorted(y, yq, side="right"), 1, len(y) - 1)
k = jnp.clip(jnp.searchsorted(z, zq, side="right"), 1, len(z) - 1)
dx = x[i] - x[i - 1]
deltax = xq - x[i - 1]
dxi = jnp.where(dx == 0, 0, 1 / dx)
tx = deltax * dxi
dy = y[j] - y[j - 1]
deltay = yq - y[j - 1]
dyi = jnp.where(dy == 0, 0, 1 / dy)
ty = deltay * dyi
dz = z[k] - z[k - 1]
deltaz = zq - z[k - 1]
dzi = jnp.where(dz == 0, 0, 1 / dz)
tz = deltaz * dzi
fs = OrderedDict()
fs["f"] = f
fs["fx"] = fx
fs["fy"] = fy
fs["fz"] = fz
fs["fxy"] = fxy
fs["fxz"] = fxz
fs["fyz"] = fyz
fs["fxyz"] = fxyz
fsq = OrderedDict()
for ff in fs.keys():
for kk in [0, 1]:
for jj in [0, 1]:
for ii in [0, 1]:
s = ff + str(ii) + str(jj) + str(kk)
fsq[s] = fs[ff][i - 1 + ii, j - 1 + jj, k - 1 + kk]
if "x" in ff:
fsq[s] = (dx * fsq[s].T).T
if "y" in ff:
fsq[s] = (dy * fsq[s].T).T
if "z" in ff:
fsq[s] = (dz * fsq[s].T).T
F = jnp.stack([foo for foo in fsq.values()], axis=0).T
coef = jnp.vectorize(jnp.matmul, signature="(n,n),(n)->(n)")(A_TRICUBIC, F).T
coef = jnp.moveaxis(coef.reshape((4, 4, 4, *coef.shape[1:]), order="F"), 3, 0)
ttx = _get_t_der(tx, derivative_x, dxi)
tty = _get_t_der(ty, derivative_y, dyi)
ttz = _get_t_der(tz, derivative_z, dzi)
fq = jnp.einsum("lijk...,li,lj,lk->l...", coef, ttx, tty, ttz)
fq = _extrap(xq, fq, x, lowx, highx)
fq = _extrap(yq, fq, y, lowy, highy)
fq = _extrap(zq, fq, z, lowz, highz)
return fq.reshape(outshape)
@partial(jit, static_argnames=("axis"))
def _make_periodic(xq: jax.Array, x: jax.Array, period: float, axis: int, *arrs):
"""Make arrays periodic along a specified axis."""
period = abs(period)
xq = xq % period
x = x % period
i = jnp.argsort(x)
x = x[i]
x = jnp.concatenate([x[-1:] - period, x, x[:1] + period])
arrs = list(arrs)
for k in range(len(arrs)):
if arrs[k] is not None:
arrs[k] = jnp.take(arrs[k], i, axis, mode="wrap")
arrs[k] = jnp.concatenate(
[
jnp.take(arrs[k], jnp.array([-1]), axis),
arrs[k],
jnp.take(arrs[k], jnp.array([0]), axis),
],
axis=axis,
)
return (xq, x, *arrs)
@jit
def _get_t_der(t: jax.Array, derivative: int, dxi: jax.Array):
"""Get arrays of [1,t,t^2,t^3] for cubic interpolation."""
t0 = jnp.zeros_like(t)
t1 = jnp.ones_like(t)
dxi = jnp.atleast_1d(dxi)[:, None]
# derivatives of monomials
d0 = lambda: jnp.array([t1, t, t**2, t**3]).T * dxi**0
d1 = lambda: jnp.array([t0, t1, 2 * t, 3 * t**2]).T * dxi
d2 = lambda: jnp.array([t0, t0, 2 * t1, 6 * t]).T * dxi**2
d3 = lambda: jnp.array([t0, t0, t0, 6 * t1]).T * dxi**3
d4 = lambda: jnp.array([t0, t0, t0, t0]).T * (dxi * 0)
return jax.lax.switch(derivative, [d0, d1, d2, d3, d4])
def _parse_ndarg(arg, n):
try:
k = len(arg)
except TypeError:
arg = tuple(arg for _ in range(n))
k = n
assert k == n, "got too many args"
return arg
def _parse_extrap(extrap, n): | if isbool(extrap): # same for lower,upper in all dimensions | 1 | 2023-10-18 13:12:20+00:00 | 8k |
city96/ComfyUI_ExtraModels | VAE/models/temporal_ae.py | [
{
"identifier": "Encoder",
"path": "VAE/models/kl.py",
"snippet": "class Encoder(nn.Module):\n\tdef __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,\n\t\t\t\t attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,\n\t\t\t\t resolution, z_channels, double_z=True, use_linear_at... | import math
import torch
import numpy as np
from torch import nn
from typing import Callable, Iterable, Union, Optional
from einops import rearrange, repeat
from comfy import model_management
from .kl import (
Encoder, Decoder, Upsample, Normalize,
AttnBlock, ResnetBlock, #MemoryEfficientAttnBlock,
DiagonalGaussianDistribution, nonlinearity, make_attn
) | 5,441 | # all_out.append(dec)
# out = torch.cat(all_out, dim=0)
## default
out = self.decoder(
z, timesteps=len(z)
)
return out
def forward(self, input, sample_posterior=True):
posterior = self.encode(input)
if sample_posterior:
z = posterior.sample()
else:
z = posterior.mode()
dec = self.decode(z)
return dec, posterior
class VideoDecoder(nn.Module):
available_time_modes = ["all", "conv-only", "attn-only"]
def __init__(
self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
attn_type="vanilla",
video_kernel_size: Union[int, list] = 3, alpha: float = 0.0, merge_strategy: str = "learned", time_mode: str = "conv-only",
**ignorekwargs
):
super().__init__()
if use_linear_attn: attn_type = "linear"
self.ch = ch
self.temb_ch = 0
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
self.resolution = resolution
self.in_channels = in_channels
self.give_pre_end = give_pre_end
self.tanh_out = tanh_out
self.video_kernel_size = video_kernel_size
self.alpha = alpha
self.merge_strategy = merge_strategy
self.time_mode = time_mode
assert (
self.time_mode in self.available_time_modes
), f"time_mode parameter has to be in {self.available_time_modes}"
# compute in_ch_mult, block_in and curr_res at lowest res
in_ch_mult = (1,)+tuple(ch_mult)
block_in = ch*ch_mult[self.num_resolutions-1]
curr_res = resolution // 2**(self.num_resolutions-1)
self.z_shape = (1,z_channels,curr_res,curr_res)
print("Working with z of shape {} = {} dimensions.".format(
self.z_shape, np.prod(self.z_shape)))
# z to block_in
self.conv_in = torch.nn.Conv2d(
z_channels,
block_in,
kernel_size=3,
stride=1,
padding=1
)
# middle
self.mid = nn.Module()
self.mid.block_1 = VideoResBlock(
in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout,
video_kernel_size=self.video_kernel_size,
alpha=self.alpha,
merge_strategy=self.merge_strategy,
)
self.mid.attn_1 = make_attn(
block_in,
attn_type=attn_type,
)
self.mid.block_2 = VideoResBlock(
in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout,
video_kernel_size=self.video_kernel_size,
alpha=self.alpha,
merge_strategy=self.merge_strategy,
)
# upsampling
self.up = nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
block = nn.ModuleList()
attn = nn.ModuleList()
block_out = ch*ch_mult[i_level]
for i_block in range(self.num_res_blocks+1):
block.append(VideoResBlock(
in_channels=block_in,
out_channels=block_out,
temb_channels=self.temb_ch,
dropout=dropout,
video_kernel_size=self.video_kernel_size,
alpha=self.alpha,
merge_strategy=self.merge_strategy,
))
block_in = block_out
if curr_res in attn_resolutions:
attn.append(make_attn(
block_in,
attn_type=attn_type,
))
up = nn.Module()
up.block = block
up.attn = attn
if i_level != 0:
up.upsample = Upsample(block_in, resamp_with_conv)
curr_res = curr_res * 2
self.up.insert(0, up) # prepend to get consistent order
# end
|
class AutoencoderKL(nn.Module):
def __init__(self, config):
super().__init__()
self.embed_dim = config["embed_dim"]
self.encoder = Encoder(**config)
self.decoder = VideoDecoder(**config)
assert config["double_z"]
# these aren't used here for some reason
# self.quant_conv = torch.nn.Conv2d(2*config["z_channels"], 2*self.embed_dim, 1)
# self.post_quant_conv = torch.nn.Conv2d(self.embed_dim, config["z_channels"], 1)
def encode(self, x):
## batched
# n_samples = x.shape[0]
# n_rounds = math.ceil(x.shape[0] / n_samples)
# all_out = []
# for n in range(n_rounds):
# h = self.encoder(
# x[n * n_samples : (n + 1) * n_samples]
# )
# moments = h # self.quant_conv(h)
# posterior = DiagonalGaussianDistribution(moments)
# all_out.append(posterior.sample())
# z = torch.cat(all_out, dim=0)
# return z
## default
h = self.encoder(x)
moments = h # self.quant_conv(h)
posterior = DiagonalGaussianDistribution(moments)
return posterior.sample()
def decode(self, z):
## batched - seems the same as default?
# n_samples = z.shape[0]
# n_rounds = math.ceil(z.shape[0] / n_samples)
# all_out = []
# for n in range(n_rounds):
# dec = self.decoder(
# z[n * n_samples : (n + 1) * n_samples],
# timesteps=len(z[n * n_samples : (n + 1) * n_samples]),
# )
# all_out.append(dec)
# out = torch.cat(all_out, dim=0)
## default
out = self.decoder(
z, timesteps=len(z)
)
return out
def forward(self, input, sample_posterior=True):
posterior = self.encode(input)
if sample_posterior:
z = posterior.sample()
else:
z = posterior.mode()
dec = self.decode(z)
return dec, posterior
class VideoDecoder(nn.Module):
available_time_modes = ["all", "conv-only", "attn-only"]
def __init__(
self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
attn_type="vanilla",
video_kernel_size: Union[int, list] = 3, alpha: float = 0.0, merge_strategy: str = "learned", time_mode: str = "conv-only",
**ignorekwargs
):
super().__init__()
if use_linear_attn: attn_type = "linear"
self.ch = ch
self.temb_ch = 0
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
self.resolution = resolution
self.in_channels = in_channels
self.give_pre_end = give_pre_end
self.tanh_out = tanh_out
self.video_kernel_size = video_kernel_size
self.alpha = alpha
self.merge_strategy = merge_strategy
self.time_mode = time_mode
assert (
self.time_mode in self.available_time_modes
), f"time_mode parameter has to be in {self.available_time_modes}"
# compute in_ch_mult, block_in and curr_res at lowest res
in_ch_mult = (1,)+tuple(ch_mult)
block_in = ch*ch_mult[self.num_resolutions-1]
curr_res = resolution // 2**(self.num_resolutions-1)
self.z_shape = (1,z_channels,curr_res,curr_res)
print("Working with z of shape {} = {} dimensions.".format(
self.z_shape, np.prod(self.z_shape)))
# z to block_in
self.conv_in = torch.nn.Conv2d(
z_channels,
block_in,
kernel_size=3,
stride=1,
padding=1
)
# middle
self.mid = nn.Module()
self.mid.block_1 = VideoResBlock(
in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout,
video_kernel_size=self.video_kernel_size,
alpha=self.alpha,
merge_strategy=self.merge_strategy,
)
self.mid.attn_1 = make_attn(
block_in,
attn_type=attn_type,
)
self.mid.block_2 = VideoResBlock(
in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout,
video_kernel_size=self.video_kernel_size,
alpha=self.alpha,
merge_strategy=self.merge_strategy,
)
# upsampling
self.up = nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
block = nn.ModuleList()
attn = nn.ModuleList()
block_out = ch*ch_mult[i_level]
for i_block in range(self.num_res_blocks+1):
block.append(VideoResBlock(
in_channels=block_in,
out_channels=block_out,
temb_channels=self.temb_ch,
dropout=dropout,
video_kernel_size=self.video_kernel_size,
alpha=self.alpha,
merge_strategy=self.merge_strategy,
))
block_in = block_out
if curr_res in attn_resolutions:
attn.append(make_attn(
block_in,
attn_type=attn_type,
))
up = nn.Module()
up.block = block
up.attn = attn
if i_level != 0:
up.upsample = Upsample(block_in, resamp_with_conv)
curr_res = curr_res * 2
self.up.insert(0, up) # prepend to get consistent order
# end | self.norm_out = Normalize(block_in) | 3 | 2023-10-20 21:19:44+00:00 | 8k |
aikunyi/FreTS | data_provider/data_factory.py | [
{
"identifier": "Dataset_Covid",
"path": "data_provider/data_loader.py",
"snippet": "class Dataset_Covid(Dataset):\n def __init__(self, root_path, flag='train', size=None,\n features='S', data_path='ETTh1.csv',\n target='OT', scale=True, timeenc=0, freq='h', train_only... | from data_provider.data_loader import Dataset_Covid, Dataset_Custom, Dataset_Pred, Dataset_Custom_
from torch.utils.data import DataLoader | 4,480 |
data_dict = {
'ETTh1': Dataset_Custom_,#Dataset_ETT_hour,
'ETTm1': Dataset_Custom_,
'traffic': Dataset_Custom,
'electricity': Dataset_Custom_,
'exchange': Dataset_Custom_,
'weather': Dataset_Custom_,
|
data_dict = {
'ETTh1': Dataset_Custom_,#Dataset_ETT_hour,
'ETTm1': Dataset_Custom_,
'traffic': Dataset_Custom,
'electricity': Dataset_Custom_,
'exchange': Dataset_Custom_,
'weather': Dataset_Custom_, | 'covid': Dataset_Covid, | 0 | 2023-10-23 13:15:14+00:00 | 8k |
apple/ml-nvas3d | nvas3d/utils/training_data_generation/generate_test_data.py | [
{
"identifier": "load_room_grid",
"path": "soundspaces_nvas3d/utils/aihabitat_utils.py",
"snippet": "def load_room_grid(\n room: str,\n grid_distance: float\n) -> T.Dict:\n \"\"\"\n Load grid data for a specified room. If the grid data does not exist, it generates one.\n\n Args:\n - ro... | import os
import glob
import json
import random
import subprocess
import concurrent.futures
import torch
import torchaudio
from itertools import product
from tqdm import tqdm
from soundspaces_nvas3d.utils.aihabitat_utils import load_room_grid
from soundspaces_nvas3d.utils.audio_utils import wiener_deconv_list
from nvas3d.utils.audio_utils import clip_two
from nvas3d.utils.utils import normalize, parse_librispeech_metadata, MP3D_SCENE_SPLITS
from nvas3d.utils.generate_dataset_utils import sample_speech, sample_nonspeech, sample_acoustic_guitar, sample_all, sample_instrument, clip_source, load_ir_source_receiver, save_audio_list, compute_reverb | 4,976 |
random.seed(42)
DATASET_NAME = f'nvas3d_square_{SOURCE1_DATA}_{SOURCE2_DATA}_queryall_{num_id_per_room}_v3'
os.makedirs(f'data/{DATASET_NAME}', exist_ok=True)
grid_distance = 1.0
grid_distance_str = str(grid_distance).replace(".", "_")
target_shape_t = 256
ir_length = 72000
ir_clip_idx = ir_length - 1
hop_length = 480
len_clip = hop_length * (target_shape_t - 1) + ir_length - 1
sample_rate = 48000
snr = 100
audio_format = 'flac'
for split in ['val']:
# LibriSpeech
if split == 'train':
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/train'
elif split == 'val':
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/validation'
elif split == 'test':
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/test'
else:
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/validation'
files_librispeech = glob.glob(librispeech_dir + '/**/*.flac', recursive=True)
librispeech_metadata = parse_librispeech_metadata(f'data/MIDI/clip/Speech/LibriSpeech48k/SPEAKERS.TXT')
# MIDI
if split == 'train':
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'train')) if os.path.isdir(path)]
elif split == 'val':
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'validation')) if os.path.isdir(path)]
elif split == 'test':
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'test')) if os.path.isdir(path)]
else:
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'validation')) if os.path.isdir(path)]
# RIR
if split == 'val_trainscene':
split_scene = 'train'
else:
split_scene = split
ir_dir = f'data/nvas3d_square/ir/{split_scene}/grid_{grid_distance_str}'
# Image
dirname_sourceimage = f'data/nvas3d_square/image/{split_scene}/grid_{grid_distance_str}'
# Iterate over rooms
for i_room, room in enumerate(tqdm(MP3D_SCENE_SPLITS[split_scene])):
grid_points = load_room_grid(room, grid_distance)['grid_points']
num_points = grid_points.shape[0]
total_pairs = []
filename = f'data/nvas3d_square/metadata/grid_{grid_distance_str}/{room}_square.json' # from generate_metadata_square.json
with open(filename, 'r') as file:
square_data = json.load(file)
pairs_all = square_data['selected_pairs']
# Add each pair with room id to the total list
random.shuffle(pairs_all)
# pairs = pairs[:num_id_per_room]
pairs = []
for pair in pairs_all:
source_idx_list, receiver_idx_list, novel_receiver_idx = pair
if (novel_receiver_idx not in source_idx_list) and (novel_receiver_idx not in receiver_idx_list):
pairs.append(pair)
# else:
# print(f'invalid idx: {source_idx_list}, {receiver_idx_list}, {novel_receiver_idx}')
if len(pairs) >= num_id_per_room:
break
# All IRs
# Initialize a list to store all combinations
all_combinations = []
# Iterate over selected pairs
for pair in pairs:
# Unpack the pair
_, receiver_idxs, _ = pair
# Get all combinations of source and receiver indices
comb = product(list(range(num_points)), receiver_idxs)
# Add these combinations to the list
all_combinations.extend(comb)
all_combinations = list(set(all_combinations)) # remove redundancy
# download wav files # Replace to render IR
# temp_list = set()
# with concurrent.futures.ThreadPoolExecutor() as executor:
# for source_idx in executor.map(download_wav, all_combinations):
# temp_list.add(source_idx)
# temp_list = list(temp_list)
# Render image
dirname_target_image = f'data/{DATASET_NAME}/{split}/{room}/image'
os.makedirs(dirname_target_image, exist_ok=True)
query_idx_list = list(range(num_points))
subprocess.run(['python', 'soundspaces_nvas3d/image_rendering/generate_target_image.py', '--room', room, '--dirname', dirname_target_image, '--source_idx_list', ' '.join(map(str, query_idx_list))])
# For each pair, make data
for i_pair, pair in enumerate(tqdm(pairs)):
dirname = f'data/{DATASET_NAME}/{split}/{room}/{i_pair}'
source_idx_list, receiver_idx_list, novel_receiver_idx = pair
os.makedirs(dirname, exist_ok=True)
# Compute source
os.makedirs(f'{dirname}/source', exist_ok=True)
if SOURCE1_DATA == 'speech':
source1_audio, source1_class = sample_speech(files_librispeech, librispeech_metadata)
elif SOURCE1_DATA == 'nonspeech':
source1_audio, source1_class = sample_nonspeech(all_instruments_dir)
elif SOURCE1_DATA == 'guitar':
source1_audio, source1_class = sample_acoustic_guitar(all_instruments_dir)
elif SOURCE1_DATA == 'all':
source1_audio, source1_class = sample_all(all_instruments_dir, librispeech_metadata)
else:
| #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
os.makedirs('data/temp', exist_ok=True)
SOURCE1_DATA = 'Guitar'
SOURCE2_DATA = 'Guitar'
num_id_per_room = 1
random.seed(42)
DATASET_NAME = f'nvas3d_square_{SOURCE1_DATA}_{SOURCE2_DATA}_queryall_{num_id_per_room}_v3'
os.makedirs(f'data/{DATASET_NAME}', exist_ok=True)
grid_distance = 1.0
grid_distance_str = str(grid_distance).replace(".", "_")
target_shape_t = 256
ir_length = 72000
ir_clip_idx = ir_length - 1
hop_length = 480
len_clip = hop_length * (target_shape_t - 1) + ir_length - 1
sample_rate = 48000
snr = 100
audio_format = 'flac'
for split in ['val']:
# LibriSpeech
if split == 'train':
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/train'
elif split == 'val':
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/validation'
elif split == 'test':
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/test'
else:
librispeech_dir = f'data/MIDI/clip/Speech/LibriSpeech48k/validation'
files_librispeech = glob.glob(librispeech_dir + '/**/*.flac', recursive=True)
librispeech_metadata = parse_librispeech_metadata(f'data/MIDI/clip/Speech/LibriSpeech48k/SPEAKERS.TXT')
# MIDI
if split == 'train':
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'train')) if os.path.isdir(path)]
elif split == 'val':
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'validation')) if os.path.isdir(path)]
elif split == 'test':
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'test')) if os.path.isdir(path)]
else:
all_instruments_dir = [path for path in glob.glob(os.path.join('data/MIDI/clip', '*/*', 'validation')) if os.path.isdir(path)]
# RIR
if split == 'val_trainscene':
split_scene = 'train'
else:
split_scene = split
ir_dir = f'data/nvas3d_square/ir/{split_scene}/grid_{grid_distance_str}'
# Image
dirname_sourceimage = f'data/nvas3d_square/image/{split_scene}/grid_{grid_distance_str}'
# Iterate over rooms
for i_room, room in enumerate(tqdm(MP3D_SCENE_SPLITS[split_scene])):
grid_points = load_room_grid(room, grid_distance)['grid_points']
num_points = grid_points.shape[0]
total_pairs = []
filename = f'data/nvas3d_square/metadata/grid_{grid_distance_str}/{room}_square.json' # from generate_metadata_square.json
with open(filename, 'r') as file:
square_data = json.load(file)
pairs_all = square_data['selected_pairs']
# Add each pair with room id to the total list
random.shuffle(pairs_all)
# pairs = pairs[:num_id_per_room]
pairs = []
for pair in pairs_all:
source_idx_list, receiver_idx_list, novel_receiver_idx = pair
if (novel_receiver_idx not in source_idx_list) and (novel_receiver_idx not in receiver_idx_list):
pairs.append(pair)
# else:
# print(f'invalid idx: {source_idx_list}, {receiver_idx_list}, {novel_receiver_idx}')
if len(pairs) >= num_id_per_room:
break
# All IRs
# Initialize a list to store all combinations
all_combinations = []
# Iterate over selected pairs
for pair in pairs:
# Unpack the pair
_, receiver_idxs, _ = pair
# Get all combinations of source and receiver indices
comb = product(list(range(num_points)), receiver_idxs)
# Add these combinations to the list
all_combinations.extend(comb)
all_combinations = list(set(all_combinations)) # remove redundancy
# download wav files # Replace to render IR
# temp_list = set()
# with concurrent.futures.ThreadPoolExecutor() as executor:
# for source_idx in executor.map(download_wav, all_combinations):
# temp_list.add(source_idx)
# temp_list = list(temp_list)
# Render image
dirname_target_image = f'data/{DATASET_NAME}/{split}/{room}/image'
os.makedirs(dirname_target_image, exist_ok=True)
query_idx_list = list(range(num_points))
subprocess.run(['python', 'soundspaces_nvas3d/image_rendering/generate_target_image.py', '--room', room, '--dirname', dirname_target_image, '--source_idx_list', ' '.join(map(str, query_idx_list))])
# For each pair, make data
for i_pair, pair in enumerate(tqdm(pairs)):
dirname = f'data/{DATASET_NAME}/{split}/{room}/{i_pair}'
source_idx_list, receiver_idx_list, novel_receiver_idx = pair
os.makedirs(dirname, exist_ok=True)
# Compute source
os.makedirs(f'{dirname}/source', exist_ok=True)
if SOURCE1_DATA == 'speech':
source1_audio, source1_class = sample_speech(files_librispeech, librispeech_metadata)
elif SOURCE1_DATA == 'nonspeech':
source1_audio, source1_class = sample_nonspeech(all_instruments_dir)
elif SOURCE1_DATA == 'guitar':
source1_audio, source1_class = sample_acoustic_guitar(all_instruments_dir)
elif SOURCE1_DATA == 'all':
source1_audio, source1_class = sample_all(all_instruments_dir, librispeech_metadata)
else: | source1_audio, source1_class = sample_instrument(all_instruments_dir, librispeech_metadata, SOURCE1_DATA) | 10 | 2023-10-19 05:35:54+00:00 | 8k |
virevolai/logos-shift-client | logos_shift_client/logos_shift.py | [
{
"identifier": "BohitaClient",
"path": "logos_shift_client/bohita.py",
"snippet": "class BohitaClient:\n def __init__(self, api_key: str):\n if api_key is None:\n logging.warning(\n \"No API KEY provided. No data will be sent to Bohita and automatic routing will not ... | import asyncio
import logging
import threading
import time
import uuid
from pathlib import Path
from collections import deque
from typing import Optional, Union
from tenacity import retry, wait_fixed
from .bohita import BohitaClient
from .router import APIRouter | 3,642 | self.file_handle.write(str(data) + "\n")
except Exception as e:
logger.error(
"Could not save to local file. This might happen because local file format is simple. Local does str(data)"
)
logger.exception(e)
@retry(wait=wait_fixed(3))
def send_data(self, data, dataset="default"):
logger.info(f"BufferManager: Sending data to dataset {dataset}. Data: {data}")
self.bohita_client.post_instrumentation_data(data, dataset)
self._write_to_local(data)
def send_data_from_buffers(self):
while True:
time.sleep(self.check_seconds)
for buffer in self.buffers:
with buffer["lock"]:
if buffer["data"]:
data_to_send = list(buffer["data"])
buffer["data"].clear()
for item in data_to_send:
logger.debug(f"Sending {item}")
self.send_data(item, dataset=item["dataset"])
def register_buffer(self, buffer, lock):
self.buffers.append({"data": buffer, "lock": lock})
class LogosShift:
"""
LogosShift is a tool for capturing, logging, and optionally sending function call data to a remote server using rollouts.
It allows developers to easily instrument their functions, capturing input arguments, output results, metadata, and optionally sending this data to the Bohita platform for further analysis. Data can also be stored locally.
It supports both synchronous and asynchronous functions. For asynchronous functions, it automatically detects and wraps them accordingly.
Attributes:
bohita_client (BohitaClient): The client used to send data to the Bohita platform.
max_entries (int): The maximum number of entries to store in a buffer before switching to the next buffer.
buffer_A (collections.deque): The first data buffer.
buffer_B (collections.deque): The second data buffer.
active_buffer (collections.deque): The currently active data buffer.
lock (threading.Lock): A lock to ensure thread-safety when modifying the buffers.
buffer_manager (BufferManager): The manager for handling data buffers and sending data.
router (APIRouter): The router for determining which API to call based on the function and user.
Examples:
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY")
>>> @logos_shift()
... def add(x, y):
... return x + y
...
>>> result = add(1, 2)
Asynchronous function:
>>> @logos_shift()
... async def add_async(x, y):
... return x + y
...
>>> result = await add_async(1, 2)
To provide feedback:
>>> logos_shift.provide_feedback(result['bohita_logos_shift_id'], "success")
To specify a dataset:
>>> @logos_shift(dataset="sales")
... def add_sales(x, y):
... return x + y
Using metadata:
>>> @logos_shift()
... def multiply(x, y, logos_shift_metadata={"user_id": "12345"}):
... return x * y
To store data locally:
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY", filename="api_calls.log")
To disable sending data to Bohita:
>>> logos_shift = LogosShift(api_key=None, filename="api_calls.log")
"""
def __init__(
self,
api_key,
bohita_client=None,
router=None,
max_entries=MAX_ENTRIES,
check_seconds=CHECK_SECONDS,
filename=None,
):
"""
Initializes a new instance of LogosShift.
Args:
api_key (str): Your API key for the Bohita platform.
bohita_client (Optional[BohitaClient]): An optional instance of BohitaClient. If not provided, a new instance will be created.
router (Optional[APIRouter]): An optional instance of APIRouter. If not provided, a new instance will be created.
max_entries (int): The maximum number of entries to store in a buffer before switching to the next buffer. Default is 10.
check_seconds (int): The interval in seconds between checks to send data from the buffers. Default is 5.
filename (Optional[Union[str, Path]]): The file path for local data storage. If None, data is not stored locally.
Examples:
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY")
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY", filename="api_calls.log")
"""
self.max_entries = max_entries
self.bohita_client = (
bohita_client if bohita_client else BohitaClient(api_key=api_key)
)
self.buffer_A, self.buffer_B = deque(), deque()
self.active_buffer = self.buffer_A
self.lock = threading.Lock()
self.buffer_manager = BufferManager(
bohita_client=self.bohita_client,
check_seconds=check_seconds,
filename=filename,
)
self.buffer_manager.register_buffer(self.buffer_A, self.lock)
self.buffer_manager.register_buffer(self.buffer_B, self.lock)
|
logger = logging.getLogger(__name__)
MAX_ENTRIES = 10
CHECK_SECONDS = 5
class SingletonMeta(type):
_instances = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class BufferManager(metaclass=SingletonMeta):
"""
A singleton class responsible for managing data buffers and sending data to a remote server.
Attributes:
bohita_client: An instance of BohitaClient used to send data to the remote server.
check_seconds: The interval in seconds between checks to send data from the buffers.
filepath: The file path for local data storage. If None, data is not stored locally.
buffers: A list of data buffers.
thread: The thread responsible for sending data from the buffers.
"""
_instance = None
lock = threading.Lock()
def __init__(
self,
bohita_client: BohitaClient,
check_seconds: int = CHECK_SECONDS,
filename: Optional[Union[str, Path]] = None,
):
self.bohita_client = bohita_client
self.check_seconds = check_seconds
self.open_handle(filename)
self.buffers = []
self.thread = threading.Thread(target=self.send_data_from_buffers, daemon=True)
self.thread.start()
logger.info("BufferManager: Initialized and sending thread started.")
def open_handle(self, filename: str):
if filename:
filepath = Path(filename)
logdir = filepath.parent
if not logdir.exists():
raise Exception(f"Directory {logdir} does not exist!")
self.file_handle = open(filepath, "a", buffering=1)
logger.debug(f"Buffered file handler opened for local file {filename}")
else:
self.file_handle = None
def __del__(self):
if self.file_handle:
self.file_handle.close()
logger.debug("Buffered file handle closed")
def _write_to_local(self, data):
try:
if self.file_handle:
self.file_handle.write(str(data) + "\n")
except Exception as e:
logger.error(
"Could not save to local file. This might happen because local file format is simple. Local does str(data)"
)
logger.exception(e)
@retry(wait=wait_fixed(3))
def send_data(self, data, dataset="default"):
logger.info(f"BufferManager: Sending data to dataset {dataset}. Data: {data}")
self.bohita_client.post_instrumentation_data(data, dataset)
self._write_to_local(data)
def send_data_from_buffers(self):
while True:
time.sleep(self.check_seconds)
for buffer in self.buffers:
with buffer["lock"]:
if buffer["data"]:
data_to_send = list(buffer["data"])
buffer["data"].clear()
for item in data_to_send:
logger.debug(f"Sending {item}")
self.send_data(item, dataset=item["dataset"])
def register_buffer(self, buffer, lock):
self.buffers.append({"data": buffer, "lock": lock})
class LogosShift:
"""
LogosShift is a tool for capturing, logging, and optionally sending function call data to a remote server using rollouts.
It allows developers to easily instrument their functions, capturing input arguments, output results, metadata, and optionally sending this data to the Bohita platform for further analysis. Data can also be stored locally.
It supports both synchronous and asynchronous functions. For asynchronous functions, it automatically detects and wraps them accordingly.
Attributes:
bohita_client (BohitaClient): The client used to send data to the Bohita platform.
max_entries (int): The maximum number of entries to store in a buffer before switching to the next buffer.
buffer_A (collections.deque): The first data buffer.
buffer_B (collections.deque): The second data buffer.
active_buffer (collections.deque): The currently active data buffer.
lock (threading.Lock): A lock to ensure thread-safety when modifying the buffers.
buffer_manager (BufferManager): The manager for handling data buffers and sending data.
router (APIRouter): The router for determining which API to call based on the function and user.
Examples:
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY")
>>> @logos_shift()
... def add(x, y):
... return x + y
...
>>> result = add(1, 2)
Asynchronous function:
>>> @logos_shift()
... async def add_async(x, y):
... return x + y
...
>>> result = await add_async(1, 2)
To provide feedback:
>>> logos_shift.provide_feedback(result['bohita_logos_shift_id'], "success")
To specify a dataset:
>>> @logos_shift(dataset="sales")
... def add_sales(x, y):
... return x + y
Using metadata:
>>> @logos_shift()
... def multiply(x, y, logos_shift_metadata={"user_id": "12345"}):
... return x * y
To store data locally:
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY", filename="api_calls.log")
To disable sending data to Bohita:
>>> logos_shift = LogosShift(api_key=None, filename="api_calls.log")
"""
def __init__(
self,
api_key,
bohita_client=None,
router=None,
max_entries=MAX_ENTRIES,
check_seconds=CHECK_SECONDS,
filename=None,
):
"""
Initializes a new instance of LogosShift.
Args:
api_key (str): Your API key for the Bohita platform.
bohita_client (Optional[BohitaClient]): An optional instance of BohitaClient. If not provided, a new instance will be created.
router (Optional[APIRouter]): An optional instance of APIRouter. If not provided, a new instance will be created.
max_entries (int): The maximum number of entries to store in a buffer before switching to the next buffer. Default is 10.
check_seconds (int): The interval in seconds between checks to send data from the buffers. Default is 5.
filename (Optional[Union[str, Path]]): The file path for local data storage. If None, data is not stored locally.
Examples:
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY")
>>> logos_shift = LogosShift(api_key="YOUR_API_KEY", filename="api_calls.log")
"""
self.max_entries = max_entries
self.bohita_client = (
bohita_client if bohita_client else BohitaClient(api_key=api_key)
)
self.buffer_A, self.buffer_B = deque(), deque()
self.active_buffer = self.buffer_A
self.lock = threading.Lock()
self.buffer_manager = BufferManager(
bohita_client=self.bohita_client,
check_seconds=check_seconds,
filename=filename,
)
self.buffer_manager.register_buffer(self.buffer_A, self.lock)
self.buffer_manager.register_buffer(self.buffer_B, self.lock) | self.router = router if router else APIRouter(bohita_client=self.bohita_client) | 1 | 2023-10-20 00:00:38+00:00 | 8k |
kwonathan/language-models-trajectory-generators | env.py | [
{
"identifier": "Robot",
"path": "robot.py",
"snippet": "class Robot:\n\n def __init__(self, args):\n\n if args.robot == \"sawyer\":\n self.base_start_position = config.base_start_position_sawyer\n self.base_start_orientation_q = p.getQuaternionFromEuler(config.base_start... | import pybullet as p
import numpy as np
import pybullet_data
import time
import config
from robot import Robot
from config import OK, PROGRESS, FAIL, ENDC
from config import CAPTURE_IMAGES, ADD_BOUNDING_CUBES, ADD_TRAJECTORY_POINTS, EXECUTE_TRAJECTORY, OPEN_GRIPPER, CLOSE_GRIPPER, TASK_COMPLETED, RESET_ENVIRONMENT | 4,110 |
class Environment:
def __init__(self, args):
self.mode = args.mode
def load(self):
p.resetDebugVisualizerCamera(config.camera_distance, config.camera_yaw, config.camera_pitch, config.camera_target_position)
object_start_position = config.object_start_position
object_start_orientation_q = p.getQuaternionFromEuler(config.object_start_orientation_e)
object_model = p.loadURDF("ycb_assets/002_master_chef_can.urdf", object_start_position, object_start_orientation_q, useFixedBase=False, globalScaling=config.global_scaling)
if self.mode == "default":
p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0)
p.configureDebugVisualizer(p.COV_ENABLE_SHADOWS, 0)
def update(self):
p.stepSimulation()
time.sleep(config.control_dt)
def run_simulation_environment(args, env_connection, logger):
# Environment set-up
logger.info(PROGRESS + "Setting up environment..." + ENDC)
physics_client = p.connect(p.GUI)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
p.setGravity(0, 0, -9.81)
plane = p.loadURDF("plane.urdf")
env = Environment(args)
env.load()
robot = Robot(args)
robot.move(env, robot.ee_start_position, robot.ee_start_orientation_e, gripper_open=True, is_trajectory=False)
env_connection_message = OK + "Finished setting up environment!" + ENDC
env_connection.send([env_connection_message])
while True:
if env_connection.poll():
env_connection_received = env_connection.recv()
if env_connection_received[0] == CAPTURE_IMAGES:
_, _ = robot.get_camera_image("head", env, save_camera_image=True, rgb_image_path=config.rgb_image_trajectory_path.format(step=0), depth_image_path=config.depth_image_trajectory_path.format(step=0))
head_camera_position, head_camera_orientation_q = robot.get_camera_image("head", env, save_camera_image=True, rgb_image_path=config.rgb_image_head_path, depth_image_path=config.depth_image_head_path)
wrist_camera_position, wrist_camera_orientation_q = robot.get_camera_image("wrist", env, save_camera_image=True, rgb_image_path=config.rgb_image_wrist_path, depth_image_path=config.depth_image_wrist_path)
env_connection_message = OK + "Finished capturing head camera image!" + ENDC
env_connection.send([head_camera_position, head_camera_orientation_q, wrist_camera_position, wrist_camera_orientation_q, env_connection_message])
elif env_connection_received[0] == ADD_BOUNDING_CUBES:
bounding_cubes_world_coordinates = env_connection_received[1]
for bounding_cube_world_coordinates in bounding_cubes_world_coordinates:
p.addUserDebugLine(bounding_cube_world_coordinates[0], bounding_cube_world_coordinates[1], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[1], bounding_cube_world_coordinates[2], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[2], bounding_cube_world_coordinates[3], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[3], bounding_cube_world_coordinates[0], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[5], bounding_cube_world_coordinates[6], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[6], bounding_cube_world_coordinates[7], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[7], bounding_cube_world_coordinates[8], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[8], bounding_cube_world_coordinates[5], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[0], bounding_cube_world_coordinates[5], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[1], bounding_cube_world_coordinates[6], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[2], bounding_cube_world_coordinates[7], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[3], bounding_cube_world_coordinates[8], [0, 1, 0], lifeTime=0)
p.addUserDebugPoints(bounding_cube_world_coordinates, [[0, 1, 0]] * len(bounding_cube_world_coordinates), pointSize=5, lifeTime=0)
env_connection_message = OK + "Finished adding bounding cubes to the environment!" + ENDC
env_connection.send([env_connection_message])
elif env_connection_received[0] == ADD_TRAJECTORY_POINTS:
trajectory = env_connection_received[1]
trajectory_points = [point[:3] for point in trajectory]
p.addUserDebugPoints(trajectory_points, [[0, 1, 1]] * len(trajectory_points), pointSize=5, lifeTime=0)
logger.info(OK + "Finished adding trajectory points to the environment!" + ENDC)
elif env_connection_received[0] == EXECUTE_TRAJECTORY:
trajectory = env_connection_received[1]
for point in trajectory:
robot.move(env, point[:3], np.array(robot.ee_start_orientation_e) + np.array([0, 0, point[3]]), gripper_open=robot.gripper_open, is_trajectory=True)
for _ in range(100):
env.update()
logger.info(OK + "Finished executing generated trajectory!" + ENDC)
|
class Environment:
def __init__(self, args):
self.mode = args.mode
def load(self):
p.resetDebugVisualizerCamera(config.camera_distance, config.camera_yaw, config.camera_pitch, config.camera_target_position)
object_start_position = config.object_start_position
object_start_orientation_q = p.getQuaternionFromEuler(config.object_start_orientation_e)
object_model = p.loadURDF("ycb_assets/002_master_chef_can.urdf", object_start_position, object_start_orientation_q, useFixedBase=False, globalScaling=config.global_scaling)
if self.mode == "default":
p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0)
p.configureDebugVisualizer(p.COV_ENABLE_SHADOWS, 0)
def update(self):
p.stepSimulation()
time.sleep(config.control_dt)
def run_simulation_environment(args, env_connection, logger):
# Environment set-up
logger.info(PROGRESS + "Setting up environment..." + ENDC)
physics_client = p.connect(p.GUI)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
p.setGravity(0, 0, -9.81)
plane = p.loadURDF("plane.urdf")
env = Environment(args)
env.load()
robot = Robot(args)
robot.move(env, robot.ee_start_position, robot.ee_start_orientation_e, gripper_open=True, is_trajectory=False)
env_connection_message = OK + "Finished setting up environment!" + ENDC
env_connection.send([env_connection_message])
while True:
if env_connection.poll():
env_connection_received = env_connection.recv()
if env_connection_received[0] == CAPTURE_IMAGES:
_, _ = robot.get_camera_image("head", env, save_camera_image=True, rgb_image_path=config.rgb_image_trajectory_path.format(step=0), depth_image_path=config.depth_image_trajectory_path.format(step=0))
head_camera_position, head_camera_orientation_q = robot.get_camera_image("head", env, save_camera_image=True, rgb_image_path=config.rgb_image_head_path, depth_image_path=config.depth_image_head_path)
wrist_camera_position, wrist_camera_orientation_q = robot.get_camera_image("wrist", env, save_camera_image=True, rgb_image_path=config.rgb_image_wrist_path, depth_image_path=config.depth_image_wrist_path)
env_connection_message = OK + "Finished capturing head camera image!" + ENDC
env_connection.send([head_camera_position, head_camera_orientation_q, wrist_camera_position, wrist_camera_orientation_q, env_connection_message])
elif env_connection_received[0] == ADD_BOUNDING_CUBES:
bounding_cubes_world_coordinates = env_connection_received[1]
for bounding_cube_world_coordinates in bounding_cubes_world_coordinates:
p.addUserDebugLine(bounding_cube_world_coordinates[0], bounding_cube_world_coordinates[1], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[1], bounding_cube_world_coordinates[2], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[2], bounding_cube_world_coordinates[3], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[3], bounding_cube_world_coordinates[0], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[5], bounding_cube_world_coordinates[6], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[6], bounding_cube_world_coordinates[7], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[7], bounding_cube_world_coordinates[8], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[8], bounding_cube_world_coordinates[5], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[0], bounding_cube_world_coordinates[5], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[1], bounding_cube_world_coordinates[6], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[2], bounding_cube_world_coordinates[7], [0, 1, 0], lifeTime=0)
p.addUserDebugLine(bounding_cube_world_coordinates[3], bounding_cube_world_coordinates[8], [0, 1, 0], lifeTime=0)
p.addUserDebugPoints(bounding_cube_world_coordinates, [[0, 1, 0]] * len(bounding_cube_world_coordinates), pointSize=5, lifeTime=0)
env_connection_message = OK + "Finished adding bounding cubes to the environment!" + ENDC
env_connection.send([env_connection_message])
elif env_connection_received[0] == ADD_TRAJECTORY_POINTS:
trajectory = env_connection_received[1]
trajectory_points = [point[:3] for point in trajectory]
p.addUserDebugPoints(trajectory_points, [[0, 1, 1]] * len(trajectory_points), pointSize=5, lifeTime=0)
logger.info(OK + "Finished adding trajectory points to the environment!" + ENDC)
elif env_connection_received[0] == EXECUTE_TRAJECTORY:
trajectory = env_connection_received[1]
for point in trajectory:
robot.move(env, point[:3], np.array(robot.ee_start_orientation_e) + np.array([0, 0, point[3]]), gripper_open=robot.gripper_open, is_trajectory=True)
for _ in range(100):
env.update()
logger.info(OK + "Finished executing generated trajectory!" + ENDC)
| elif env_connection_received[0] == OPEN_GRIPPER: | 9 | 2023-10-18 16:38:09+00:00 | 8k |
kvablack/susie | scripts/train.py | [
{
"identifier": "sampling",
"path": "susie/sampling.py",
"snippet": "def q_sample(x_0, log_snr, noise):\ndef model_predict(state, x, y, prompt_embeds, t, use_ema=True):\ndef sample_step(\n rng,\n state,\n x,\n y,\n prompt_embeds,\n uncond_y,\n uncond_prompt_embeds,\n t,\n t_ne... | import datetime
import functools
import logging
import os
import tempfile
import time
import einops as eo
import jax
import jax.numpy as jnp
import numpy as np
import optax
import orbax.checkpoint
import tensorflow as tf
import tqdm
import wandb
from collections import defaultdict
from functools import partial
from absl import app, flags
from flax.training import orbax_utils
from jax.experimental import multihost_utils
from jax.lax import with_sharding_constraint as wsc
from jax.sharding import NamedSharding
from jax.sharding import PartitionSpec as P
from ml_collections import ConfigDict, config_flags
from PIL import Image
from susie import sampling, scheduling
from susie.data.datasets import get_data_loader
from susie.jax_utils import (
host_broadcast_str,
initialize_compilation_cache,
)
from susie.model import (
EmaTrainState,
create_model_def,
load_pretrained_unet,
load_text_encoder,
load_vae,
)
from jax_smi import initialise_tracking # type: ignore | 4,621 |
# seems like remat is actually enabled by default -- this disables it
# @partial(jax.checkpoint, policy=jax.checkpoint_policies.everything_saveable)
def loss_fn(params, rng):
pred = state.apply_fn(
{"params": params},
input,
t * 1000,
prompt_embeds,
train=not eval_only,
rngs={"dropout": rng},
)
assert pred.shape == noise.shape
loss = (pred - noise) ** 2
return jnp.mean(loss)
info = {}
if not eval_only:
grad_fn = jax.value_and_grad(loss_fn)
rng, dropout_rng = jax.random.split(rng)
info["loss"], grads = grad_fn(state.params, dropout_rng)
info["grad_norm"] = optax.global_norm(grads)
new_state = state.apply_gradients(grads=grads)
else:
rng, dropout_rng = jax.random.split(rng)
info["loss"] = loss_fn(state.params, dropout_rng)
rng, dropout_rng = jax.random.split(rng)
info["loss_ema"] = loss_fn(state.params_ema, dropout_rng)
new_state = state
return new_state, info
FLAGS = flags.FLAGS
config_flags.DEFINE_config_file(
"config",
None,
"File path to the hyperparameter configuration.",
lock_config=False,
)
def main(_):
config = FLAGS.config
assert config.sample.num_contexts % 4 == 0
# prevent tensorflow from using GPUs
tf.config.experimental.set_visible_devices([], "GPU")
tf.random.set_seed(config.seed + jax.process_index())
# get jax devices
logging.info(f"JAX process: {jax.process_index()} of {jax.process_count()}")
logging.info(f"Local devices: {jax.local_device_count()}")
logging.info(f"Global devices: {jax.device_count()}")
mesh = jax.sharding.Mesh(
# create_device_mesh([32, 1]), # can't make contiguous meshes for the v4-64 pod for some reason
np.array(jax.devices()).reshape(*config.mesh),
axis_names=["dp", "fsdp"],
)
replicated_sharding = NamedSharding(mesh, P())
# data gets sharded over both dp and fsdp logical axes
data_sharding = NamedSharding(mesh, P(["dp", "fsdp"]))
# initial rng
rng = jax.random.PRNGKey(config.seed + jax.process_index())
# set up wandb run
if config.wandb_resume_id is not None:
run = wandb.Api().run(config.wandb_resume_id)
old_num_steps = config.num_steps
config = ConfigDict(run.config)
config.num_steps = old_num_steps
config.wandb_resume_id = run.id
logdir = tf.io.gfile.join(config.logdir, run.name)
if jax.process_index() == 0:
wandb.init(
project=run.project,
id=run.id,
resume="must",
)
else:
unique_id = datetime.datetime.now().strftime("%Y.%m.%d_%H.%M.%S")
unique_id = host_broadcast_str(unique_id)
if not config.run_name:
config.run_name = unique_id
else:
config.run_name += "_" + unique_id
logdir = tf.io.gfile.join(config.logdir, config.run_name)
if jax.process_index() == 0:
tf.io.gfile.makedirs(logdir)
wandb.init(
project=config.wandb_project,
name=config.run_name,
config=config.to_dict(),
)
checkpointer = orbax.checkpoint.CheckpointManager(
logdir,
checkpointers={
"state": orbax.checkpoint.PyTreeCheckpointer(),
"params_ema": orbax.checkpoint.PyTreeCheckpointer(),
},
)
log_snr_fn = scheduling.create_log_snr_fn(config.scheduling)
ema_decay_fn = scheduling.create_ema_decay_fn(config.ema)
# load vae
if config.vae is not None:
vae_encode, vae_decode = load_vae(config.vae)
# load text encoder
|
if jax.process_count() > 1:
jax.distributed.initialize()
tqdm = partial(tqdm.tqdm, dynamic_ncols=True)
try:
initialise_tracking()
except ImportError:
pass
def fsdp_sharding(mesh: jax.sharding.Mesh, array: jax.ShapeDtypeStruct):
if array.ndim < 2:
# replicate scalar and vector arrays
return NamedSharding(mesh, P())
# shard matrices and larger tensors across the fsdp dimension. the conv kernels are a little tricky because they
# vary in which axis is a power of 2, so I'll just search for the first one that works.
l = []
for n in array.shape:
if n % mesh.shape["fsdp"] == 0:
l.append("fsdp")
return NamedSharding(mesh, P(*l))
l.append(None)
logging.warning(
f"Could not find a valid sharding for array of shape {array.shape} with mesh of shape {mesh.shape}"
)
return NamedSharding(mesh, P())
def train_step(
rng,
state,
batch,
# static args
log_snr_fn,
uncond_prompt_embed,
text_encode_fn,
vae_encode_fn,
curr_drop_rate=0.0,
goal_drop_rate=0.0,
prompt_drop_rate=0.0,
eval_only=False,
):
batch_size = batch["subgoals"].shape[0]
# encode stuff
for key in {"curr", "goals", "subgoals"}.intersection(batch.keys()):
# VERY IMPORTANT: for some godforsaken reason, the context latents are
# NOT scaled in InstructPix2Pix
scale = key == "subgoals"
rng, encode_rng = jax.random.split(rng)
batch[key] = vae_encode_fn(encode_rng, batch[key], scale=scale)
prompt_embeds = text_encode_fn(batch["prompt_ids"])
if goal_drop_rate == 1.0:
batch["goals"] = jnp.zeros(
batch["subgoals"].shape[:-1] + (0,), batch["subgoals"].dtype
)
elif goal_drop_rate > 0:
rng, mask_rng = jax.random.split(rng)
batch["goals"] = jnp.where(
jax.random.uniform(mask_rng, shape=(batch_size, 1, 1, 1)) < goal_drop_rate,
0,
batch["goals"],
)
if curr_drop_rate > 0:
rng, mask_rng = jax.random.split(rng)
batch["curr"] = jnp.where(
jax.random.uniform(mask_rng, shape=(batch_size, 1, 1, 1)) < curr_drop_rate,
0,
batch["curr"],
)
if prompt_drop_rate > 0:
rng, mask_rng = jax.random.split(rng)
prompt_embeds = jnp.where(
jax.random.uniform(mask_rng, shape=(batch_size, 1, 1)) < prompt_drop_rate,
uncond_prompt_embed,
prompt_embeds,
)
x = batch["subgoals"] # the generation target
y = jnp.concatenate(
[batch["curr"], batch["goals"]], axis=-1
) # the conditioning image(s)
# sample batch of timesteps from t ~ U[0, num_train_timesteps)
rng, t_rng = jax.random.split(rng)
t = jax.random.uniform(t_rng, shape=(batch_size,), dtype=jnp.float32)
# sample noise (epsilon) from N(0, I)
rng, noise_rng = jax.random.split(rng)
noise = jax.random.normal(noise_rng, x.shape)
log_snr = log_snr_fn(t)
# generate the noised image from q(x_t | x_0, y)
x_t = sampling.q_sample(x, log_snr, noise)
input = jnp.concatenate([x_t, y], axis=-1)
# seems like remat is actually enabled by default -- this disables it
# @partial(jax.checkpoint, policy=jax.checkpoint_policies.everything_saveable)
def loss_fn(params, rng):
pred = state.apply_fn(
{"params": params},
input,
t * 1000,
prompt_embeds,
train=not eval_only,
rngs={"dropout": rng},
)
assert pred.shape == noise.shape
loss = (pred - noise) ** 2
return jnp.mean(loss)
info = {}
if not eval_only:
grad_fn = jax.value_and_grad(loss_fn)
rng, dropout_rng = jax.random.split(rng)
info["loss"], grads = grad_fn(state.params, dropout_rng)
info["grad_norm"] = optax.global_norm(grads)
new_state = state.apply_gradients(grads=grads)
else:
rng, dropout_rng = jax.random.split(rng)
info["loss"] = loss_fn(state.params, dropout_rng)
rng, dropout_rng = jax.random.split(rng)
info["loss_ema"] = loss_fn(state.params_ema, dropout_rng)
new_state = state
return new_state, info
FLAGS = flags.FLAGS
config_flags.DEFINE_config_file(
"config",
None,
"File path to the hyperparameter configuration.",
lock_config=False,
)
def main(_):
config = FLAGS.config
assert config.sample.num_contexts % 4 == 0
# prevent tensorflow from using GPUs
tf.config.experimental.set_visible_devices([], "GPU")
tf.random.set_seed(config.seed + jax.process_index())
# get jax devices
logging.info(f"JAX process: {jax.process_index()} of {jax.process_count()}")
logging.info(f"Local devices: {jax.local_device_count()}")
logging.info(f"Global devices: {jax.device_count()}")
mesh = jax.sharding.Mesh(
# create_device_mesh([32, 1]), # can't make contiguous meshes for the v4-64 pod for some reason
np.array(jax.devices()).reshape(*config.mesh),
axis_names=["dp", "fsdp"],
)
replicated_sharding = NamedSharding(mesh, P())
# data gets sharded over both dp and fsdp logical axes
data_sharding = NamedSharding(mesh, P(["dp", "fsdp"]))
# initial rng
rng = jax.random.PRNGKey(config.seed + jax.process_index())
# set up wandb run
if config.wandb_resume_id is not None:
run = wandb.Api().run(config.wandb_resume_id)
old_num_steps = config.num_steps
config = ConfigDict(run.config)
config.num_steps = old_num_steps
config.wandb_resume_id = run.id
logdir = tf.io.gfile.join(config.logdir, run.name)
if jax.process_index() == 0:
wandb.init(
project=run.project,
id=run.id,
resume="must",
)
else:
unique_id = datetime.datetime.now().strftime("%Y.%m.%d_%H.%M.%S")
unique_id = host_broadcast_str(unique_id)
if not config.run_name:
config.run_name = unique_id
else:
config.run_name += "_" + unique_id
logdir = tf.io.gfile.join(config.logdir, config.run_name)
if jax.process_index() == 0:
tf.io.gfile.makedirs(logdir)
wandb.init(
project=config.wandb_project,
name=config.run_name,
config=config.to_dict(),
)
checkpointer = orbax.checkpoint.CheckpointManager(
logdir,
checkpointers={
"state": orbax.checkpoint.PyTreeCheckpointer(),
"params_ema": orbax.checkpoint.PyTreeCheckpointer(),
},
)
log_snr_fn = scheduling.create_log_snr_fn(config.scheduling)
ema_decay_fn = scheduling.create_ema_decay_fn(config.ema)
# load vae
if config.vae is not None:
vae_encode, vae_decode = load_vae(config.vae)
# load text encoder | tokenize, untokenize, text_encode = load_text_encoder(config.text_encoder) | 8 | 2023-10-17 05:05:57+00:00 | 8k |
mlvlab/Flipped-VQA | llama_vqa.py | [
{
"identifier": "ModelArgs",
"path": "llama/model.py",
"snippet": "class ModelArgs:\n dim: int = 512\n n_layers: int = 8\n n_heads: int = 8\n vocab_size: int = -1 # defined later by tokenizer\n multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2\n norm... | import torch
import json
from llama import ModelArgs, Tokenizer, Transformer
from pathlib import Path | 4,682 |
def LLaMA_VQA(args, **kwargs):
with open(f'{args.llama_model_path}{args.model}/params.json', "r") as f:
params = json.loads(f.read())
tokenizer = Tokenizer(model_path=f'{args.llama_model_path}/tokenizer.model')
print(f"Using model: {args.model}")
checkpoints = (Path(args.llama_model_path) / args.model).glob("*.pth")
checkpoints = sorted(checkpoints)
loaded = []
for x in checkpoints:
print("loading from", x)
loaded.append(torch.load(x, map_location="cpu"))
if len(loaded) == 1:
full_state_dict = loaded[0]
else:
full_state_dict = {}
split_dims = {}
def add_weight_with_split_dim(name, dim):
if dim < 0: # bcast without split
full_state_dict[name] = loaded[0][name].clone()
else:
full_state_dict[name] = torch.cat([x[name] for x in loaded], dim=dim)
for x in loaded:
del x[name]
split_dims[name] = dim
add_weight_with_split_dim("tok_embeddings.weight", 1)
add_weight_with_split_dim("norm.weight", -1)
add_weight_with_split_dim("output.weight", 0)
for i in range(params["n_layers"]):
print("gathering layer %d of %d" % (i, params["n_layers"]))
layer_prefix = f"layers.{i}."
bcast_names = ["attention_norm.weight", "ffn_norm.weight"]
column_parallel_names = ["attention.wq.weight", "attention.wk.weight", "attention.wv.weight", "feed_forward.w1.weight", "feed_forward.w3.weight"]
row_parallel_names = ["attention.wo.weight", "feed_forward.w2.weight"]
for key in bcast_names:
add_weight_with_split_dim(layer_prefix + key, -1)
for key in column_parallel_names:
add_weight_with_split_dim(layer_prefix + key, 0)
for key in row_parallel_names:
add_weight_with_split_dim(layer_prefix + key, 1)
|
def LLaMA_VQA(args, **kwargs):
with open(f'{args.llama_model_path}{args.model}/params.json', "r") as f:
params = json.loads(f.read())
tokenizer = Tokenizer(model_path=f'{args.llama_model_path}/tokenizer.model')
print(f"Using model: {args.model}")
checkpoints = (Path(args.llama_model_path) / args.model).glob("*.pth")
checkpoints = sorted(checkpoints)
loaded = []
for x in checkpoints:
print("loading from", x)
loaded.append(torch.load(x, map_location="cpu"))
if len(loaded) == 1:
full_state_dict = loaded[0]
else:
full_state_dict = {}
split_dims = {}
def add_weight_with_split_dim(name, dim):
if dim < 0: # bcast without split
full_state_dict[name] = loaded[0][name].clone()
else:
full_state_dict[name] = torch.cat([x[name] for x in loaded], dim=dim)
for x in loaded:
del x[name]
split_dims[name] = dim
add_weight_with_split_dim("tok_embeddings.weight", 1)
add_weight_with_split_dim("norm.weight", -1)
add_weight_with_split_dim("output.weight", 0)
for i in range(params["n_layers"]):
print("gathering layer %d of %d" % (i, params["n_layers"]))
layer_prefix = f"layers.{i}."
bcast_names = ["attention_norm.weight", "ffn_norm.weight"]
column_parallel_names = ["attention.wq.weight", "attention.wk.weight", "attention.wv.weight", "feed_forward.w1.weight", "feed_forward.w3.weight"]
row_parallel_names = ["attention.wo.weight", "feed_forward.w2.weight"]
for key in bcast_names:
add_weight_with_split_dim(layer_prefix + key, -1)
for key in column_parallel_names:
add_weight_with_split_dim(layer_prefix + key, 0)
for key in row_parallel_names:
add_weight_with_split_dim(layer_prefix + key, 1)
| model_args: ModelArgs = ModelArgs(max_seq_len=args.max_seq_len, max_batch_size=32, adapter_len=args.adapter_len, adapter_layer=args.adapter_layer, **params) | 0 | 2023-10-19 02:06:04+00:00 | 8k |
openvpi/SingingVocoders | models/nsf_univnet/nsfunivnet.py | [
{
"identifier": "LVCBlock",
"path": "modules/univ_ddsp/block.py",
"snippet": "class LVCBlock(torch.nn.Module):\n ''' the location-variable convolutions\n '''\n\n def __init__(self,\n in_channels,\n cond_channels,\n upsample_ratio,\n ... | import numpy as np
import torch
import logging
import torch.nn.functional as F
from torch import nn
from modules.univ_ddsp.block import LVCBlock
from modules.ddsp.vocoder import CombSub, Sins | 4,926 | super(SineGen, self).__init__()
self.sine_amp = sine_amp
self.noise_std = noise_std
self.harmonic_num = harmonic_num
self.dim = self.harmonic_num + 1
self.sampling_rate = samp_rate
self.voiced_threshold = voiced_threshold
def _f02uv(self, f0):
# generate uv signal
uv = torch.ones_like(f0)
uv = uv * (f0 > self.voiced_threshold)
return uv
def _f02sine(self, f0_values, upp):
""" f0_values: (batchsize, length, dim)
where dim indicates fundamental tone and overtones
"""
rad_values = (f0_values / self.sampling_rate).fmod(1.) # %1意味着n_har的乘积无法后处理优化
rand_ini = torch.rand(1, self.dim, device=f0_values.device)
rand_ini[:, 0] = 0
rad_values[:, 0, :] += rand_ini
is_half = rad_values.dtype is not torch.float32
tmp_over_one = torch.cumsum(rad_values.double(), 1) # % 1 #####%1意味着后面的cumsum无法再优化
if is_half:
tmp_over_one = tmp_over_one.half()
else:
tmp_over_one = tmp_over_one.float()
tmp_over_one *= upp
tmp_over_one = F.interpolate(
tmp_over_one.transpose(2, 1), scale_factor=upp,
mode='linear', align_corners=True
).transpose(2, 1)
rad_values = F.interpolate(rad_values.transpose(2, 1), scale_factor=upp, mode='nearest').transpose(2, 1)
tmp_over_one = tmp_over_one.fmod(1.)
diff = F.conv2d(
tmp_over_one.unsqueeze(1), torch.FloatTensor([[[[-1.], [1.]]]]).to(tmp_over_one.device),
stride=(1, 1), padding=0, dilation=(1, 1)
).squeeze(1) # Equivalent to torch.diff, but able to export ONNX
cumsum_shift = (diff < 0).double()
cumsum_shift = torch.cat((
torch.zeros((f0_values.size()[0], 1, self.dim), dtype=torch.double).to(f0_values.device),
cumsum_shift
), dim=1)
sines = torch.sin(torch.cumsum(rad_values.double() + cumsum_shift, dim=1) * 2 * np.pi)
if is_half:
sines = sines.half()
else:
sines = sines.float()
return sines
@torch.no_grad()
def forward(self, f0, upp):
""" sine_tensor, uv = forward(f0)
input F0: tensor(batchsize=1, length, dim=1)
f0 for unvoiced steps should be 0
output sine_tensor: tensor(batchsize=1, length, dim)
output uv: tensor(batchsize=1, length, 1)
"""
f0 = f0.unsqueeze(-1)
fn = torch.multiply(f0, torch.arange(1, self.dim + 1, device=f0.device).reshape((1, 1, -1)))
sine_waves = self._f02sine(fn, upp) * self.sine_amp
uv = (f0 > self.voiced_threshold).float()
uv = F.interpolate(uv.transpose(2, 1), scale_factor=upp, mode='nearest').transpose(2, 1)
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
noise = noise_amp * torch.randn_like(sine_waves)
sine_waves = sine_waves * uv + noise
return sine_waves
class SourceModuleHnNSF(torch.nn.Module):
""" SourceModule for hn-nsf
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
add_noise_std=0.003, voiced_threshod=0)
sampling_rate: sampling_rate in Hz
harmonic_num: number of harmonic above F0 (default: 0)
sine_amp: amplitude of sine source signal (default: 0.1)
add_noise_std: std of additive Gaussian noise (default: 0.003)
note that amplitude of noise in unvoiced is decided
by sine_amp
voiced_threshold: threhold to set U/V given F0 (default: 0)
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
F0_sampled (batchsize, length, 1)
Sine_source (batchsize, length, 1)
noise_source (batchsize, length 1)
uv (batchsize, length, 1)
"""
def __init__(self, sampling_rate, harmonic_num=0, sine_amp=0.1,
add_noise_std=0.003, voiced_threshold=0):
super(SourceModuleHnNSF, self).__init__()
self.sine_amp = sine_amp
self.noise_std = add_noise_std
# to produce sine waveforms
self.l_sin_gen = SineGen(sampling_rate, harmonic_num,
sine_amp, add_noise_std, voiced_threshold)
# to merge source harmonics into a single excitation
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
self.l_tanh = torch.nn.Tanh()
def forward(self, x, upp):
sine_wavs = self.l_sin_gen(x, upp)
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
return sine_merge
class DDSP(nn.Module):
def __init__(self,config):
super().__init__()
if config['model_args']['type']=='CombSub':
self.ddsp = CombSub(
sampling_rate=config['audio_sample_rate'],
block_size=config['hop_size'],
win_length=config['win_size'],
n_mag_harmonic=config['model_args']['n_mag_harmonic'],
n_mag_noise=config['model_args']['n_mag_noise'],
n_mels=config['audio_num_mel_bins'])
elif config['model_args']['type']=='Sins':
| # from modules import LVCBlock
LRELU_SLOPE = 0.1
class SineGen(torch.nn.Module):
""" Definition of sine generator
SineGen(samp_rate, harmonic_num = 0,
sine_amp = 0.1, noise_std = 0.003,
voiced_threshold = 0,
flag_for_pulse=False)
samp_rate: sampling rate in Hz
harmonic_num: number of harmonic overtones (default 0)
sine_amp: amplitude of sine-waveform (default 0.1)
noise_std: std of Gaussian noise (default 0.003)
voiced_threshold: F0 threshold for U/V classification (default 0)
flag_for_pulse: this SinGen is used inside PulseGen (default False)
Note: when flag_for_pulse is True, the first time step of a voiced
segment is always sin(np.pi) or cos(0)
"""
def __init__(self, samp_rate, harmonic_num=0,
sine_amp=0.1, noise_std=0.003,
voiced_threshold=0):
super(SineGen, self).__init__()
self.sine_amp = sine_amp
self.noise_std = noise_std
self.harmonic_num = harmonic_num
self.dim = self.harmonic_num + 1
self.sampling_rate = samp_rate
self.voiced_threshold = voiced_threshold
def _f02uv(self, f0):
# generate uv signal
uv = torch.ones_like(f0)
uv = uv * (f0 > self.voiced_threshold)
return uv
def _f02sine(self, f0_values, upp):
""" f0_values: (batchsize, length, dim)
where dim indicates fundamental tone and overtones
"""
rad_values = (f0_values / self.sampling_rate).fmod(1.) # %1意味着n_har的乘积无法后处理优化
rand_ini = torch.rand(1, self.dim, device=f0_values.device)
rand_ini[:, 0] = 0
rad_values[:, 0, :] += rand_ini
is_half = rad_values.dtype is not torch.float32
tmp_over_one = torch.cumsum(rad_values.double(), 1) # % 1 #####%1意味着后面的cumsum无法再优化
if is_half:
tmp_over_one = tmp_over_one.half()
else:
tmp_over_one = tmp_over_one.float()
tmp_over_one *= upp
tmp_over_one = F.interpolate(
tmp_over_one.transpose(2, 1), scale_factor=upp,
mode='linear', align_corners=True
).transpose(2, 1)
rad_values = F.interpolate(rad_values.transpose(2, 1), scale_factor=upp, mode='nearest').transpose(2, 1)
tmp_over_one = tmp_over_one.fmod(1.)
diff = F.conv2d(
tmp_over_one.unsqueeze(1), torch.FloatTensor([[[[-1.], [1.]]]]).to(tmp_over_one.device),
stride=(1, 1), padding=0, dilation=(1, 1)
).squeeze(1) # Equivalent to torch.diff, but able to export ONNX
cumsum_shift = (diff < 0).double()
cumsum_shift = torch.cat((
torch.zeros((f0_values.size()[0], 1, self.dim), dtype=torch.double).to(f0_values.device),
cumsum_shift
), dim=1)
sines = torch.sin(torch.cumsum(rad_values.double() + cumsum_shift, dim=1) * 2 * np.pi)
if is_half:
sines = sines.half()
else:
sines = sines.float()
return sines
@torch.no_grad()
def forward(self, f0, upp):
""" sine_tensor, uv = forward(f0)
input F0: tensor(batchsize=1, length, dim=1)
f0 for unvoiced steps should be 0
output sine_tensor: tensor(batchsize=1, length, dim)
output uv: tensor(batchsize=1, length, 1)
"""
f0 = f0.unsqueeze(-1)
fn = torch.multiply(f0, torch.arange(1, self.dim + 1, device=f0.device).reshape((1, 1, -1)))
sine_waves = self._f02sine(fn, upp) * self.sine_amp
uv = (f0 > self.voiced_threshold).float()
uv = F.interpolate(uv.transpose(2, 1), scale_factor=upp, mode='nearest').transpose(2, 1)
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
noise = noise_amp * torch.randn_like(sine_waves)
sine_waves = sine_waves * uv + noise
return sine_waves
class SourceModuleHnNSF(torch.nn.Module):
""" SourceModule for hn-nsf
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
add_noise_std=0.003, voiced_threshod=0)
sampling_rate: sampling_rate in Hz
harmonic_num: number of harmonic above F0 (default: 0)
sine_amp: amplitude of sine source signal (default: 0.1)
add_noise_std: std of additive Gaussian noise (default: 0.003)
note that amplitude of noise in unvoiced is decided
by sine_amp
voiced_threshold: threhold to set U/V given F0 (default: 0)
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
F0_sampled (batchsize, length, 1)
Sine_source (batchsize, length, 1)
noise_source (batchsize, length 1)
uv (batchsize, length, 1)
"""
def __init__(self, sampling_rate, harmonic_num=0, sine_amp=0.1,
add_noise_std=0.003, voiced_threshold=0):
super(SourceModuleHnNSF, self).__init__()
self.sine_amp = sine_amp
self.noise_std = add_noise_std
# to produce sine waveforms
self.l_sin_gen = SineGen(sampling_rate, harmonic_num,
sine_amp, add_noise_std, voiced_threshold)
# to merge source harmonics into a single excitation
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
self.l_tanh = torch.nn.Tanh()
def forward(self, x, upp):
sine_wavs = self.l_sin_gen(x, upp)
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
return sine_merge
class DDSP(nn.Module):
def __init__(self,config):
super().__init__()
if config['model_args']['type']=='CombSub':
self.ddsp = CombSub(
sampling_rate=config['audio_sample_rate'],
block_size=config['hop_size'],
win_length=config['win_size'],
n_mag_harmonic=config['model_args']['n_mag_harmonic'],
n_mag_noise=config['model_args']['n_mag_noise'],
n_mels=config['audio_num_mel_bins'])
elif config['model_args']['type']=='Sins': | self.ddsp = Sins( | 2 | 2023-10-17 13:45:09+00:00 | 8k |
OllieBoyne/FOUND | FOUND/utils/eval_utils.py | [
{
"identifier": "modified_chamf",
"path": "FOUND/utils/pytorch3d.py",
"snippet": "def modified_chamf(x,y, x_lengths=None, y_lengths=None,\n x_normals=None, y_normals=None,\n norm: int = 2):\n \"\"\"\n \tA modified version of pytorch3d.loss.chamfer_distance\n \tto allow for no point or batch... | from pytorch3d.renderer import TexturesVertex
from pytorch3d.structures import Meshes
from multiprocessing import Process
from prettytable import PrettyTable
from .pytorch3d import modified_chamf, modified_sample
from .renderer import Renderer, view_from
from .vis import produce_grid, put_text, colourbar
from matplotlib import pyplot as plt
import os
import trimesh
import cv2
import multiprocessing as mp
import torch
import torch.nn.functional as F
import numpy as np
import json | 6,852 |
fracs = (err - vmin) / (vmax - vmin)
rgba = (colmin + fracs.unsqueeze(-1) * (colmax - colmin)).to(err.device)
rgba = torch.clip(rgba, min=0, max=1)
rgba[torch.any(torch.isnan(rgba), dim=-1)] = colnan
return rgba
class Reporter:
"""Receive statements, on exit print all and save all to file"""
def __init__(self, out_file_loc):
self.lines = []
self.out_file_loc = out_file_loc
def __call__(self, line):
self.lines.append(line)
def __enter__(self, *args):
return self
def __exit__(self, *args):
[*map(print, self.lines)]
with open(self.out_file_loc, 'w') as outfile:
outfile.writelines([s + '\n' for s in self.lines])
def get_max_fit(exp_dir):
"""Search in an experiment directory for the fit_xx.obj with the highest value"""
f = lambda s: -1 if 'fit_' not in s else int(s.split('fit_')[1].split('.obj')[0])
return max(os.listdir(exp_dir), key=f)
def cutoff_slice_FIND(mesh, max_heel_height = 0.04, cutoff_height = 0.1):
"""Similar mesh slicing method to FIND: identify heel keypoint, slice off 1cm above"""
X, Y, Z = mesh.vertices.T
Xma = np.ma.array(X, mask= Z >= max_heel_height)
heel_idx = np.ma.argmin(Xma)
slice_height = min(Z[heel_idx] + cutoff_height, Z.max() - 5e-3)
return mesh.slice_plane([0, 0, slice_height], [0, 0, -1], cap=False)
def get_loghist(x, nbins):
hist, bins = np.histogram(x, bins=nbins)
logbins = np.logspace(np.log10(bins[0]),np.log10(bins[-1]),len(bins))
return dict(x=x, bins=logbins)
def eval_exp(exp_dir, render=True):
results = {} # return results as errors
if not any('fit_' in f for f in os.listdir(exp_dir)):
print(f"No fits for {exp_dir}, skipping...")
return
pred_obj_loc = os.path.join(exp_dir, get_max_fit(exp_dir))
# load settings to get folder
opts_loc = os.path.join(exp_dir, 'opts.json')
if not os.path.isfile(opts_loc):
print(f"No opts for {exp_dir}, skipping...")
return
with open(opts_loc) as infile:
settings = json.load(infile)
# assume GT OBJ loc is
# (1) saved in <data_folder>/mesh.obj if <data_folder> given
if 'data_folder' in settings:
gt_obj_loc = os.path.join(settings['data_folder'], 'mesh.obj')
# (2) saved in <exp_dir>/gt_mesh.obj otherwise
else:
gt_obj_loc = os.path.join(exp_dir, 'gt_mesh.obj')
eval_dir = os.path.join(exp_dir, 'eval')
os.makedirs(eval_dir, exist_ok=True)
with open(gt_obj_loc) as infile:
d = trimesh.exchange.obj.load_obj(infile, process=False)
gt_mesh_trimesh = trimesh.Trimesh(**d)
with open(pred_obj_loc) as infile:
d = trimesh.exchange.obj.load_obj(infile, process=False)
pred_mesh_trimesh = trimesh.Trimesh(**d)
# pre-process meshes, w/ cutoff
# Same method as used for Foot3D here for slicing GT
gt_mesh_trimesh = cutoff_slice_FIND(gt_mesh_trimesh)
if settings.get('model', 'FIND') == 'FIND':
# slice FIND faces
FIND_cutoff_surface = np.load(os.path.join(settings['find_pth'], 'templ_masked_faces.npy'))
FIND_sole_faces = np.load(os.path.join(settings['find_pth'], 'templ_sole_faces.npy'))
FIND_sole_verts = np.unique(np.ravel(pred_mesh_trimesh.faces[FIND_sole_faces])) # all vertices considered part of the sole
sole_vert_positions = pred_mesh_trimesh.vertices[FIND_sole_verts] # save sole vertex positions to refind them after mesh pre-processing
pred_mesh_trimesh.update_faces(~np.isin(np.arange(pred_mesh_trimesh.faces.shape[0]), FIND_cutoff_surface))
pred_mesh_trimesh = cutoff_slice_FIND(pred_mesh_trimesh)
# define a mask
# want to be able to define a mask on the FIND model, so that errors of verts in this mask aren't considered real -> pred, but are considered in reverse
# (for sole verts, unfair to count the error on them, but likewise incorrect to just remove them all, especially at the boundary)
# recalculate sole vertices
FIND_sole_vert_idxs = np.argwhere(np.all(pred_mesh_trimesh.vertices[:, None, :] == sole_vert_positions[None, ...], axis=-1))[:, 0]
FIND_sole_vertex_mask = np.isin(np.arange(pred_mesh_trimesh.vertices.shape[0]), FIND_sole_vert_idxs) # mask of which vertices correspond to the sole
FIND_sole_faces_mask = np.any(FIND_sole_vertex_mask[pred_mesh_trimesh.faces], axis=-1) # mask of which faces are in sole
else:
pred_mesh_trimesh = cutoff_slice_FIND(pred_mesh_trimesh)
# Convert to PyTorch3D
p3d_from_trimesh = lambda mesh: Meshes(verts=torch.from_numpy(np.asarray(mesh.vertices)[None, ...]).float(),
faces=torch.from_numpy(np.asarray(mesh.faces)[None, ...])).to(device)
gt_mesh = p3d_from_trimesh(gt_mesh_trimesh)
pred_mesh = p3d_from_trimesh(pred_mesh_trimesh)
# Sample vertices uniformly from mesh, returning vertex position, normal, and original face/vert idxs
| """Evaluate the performance of a fitted mesh"""
device = 'cuda'
def eval_metrics(arr, cutoffs=[5, 7.5, 11.25, 22.5, 30]):
"""Given a 1d array, return mean, median, rmse,
and % of values less than each in `cutoffs`"""
assert arr.ndim == 1, "eval_metrics requires 1D array"
out = dict(mean = arr.mean(), median = np.median(arr), rmse = (arr ** 2).mean() **.5,
cutoffs = [(arr < i).mean() for i in cutoffs])
return out
def err_to_colour(err: torch.Tensor, vmin:float=None, vmax:float=None, colmin=(0, 1, 0), colmax=(1, 0, 0), nan_colour=(0.3, 0.3, 0.3)):
"""Convert a tensor of errors (...) to an RGB colour scale (..., 3).
Linearly interpolate so that err of vmin -> colmin, err of vmax -> colmax
if vmin and vmax not given, take min and max of err
If any nan's given, set their colour to nan_colour
"""
ndim = err.ndim
colmin = torch.tensor(colmin)[(None,)*ndim].to(err.device) # expand colmin to [..., 3]
colmax = torch.tensor(colmax)[(None,)*ndim].to(err.device)
colnan = torch.tensor(nan_colour)[(None,)*ndim].to(err.device)
vmin = err.nanmin() if vmin is None else vmin
vmax = err.nanmax() if vmax is None else vmax
fracs = (err - vmin) / (vmax - vmin)
rgba = (colmin + fracs.unsqueeze(-1) * (colmax - colmin)).to(err.device)
rgba = torch.clip(rgba, min=0, max=1)
rgba[torch.any(torch.isnan(rgba), dim=-1)] = colnan
return rgba
class Reporter:
"""Receive statements, on exit print all and save all to file"""
def __init__(self, out_file_loc):
self.lines = []
self.out_file_loc = out_file_loc
def __call__(self, line):
self.lines.append(line)
def __enter__(self, *args):
return self
def __exit__(self, *args):
[*map(print, self.lines)]
with open(self.out_file_loc, 'w') as outfile:
outfile.writelines([s + '\n' for s in self.lines])
def get_max_fit(exp_dir):
"""Search in an experiment directory for the fit_xx.obj with the highest value"""
f = lambda s: -1 if 'fit_' not in s else int(s.split('fit_')[1].split('.obj')[0])
return max(os.listdir(exp_dir), key=f)
def cutoff_slice_FIND(mesh, max_heel_height = 0.04, cutoff_height = 0.1):
"""Similar mesh slicing method to FIND: identify heel keypoint, slice off 1cm above"""
X, Y, Z = mesh.vertices.T
Xma = np.ma.array(X, mask= Z >= max_heel_height)
heel_idx = np.ma.argmin(Xma)
slice_height = min(Z[heel_idx] + cutoff_height, Z.max() - 5e-3)
return mesh.slice_plane([0, 0, slice_height], [0, 0, -1], cap=False)
def get_loghist(x, nbins):
hist, bins = np.histogram(x, bins=nbins)
logbins = np.logspace(np.log10(bins[0]),np.log10(bins[-1]),len(bins))
return dict(x=x, bins=logbins)
def eval_exp(exp_dir, render=True):
results = {} # return results as errors
if not any('fit_' in f for f in os.listdir(exp_dir)):
print(f"No fits for {exp_dir}, skipping...")
return
pred_obj_loc = os.path.join(exp_dir, get_max_fit(exp_dir))
# load settings to get folder
opts_loc = os.path.join(exp_dir, 'opts.json')
if not os.path.isfile(opts_loc):
print(f"No opts for {exp_dir}, skipping...")
return
with open(opts_loc) as infile:
settings = json.load(infile)
# assume GT OBJ loc is
# (1) saved in <data_folder>/mesh.obj if <data_folder> given
if 'data_folder' in settings:
gt_obj_loc = os.path.join(settings['data_folder'], 'mesh.obj')
# (2) saved in <exp_dir>/gt_mesh.obj otherwise
else:
gt_obj_loc = os.path.join(exp_dir, 'gt_mesh.obj')
eval_dir = os.path.join(exp_dir, 'eval')
os.makedirs(eval_dir, exist_ok=True)
with open(gt_obj_loc) as infile:
d = trimesh.exchange.obj.load_obj(infile, process=False)
gt_mesh_trimesh = trimesh.Trimesh(**d)
with open(pred_obj_loc) as infile:
d = trimesh.exchange.obj.load_obj(infile, process=False)
pred_mesh_trimesh = trimesh.Trimesh(**d)
# pre-process meshes, w/ cutoff
# Same method as used for Foot3D here for slicing GT
gt_mesh_trimesh = cutoff_slice_FIND(gt_mesh_trimesh)
if settings.get('model', 'FIND') == 'FIND':
# slice FIND faces
FIND_cutoff_surface = np.load(os.path.join(settings['find_pth'], 'templ_masked_faces.npy'))
FIND_sole_faces = np.load(os.path.join(settings['find_pth'], 'templ_sole_faces.npy'))
FIND_sole_verts = np.unique(np.ravel(pred_mesh_trimesh.faces[FIND_sole_faces])) # all vertices considered part of the sole
sole_vert_positions = pred_mesh_trimesh.vertices[FIND_sole_verts] # save sole vertex positions to refind them after mesh pre-processing
pred_mesh_trimesh.update_faces(~np.isin(np.arange(pred_mesh_trimesh.faces.shape[0]), FIND_cutoff_surface))
pred_mesh_trimesh = cutoff_slice_FIND(pred_mesh_trimesh)
# define a mask
# want to be able to define a mask on the FIND model, so that errors of verts in this mask aren't considered real -> pred, but are considered in reverse
# (for sole verts, unfair to count the error on them, but likewise incorrect to just remove them all, especially at the boundary)
# recalculate sole vertices
FIND_sole_vert_idxs = np.argwhere(np.all(pred_mesh_trimesh.vertices[:, None, :] == sole_vert_positions[None, ...], axis=-1))[:, 0]
FIND_sole_vertex_mask = np.isin(np.arange(pred_mesh_trimesh.vertices.shape[0]), FIND_sole_vert_idxs) # mask of which vertices correspond to the sole
FIND_sole_faces_mask = np.any(FIND_sole_vertex_mask[pred_mesh_trimesh.faces], axis=-1) # mask of which faces are in sole
else:
pred_mesh_trimesh = cutoff_slice_FIND(pred_mesh_trimesh)
# Convert to PyTorch3D
p3d_from_trimesh = lambda mesh: Meshes(verts=torch.from_numpy(np.asarray(mesh.vertices)[None, ...]).float(),
faces=torch.from_numpy(np.asarray(mesh.faces)[None, ...])).to(device)
gt_mesh = p3d_from_trimesh(gt_mesh_trimesh)
pred_mesh = p3d_from_trimesh(pred_mesh_trimesh)
# Sample vertices uniformly from mesh, returning vertex position, normal, and original face/vert idxs | gt_sample_dict = modified_sample(gt_mesh, num_samples=10_000, return_normals=True) | 1 | 2023-10-24 11:46:42+00:00 | 8k |
RobertCsordas/moe | layers/transformer/relative_preln_kvmem_transformer.py | [
{
"identifier": "ActivationFunction",
"path": "layers/transformer/transformer.py",
"snippet": "class TransformerEncoderLayer(torch.nn.Module):\nclass TransformerDecoderLayer(torch.nn.Module):\nclass TransformerDecoderBase(torch.nn.Module):\n class State:\nclass TransformerEncoder(torch.nn.Module):\nc... | from typing import Optional, List, Union, Tuple
from .transformer import ActivationFunction
from .multi_head_relative_pos_attention import FixedRelativeMultiheadAttention, AttentionMask
from .transformer_preln import reset_prenorm_params
from layers.lowrank_approximate_2layer import LowrankApproximate2Layer
import torch
import torch.nn
import torch.nn.functional as F
import math | 6,356 |
class PrelnRelativeKVMemTransformerEncoderLayer(torch.nn.Module):
def __init__(self, d_model, nhead, n_keys: Union[int, Tuple[int, int]], n_layers: int, dim_feedforward=2048,
dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0,
test_pos_clamp: Optional[int] = None, pkm_heads: int = 1, pkm_stochastic: bool = True,
pkm_custom_init: int = 0, pkm_slice_values: bool = False,
pkm_knn: int = 32, linproj: bool = False, head_merge_topk: bool = False, load_balance: bool = True,
kvmem_dropout: str = "none", kvmem_randomize_indices: bool = False, kvmem_query_bias: bool = False,
standard_parallel: bool = False, approx_topk: bool = False, factorize: bool = False,
full_key: bool = False, key_redundancy_factor: int = 1, two_stage: bool = False,
factors: Optional[List[int]] = None, head_exclusive: bool = False,
head_projection_size: Optional[int] = None):
super().__init__()
self.self_attn = FixedRelativeMultiheadAttention(
d_model, nhead, dropout=attention_dropout, test_pos_clamp=test_pos_clamp,
projection_size=head_projection_size)
self.pkm = LowrankApproximate2Layer(
d_model, n_keys, pkm_heads, stochastic=pkm_stochastic, custom_init=pkm_custom_init,
weight_scale=math.sqrt(2.0 / n_layers), slice_values=pkm_slice_values, knn=pkm_knn,
head_merge_topk=head_merge_topk, load_balance=load_balance, dropout=dropout,
query_proj=linproj, randomize_indices=kvmem_randomize_indices, dropout_mode=kvmem_dropout,
query_bias=kvmem_query_bias, approx=approx_topk, factorize=factorize, full_key=full_key,
key_redundancy_factor=key_redundancy_factor, two_stage=two_stage, factors=factors,
head_exclusive=head_exclusive, activation=activation)
self.norm1 = torch.nn.LayerNorm(d_model)
self.norm2 = torch.nn.LayerNorm(d_model)
self.dropout = torch.nn.Dropout(dropout)
self.activation = activation
self.standard_parallel = standard_parallel
reset_prenorm_params(self, n_layers)
if self.standard_parallel:
self.linear1 = torch.nn.Linear(d_model, dim_feedforward, bias=False)
self.linear2 = torch.nn.Linear(dim_feedforward, d_model, bias=False)
initializer = self.pkm.get_custom_init()
s_real = dim_feedforward + self.pkm.size
# s_real = dim_feedforward + self.pkm.heads * self.pkm.knn
initializer(self.linear2.weight, std=math.sqrt(2 / (n_layers * s_real)))
initializer(self.pkm.values.weight, std=math.sqrt(2 / (n_layers * s_real)))
initializer(self.linear1.weight, std=math.sqrt(2 / (n_layers * d_model)))
if self.pkm.two_stage:
initializer(self.pkm.full_keys, std=math.sqrt(2 / (n_layers * d_model)))
|
class PrelnRelativeKVMemTransformerEncoderLayer(torch.nn.Module):
def __init__(self, d_model, nhead, n_keys: Union[int, Tuple[int, int]], n_layers: int, dim_feedforward=2048,
dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0,
test_pos_clamp: Optional[int] = None, pkm_heads: int = 1, pkm_stochastic: bool = True,
pkm_custom_init: int = 0, pkm_slice_values: bool = False,
pkm_knn: int = 32, linproj: bool = False, head_merge_topk: bool = False, load_balance: bool = True,
kvmem_dropout: str = "none", kvmem_randomize_indices: bool = False, kvmem_query_bias: bool = False,
standard_parallel: bool = False, approx_topk: bool = False, factorize: bool = False,
full_key: bool = False, key_redundancy_factor: int = 1, two_stage: bool = False,
factors: Optional[List[int]] = None, head_exclusive: bool = False,
head_projection_size: Optional[int] = None):
super().__init__()
self.self_attn = FixedRelativeMultiheadAttention(
d_model, nhead, dropout=attention_dropout, test_pos_clamp=test_pos_clamp,
projection_size=head_projection_size)
self.pkm = LowrankApproximate2Layer(
d_model, n_keys, pkm_heads, stochastic=pkm_stochastic, custom_init=pkm_custom_init,
weight_scale=math.sqrt(2.0 / n_layers), slice_values=pkm_slice_values, knn=pkm_knn,
head_merge_topk=head_merge_topk, load_balance=load_balance, dropout=dropout,
query_proj=linproj, randomize_indices=kvmem_randomize_indices, dropout_mode=kvmem_dropout,
query_bias=kvmem_query_bias, approx=approx_topk, factorize=factorize, full_key=full_key,
key_redundancy_factor=key_redundancy_factor, two_stage=two_stage, factors=factors,
head_exclusive=head_exclusive, activation=activation)
self.norm1 = torch.nn.LayerNorm(d_model)
self.norm2 = torch.nn.LayerNorm(d_model)
self.dropout = torch.nn.Dropout(dropout)
self.activation = activation
self.standard_parallel = standard_parallel
reset_prenorm_params(self, n_layers)
if self.standard_parallel:
self.linear1 = torch.nn.Linear(d_model, dim_feedforward, bias=False)
self.linear2 = torch.nn.Linear(dim_feedforward, d_model, bias=False)
initializer = self.pkm.get_custom_init()
s_real = dim_feedforward + self.pkm.size
# s_real = dim_feedforward + self.pkm.heads * self.pkm.knn
initializer(self.linear2.weight, std=math.sqrt(2 / (n_layers * s_real)))
initializer(self.pkm.values.weight, std=math.sqrt(2 / (n_layers * s_real)))
initializer(self.linear1.weight, std=math.sqrt(2 / (n_layers * d_model)))
if self.pkm.two_stage:
initializer(self.pkm.full_keys, std=math.sqrt(2 / (n_layers * d_model)))
| def forward(self, src: torch.Tensor, mask: Optional[AttentionMask] = None, attend_to: Optional[torch.Tensor] = None, | 1 | 2023-10-16 11:26:45+00:00 | 8k |
enkeejunior1/Diffusion-Pullback | src/models/improved_ddpm_old/unet.py | [
{
"identifier": "convert_module_to_f16",
"path": "src/models/improved_ddpm_old/fp16_util.py",
"snippet": "def convert_module_to_f16(l):\n \"\"\"\n Convert primitive modules to float16.\n \"\"\"\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):\n l.weight.data = l.weight.data.half... | import time
import torchvision.utils as tvu
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange, reduce, repeat, einsum
from abc import abstractmethod
from .fp16_util import convert_module_to_f16, convert_module_to_f32
from .nn import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
) | 3,935 |
if i == max_iter - 1:
print('last convergence : ', convergence)
u, s, vT = u.view(-1, c_o*w_o*h_o).T.detach(), s.sqrt().detach(), v.view(-1, c_i*w_i*h_i).detach()
return u, s, vT
##############
# submodules #
##############
class AttentionPool2d(nn.Module):
"""
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
"""
def __init__(
self,
spacial_dim: int,
embed_dim: int,
num_heads_channels: int,
output_dim: int = None,
):
super().__init__()
self.positional_embedding = nn.Parameter(
th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
)
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
self.num_heads = embed_dim // num_heads_channels
self.attention = QKVAttention(self.num_heads)
def forward(self, x):
b, c, *_spatial = x.shape
x = x.reshape(b, c, -1) # NC(HW)
x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
x = self.qkv_proj(x)
x = self.attention(x)
x = self.c_proj(x)
return x[:, :, 0]
class TimestepBlock(nn.Module):
"""
Any module where forward() takes timestep embeddings as a second argument.
"""
@abstractmethod
def forward(self, x, emb):
"""
Apply the module to `x` given `emb` timestep embeddings.
"""
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
else:
x = layer(x)
return x
class Upsample(nn.Module):
"""
An upsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
upsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2, out_channels=None):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.dims = dims
if use_conv:
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
def forward(self, x):
assert x.shape[1] == self.channels
if self.dims == 3:
x = F.interpolate(
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
)
else:
x = F.interpolate(x, scale_factor=2, mode="nearest")
if self.use_conv:
x = self.conv(x)
return x
class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2, out_channels=None):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.dims = dims
stride = 2 if dims != 3 else (1, 2, 2)
if use_conv:
self.op = conv_nd(
dims, self.channels, self.out_channels, 3, stride=stride, padding=1
)
else:
assert self.channels == self.out_channels
| """
Codebase for "Improved Denoising Diffusion Probabilistic Models".
"""
#########
# model #
#########
class UNetModel(nn.Module):
"""
The full UNet model with attention and timestep embedding.
:param in_channels: channels in the input Tensor.
:param model_channels: base channel count for the model.
:param out_channels: channels in the output Tensor.
:param num_res_blocks: number of residual blocks per downsample.
:param attention_resolutions: a collection of downsample rates at which
attention will take place. May be a set, list, or tuple.
For example, if this contains 4, then at 4x downsampling, attention
will be used.
:param dropout: the dropout probability.
:param channel_mult: channel multiplier for each level of the UNet.
:param conv_resample: if True, use learned convolutions for upsampling and
downsampling.
:param dims: determines if the signal is 1D, 2D, or 3D.
:param num_classes: if specified (as an int), then this model will be
class-conditional with `num_classes` classes.
:param use_checkpoint: use gradient checkpointing to reduce memory usage.
:param num_heads: the number of attention heads in each attention layer.
:param num_heads_channels: if specified, ignore num_heads and instead use
a fixed channel width per attention head.
:param num_heads_upsample: works with num_heads to set a different number
of heads for upsampling. Deprecated.
:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
:param resblock_updown: use residual blocks for up/downsampling.
:param use_new_attention_order: use a different attention pattern for potentially
increased efficiency.
"""
def __init__(
self,
args,
image_size,
in_channels,
model_channels,
out_channels,
num_res_blocks,
attention_resolutions,
dropout=0,
channel_mult=(1, 2, 4, 8),
conv_resample=True,
dims=2,
num_classes=None,
use_checkpoint=False,
use_fp16=False,
num_heads=1,
num_head_channels=-1,
num_heads_upsample=-1,
use_scale_shift_norm=False,
resblock_updown=False,
use_new_attention_order=False,
):
super().__init__()
if num_heads_upsample == -1:
num_heads_upsample = num_heads
self.image_size = image_size
self.in_channels = in_channels
self.model_channels = model_channels
self.out_channels = out_channels
self.num_res_blocks = num_res_blocks
self.attention_resolutions = attention_resolutions
self.dropout = dropout
self.channel_mult = channel_mult
self.conv_resample = conv_resample
self.num_classes = num_classes
self.use_checkpoint = use_checkpoint
self.dtype = th.float16 if use_fp16 else th.float32
self.num_heads = num_heads
self.num_head_channels = num_head_channels
self.num_heads_upsample = num_heads_upsample
time_embed_dim = model_channels * 4
self.time_embed = nn.Sequential(
linear(model_channels, time_embed_dim),
nn.SiLU(),
linear(time_embed_dim, time_embed_dim),
)
if self.num_classes is not None:
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
ch = input_ch = int(channel_mult[0] * model_channels)
self.input_blocks = nn.ModuleList(
[TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
)
self._feature_size = ch
input_block_chans = [ch]
ds = 1
for level, mult in enumerate(channel_mult):
for _ in range(num_res_blocks):
layers = [
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=int(mult * model_channels),
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = int(mult * model_channels)
if ds in attention_resolutions:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
)
)
self.input_blocks.append(TimestepEmbedSequential(*layers))
self._feature_size += ch
input_block_chans.append(ch)
if level != len(channel_mult) - 1:
out_ch = ch
self.input_blocks.append(
TimestepEmbedSequential(
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=out_ch,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
down=True,
)
if resblock_updown
else Downsample(
ch, conv_resample, dims=dims, out_channels=out_ch
)
)
)
ch = out_ch
input_block_chans.append(ch)
ds *= 2
self._feature_size += ch
self.middle_block = TimestepEmbedSequential(
ResBlock(
ch,
time_embed_dim,
dropout,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
),
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
),
ResBlock(
ch,
time_embed_dim,
dropout,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
),
)
self._feature_size += ch
self.output_blocks = nn.ModuleList([])
for level, mult in list(enumerate(channel_mult))[::-1]:
for i in range(num_res_blocks + 1):
ich = input_block_chans.pop()
layers = [
ResBlock(
ch + ich,
time_embed_dim,
dropout,
out_channels=int(model_channels * mult),
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = int(model_channels * mult)
if ds in attention_resolutions:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads_upsample,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
)
)
if level and i == num_res_blocks:
out_ch = ch
layers.append(
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=out_ch,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
up=True,
)
if resblock_updown
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
)
ds //= 2
self.output_blocks.append(TimestepEmbedSequential(*layers))
self._feature_size += ch
self.out = nn.Sequential(
normalization(ch),
nn.SiLU(),
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
)
############
# Pullback #
############
self.device = args.device
self.dtype = args.dtype
def convert_to_fp16(self):
"""
Convert the torso of the model to float16.
"""
self.input_blocks.apply(convert_module_to_f16)
self.middle_block.apply(convert_module_to_f16)
self.output_blocks.apply(convert_module_to_f16)
def convert_to_fp32(self):
"""
Convert the torso of the model to float32.
"""
self.input_blocks.apply(convert_module_to_f32)
self.middle_block.apply(convert_module_to_f32)
self.output_blocks.apply(convert_module_to_f32)
def forward(
self, x, t, u=None, return_sigma=False, **kwargs
):
"""
Apply the model to an input batch.
:param x: an [N x C x ...] Tensor of inputs.
:param t: a 1-D batch of t.
:param y: an [N] Tensor of labels, if class-conditional.
:return: an [N x C x ...] Tensor of outputs.
"""
# assert (y is not None) == (
# self.num_classes is not None
# ), "must specify y if and only if the model is class-conditional"
t = t.unsqueeze(0) if len(t.shape) == 0 else t
t = t.to(device=self.device, dtype=self.dtype)
hs = []
emb = self.time_embed(timestep_embedding(t, self.model_channels))
# if self.num_classes is not None:
# assert y.shape == (x.shape[0],)
# emb = emb + self.label_emb(y)
h = x.type(self.dtype)
for module in self.input_blocks:
h = module(h, emb)
hs.append(h)
h = self.middle_block(h, emb)
if u is not None:
h = h + u.view(-1, *h[-1].shape)
for module in self.output_blocks:
h = th.cat([h, hs.pop()], dim=1)
h = module(h, emb)
h = h.type(x.dtype)
h = self.out(h)
return h
# et, logvar_learned = th.split(h, h.shape[1] // 2, dim=1)
# if return_sigma:
# return et, logvar_learned
# else:
# return et
def get_h(
self, x, t, **kwargs
):
if isinstance(t, int):
t = th.tensor([t]).to(self.device)
elif isinstance(t, th.Tensor):
t = t.unsqueeze(0) if len(t.shape) == 0 else t
else:
raise ValueError('t must be int or torch.Tensor')
emb = self.time_embed(timestep_embedding(t, self.model_channels))
h = x.type(self.dtype)
for module in self.input_blocks:
h = module(h, emb)
h = self.middle_block(h, emb)
return h
def inv_jac_xt(
self, x=None, t=None, op=None, block_idx=None,
u=None, perturb_h=1e-1,
):
# original h
h = self.get_h(
x=x, t=t, op=op, block_idx=block_idx,
)
# get number of h space directions
if len(u.shape) > 1:
pca_rank = u.size(1)
h = h.repeat(pca_rank, 1, 1, 1).detach()
u = rearrange(u, '(c w h) k -> k c w h', c=h.size(1), w=h.size(2), h=h.size(3))
else:
pca_rank = 1
u = u.view(*h.shape)
# perturb h
perturbed_h = h + perturb_h * u
# get corresponding x direction (argmin_v perturbed_h - f(xt + v))
jacx = lambda x : (perturbed_h - self.get_h(
x=x, t=t, op=op, block_idx=block_idx,
)).view(pca_rank, -1).norm(dim=-1)
jac = th.autograd.functional.jacobian(jacx, x)
# normalize direction
vT = normalize_wrt_batch(jac).view(pca_rank, -1)
return vT
def local_encoder_pullback_xt(
self, x=None, t=None, op=None, block_idx=None, pca_rank=16, chunk_size=25,
min_iter=10, max_iter=100, convergence_threshold=1e-3,
):
'''
Args
- sample : zt
- op : ['down', 'mid', 'up']
- block_idx : op == down, up : [0,1,2,3], op == mid : [0]
- pooling : ['pixel-sum', 'channel-sum', 'single-channel', 'multiple-channel']
Returns
- h : hidden feature
'''
# necessary variables
num_chunk = pca_rank // chunk_size if pca_rank % chunk_size == 0 else pca_rank // chunk_size + 1
get_h = lambda x : self.get_h(
x, t=t, op=op, block_idx=block_idx,
)
h_shape = get_h(x).shape
print('h_shape : ', h_shape)
c_i, w_i, h_i = x.size(1), x.size(2), x.size(3)
c_o, w_o, h_o = h_shape[1], h_shape[2], h_shape[3]
a = th.tensor(0., device=x.device)
# Algorithm 1
vT = th.randn(c_i*w_i*h_i, pca_rank, device=x.device)
vT, _ = th.linalg.qr(vT)
v = vT.T
v = v.view(-1, c_i, w_i, h_i)
for i in range(max_iter):
v_prev = v.detach().cpu().clone()
u = []
time_s = time.time()
v_buffer = list(v.chunk(num_chunk))
for vi in v_buffer:
# g = lambda a : get_h(x + a*vi.unsqueeze(0) if vi.size(0) == v.size(-1) else x + a*vi)
g = lambda a : get_h(x + a*vi)
ui = th.func.jacfwd(g, argnums=0, has_aux=False, randomness='error')(a)
u.append(ui.detach().cpu().clone())
time_e = time.time()
print('single v jacfwd t ==', time_e - time_s)
u = th.cat(u, dim=0)
u = u.to(x.device)
# time_s = time.time()
# g = lambda a : get_h(x + a*v)
# u = th.func.jacfwd(g, argnums=0, has_aux=False, randomness='error')(a)
# time_e = time.time()
# print('single vi jacfwd t ==', time_e - time_s)
g = lambda x : einsum(u, get_h(x), 'b c w h, i c w h -> b')
v_ = th.autograd.functional.jacobian(g, x)
v_ = v_.view(-1, c_i*w_i*h_i)
_, s, v = th.linalg.svd(v_, full_matrices=False)
v = v.view(-1, c_i, w_i, h_i)
u = u.view(-1, c_o, w_o, h_o)
convergence = th.dist(v_prev, v.detach().cpu())
print(f'power method : {i}-th step convergence : ', convergence)
if th.allclose(v_prev, v.detach().cpu(), atol=convergence_threshold) and (i > min_iter):
print('reach convergence threshold : ', convergence)
break
if i == max_iter - 1:
print('last convergence : ', convergence)
u, s, vT = u.view(-1, c_o*w_o*h_o).T.detach(), s.sqrt().detach(), v.view(-1, c_i*w_i*h_i).detach()
return u, s, vT
##############
# submodules #
##############
class AttentionPool2d(nn.Module):
"""
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
"""
def __init__(
self,
spacial_dim: int,
embed_dim: int,
num_heads_channels: int,
output_dim: int = None,
):
super().__init__()
self.positional_embedding = nn.Parameter(
th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
)
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
self.num_heads = embed_dim // num_heads_channels
self.attention = QKVAttention(self.num_heads)
def forward(self, x):
b, c, *_spatial = x.shape
x = x.reshape(b, c, -1) # NC(HW)
x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
x = self.qkv_proj(x)
x = self.attention(x)
x = self.c_proj(x)
return x[:, :, 0]
class TimestepBlock(nn.Module):
"""
Any module where forward() takes timestep embeddings as a second argument.
"""
@abstractmethod
def forward(self, x, emb):
"""
Apply the module to `x` given `emb` timestep embeddings.
"""
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
else:
x = layer(x)
return x
class Upsample(nn.Module):
"""
An upsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
upsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2, out_channels=None):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.dims = dims
if use_conv:
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
def forward(self, x):
assert x.shape[1] == self.channels
if self.dims == 3:
x = F.interpolate(
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
)
else:
x = F.interpolate(x, scale_factor=2, mode="nearest")
if self.use_conv:
x = self.conv(x)
return x
class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2, out_channels=None):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.dims = dims
stride = 2 if dims != 3 else (1, 2, 2)
if use_conv:
self.op = conv_nd(
dims, self.channels, self.out_channels, 3, stride=stride, padding=1
)
else:
assert self.channels == self.out_channels | self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) | 5 | 2023-10-21 04:08:44+00:00 | 8k |
NVIDIA-Omniverse/IsaacSim-Automator | src/tests/deployer.test.py | [
{
"identifier": "c",
"path": "src/python/config.py",
"snippet": ""
},
{
"identifier": "Deployer",
"path": "src/python/deployer.py",
"snippet": "class Deployer:\n def __init__(self, params, config):\n self.tf_outputs = {}\n self.params = params\n self.config = conf... | import unittest
from src.python.config import c
from src.python.deployer import Deployer
from pathlib import Path | 4,761 | #!/usr/bin/env python3
class Test_Deployer(unittest.TestCase):
def setUp(self):
self.config = c
self.config["state_dir"] = f"{c['tests_dir']}/res/state"
| #!/usr/bin/env python3
class Test_Deployer(unittest.TestCase):
def setUp(self):
self.config = c
self.config["state_dir"] = f"{c['tests_dir']}/res/state"
| self.deployer = Deployer( | 1 | 2023-10-18 17:25:44+00:00 | 8k |
blackgold3/SemanticBoost | SMPLX/transfer_smpls.py | [
{
"identifier": "write_obj",
"path": "SMPLX/transfer_model/write_obj.py",
"snippet": "def write_obj(\n model_folder,\n motion_file,\n output_folder,\n model_type=\"smplh\",\n gender=\"neutral\",\n num_betas=10,\n num_expression_coeffs=10,\n use_face_contour=False,\n device=\"c... | import argparse
import numpy as np
import pickle
import os
import torch
import subprocess
import platform
import time
from SMPLX.transfer_model.write_obj import write_obj
from SMPLX.transfer_model.utils import read_deformation_transfer
from SMPLX.transfer_model.data import build_dataloader
from SMPLX.transfer_model.transfer_model import run_fitting
from SMPLX.transfer_model.merge_output import merge
from SMPLX.smplx import build_layer
from tqdm import tqdm | 4,752 |
def load_npz(path):
return np.load(path)
def load_pickle(path):
with open(path, "rb") as f:
res = pickle.load(f, encoding="latin1")
return res
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='transfer between smpls')
parser.add_argument('--source', default="smpl")
parser.add_argument("--target", default="smplh")
parser.add_argument("--model_path", default="/data/TTA/data/body_models")
parser.add_argument("--extra_dir", default="/data/TTA/data/extra_dir", help="https://smpl-x.is.tue.mpg.de/download.php")
parser.add_argument("--source_path", default="/data/TTA/data/humanact_smpl")
parser.add_argument("--target_path", default="/data/TTA/data/humanact_smplh")
parser.add_argument("--batch_size", default=500, type=int)
args = parser.parse_args()
device = "cuda"
if args.target == "smplx" or args.source == "smplx":
deformation_transfer_path = os.path.join(args.extra_dir, "{}2{}_deftrafo_setup.pkl".format(args.source, args.target))
else:
deformation_transfer_path = os.path.join(args.extra_dir, "{}2{}_def_transfer.pkl".format(args.source, args.target))
if args.target == "smplx":
model_params = {"betas":{"num":10}, "expression":{"num": 10}}
mask_ids_fname = os.path.join(args.extra_dir, "smplx_mask_ids.npy")
if os.path.exists(mask_ids_fname):
mask_ids = np.load(mask_ids_fname)
mask_ids = torch.from_numpy(mask_ids).to(device=device)
else:
print(f'Mask ids fname not found: {mask_ids_fname}')
elif args.target == "smplh" or args.target == "smpl":
model_params = {"betas":{"num":10}}
mask_ids_fname = ""
mask_ids = None
body_model_conf = {
"ext":"npz",
"model_type": args.target,
"folder": args.model_path,
"use_compressed": False,
args.target:model_params
}
if args.target == "smplx" or args.target == "smpl":
body_model_conf["use_face_contour"] = True
for root, dirs, files in os.walk(args.source_path):
for name in files:
curr_file = os.path.join(root, name)
new_root = os.path.join(args.target_path , "/".join(root.split("/")[:-2:-1]))
os.makedirs(new_root, exist_ok=True)
curr_target = os.path.join(new_root, name.replace(".npz", ".npy"))
if os.path.exists(curr_target):
print("%s has been competed"%(curr_target))
continue
if name.split(".")[-1] == "npz":
curr = load_npz(curr_file)
body_pose = None
elif name.split(".")[-1] == "pkl":
curr = load_pickle(curr_file)
body_pose = None
elif name.split(".")[-1] == "npy":
curr = np.load(curr_file)
body_pose = curr
else:
continue
if body_pose is None:
try:
body_pose = curr["poses"]
except:
print("Not Pose Data")
continue
gender = str(curr["gender"])
body_model_conf["gender"] = gender
else:
gender = "neutral"
body_model_conf["gender"] = gender
cid = name.split(".")[0]
save_folder1 = os.path.join("temp", "objs")
save_folder2 = os.path.join(new_root, str(time.time()))
os.makedirs(save_folder1, exist_ok=True)
os.makedirs(save_folder2, exist_ok=True)
write_obj(args.model_path, curr_file, save_folder1, args.source, gender, 10, 10, True, device)
|
def load_npz(path):
return np.load(path)
def load_pickle(path):
with open(path, "rb") as f:
res = pickle.load(f, encoding="latin1")
return res
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='transfer between smpls')
parser.add_argument('--source', default="smpl")
parser.add_argument("--target", default="smplh")
parser.add_argument("--model_path", default="/data/TTA/data/body_models")
parser.add_argument("--extra_dir", default="/data/TTA/data/extra_dir", help="https://smpl-x.is.tue.mpg.de/download.php")
parser.add_argument("--source_path", default="/data/TTA/data/humanact_smpl")
parser.add_argument("--target_path", default="/data/TTA/data/humanact_smplh")
parser.add_argument("--batch_size", default=500, type=int)
args = parser.parse_args()
device = "cuda"
if args.target == "smplx" or args.source == "smplx":
deformation_transfer_path = os.path.join(args.extra_dir, "{}2{}_deftrafo_setup.pkl".format(args.source, args.target))
else:
deformation_transfer_path = os.path.join(args.extra_dir, "{}2{}_def_transfer.pkl".format(args.source, args.target))
if args.target == "smplx":
model_params = {"betas":{"num":10}, "expression":{"num": 10}}
mask_ids_fname = os.path.join(args.extra_dir, "smplx_mask_ids.npy")
if os.path.exists(mask_ids_fname):
mask_ids = np.load(mask_ids_fname)
mask_ids = torch.from_numpy(mask_ids).to(device=device)
else:
print(f'Mask ids fname not found: {mask_ids_fname}')
elif args.target == "smplh" or args.target == "smpl":
model_params = {"betas":{"num":10}}
mask_ids_fname = ""
mask_ids = None
body_model_conf = {
"ext":"npz",
"model_type": args.target,
"folder": args.model_path,
"use_compressed": False,
args.target:model_params
}
if args.target == "smplx" or args.target == "smpl":
body_model_conf["use_face_contour"] = True
for root, dirs, files in os.walk(args.source_path):
for name in files:
curr_file = os.path.join(root, name)
new_root = os.path.join(args.target_path , "/".join(root.split("/")[:-2:-1]))
os.makedirs(new_root, exist_ok=True)
curr_target = os.path.join(new_root, name.replace(".npz", ".npy"))
if os.path.exists(curr_target):
print("%s has been competed"%(curr_target))
continue
if name.split(".")[-1] == "npz":
curr = load_npz(curr_file)
body_pose = None
elif name.split(".")[-1] == "pkl":
curr = load_pickle(curr_file)
body_pose = None
elif name.split(".")[-1] == "npy":
curr = np.load(curr_file)
body_pose = curr
else:
continue
if body_pose is None:
try:
body_pose = curr["poses"]
except:
print("Not Pose Data")
continue
gender = str(curr["gender"])
body_model_conf["gender"] = gender
else:
gender = "neutral"
body_model_conf["gender"] = gender
cid = name.split(".")[0]
save_folder1 = os.path.join("temp", "objs")
save_folder2 = os.path.join(new_root, str(time.time()))
os.makedirs(save_folder1, exist_ok=True)
os.makedirs(save_folder2, exist_ok=True)
write_obj(args.model_path, curr_file, save_folder1, args.source, gender, 10, 10, True, device)
| body_model = build_layer(args.model_path, **body_model_conf) | 5 | 2023-10-20 14:53:26+00:00 | 8k |
justchenhao/SILI_CD | compared_models/changeformer.py | [
{
"identifier": "UpsampleConvLayer",
"path": "compared_models/changeformerbase.py",
"snippet": "class UpsampleConvLayer(torch.nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride):\n super(UpsampleConvLayer, self).__init__()\n self.conv2d = nn.ConvTranspose2d(... | import torch
import torch.nn as nn
import torch.nn.functional
import torch.nn.functional as F
import warnings
import math
import os
from functools import partial
from .changeformerbase import UpsampleConvLayer, ResidualBlock, ConvLayer
from timm.models.layers import DropPath, to_2tuple, trunc_normal_ | 3,746 | 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 reset_drop_path(self, drop_path_rate):
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
cur = 0
for i in range(self.depths[0]):
self.block1[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[0]
for i in range(self.depths[1]):
self.block2[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[1]
for i in range(self.depths[2]):
self.block3[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[2]
for i in range(self.depths[3]):
self.block4[i].drop_path.drop_prob = dpr[cur + i]
def forward_features(self, x):
B = x.shape[0]
outs = []
# stage 1
x1, H1, W1 = self.patch_embed1(x)
for i, blk in enumerate(self.block1):
x1 = blk(x1, H1, W1)
x1 = self.norm1(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
# stage 2
x1, H1, W1 = self.patch_embed2(x1)
for i, blk in enumerate(self.block2):
x1 = blk(x1, H1, W1)
x1 = self.norm2(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
# stage 3
x1, H1, W1 = self.patch_embed3(x1)
for i, blk in enumerate(self.block3):
x1 = blk(x1, H1, W1)
x1 = self.norm3(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
# stage 4
x1, H1, W1 = self.patch_embed4(x1)
for i, blk in enumerate(self.block4):
x1 = blk(x1, H1, W1)
x1 = self.norm4(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
return outs
def forward(self, x):
x = self.forward_features(x)
return x
class DecoderTransformer_v3(nn.Module):
"""
Transformer Decoder
"""
def __init__(self, input_transform='multiple_select', in_index=[0, 1, 2, 3], align_corners=True,
in_channels=[32, 64, 128, 256], embedding_dim=64, output_nc=2,
decoder_softmax=False, feature_strides=[2, 4, 8, 16]):
super(DecoderTransformer_v3, self).__init__()
# assert
assert len(feature_strides) == len(in_channels)
assert min(feature_strides) == feature_strides[0]
# settings
self.feature_strides = feature_strides
self.input_transform = input_transform
self.in_index = in_index
self.align_corners = align_corners
self.in_channels = in_channels
self.embedding_dim = embedding_dim
self.output_nc = output_nc
c1_in_channels, c2_in_channels, c3_in_channels, c4_in_channels = self.in_channels
# MLP decoder heads
self.linear_c4 = MLP(input_dim=c4_in_channels, embed_dim=self.embedding_dim)
self.linear_c3 = MLP(input_dim=c3_in_channels, embed_dim=self.embedding_dim)
self.linear_c2 = MLP(input_dim=c2_in_channels, embed_dim=self.embedding_dim)
self.linear_c1 = MLP(input_dim=c1_in_channels, embed_dim=self.embedding_dim)
# convolutional Difference Modules
self.diff_c4 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
self.diff_c3 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
self.diff_c2 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
self.diff_c1 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
# taking outputs from middle of the encoder
self.make_pred_c4 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
self.make_pred_c3 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
self.make_pred_c2 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
self.make_pred_c1 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
# Final linear fusion layer
self.linear_fuse = nn.Sequential(
nn.Conv2d(in_channels=self.embedding_dim * len(in_channels), out_channels=self.embedding_dim,
kernel_size=1),
nn.BatchNorm2d(self.embedding_dim)
)
# Final predction head
|
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):
# pdb.set_trace()
x = self.proj(x)
_, _, H, W = x.shape
x = x.flatten(2).transpose(1, 2)
x = self.norm(x)
return x, H, W
def resize(input,
size=None,
scale_factor=None,
mode='nearest',
align_corners=None,
warning=True):
if warning:
if size is not None and align_corners:
input_h, input_w = tuple(int(x) for x in input.shape[2:])
output_h, output_w = tuple(int(x) for x in size)
if output_h > input_h or output_w > output_h:
if ((output_h > 1 and output_w > 1 and input_h > 1
and input_w > 1) and (output_h - 1) % (input_h - 1)
and (output_w - 1) % (input_w - 1)):
warnings.warn(
f'When align_corners={align_corners}, '
'the output would more aligned if '
f'input size {(input_h, input_w)} is `x+1` and '
f'out size {(output_h, output_w)} is `nx+1`')
return F.interpolate(input, size, scale_factor, mode, align_corners)
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.dwconv = DWConv(hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
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, H, W):
x = self.fc1(x)
x = self.dwconv(x, H, W)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
super().__init__()
assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
self.dim = dim
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.sr_ratio = sr_ratio
if sr_ratio > 1:
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
self.norm = nn.LayerNorm(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, H, W):
B, N, C = x.shape
q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
else:
kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
k, v = kv[0], kv[1]
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Attention_dec(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
super().__init__()
assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
self.dim = dim
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
self.task_query = nn.Parameter(torch.randn(1, 48, dim))
self.sr_ratio = sr_ratio
if sr_ratio > 1:
self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
self.norm = nn.LayerNorm(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, H, W):
B, N, C = x.shape
task_q = self.task_query
# This is because we fix the task parameters to be of a certain dimension, so with varying batch size, we just stack up the same queries to operate on the entire batch
if B > 1:
task_q = task_q.unsqueeze(0).repeat(B, 1, 1, 1)
task_q = task_q.squeeze(1)
q = self.q(task_q).reshape(B, task_q.shape[1], self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
else:
kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
k, v = kv[0], kv[1]
q = torch.nn.functional.interpolate(q, size=(v.shape[2], v.shape[3]))
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block_dec(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention_dec(
dim,
num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
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, H, W):
x = x + self.drop_path(self.attn(self.norm1(x), H, W))
x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
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, H, W):
x = x + self.drop_path(self.attn(self.norm1(x), H, W))
x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
return x
class DWConv(nn.Module):
def __init__(self, dim=768):
super(DWConv, self).__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, x, H, W):
B, N, C = x.shape
x = x.transpose(1, 2).view(B, C, H, W)
x = self.dwconv(x)
x = x.flatten(2).transpose(1, 2)
return x
# Transformer Decoder
class MLP(nn.Module):
"""
Linear Embedding
"""
def __init__(self, input_dim=2048, embed_dim=768):
super().__init__()
self.proj = nn.Linear(input_dim, embed_dim)
def forward(self, x):
x = x.flatten(2).transpose(1, 2)
x = self.proj(x)
return x
# Difference module
def conv_diff(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(out_channels),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
nn.ReLU()
)
# Intermediate prediction module
def make_prediction(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(out_channels),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
)
# Transormer Ecoder with x2, x4, x8, x16 scales
class EncoderTransformer_v3(nn.Module):
def __init__(self, img_size=256, patch_size=3, in_chans=3, num_classes=2, embed_dims=[32, 64, 128, 256],
num_heads=[2, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, qk_scale=None, drop_rate=0.,
attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
depths=[3, 3, 6, 18], sr_ratios=[8, 4, 2, 1]):
super().__init__()
self.num_classes = num_classes
self.depths = depths
self.embed_dims = embed_dims
# patch embedding definitions
self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_chans=in_chans,
embed_dim=embed_dims[0])
self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=patch_size, stride=2,
in_chans=embed_dims[0],
embed_dim=embed_dims[1])
self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=patch_size, stride=2,
in_chans=embed_dims[1],
embed_dim=embed_dims[2])
self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=patch_size, stride=2,
in_chans=embed_dims[2],
embed_dim=embed_dims[3])
# Stage-1 (x1/4 scale)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
cur = 0
self.block1 = nn.ModuleList([Block(
dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
sr_ratio=sr_ratios[0])
for i in range(depths[0])])
self.norm1 = norm_layer(embed_dims[0])
# Stage-2 (x1/8 scale)
cur += depths[0]
self.block2 = nn.ModuleList([Block(
dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
sr_ratio=sr_ratios[1])
for i in range(depths[1])])
self.norm2 = norm_layer(embed_dims[1])
# Stage-3 (x1/16 scale)
cur += depths[1]
self.block3 = nn.ModuleList([Block(
dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
sr_ratio=sr_ratios[2])
for i in range(depths[2])])
self.norm3 = norm_layer(embed_dims[2])
# Stage-4 (x1/32 scale)
cur += depths[2]
self.block4 = nn.ModuleList([Block(
dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
sr_ratio=sr_ratios[3])
for i in range(depths[3])])
self.norm4 = norm_layer(embed_dims[3])
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 reset_drop_path(self, drop_path_rate):
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
cur = 0
for i in range(self.depths[0]):
self.block1[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[0]
for i in range(self.depths[1]):
self.block2[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[1]
for i in range(self.depths[2]):
self.block3[i].drop_path.drop_prob = dpr[cur + i]
cur += self.depths[2]
for i in range(self.depths[3]):
self.block4[i].drop_path.drop_prob = dpr[cur + i]
def forward_features(self, x):
B = x.shape[0]
outs = []
# stage 1
x1, H1, W1 = self.patch_embed1(x)
for i, blk in enumerate(self.block1):
x1 = blk(x1, H1, W1)
x1 = self.norm1(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
# stage 2
x1, H1, W1 = self.patch_embed2(x1)
for i, blk in enumerate(self.block2):
x1 = blk(x1, H1, W1)
x1 = self.norm2(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
# stage 3
x1, H1, W1 = self.patch_embed3(x1)
for i, blk in enumerate(self.block3):
x1 = blk(x1, H1, W1)
x1 = self.norm3(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
# stage 4
x1, H1, W1 = self.patch_embed4(x1)
for i, blk in enumerate(self.block4):
x1 = blk(x1, H1, W1)
x1 = self.norm4(x1)
x1 = x1.reshape(B, H1, W1, -1).permute(0, 3, 1, 2).contiguous()
outs.append(x1)
return outs
def forward(self, x):
x = self.forward_features(x)
return x
class DecoderTransformer_v3(nn.Module):
"""
Transformer Decoder
"""
def __init__(self, input_transform='multiple_select', in_index=[0, 1, 2, 3], align_corners=True,
in_channels=[32, 64, 128, 256], embedding_dim=64, output_nc=2,
decoder_softmax=False, feature_strides=[2, 4, 8, 16]):
super(DecoderTransformer_v3, self).__init__()
# assert
assert len(feature_strides) == len(in_channels)
assert min(feature_strides) == feature_strides[0]
# settings
self.feature_strides = feature_strides
self.input_transform = input_transform
self.in_index = in_index
self.align_corners = align_corners
self.in_channels = in_channels
self.embedding_dim = embedding_dim
self.output_nc = output_nc
c1_in_channels, c2_in_channels, c3_in_channels, c4_in_channels = self.in_channels
# MLP decoder heads
self.linear_c4 = MLP(input_dim=c4_in_channels, embed_dim=self.embedding_dim)
self.linear_c3 = MLP(input_dim=c3_in_channels, embed_dim=self.embedding_dim)
self.linear_c2 = MLP(input_dim=c2_in_channels, embed_dim=self.embedding_dim)
self.linear_c1 = MLP(input_dim=c1_in_channels, embed_dim=self.embedding_dim)
# convolutional Difference Modules
self.diff_c4 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
self.diff_c3 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
self.diff_c2 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
self.diff_c1 = conv_diff(in_channels=2 * self.embedding_dim, out_channels=self.embedding_dim)
# taking outputs from middle of the encoder
self.make_pred_c4 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
self.make_pred_c3 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
self.make_pred_c2 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
self.make_pred_c1 = make_prediction(in_channels=self.embedding_dim, out_channels=self.output_nc)
# Final linear fusion layer
self.linear_fuse = nn.Sequential(
nn.Conv2d(in_channels=self.embedding_dim * len(in_channels), out_channels=self.embedding_dim,
kernel_size=1),
nn.BatchNorm2d(self.embedding_dim)
)
# Final predction head | self.convd2x = UpsampleConvLayer(self.embedding_dim, self.embedding_dim, kernel_size=4, stride=2) | 0 | 2023-10-21 09:09:57+00:00 | 8k |
pythonlessons/FinRock | experiments/training_ppo_sinusoid.py | [
{
"identifier": "PdDataFeeder",
"path": "finrock/data_feeder.py",
"snippet": "class PdDataFeeder:\n def __init__(\n self, \n df: pd.DataFrame,\n indicators: list = [],\n min: float = None,\n max: float = None\n ) -> None:\n self... | import numpy as np
import pandas as pd
import tensorflow as tf
from keras import layers, models
from finrock.data_feeder import PdDataFeeder
from finrock.trading_env import TradingEnv
from finrock.scalers import MinMaxScaler
from finrock.reward import simpleReward
from finrock.metrics import DifferentActions, AccountValue, MaxDrawdown, SharpeRatio
from finrock.indicators import BolingerBands, RSI, PSAR, SMA
from rockrl.utils.misc import MeanAverage
from rockrl.utils.memory import Memory
from rockrl.tensorflow import PPOAgent | 6,517 | tf.get_logger().setLevel('ERROR')
for gpu in tf.config.experimental.list_physical_devices('GPU'):
tf.config.experimental.set_memory_growth(gpu, True)
df = pd.read_csv('Datasets/random_sinusoid.csv')
df = df[:-1000] # leave 1000 for testing
pd_data_feeder = PdDataFeeder(
df,
indicators = [
BolingerBands(data=df, period=20, std=2),
RSI(data=df, period=14),
| tf.get_logger().setLevel('ERROR')
for gpu in tf.config.experimental.list_physical_devices('GPU'):
tf.config.experimental.set_memory_growth(gpu, True)
df = pd.read_csv('Datasets/random_sinusoid.csv')
df = df[:-1000] # leave 1000 for testing
pd_data_feeder = PdDataFeeder(
df,
indicators = [
BolingerBands(data=df, period=20, std=2),
RSI(data=df, period=14), | PSAR(data=df), | 10 | 2023-10-23 07:44:54+00:00 | 8k |
hitlic/deepepochs | deepepochs/callbacks/interprete.py | [
{
"identifier": "Callback",
"path": "deepepochs/callbacks/callback.py",
"snippet": "class Callback:\n \"\"\"\n 所有Callback的基类。\n\n 方法执行流程:\n on_before_fit\n on_before_epoch\n on_before_train_epochs # 多个训练任务\n on_before_train_epoch\n ... | from torch.utils.tensorboard import SummaryWriter
from os import path as osp
from matplotlib import pyplot as plt
from .callback import Callback
from .log import run_tensorboard
from ..tools import plot_confusion, TopKQueue
from ..metrics import confusion_matrix, get_class_num
from ..loops import check_path | 4,198 |
class InterpreteCallback(Callback):
def __init__(self, metric=None, k=100, mode='max', stages=('train', 'val', 'test'), class_num=None, log_dir='./logs', image_data=False):
"""
Args:
metric: none reducted callable
k: number of samples to keep
mode: 'max' or 'min'
stages: 'train' 'val' or 'test'
class_num: 类别数量
log_dir: 日志存储路径
image_data: 数据是否是图片(如果是则在tensorboard中保存图片)
"""
super().__init__()
assert mode in ['min', 'max']
stages = stages if isinstance(stages, (list, tuple)) else [stages]
assert all(s in ['train', 'val', 'test'] for s in stages ), 'stages的值为 train、val、test或者其组合'
self.metric = metric
self.stages = stages
self.mode = mode
self.batch_recorder = []
self.top_queue = TopKQueue(k=k)
self.confusion_matrix = None
self.class_num = class_num
self.log_dir = log_dir
self.image_data = image_data
def on_before_fit(self, trainer, epochs):
log_dir = osp.join(self.log_dir, trainer.running_id)
check_path(log_dir)
logger = getattr(trainer, 'logger', None)
if logger is None:
self.logger = SummaryWriter(log_dir=log_dir)
trainer.logger = self.logger
else:
self.logger = logger
def on_before_train_epochs(self, trainer, tasks, epoch_idx):
self.confusion_matrix=None
def on_before_val_epochs(self, trainer, tasks, epoch_idx):
self.confusion_matrix=None
def on_before_test_epochs(self, trainer, tasks):
self.confusion_matrix=None
def on_before_train_batch(self, trainer, batch_x, batch_y, batch_idx):
if self.class_num is None:
|
class InterpreteCallback(Callback):
def __init__(self, metric=None, k=100, mode='max', stages=('train', 'val', 'test'), class_num=None, log_dir='./logs', image_data=False):
"""
Args:
metric: none reducted callable
k: number of samples to keep
mode: 'max' or 'min'
stages: 'train' 'val' or 'test'
class_num: 类别数量
log_dir: 日志存储路径
image_data: 数据是否是图片(如果是则在tensorboard中保存图片)
"""
super().__init__()
assert mode in ['min', 'max']
stages = stages if isinstance(stages, (list, tuple)) else [stages]
assert all(s in ['train', 'val', 'test'] for s in stages ), 'stages的值为 train、val、test或者其组合'
self.metric = metric
self.stages = stages
self.mode = mode
self.batch_recorder = []
self.top_queue = TopKQueue(k=k)
self.confusion_matrix = None
self.class_num = class_num
self.log_dir = log_dir
self.image_data = image_data
def on_before_fit(self, trainer, epochs):
log_dir = osp.join(self.log_dir, trainer.running_id)
check_path(log_dir)
logger = getattr(trainer, 'logger', None)
if logger is None:
self.logger = SummaryWriter(log_dir=log_dir)
trainer.logger = self.logger
else:
self.logger = logger
def on_before_train_epochs(self, trainer, tasks, epoch_idx):
self.confusion_matrix=None
def on_before_val_epochs(self, trainer, tasks, epoch_idx):
self.confusion_matrix=None
def on_before_test_epochs(self, trainer, tasks):
self.confusion_matrix=None
def on_before_train_batch(self, trainer, batch_x, batch_y, batch_idx):
if self.class_num is None: | self.class_num = get_class_num(batch_x, batch_y) | 5 | 2023-10-19 05:41:48+00:00 | 8k |
Beautifuldog01/AcademicDocumentClassifier_without_AllenNLP | main_meta_CNN.py | [
{
"identifier": "TextClassifier",
"path": "model.py",
"snippet": "class TextClassifier(nn.Module):\n def __init__(self, vocab_size, embedding_dim):\n super(TextClassifier, self).__init__()\n self.embedding = nn.Embedding(vocab_size, embedding_dim * 6)\n self.title_cnn_3 = nn.Conv... | import os
import datetime
import argparse
import torch
import numpy as np
import torch.optim as optim
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from torch.nn import BCEWithLogitsLoss
from model import TextClassifier, NonNegativePULoss
from dataset_pubmed import (
make_PU_meta,
BiDataset,
BalancedBatchSampler,
ProportionalSampler,
)
from utils import (
set_seed,
build_vocab,
getFeatures,
get_metric,
log_metrics,
print_info,
) | 4,784 |
parser = argparse.ArgumentParser(description="Run Text Classification Experiments")
parser.add_argument(
"--batch_size", type=int, default=128, help="Batch size for training"
)
parser.add_argument(
"--num_epochs", type=int, default=50, help="Number of training epochs"
)
parser.add_argument(
"--lr", type=float, default=0.001, help="Learning rate for the optimizer"
)
parser.add_argument(
"--prior",
type=float,
default=0.5,
help="Prior probability for Non-Negative PU Loss",
)
parser.add_argument(
"--max_length", type=int, default=800, help="Maximum length of the input sequence"
)
parser.add_argument(
"--embedding_dim",
type=int,
default=50,
help="Embedding dimension for text classifier",
)
parser.add_argument(
"--models_dir", type=str, default="models", help="Directory to save the models"
)
parser.add_argument(
"--seed", type=int, default=42, help="Random seed for reproducibility"
)
args = parser.parse_args()
batch_size = args.batch_size
num_epochs = args.num_epochs
learning_rate = args.lr
prior = args.prior
embedding_dim = args.embedding_dim
models_dir = args.models_dir
set_seed(args.seed)
experiments = [
"data/pubmed-dse/L50/D000328.D008875.D015658",
"data/pubmed-dse/L50/D000818.D001921.D051381",
"data/pubmed-dse/L50/D006435.D007676.D008875",
"data/pubmed-dse/L20/D000328.D008875.D015658",
"data/pubmed-dse/L20/D000818.D001921.D051381",
"data/pubmed-dse/L20/D006435.D007676.D008875",
]
root_dir = experiments[1]
tr_file_path = os.path.join(root_dir, "train.jsonl")
va_file_path = os.path.join(root_dir, "valid.jsonl")
ts_file_path = os.path.join(root_dir, "test.jsonl")
all_df = make_PU_meta(tr_file_path, va_file_path, ts_file_path)
train_index = all_df.query("tr == 1").index
train_labels = all_df.query("tr == 1")["pulabel"].values
val_index = all_df.query("ca == 1").index
val_labels = all_df.query("ca == 1")["label"].values
test_index = all_df.query("ts == 1").index
test_labels = all_df.query("ts == 1")["label"].values
all_df["combined_text"] = all_df["title"] + " " + all_df["abstract"]
all_texts = all_df["combined_text"].tolist()
vocab = build_vocab(all_texts)
word_to_index = {word: index for index, word in enumerate(vocab)}
max_length = args.max_length
all_features = getFeatures(all_df, word_to_index, max_length=max_length)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TextClassifier(len(vocab), embedding_dim).to(device)
loss_fct = NonNegativePULoss(prior=prior)
# loss_fct = BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
best_va_f1 = 0
best_ts_f1 = 0
writer = SummaryWriter("runs/nnPU_CNN")
|
parser = argparse.ArgumentParser(description="Run Text Classification Experiments")
parser.add_argument(
"--batch_size", type=int, default=128, help="Batch size for training"
)
parser.add_argument(
"--num_epochs", type=int, default=50, help="Number of training epochs"
)
parser.add_argument(
"--lr", type=float, default=0.001, help="Learning rate for the optimizer"
)
parser.add_argument(
"--prior",
type=float,
default=0.5,
help="Prior probability for Non-Negative PU Loss",
)
parser.add_argument(
"--max_length", type=int, default=800, help="Maximum length of the input sequence"
)
parser.add_argument(
"--embedding_dim",
type=int,
default=50,
help="Embedding dimension for text classifier",
)
parser.add_argument(
"--models_dir", type=str, default="models", help="Directory to save the models"
)
parser.add_argument(
"--seed", type=int, default=42, help="Random seed for reproducibility"
)
args = parser.parse_args()
batch_size = args.batch_size
num_epochs = args.num_epochs
learning_rate = args.lr
prior = args.prior
embedding_dim = args.embedding_dim
models_dir = args.models_dir
set_seed(args.seed)
experiments = [
"data/pubmed-dse/L50/D000328.D008875.D015658",
"data/pubmed-dse/L50/D000818.D001921.D051381",
"data/pubmed-dse/L50/D006435.D007676.D008875",
"data/pubmed-dse/L20/D000328.D008875.D015658",
"data/pubmed-dse/L20/D000818.D001921.D051381",
"data/pubmed-dse/L20/D006435.D007676.D008875",
]
root_dir = experiments[1]
tr_file_path = os.path.join(root_dir, "train.jsonl")
va_file_path = os.path.join(root_dir, "valid.jsonl")
ts_file_path = os.path.join(root_dir, "test.jsonl")
all_df = make_PU_meta(tr_file_path, va_file_path, ts_file_path)
train_index = all_df.query("tr == 1").index
train_labels = all_df.query("tr == 1")["pulabel"].values
val_index = all_df.query("ca == 1").index
val_labels = all_df.query("ca == 1")["label"].values
test_index = all_df.query("ts == 1").index
test_labels = all_df.query("ts == 1")["label"].values
all_df["combined_text"] = all_df["title"] + " " + all_df["abstract"]
all_texts = all_df["combined_text"].tolist()
vocab = build_vocab(all_texts)
word_to_index = {word: index for index, word in enumerate(vocab)}
max_length = args.max_length
all_features = getFeatures(all_df, word_to_index, max_length=max_length)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TextClassifier(len(vocab), embedding_dim).to(device)
loss_fct = NonNegativePULoss(prior=prior)
# loss_fct = BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
best_va_f1 = 0
best_ts_f1 = 0
writer = SummaryWriter("runs/nnPU_CNN") | train_data = BiDataset( | 3 | 2023-10-18 06:15:13+00:00 | 8k |
colour-science/colour-visuals | colour_visuals/diagrams.py | [
{
"identifier": "DEFAULT_FLOAT_DTYPE_WGPU",
"path": "colour_visuals/common.py",
"snippet": "DEFAULT_FLOAT_DTYPE_WGPU = np.float32"
},
{
"identifier": "DEFAULT_INT_DTYPE_WGPU",
"path": "colour_visuals/common.py",
"snippet": "DEFAULT_INT_DTYPE_WGPU = np.uint32"
},
{
"identifier": "... | import numpy as np
import pygfx as gfx
from colour.algebra import euclidean_distance, normalise_maximum
from colour.colorimetry import MultiSpectralDistributions
from colour.hints import (
ArrayLike,
Literal,
LiteralColourspaceModel,
Sequence,
Type,
cast,
)
from colour.models import XYZ_to_RGB
from colour.plotting import (
CONSTANTS_COLOUR_STYLE,
LABELS_CHROMATICITY_DIAGRAM_DEFAULT,
METHODS_CHROMATICITY_DIAGRAM,
XYZ_to_plotting_colourspace,
colourspace_model_axis_reorder,
)
from colour.plotting.diagrams import lines_spectral_locus
from colour.utilities import (
full,
optional,
tstack,
)
from scipy.spatial import Delaunay
from colour_visuals.common import (
DEFAULT_FLOAT_DTYPE_WGPU,
DEFAULT_INT_DTYPE_WGPU,
XYZ_to_colourspace_model,
append_channel,
as_contiguous_array,
)
from colour_visuals.visual import (
MixinPropertyCMFS,
MixinPropertyColour,
MixinPropertyKwargs,
MixinPropertyMethod,
MixinPropertyModel,
MixinPropertyOpacity,
MixinPropertySamples,
MixinPropertyThickness,
MixinPropertyTypeMaterial,
MixinPropertyWireframe,
Visual,
visual_property,
) | 5,938 |
Attributes
----------
- :attr:`~colour_visuals.VisualSpectralLocus3D.cmfs`
- :attr:`~colour_visuals.VisualSpectralLocus3D.model`
- :attr:`~colour_visuals.VisualSpectralLocus3D.labels`
- :attr:`~colour_visuals.VisualSpectralLocus3D.colour`
- :attr:`~colour_visuals.VisualSpectralLocus3D.opacity`
- :attr:`~colour_visuals.VisualSpectralLocus3D.thickness`
Methods
-------
- :meth:`~colour_visuals.VisualSpectralLocus3D.__init__`
- :meth:`~colour_visuals.VisualSpectralLocus3D.update`
Examples
--------
>>> import os
>>> from colour.utilities import suppress_stdout
>>> from wgpu.gui.auto import WgpuCanvas
>>> with suppress_stdout():
... canvas = WgpuCanvas(size=(960, 540))
... scene = gfx.Scene()
... scene.add(
... gfx.Background(
... None, gfx.BackgroundMaterial(np.array([0.18, 0.18, 0.18]))
... )
... )
... visual = VisualSpectralLocus3D(model="CIE XYZ")
... camera = gfx.PerspectiveCamera(50, 16 / 9)
... camera.show_object(visual, up=np.array([0, 0, 1]), scale=1.25)
... scene.add(visual)
... if os.environ.get("CI") is None:
... gfx.show(scene, camera=camera, canvas=canvas)
...
.. image:: ../_static/Plotting_VisualSpectralLocus3D.png
:align: center
:alt: visual-spectral-locus-3d
"""
def __init__(
self,
cmfs: MultiSpectralDistributions
| str
| Sequence[
MultiSpectralDistributions | str
] = "CIE 1931 2 Degree Standard Observer",
model: LiteralColourspaceModel | str = "CIE xyY",
colour: ArrayLike | None = None,
opacity: float = 1,
thickness: float = 1,
**kwargs,
):
super().__init__()
self._spectral_locus = None
with self.block_update():
self.cmfs = cmfs
self.model = model
self.colour = colour
self.opacity = opacity
self.thickness = thickness
self.kwargs = kwargs
self.update()
def update(self):
"""Update the visual."""
if self._is_update_blocked:
return
self.clear()
colourspace = CONSTANTS_COLOUR_STYLE.colour.colourspace
positions = colourspace_model_axis_reorder(
XYZ_to_colourspace_model(
self._cmfs.values,
colourspace.whitepoint,
self._model,
**self._kwargs,
),
self._model,
)
positions = np.concatenate(
[positions[:-1], positions[1:]], axis=1
).reshape([-1, 3])
if self._colour is None:
colour = XYZ_to_RGB(self._cmfs.values, colourspace)
colour = np.concatenate([colour[:-1], colour[1:]], axis=1).reshape(
[-1, 3]
)
else:
colour = np.tile(self._colour, (positions.shape[0], 1))
self._spectral_locus = gfx.Line(
gfx.Geometry(
positions=as_contiguous_array(positions),
colors=as_contiguous_array(
append_channel(colour, self._opacity)
),
),
gfx.LineSegmentMaterial(
thickness=self._thickness, color_mode="vertex"
),
)
self.add(self._spectral_locus)
class VisualChromaticityDiagram(
MixinPropertyCMFS,
MixinPropertyColour,
MixinPropertyTypeMaterial,
MixinPropertyMethod,
MixinPropertyOpacity,
MixinPropertySamples,
| # !/usr/bin/env python
"""
Chromaticity Diagram Visuals
============================
Defines the *Chromaticity Diagram* visuals:
- :class:`colour_visuals.VisualSpectralLocus2D`
- :class:`colour_visuals.VisualSpectralLocus3D`
- :class:`colour_visuals.VisualChromaticityDiagram`
- :class:`colour_visuals.VisualChromaticityDiagramCIE1931`
- :class:`colour_visuals.VisualChromaticityDiagramCIE1960UCS`
- :class:`colour_visuals.VisualChromaticityDiagramCIE1976UCS`
"""
from __future__ import annotations
__author__ = "Colour Developers"
__copyright__ = "Copyright 2023 Colour Developers"
__license__ = "BSD-3-Clause - https://opensource.org/licenses/BSD-3-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = [
"VisualSpectralLocus2D",
"VisualSpectralLocus3D",
"VisualChromaticityDiagram",
"MixinPropertyKwargsVisualSpectralLocus",
"MixinPropertyKwargsVisualChromaticityDiagram",
"VisualChromaticityDiagramCIE1931",
"VisualChromaticityDiagramCIE1960UCS",
"VisualChromaticityDiagramCIE1976UCS",
]
class VisualSpectralLocus2D(
MixinPropertyCMFS,
MixinPropertyColour,
MixinPropertyMethod,
MixinPropertyOpacity,
MixinPropertyThickness,
Visual,
):
"""
Create a 2D *Spectral Locus* visual.
Parameters
----------
cmfs
Standard observer colour matching functions used for computing the
spectrum domain and colours. ``cmfs`` can be of any type or form
supported by the :func:`colour.plotting.common.filter_cmfs` definition.
method
*Chromaticity Diagram* method.
labels
Array of wavelength labels used to customise which labels will be drawn
around the spectral locus. Passing an empty array will result in no
wavelength labels being drawn.
colour
Colour of the visual, if *None*, the colour is computed from the visual
geometry.
opacity
Opacity of the visual.
thickness
Thickness of the visual lines.
Attributes
----------
- :attr:`~colour_visuals.VisualSpectralLocus2D.cmfs`
- :attr:`~colour_visuals.VisualSpectralLocus2D.method`
- :attr:`~colour_visuals.VisualSpectralLocus2D.labels`
- :attr:`~colour_visuals.VisualSpectralLocus2D.colour`
- :attr:`~colour_visuals.VisualSpectralLocus2D.opacity`
- :attr:`~colour_visuals.VisualSpectralLocus2D.thickness`
Methods
-------
- :meth:`~colour_visuals.VisualSpectralLocus2D.__init__`
- :meth:`~colour_visuals.VisualSpectralLocus2D.update`
Examples
--------
>>> import os
>>> from colour.utilities import suppress_stdout
>>> from wgpu.gui.auto import WgpuCanvas
>>> with suppress_stdout():
... canvas = WgpuCanvas(size=(960, 540))
... scene = gfx.Scene()
... scene.add(
... gfx.Background(
... None, gfx.BackgroundMaterial(np.array([0.18, 0.18, 0.18]))
... )
... )
... visual = VisualSpectralLocus2D()
... camera = gfx.PerspectiveCamera(50, 16 / 9)
... camera.show_object(visual, up=np.array([0, 0, 1]), scale=1.25)
... scene.add(visual)
... if os.environ.get("CI") is None:
... gfx.show(scene, camera=camera, canvas=canvas)
...
.. image:: ../_static/Plotting_VisualSpectralLocus2D.png
:align: center
:alt: visual-spectral-locus-2d
"""
def __init__(
self,
cmfs: MultiSpectralDistributions
| str
| Sequence[
MultiSpectralDistributions | str
] = "CIE 1931 2 Degree Standard Observer",
method: Literal["CIE 1931", "CIE 1960 UCS", "CIE 1976 UCS"]
| str = "CIE 1931",
labels: Sequence | None = None,
colour: ArrayLike | None = None,
opacity: float = 1,
thickness: float = 1,
):
super().__init__()
self._spectral_locus = None
self._wavelengths = None
self._texts = None
self._points = None
self._labels = None
with self.block_update():
self.cmfs = cmfs
self.method = method
self.labels = labels
self.colour = colour
self.opacity = opacity
self.thickness = thickness
self.update()
@visual_property
def labels(
self,
) -> Sequence | None:
"""
Getter and setter property for the labels.
Parameters
----------
value
Value to set the labels with.
Returns
-------
:class:`str`
Labels.
"""
return self._labels
@labels.setter
def labels(self, value: Sequence | None):
"""Setter for the **self.labels** property."""
self._labels = cast(
Sequence,
optional(value, LABELS_CHROMATICITY_DIAGRAM_DEFAULT[self._method]),
)
def update(self):
"""Update the visual."""
if self._is_update_blocked:
return
self.clear()
lines_sl, lines_w = lines_spectral_locus(
self._cmfs, self._labels, self._method
)
# Spectral Locus
positions = np.concatenate(
[lines_sl["position"][:-1], lines_sl["position"][1:]], axis=1
).reshape([-1, 2])
positions = np.hstack(
[
positions,
np.full((positions.shape[0], 1), 0, DEFAULT_FLOAT_DTYPE_WGPU),
]
)
if self._colour is None:
colour_sl = np.concatenate(
[lines_sl["colour"][:-1], lines_sl["colour"][1:]], axis=1
).reshape([-1, 3])
else:
colour_sl = np.tile(self._colour, (positions.shape[0], 1))
self._spectral_locus = gfx.Line(
gfx.Geometry(
positions=as_contiguous_array(positions),
colors=as_contiguous_array(
append_channel(colour_sl, self._opacity)
),
),
gfx.LineSegmentMaterial(
thickness=self._thickness, color_mode="vertex"
),
)
self.add(self._spectral_locus)
if not self._labels:
return
# Wavelengths
positions = lines_w["position"]
positions = np.hstack(
[
positions,
np.full((positions.shape[0], 1), 0, DEFAULT_FLOAT_DTYPE_WGPU),
]
)
if self._colour is None:
colour_w = lines_w["colour"]
else:
colour_w = np.tile(self._colour, (positions.shape[0], 1))
self._wavelengths = gfx.Line(
gfx.Geometry(
positions=as_contiguous_array(positions),
colors=as_contiguous_array(
append_channel(colour_w, self._opacity)
),
),
gfx.LineSegmentMaterial(
thickness=self._thickness, color_mode="vertex"
),
)
self.add(self._wavelengths)
# Labels
self._texts = []
for i, label in enumerate(
[
label
for label in self._labels
if label in self._cmfs.wavelengths
]
):
positions = lines_w["position"][::2]
normals = lines_w["normal"][::2]
text = gfx.Text(
gfx.TextGeometry(
str(label),
font_size=CONSTANTS_COLOUR_STYLE.font.size,
screen_space=True,
anchor="Center-Left"
if lines_w["normal"][::2][i, 0] >= 0
else "Center-Right",
),
gfx.TextMaterial(color=CONSTANTS_COLOUR_STYLE.colour.light),
)
text.local.position = np.array(
[
positions[i, 0] + normals[i, 0] / 50 * 1.25,
positions[i, 1] + normals[i, 1] / 50 * 1.25,
0,
]
)
self._texts.append(text)
self.add(text)
positions = np.hstack(
[
lines_w["position"][::2],
np.full(
(lines_w["position"][::2].shape[0], 1),
0,
DEFAULT_FLOAT_DTYPE_WGPU,
),
]
)
if self._colour is None:
colour_lp = lines_w["colour"][::2]
else:
colour_lp = np.tile(self._colour, (positions.shape[0], 1))
self._points = gfx.Points(
gfx.Geometry(
positions=as_contiguous_array(positions),
sizes=as_contiguous_array(
full(
lines_w["position"][::2].shape[0], self._thickness * 3
)
),
colors=as_contiguous_array(
append_channel(colour_lp, self._opacity)
),
),
gfx.PointsMaterial(color_mode="vertex", vertex_sizes=True),
)
self.add(self._points)
class VisualSpectralLocus3D(
MixinPropertyCMFS,
MixinPropertyColour,
MixinPropertyKwargs,
MixinPropertyModel,
MixinPropertyOpacity,
MixinPropertyThickness,
Visual,
):
"""
Create a 3D *Spectral Locus* visual.
Parameters
----------
cmfs
Standard observer colour matching functions used for computing the
spectrum domain and colours. ``cmfs`` can be of any type or form
supported by the :func:`colour.plotting.common.filter_cmfs` definition.
model
Colourspace model, see :attr:`colour.COLOURSPACE_MODELS` attribute for
the list of supported colourspace models.
labels
Array of wavelength labels used to customise which labels will be drawn
around the spectral locus. Passing an empty array will result in no
wavelength labels being drawn.
colour
Colour of the visual, if *None*, the colour is computed from the visual
geometry.
opacity
Opacity of the visual.
thickness
Thickness of the visual lines.
Other Parameters
----------------
kwargs
See the documentation of the supported conversion definitions.
Attributes
----------
- :attr:`~colour_visuals.VisualSpectralLocus3D.cmfs`
- :attr:`~colour_visuals.VisualSpectralLocus3D.model`
- :attr:`~colour_visuals.VisualSpectralLocus3D.labels`
- :attr:`~colour_visuals.VisualSpectralLocus3D.colour`
- :attr:`~colour_visuals.VisualSpectralLocus3D.opacity`
- :attr:`~colour_visuals.VisualSpectralLocus3D.thickness`
Methods
-------
- :meth:`~colour_visuals.VisualSpectralLocus3D.__init__`
- :meth:`~colour_visuals.VisualSpectralLocus3D.update`
Examples
--------
>>> import os
>>> from colour.utilities import suppress_stdout
>>> from wgpu.gui.auto import WgpuCanvas
>>> with suppress_stdout():
... canvas = WgpuCanvas(size=(960, 540))
... scene = gfx.Scene()
... scene.add(
... gfx.Background(
... None, gfx.BackgroundMaterial(np.array([0.18, 0.18, 0.18]))
... )
... )
... visual = VisualSpectralLocus3D(model="CIE XYZ")
... camera = gfx.PerspectiveCamera(50, 16 / 9)
... camera.show_object(visual, up=np.array([0, 0, 1]), scale=1.25)
... scene.add(visual)
... if os.environ.get("CI") is None:
... gfx.show(scene, camera=camera, canvas=canvas)
...
.. image:: ../_static/Plotting_VisualSpectralLocus3D.png
:align: center
:alt: visual-spectral-locus-3d
"""
def __init__(
self,
cmfs: MultiSpectralDistributions
| str
| Sequence[
MultiSpectralDistributions | str
] = "CIE 1931 2 Degree Standard Observer",
model: LiteralColourspaceModel | str = "CIE xyY",
colour: ArrayLike | None = None,
opacity: float = 1,
thickness: float = 1,
**kwargs,
):
super().__init__()
self._spectral_locus = None
with self.block_update():
self.cmfs = cmfs
self.model = model
self.colour = colour
self.opacity = opacity
self.thickness = thickness
self.kwargs = kwargs
self.update()
def update(self):
"""Update the visual."""
if self._is_update_blocked:
return
self.clear()
colourspace = CONSTANTS_COLOUR_STYLE.colour.colourspace
positions = colourspace_model_axis_reorder(
XYZ_to_colourspace_model(
self._cmfs.values,
colourspace.whitepoint,
self._model,
**self._kwargs,
),
self._model,
)
positions = np.concatenate(
[positions[:-1], positions[1:]], axis=1
).reshape([-1, 3])
if self._colour is None:
colour = XYZ_to_RGB(self._cmfs.values, colourspace)
colour = np.concatenate([colour[:-1], colour[1:]], axis=1).reshape(
[-1, 3]
)
else:
colour = np.tile(self._colour, (positions.shape[0], 1))
self._spectral_locus = gfx.Line(
gfx.Geometry(
positions=as_contiguous_array(positions),
colors=as_contiguous_array(
append_channel(colour, self._opacity)
),
),
gfx.LineSegmentMaterial(
thickness=self._thickness, color_mode="vertex"
),
)
self.add(self._spectral_locus)
class VisualChromaticityDiagram(
MixinPropertyCMFS,
MixinPropertyColour,
MixinPropertyTypeMaterial,
MixinPropertyMethod,
MixinPropertyOpacity,
MixinPropertySamples, | MixinPropertyWireframe, | 14 | 2023-10-15 04:30:47+00:00 | 8k |
JiahuiLei/NAP | eval/save_viz_utils.py | [
{
"identifier": "get_G_from_VE",
"path": "object_utils/arti_graph_utils_v3.py",
"snippet": "def get_G_from_VE(V, E):\n # v: [mask_occ(1), bbox(3), r_gl(3), t_gl(3) | additional codes in the future]\n # e: [type(3), plucker(6), rlim(2), plim(2)]\n # ! warning, here occ v mask must after sigmoid;... | import sys, os, os.path as osp
import yaml, logging, imageio, torch, os
import os.path as osp
import numpy as np
import networkx as nx
import trimesh
import pickle
from matplotlib.axes._axes import _log as matplotlib_axes_logger
from tqdm import tqdm
from sklearn.neighbors import NearestNeighbors
from copy import deepcopy
from object_utils.arti_graph_utils_v3 import get_G_from_VE
from object_utils.arti_viz_utils import append_mesh_to_G, viz_G_topology, viz_G
from multiprocessing import Pool | 3,918 | # helpers for Save the generated V, E
sys.path.append(osp.dirname(os.getcwd()))
matplotlib_axes_logger.setLevel("ERROR")
device = torch.device("cuda:0")
# import multiprocessing
def extract_recon_mesh_for_nodes(G, extract_fn):
for v, v_data in G.nodes(data=True):
if "additional" not in v_data:
continue
z = v_data["additional"][None, :]
mesh = extract_fn(torch.from_numpy(z).cuda())
mesh_centroid = mesh.bounds.mean(0)
mesh.apply_translation(-mesh_centroid)
bbox = v_data["bbox"].copy()
scale = 2.0 * np.linalg.norm(bbox) / np.linalg.norm(mesh.bounds[1] - mesh.bounds[0])
mesh.apply_scale(scale)
nx.set_node_attributes(G, {v: {"mesh": mesh}})
return G
def find_nn_database_mesh_and_update_G(G, database, mesh_names, mesh_dir):
for v, v_data in G.nodes(data=True):
if "additional" not in v_data:
continue
z = v_data["additional"][None, :]
# find nn
_d, _ind = database.kneighbors(z, return_distance=True)
# print(_ind)
_ind = int(_ind.squeeze(0))
fn = osp.join(mesh_dir, mesh_names[int(_ind)] + ".off")
gt_mesh = trimesh.load(fn, force="mesh", process=False) # ! debug
mesh_centroid = gt_mesh.bounds.mean(0)
gt_mesh.apply_translation(-mesh_centroid)
bbox = v_data["bbox"].copy()
scale = 2.0 * np.linalg.norm(bbox) / np.linalg.norm(gt_mesh.bounds[1] - gt_mesh.bounds[0])
gt_mesh.apply_scale(scale)
nx.set_node_attributes(G, {v: {"mesh": gt_mesh}})
return G
def _save_viz_thread(p):
G, save_dir, name = p
# print(p)
viz_dir = save_dir + "_viz"
os.makedirs(viz_dir, exist_ok=True)
os.makedirs(save_dir, exist_ok=True)
# viz_topo = viz_G_topology(G)
# imageio.imwrite(osp.join(viz_dir, f"{name}.png"), viz_topo)
# print("start rendering...")
| # helpers for Save the generated V, E
sys.path.append(osp.dirname(os.getcwd()))
matplotlib_axes_logger.setLevel("ERROR")
device = torch.device("cuda:0")
# import multiprocessing
def extract_recon_mesh_for_nodes(G, extract_fn):
for v, v_data in G.nodes(data=True):
if "additional" not in v_data:
continue
z = v_data["additional"][None, :]
mesh = extract_fn(torch.from_numpy(z).cuda())
mesh_centroid = mesh.bounds.mean(0)
mesh.apply_translation(-mesh_centroid)
bbox = v_data["bbox"].copy()
scale = 2.0 * np.linalg.norm(bbox) / np.linalg.norm(mesh.bounds[1] - mesh.bounds[0])
mesh.apply_scale(scale)
nx.set_node_attributes(G, {v: {"mesh": mesh}})
return G
def find_nn_database_mesh_and_update_G(G, database, mesh_names, mesh_dir):
for v, v_data in G.nodes(data=True):
if "additional" not in v_data:
continue
z = v_data["additional"][None, :]
# find nn
_d, _ind = database.kneighbors(z, return_distance=True)
# print(_ind)
_ind = int(_ind.squeeze(0))
fn = osp.join(mesh_dir, mesh_names[int(_ind)] + ".off")
gt_mesh = trimesh.load(fn, force="mesh", process=False) # ! debug
mesh_centroid = gt_mesh.bounds.mean(0)
gt_mesh.apply_translation(-mesh_centroid)
bbox = v_data["bbox"].copy()
scale = 2.0 * np.linalg.norm(bbox) / np.linalg.norm(gt_mesh.bounds[1] - gt_mesh.bounds[0])
gt_mesh.apply_scale(scale)
nx.set_node_attributes(G, {v: {"mesh": gt_mesh}})
return G
def _save_viz_thread(p):
G, save_dir, name = p
# print(p)
viz_dir = save_dir + "_viz"
os.makedirs(viz_dir, exist_ok=True)
os.makedirs(save_dir, exist_ok=True)
# viz_topo = viz_G_topology(G)
# imageio.imwrite(osp.join(viz_dir, f"{name}.png"), viz_topo)
# print("start rendering...") | viz_list = viz_G(G, cam_dist=3.0, viz_frame_N=5, shape=(128, 128)) | 3 | 2023-10-22 03:46:35+00:00 | 8k |
yongliang-wu/ExploreCfg | open_flamingo/src/factory.py | [
{
"identifier": "Flamingo",
"path": "open_flamingo/src/flamingo.py",
"snippet": "class Flamingo(nn.Module):\n def __init__(\n self,\n vision_encoder: nn.Module,\n lang_encoder: nn.Module,\n eoc_token_id: int,\n media_token_id: int,\n vis_dim: int,\n cr... | from transformers import AutoModelForCausalLM, AutoTokenizer
from typing import Literal, Optional
from .flamingo import Flamingo
from .flamingo_lm import FlamingoLMMixin
from .utils import extend_instance
from open_clip import transformer
from torch.nn import functional as F
import open_clip
import torch | 3,641 |
def LNormforward(self, x: torch.Tensor):
#x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
transformer.LayerNormFp32.forward = LNormforward
def create_model_and_transforms(
clip_vision_encoder_path: str,
clip_vision_encoder_pretrained: str,
lang_encoder_path: str,
tokenizer_path: str,
cross_attn_every_n_layers: int = 1,
use_local_files: bool = False,
decoder_layers_attr_name: Optional[str] = None,
inference: bool = False,
precision: Literal["fp16","fp32"] = "fp32",
device: str = "cpu",
checkpoint_path: Optional[str] = None,
**flamingo_kwargs,
):
"""
Initialize a Flamingo model from a pretrained vision encoder and language encoder.
Appends special tokens to the tokenizer and freezes backbones.
Args:
clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32")
clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "laion2b_s32b_b79k")
lang_encoder_path (str): path to pretrained language encoder
tokenizer_path (str): path to pretrained tokenizer
cross_attn_every_n_layers (int, optional): determines how often to add a cross-attention layer. Defaults to 1.
use_local_files (bool, optional): whether to use local files. Defaults to False.
decoder_layers_attr_name (str, optional): name of the decoder layers attribute. Defaults to None.
inference (bool, optional): whether to use inference mode. Defaults to True.
precision (str, optional): precision to use. Defaults to "fp16".
device (str, optional): device to use. Defaults to "cuda".
checkpoint_path (str, optional): path to flamingo checkpoint. Defaults to None.
Returns:
Flamingo: Flamingo model from pretrained vision and language encoders
Image processor: Pipeline to preprocess input images
Tokenizer: A tokenizer for the language model
"""
vision_encoder, _, image_processor = open_clip.create_model_and_transforms(
clip_vision_encoder_path, pretrained=clip_vision_encoder_pretrained,
precision=precision, device=device
)
# set the vision encoder to output the visual features
vision_encoder.visual.output_tokens = True
text_tokenizer = AutoTokenizer.from_pretrained(
tokenizer_path, local_files_only=use_local_files
)
# add Flamingo special tokens to the tokenizer
text_tokenizer.add_special_tokens(
{"additional_special_tokens": ["<|endofchunk|>", "<image>"]}
)
if text_tokenizer.pad_token is None:
# Issue: GPT models don't have a pad token, which we use to
# modify labels for the loss.
text_tokenizer.add_special_tokens({"pad_token": "<PAD>"})
dtype = torch.float16 if precision == "fp16" else torch.float32
lang_encoder = AutoModelForCausalLM.from_pretrained(
lang_encoder_path, local_files_only=use_local_files,
torch_dtype=dtype, # DO NOT EVER USE device_map HERE IT WILL CAUSE HORROR
).to(device)
extend_instance(lang_encoder, FlamingoLMMixin)
if decoder_layers_attr_name is None:
decoder_layers_attr_name = _infer_decoder_layers_attr_name(lang_encoder)
lang_encoder.set_decoder_layers_attr_name(decoder_layers_attr_name)
lang_encoder.resize_token_embeddings(len(text_tokenizer))
|
def LNormforward(self, x: torch.Tensor):
#x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
transformer.LayerNormFp32.forward = LNormforward
def create_model_and_transforms(
clip_vision_encoder_path: str,
clip_vision_encoder_pretrained: str,
lang_encoder_path: str,
tokenizer_path: str,
cross_attn_every_n_layers: int = 1,
use_local_files: bool = False,
decoder_layers_attr_name: Optional[str] = None,
inference: bool = False,
precision: Literal["fp16","fp32"] = "fp32",
device: str = "cpu",
checkpoint_path: Optional[str] = None,
**flamingo_kwargs,
):
"""
Initialize a Flamingo model from a pretrained vision encoder and language encoder.
Appends special tokens to the tokenizer and freezes backbones.
Args:
clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32")
clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "laion2b_s32b_b79k")
lang_encoder_path (str): path to pretrained language encoder
tokenizer_path (str): path to pretrained tokenizer
cross_attn_every_n_layers (int, optional): determines how often to add a cross-attention layer. Defaults to 1.
use_local_files (bool, optional): whether to use local files. Defaults to False.
decoder_layers_attr_name (str, optional): name of the decoder layers attribute. Defaults to None.
inference (bool, optional): whether to use inference mode. Defaults to True.
precision (str, optional): precision to use. Defaults to "fp16".
device (str, optional): device to use. Defaults to "cuda".
checkpoint_path (str, optional): path to flamingo checkpoint. Defaults to None.
Returns:
Flamingo: Flamingo model from pretrained vision and language encoders
Image processor: Pipeline to preprocess input images
Tokenizer: A tokenizer for the language model
"""
vision_encoder, _, image_processor = open_clip.create_model_and_transforms(
clip_vision_encoder_path, pretrained=clip_vision_encoder_pretrained,
precision=precision, device=device
)
# set the vision encoder to output the visual features
vision_encoder.visual.output_tokens = True
text_tokenizer = AutoTokenizer.from_pretrained(
tokenizer_path, local_files_only=use_local_files
)
# add Flamingo special tokens to the tokenizer
text_tokenizer.add_special_tokens(
{"additional_special_tokens": ["<|endofchunk|>", "<image>"]}
)
if text_tokenizer.pad_token is None:
# Issue: GPT models don't have a pad token, which we use to
# modify labels for the loss.
text_tokenizer.add_special_tokens({"pad_token": "<PAD>"})
dtype = torch.float16 if precision == "fp16" else torch.float32
lang_encoder = AutoModelForCausalLM.from_pretrained(
lang_encoder_path, local_files_only=use_local_files,
torch_dtype=dtype, # DO NOT EVER USE device_map HERE IT WILL CAUSE HORROR
).to(device)
extend_instance(lang_encoder, FlamingoLMMixin)
if decoder_layers_attr_name is None:
decoder_layers_attr_name = _infer_decoder_layers_attr_name(lang_encoder)
lang_encoder.set_decoder_layers_attr_name(decoder_layers_attr_name)
lang_encoder.resize_token_embeddings(len(text_tokenizer))
| model = Flamingo( | 0 | 2023-10-18 02:38:00+00:00 | 8k |
vorausrobotik/voraus-ad-dataset | train.py | [
{
"identifier": "Configuration",
"path": "configuration.py",
"snippet": "class Configuration(BaseModel):\n \"\"\"Describes the configuration parameters.\"\"\"\n\n seed: int\n epochs: int\n batchsize: int\n n_hidden_layers: int = Field(alias=\"nHiddenLayers\")\n n_coupling_blocks: int =... | import random
import numpy
import pandas
import torch
import torch.backends.cudnn
from pathlib import Path
from typing import Dict, List, Optional
from sklearn import metrics
from torch import optim
from configuration import Configuration
from normalizing_flow import NormalizingFlow, get_loss, get_loss_per_sample
from voraus_ad import ANOMALY_CATEGORIES, Signals, load_torch_dataloaders | 7,087 | """Contains the training of the normalizing flow model."""
# If deterministic CUDA is activated, some calculations cannot be calculated in parallel on the GPU.
# The training will take much longer but is reproducible.
DETERMINISTIC_CUDA = False
DATASET_PATH = Path.home() / "Downloads" / "voraus-ad-dataset-100hz.parquet"
MODEL_PATH: Optional[Path] = Path.cwd() / "model.pth"
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Define the training configuration and hyperparameters of the model.
| """Contains the training of the normalizing flow model."""
# If deterministic CUDA is activated, some calculations cannot be calculated in parallel on the GPU.
# The training will take much longer but is reproducible.
DETERMINISTIC_CUDA = False
DATASET_PATH = Path.home() / "Downloads" / "voraus-ad-dataset-100hz.parquet"
MODEL_PATH: Optional[Path] = Path.cwd() / "model.pth"
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Define the training configuration and hyperparameters of the model. | configuration = Configuration( | 0 | 2023-10-18 15:09:24+00:00 | 8k |
invictus717/UniDG | domainbed/scripts/sweep.py | [
{
"identifier": "datasets",
"path": "domainbed/datasets.py",
"snippet": "DATASETS = [\n # Debug\n \"Debug28\",\n \"Debug224\",\n # Small images\n \"ColoredMNIST\",\n \"RotatedMNIST\",\n # Big images\n \"VLCS\",\n \"PACS\",\n \"OfficeHome\",\n \"TerraIncognita\",\n \"D... | import argparse
import copy
import getpass
import hashlib
import json
import os
import random
import shutil
import time
import uuid
import numpy as np
import torch
import tqdm
import shlex
from domainbed import datasets
from domainbed import hparams_registry
from domainbed import algorithms
from domainbed.lib import misc
from domainbed import command_launchers | 4,431 | '--input_dir', self.train_args['output_dir'],
'--ft_mode', ft_mode
]
self.command_str = ' '.join(command)
if os.path.exists(os.path.join(self.output_dir, 'done')):
if os.path.exists(os.path.join(self.output_dir, 'done_{}'.format(ft_mode))):
self.state = SAJob.DONE
else:
self.state = SAJob.PRETRAINED
elif os.path.exists(os.path.join(self.output_dir, 'results_{}.jsonl'.format(ft_mode))):
self.state = SAJob.INCOMPLETE
else:
self.state = SAJob.NOT_LAUNCHED
def __str__(self):
job_info = (self.train_args['dataset'],
self.train_args['algorithm'],
self.train_args['test_envs'],
self.train_args['hparams_seed'], self.ft_mode)
return '{}: {} {}'.format(
self.state,
self.output_dir,
job_info)
@staticmethod
def launch(jobs, launcher_fn):
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
class UAJob:
NOT_LAUNCHED = 'Not launched'
INCOMPLETE = 'Incomplete'
PRETRAINED = 'Pretrained'
DONE = 'Done'
def __init__(self, train_args, sweep_output_dir, adapt_algorithm):
args_str = json.dumps(train_args, sort_keys=True)
args_hash = hashlib.md5(args_str.encode('utf-8')).hexdigest()
self.output_dir = os.path.join(sweep_output_dir, args_hash)
self.adapt_algorithm = adapt_algorithm
self.train_args = copy.deepcopy(train_args)
self.train_args['output_dir'] = self.output_dir
command = [
'python', '-m', 'domainbed.scripts.unsupervised_adaptation',
'--input_dir', self.train_args['output_dir'],
'--adapt_algorithm', adapt_algorithm
]
self.command_str = ' '.join(command)
if os.path.exists(os.path.join(self.output_dir, 'done')):
if os.path.exists(os.path.join(self.output_dir, 'done_{}'.format(adapt_algorithm))):
self.state = UAJob.DONE
else:
self.state = UAJob.PRETRAINED
elif os.path.exists(os.path.join(self.output_dir, 'results_{}.jsonl'.format(adapt_algorithm))):
self.state = UAJob.INCOMPLETE
else:
self.state = UAJob.NOT_LAUNCHED
def __str__(self):
job_info = (self.train_args['dataset'],
self.train_args['algorithm'],
self.train_args['test_envs'],
self.train_args['hparams_seed'], self.adapt_algorithm)
return '{}: {} {}'.format(
self.state,
self.output_dir,
job_info)
@staticmethod
def launch(jobs, launcher_fn):
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
def all_test_env_combinations(n):
"""
For a dataset with n >= 3 envs, return all combinations of 1 and 2 test
envs.
"""
assert(n >= 3)
for i in range(n):
yield [i]
for j in range(i+1, n):
yield [i, j]
| # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Run sweeps
"""
class Job:
NOT_LAUNCHED = 'Not launched'
INCOMPLETE = 'Incomplete'
DONE = 'Done'
def __init__(self, train_args, sweep_output_dir):
args_str = json.dumps(train_args, sort_keys=True)
args_hash = hashlib.md5(args_str.encode('utf-8')).hexdigest()
self.output_dir = os.path.join(sweep_output_dir, args_hash)
self.train_args = copy.deepcopy(train_args)
self.train_args['output_dir'] = self.output_dir
command = ['OMP_NUM_THREADS=1', 'python', '-m', 'domainbed.scripts.train']
for k, v in sorted(self.train_args.items()):
if isinstance(v, list):
v = ' '.join([str(v_) for v_ in v])
elif isinstance(v, str):
v = shlex.quote(v)
command.append(f'--{k} {v}')
self.command_str = ' '.join(command)
if os.path.exists(os.path.join(self.output_dir, 'done')):
self.state = Job.DONE
elif os.path.exists(self.output_dir):
self.state = Job.INCOMPLETE
else:
self.state = Job.NOT_LAUNCHED
def __str__(self):
job_info = (self.train_args['dataset'],
self.train_args['algorithm'],
self.train_args['test_envs'],
self.train_args['hparams_seed'])
return '{}: {} {}'.format(
self.state,
self.output_dir,
job_info)
@staticmethod
def launch(jobs, launcher_fn):
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
@staticmethod
def delete(jobs):
print('Deleting...')
for job in jobs:
shutil.rmtree(job.output_dir)
print(f'Deleted {len(jobs)} jobs!')
class SAJob:
NOT_LAUNCHED = 'Not launched'
INCOMPLETE = 'Incomplete'
PRETRAINED = 'Pretrained'
DONE = 'Done'
def __init__(self, train_args, sweep_output_dir, ft_mode):
args_str = json.dumps(train_args, sort_keys=True)
args_hash = hashlib.md5(args_str.encode('utf-8')).hexdigest()
self.output_dir = os.path.join(sweep_output_dir, args_hash)
self.ft_mode = ft_mode
self.train_args = copy.deepcopy(train_args)
self.train_args['output_dir'] = self.output_dir
command = [
'python', '-m', 'domainbed.scripts.supervised_adaptation',
'--input_dir', self.train_args['output_dir'],
'--ft_mode', ft_mode
]
self.command_str = ' '.join(command)
if os.path.exists(os.path.join(self.output_dir, 'done')):
if os.path.exists(os.path.join(self.output_dir, 'done_{}'.format(ft_mode))):
self.state = SAJob.DONE
else:
self.state = SAJob.PRETRAINED
elif os.path.exists(os.path.join(self.output_dir, 'results_{}.jsonl'.format(ft_mode))):
self.state = SAJob.INCOMPLETE
else:
self.state = SAJob.NOT_LAUNCHED
def __str__(self):
job_info = (self.train_args['dataset'],
self.train_args['algorithm'],
self.train_args['test_envs'],
self.train_args['hparams_seed'], self.ft_mode)
return '{}: {} {}'.format(
self.state,
self.output_dir,
job_info)
@staticmethod
def launch(jobs, launcher_fn):
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
class UAJob:
NOT_LAUNCHED = 'Not launched'
INCOMPLETE = 'Incomplete'
PRETRAINED = 'Pretrained'
DONE = 'Done'
def __init__(self, train_args, sweep_output_dir, adapt_algorithm):
args_str = json.dumps(train_args, sort_keys=True)
args_hash = hashlib.md5(args_str.encode('utf-8')).hexdigest()
self.output_dir = os.path.join(sweep_output_dir, args_hash)
self.adapt_algorithm = adapt_algorithm
self.train_args = copy.deepcopy(train_args)
self.train_args['output_dir'] = self.output_dir
command = [
'python', '-m', 'domainbed.scripts.unsupervised_adaptation',
'--input_dir', self.train_args['output_dir'],
'--adapt_algorithm', adapt_algorithm
]
self.command_str = ' '.join(command)
if os.path.exists(os.path.join(self.output_dir, 'done')):
if os.path.exists(os.path.join(self.output_dir, 'done_{}'.format(adapt_algorithm))):
self.state = UAJob.DONE
else:
self.state = UAJob.PRETRAINED
elif os.path.exists(os.path.join(self.output_dir, 'results_{}.jsonl'.format(adapt_algorithm))):
self.state = UAJob.INCOMPLETE
else:
self.state = UAJob.NOT_LAUNCHED
def __str__(self):
job_info = (self.train_args['dataset'],
self.train_args['algorithm'],
self.train_args['test_envs'],
self.train_args['hparams_seed'], self.adapt_algorithm)
return '{}: {} {}'.format(
self.state,
self.output_dir,
job_info)
@staticmethod
def launch(jobs, launcher_fn):
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
print('Launching...')
jobs = jobs.copy()
np.random.shuffle(jobs)
print('Making job directories:')
for job in tqdm.tqdm(jobs, leave=False):
os.makedirs(job.output_dir, exist_ok=True)
commands = [job.command_str for job in jobs]
launcher_fn(commands)
print(f'Launched {len(jobs)} jobs!')
def all_test_env_combinations(n):
"""
For a dataset with n >= 3 envs, return all combinations of 1 and 2 test
envs.
"""
assert(n >= 3)
for i in range(n):
yield [i]
for j in range(i+1, n):
yield [i, j]
| def make_args_list(n_trials_from, n_trials, dataset_names, algorithms, n_hparams_from, n_hparams, steps, | 2 | 2023-10-15 14:26:12+00:00 | 8k |
AI-Application-and-Integration-Lab/DGUA_FAS | experiment/m/train.py | [
{
"identifier": "save_checkpoint",
"path": "util/utils.py",
"snippet": "def save_checkpoint(save_list, is_best, model, gpus, checkpoint_path, best_model_path, filename='_checkpoint.pth.tar'):\n epoch = save_list[0]\n valid_args = save_list[1]\n best_model_HTER = round(save_list[2], 5)\n best... | import sys
import random
import numpy as np
import time
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.functional as F
from util.utils import save_checkpoint, AverageMeter, Logger, accuracy, mkdirs, time_to_str
from util.evaluate import eval
from util.get_loader import get_dataset
from config import config
from datetime import datetime
from timeit import default_timer as timer
from torch.utils.tensorboard import SummaryWriter
from cvnets.models import get_model
from option import get_training_arguments | 5,495 | if (iter_num % src1_iter_per_epoch_fake == 0):
src1_train_iter_fake = iter(src1_train_dataloader_fake)
if (iter_num % src2_iter_per_epoch_fake == 0):
src2_train_iter_fake = iter(src2_train_dataloader_fake)
if (iter_num % src3_iter_per_epoch_fake == 0):
src3_train_iter_fake = iter(src3_train_dataloader_fake)
if (iter_num != 0 and iter_num % iter_per_epoch == 0):
epoch = epoch + 1
param_lr_tmp = []
for param_group in optimizer.param_groups:
param_lr_tmp.append(param_group["lr"])
net.train(True)
optimizer.zero_grad()
######### data prepare #########
src1_img_real, src1_label_real = src1_train_iter_real.next()
src1_img_real = src1_img_real.cuda()
src1_label_real = src1_label_real.cuda()
src2_img_real, src2_label_real = src2_train_iter_real.next()
src2_img_real = src2_img_real.cuda()
src2_label_real = src2_label_real.cuda()
src3_img_real, src3_label_real = src3_train_iter_real.next()
src3_img_real = src3_img_real.cuda()
src3_label_real = src3_label_real.cuda()
src1_img_fake, src1_label_fake = src1_train_iter_fake.next()
src1_img_fake = src1_img_fake.cuda()
src1_label_fake = src1_label_fake.cuda()
src2_img_fake, src2_label_fake = src2_train_iter_fake.next()
src2_img_fake = src2_img_fake.cuda()
src2_label_fake = src2_label_fake.cuda()
src3_img_fake, src3_label_fake = src3_train_iter_fake.next()
src3_img_fake = src3_img_fake.cuda()
src3_label_fake = src3_label_fake.cuda()
input_data = torch.cat([src1_img_real, src1_img_fake, src2_img_real, src2_img_fake, src3_img_real, src3_img_fake], dim=0)
source_label = torch.cat([src1_label_real, src1_label_fake,
src2_label_real, src2_label_fake,
src3_label_real, src3_label_fake,
], dim=0)
######### forward #########
######### Copycat train #########
bsz = source_label.size(0)
net.train(False)
net2.train(True) # Copycat Model
optimizer2.zero_grad()
classifier_label_out, x11, x12, x13 = net(input_data, return_feature=True)
classifier_label_out2, x21, x22, x23 = net2(input_data, return_feature=True)
pullloss1 = criterion["l1"](x11.reshape(bsz, -1),x21.reshape(bsz,-1))
pullloss2 = criterion["l1"](x12.reshape(bsz, -1),x22.reshape(bsz,-1))
cls_loss = criterion["softmax"](classifier_label_out2.narrow(0, 0, input_data.size(0)), source_label)
pullloss = (pullloss1 + pullloss2) / 2
cls_loss = cls_loss + pullloss
cls_loss.backward()
optimizer2.step()
######## MainModel train ########
net.train(True)
net2.train(False) # Copycat Model
optimizer.zero_grad()
classifier_label_out, x11, x12, x13 = net(input_data, return_feature=True)
classifier_label_out2, x21, x22, x23 = net2(input_data, return_feature=True)
out21 = net(input_data, x1 = x21)
out22 = net(input_data, x2 = x22)
out23 = net(input_data, x3 = x23)
klu0 = criterion["lsr_hard"](out21, source_label)
klu1 = criterion["lsr_hard"](out22, source_label)
klu2 = criterion["lsr_easy"](out23, source_label)
klu = (klu0 + klu1 + klu2) / 3
# features_dim = 20*640*8*8
real_features = net.extract_features(input_data[source_label == 1])
l1_loss = criterion["l1"](real_features, torch.zeros_like(real_features))
######### cross-entropy loss #########
cls_loss = criterion["softmax"](classifier_label_out.narrow(0, 0, input_data.size(0)), source_label)
######### backward #########
total_loss = cls_loss + l1_loss + 0.1 * klu
total_loss.backward()
optimizer.step()
optimizer.zero_grad()
loss_classifier.update(cls_loss.item())
acc = accuracy(classifier_label_out.narrow(0, 0, input_data.size(0)), source_label, topk=(1,))
classifer_top1.update(acc[0])
print('\r', end='', flush=True)
print(
' %4.1f | %5.3f %6.3f %6.3f %6.3f | %6.3f %6.3f | %6.3f %6.3f %6.3f | %s'
% (
(iter_num+1) / iter_per_epoch,
valid_args[0], valid_args[1], valid_args[3] * 100, valid_args[4] * 100,
loss_classifier.avg, classifer_top1.avg,
float(best_model_ACC), float(best_model_HTER * 100), float(best_model_AUC * 100),
time_to_str(timer() - start, 'min'))
, end='', flush=True)
if (iter_num != 0 and (iter_num+1) % iter_per_epoch == 0):
train_loss = loss_classifier.avg
train_acc = classifer_top1.avg
# 0:loss, 1:top-1, 2:EER, 3:HTER, 4:AUC, 5:threshold, 6:ACC_threshold
| sys.path.append('../../')
class SmoothCrossEntropy(nn.Module):
def __init__(self, alpha=0.5):
super(SmoothCrossEntropy, self).__init__()
self.alpha = alpha
def forward(self, logits, labels):
num_classes = logits.shape[-1]
alpha_div_k = self.alpha / num_classes
target_probs = nn.functional.one_hot(labels, num_classes=num_classes).float() * \
(1. - self.alpha) + alpha_div_k
loss = -(target_probs * torch.log_softmax(logits, dim=-1)).sum(dim=-1)
return loss.mean()
random.seed(config.seed)
np.random.seed(config.seed)
torch.manual_seed(config.seed)
torch.cuda.manual_seed_all(config.seed)
torch.cuda.manual_seed(config.seed)
os.environ["CUDA_VISIBLE_DEVICES"] = config.gpus
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
device = 'cuda'
def train():
mkdirs(config.checkpoint_path, config.best_model_path, config.logs)
# load data
src1_train_dataloader_fake, src1_train_dataloader_real, \
src2_train_dataloader_fake, src2_train_dataloader_real, \
src3_train_dataloader_fake, src3_train_dataloader_real, \
tgt_valid_dataloader = get_dataset(config.src1_data, config.src1_train_num_frames,
config.src2_data, config.src2_train_num_frames,
config.src3_data, config.src3_train_num_frames,
config.tgt_data, config.tgt_test_num_frames, config.batch_size)
best_model_ACC = 0.0
best_model_HTER = 1.0
best_model_ACER = 1.0
best_model_AUC = 0.0
# 0:loss, 1:top-1, 2:EER, 3:HTER, 4:ACER, 5:AUC, 6:threshold
valid_args = [np.inf, 0, 0, 0, 0, 0, 0, 0]
loss_classifier = AverageMeter()
classifer_top1 = AverageMeter()
opts = get_training_arguments(config_path='./../../configs/mobilevit_s.yaml')
net = get_model(opts).to(device)
net2 = get_model(opts).to(device)
state_dict = torch.load('./../../pretrained_model/mobilevit_s.pt')
del state_dict['classifier.fc.weight']
del state_dict['classifier.fc.bias']
net.load_state_dict(state_dict, strict=False)
net2.load_state_dict(state_dict, strict=False)
writer = SummaryWriter('./logs/runs')
log = Logger()
log.open(config.logs + config.tgt_data + '_log.txt', mode='a')
log.write("\n----------------------------------------------- [START %s] %s\n\n" % (
datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '-' * 51))
log.write('** start training target model! **\n')
log.write(
'--------|------------- VALID -------------|--- classifier ---|------ Current Best ------|--------------|\n')
log.write(
' iter | loss top-1 HTER AUC | loss top-1 | top-1 HTER AUC | time |\n')
log.write(
'-------------------------------------------------------------------------------------------------------|\n')
start = timer()
criterion = {
'softmax': nn.CrossEntropyLoss(label_smoothing=0.1).cuda(),
'l1': nn.L1Loss().cuda(),
'lsr_hard' : SmoothCrossEntropy(0.5),
'lsr_easy' : SmoothCrossEntropy(1.0)
}
optimizer_dict = [
{"params": filter(lambda p: p.requires_grad, net.parameters()), "lr": config.init_lr},
]
optimizer_dict2 = [
{"params": filter(lambda p: p.requires_grad, net2.parameters()), "lr": config.init_lr},
]
optimizer = optim.Adam(optimizer_dict, lr=config.init_lr, weight_decay=config.weight_decay)
optimizer2 = optim.Adam(optimizer_dict2, lr=config.init_lr, weight_decay=config.weight_decay)
init_param_lr = []
for param_group in optimizer.param_groups:
init_param_lr.append(param_group["lr"])
iter_per_epoch = 10
src1_train_iter_real = iter(src1_train_dataloader_real)
src1_iter_per_epoch_real = len(src1_train_iter_real)
src2_train_iter_real = iter(src2_train_dataloader_real)
src2_iter_per_epoch_real = len(src2_train_iter_real)
src3_train_iter_real = iter(src3_train_dataloader_real)
src3_iter_per_epoch_real = len(src3_train_iter_real)
src1_train_iter_fake = iter(src1_train_dataloader_fake)
src1_iter_per_epoch_fake = len(src1_train_iter_fake)
src2_train_iter_fake = iter(src2_train_dataloader_fake)
src2_iter_per_epoch_fake = len(src2_train_iter_fake)
src3_train_iter_fake = iter(src3_train_dataloader_fake)
src3_iter_per_epoch_fake = len(src3_train_iter_fake)
max_iter = config.max_iter
epoch = 1
if(len(config.gpus) > 1):
net = torch.nn.DataParallel(net).cuda()
net2 = torch.nn.DataParallel(net).cuda()
for iter_num in range(max_iter+1):
if (iter_num % src1_iter_per_epoch_real == 0):
src1_train_iter_real = iter(src1_train_dataloader_real)
if (iter_num % src2_iter_per_epoch_real == 0):
src2_train_iter_real = iter(src2_train_dataloader_real)
if (iter_num % src3_iter_per_epoch_real == 0):
src3_train_iter_real = iter(src3_train_dataloader_real)
if (iter_num % src1_iter_per_epoch_fake == 0):
src1_train_iter_fake = iter(src1_train_dataloader_fake)
if (iter_num % src2_iter_per_epoch_fake == 0):
src2_train_iter_fake = iter(src2_train_dataloader_fake)
if (iter_num % src3_iter_per_epoch_fake == 0):
src3_train_iter_fake = iter(src3_train_dataloader_fake)
if (iter_num != 0 and iter_num % iter_per_epoch == 0):
epoch = epoch + 1
param_lr_tmp = []
for param_group in optimizer.param_groups:
param_lr_tmp.append(param_group["lr"])
net.train(True)
optimizer.zero_grad()
######### data prepare #########
src1_img_real, src1_label_real = src1_train_iter_real.next()
src1_img_real = src1_img_real.cuda()
src1_label_real = src1_label_real.cuda()
src2_img_real, src2_label_real = src2_train_iter_real.next()
src2_img_real = src2_img_real.cuda()
src2_label_real = src2_label_real.cuda()
src3_img_real, src3_label_real = src3_train_iter_real.next()
src3_img_real = src3_img_real.cuda()
src3_label_real = src3_label_real.cuda()
src1_img_fake, src1_label_fake = src1_train_iter_fake.next()
src1_img_fake = src1_img_fake.cuda()
src1_label_fake = src1_label_fake.cuda()
src2_img_fake, src2_label_fake = src2_train_iter_fake.next()
src2_img_fake = src2_img_fake.cuda()
src2_label_fake = src2_label_fake.cuda()
src3_img_fake, src3_label_fake = src3_train_iter_fake.next()
src3_img_fake = src3_img_fake.cuda()
src3_label_fake = src3_label_fake.cuda()
input_data = torch.cat([src1_img_real, src1_img_fake, src2_img_real, src2_img_fake, src3_img_real, src3_img_fake], dim=0)
source_label = torch.cat([src1_label_real, src1_label_fake,
src2_label_real, src2_label_fake,
src3_label_real, src3_label_fake,
], dim=0)
######### forward #########
######### Copycat train #########
bsz = source_label.size(0)
net.train(False)
net2.train(True) # Copycat Model
optimizer2.zero_grad()
classifier_label_out, x11, x12, x13 = net(input_data, return_feature=True)
classifier_label_out2, x21, x22, x23 = net2(input_data, return_feature=True)
pullloss1 = criterion["l1"](x11.reshape(bsz, -1),x21.reshape(bsz,-1))
pullloss2 = criterion["l1"](x12.reshape(bsz, -1),x22.reshape(bsz,-1))
cls_loss = criterion["softmax"](classifier_label_out2.narrow(0, 0, input_data.size(0)), source_label)
pullloss = (pullloss1 + pullloss2) / 2
cls_loss = cls_loss + pullloss
cls_loss.backward()
optimizer2.step()
######## MainModel train ########
net.train(True)
net2.train(False) # Copycat Model
optimizer.zero_grad()
classifier_label_out, x11, x12, x13 = net(input_data, return_feature=True)
classifier_label_out2, x21, x22, x23 = net2(input_data, return_feature=True)
out21 = net(input_data, x1 = x21)
out22 = net(input_data, x2 = x22)
out23 = net(input_data, x3 = x23)
klu0 = criterion["lsr_hard"](out21, source_label)
klu1 = criterion["lsr_hard"](out22, source_label)
klu2 = criterion["lsr_easy"](out23, source_label)
klu = (klu0 + klu1 + klu2) / 3
# features_dim = 20*640*8*8
real_features = net.extract_features(input_data[source_label == 1])
l1_loss = criterion["l1"](real_features, torch.zeros_like(real_features))
######### cross-entropy loss #########
cls_loss = criterion["softmax"](classifier_label_out.narrow(0, 0, input_data.size(0)), source_label)
######### backward #########
total_loss = cls_loss + l1_loss + 0.1 * klu
total_loss.backward()
optimizer.step()
optimizer.zero_grad()
loss_classifier.update(cls_loss.item())
acc = accuracy(classifier_label_out.narrow(0, 0, input_data.size(0)), source_label, topk=(1,))
classifer_top1.update(acc[0])
print('\r', end='', flush=True)
print(
' %4.1f | %5.3f %6.3f %6.3f %6.3f | %6.3f %6.3f | %6.3f %6.3f %6.3f | %s'
% (
(iter_num+1) / iter_per_epoch,
valid_args[0], valid_args[1], valid_args[3] * 100, valid_args[4] * 100,
loss_classifier.avg, classifer_top1.avg,
float(best_model_ACC), float(best_model_HTER * 100), float(best_model_AUC * 100),
time_to_str(timer() - start, 'min'))
, end='', flush=True)
if (iter_num != 0 and (iter_num+1) % iter_per_epoch == 0):
train_loss = loss_classifier.avg
train_acc = classifer_top1.avg
# 0:loss, 1:top-1, 2:EER, 3:HTER, 4:AUC, 5:threshold, 6:ACC_threshold | valid_args = eval(tgt_valid_dataloader, net) | 6 | 2023-10-17 15:35:33+00:00 | 8k |
jianlanluo/SAQ | vqn/vqiql_main.py | [
{
"identifier": "VQIQLLearner",
"path": "vqn/vqiql.py",
"snippet": "class VQIQLLearner(Agent):\n\n def __init__(self,\n seed: int,\n observations: jnp.ndarray,\n actions: jnp.ndarray,\n vqvae_lr: float = 3e-4,\n embedding... | from absl import app, flags
from ml_collections import config_flags
from robomimic.utils.dataset import SequenceDataset
from .vqiql import VQIQLLearner, IQLSamplerPolicy, split_into_trajectories
from .replay_buffer import get_d4rl_dataset
from .sampler import TrajSampler
from .robomimic_utils import (
OfflineDataset, process_robomimic_dataset, D4RLDataset, get_robomimic_env,
ENV_TO_HORIZON_MAP, OBS_KEYS
)
from .utils import (
Timer, define_flags_with_default, set_random_seed,
get_user_flags, prefix_metrics, WandBLogger
)
import cloudpickle as pickle
import tqdm
import gym
import numpy as np
import d4rl | 6,559 |
FLAGS = flags.FLAGS
FLAGS_DEF = define_flags_with_default(
env='pen-human-v1',
dataset_dir = '',
seed=42,
save_model=False,
zero_reward=False,
reward_scale=1.0,
reward_bias=0.0,
max_traj_length=200,
eval_n_trajs=10,
eval_period=10,
batch_size=256,
vqvae_n_epochs=500,
n_epochs=1000,
n_pi_beta_epochs=2000,
n_train_step_per_epoch=50,
tqdm=True,
embedding_dim=128,
codebook_size=64,
commitment_cost=1.0,
quantization_cost=1.0,
entropy_loss_ratio=0.0,
entropy_loss_type="softmax",
entropy_temperature=1.0,
vqvae_arch='512-512',
sample_action=True,
policy_weight_decay=0.0,
kl_divergence_weight=0.0,
qf_weight_decay=0.0,
qf_arch='256-256',
iql_expectile=0.8,
iql_temperature=0.1,
iql_bc_loss_weight=0.0,
logging=WandBLogger.get_default_config(),
)
OBS_KEYS = ("robot0_eef_pos", "robot0_eef_quat", "robot0_gripper_qpos", "object")
ENV_TO_HORIZON_MAP = {'lift': 400,
'can': 400,
'square': 400,
'transport': 700,
'tool_hang': 700}
def normalize(dataset):
trajs = split_into_trajectories(dataset.observations, dataset.actions,
dataset.rewards, dataset.masks,
dataset.dones_float,
dataset.next_observations)
def compute_returns(traj):
episode_return = 0
for _, _, rew, _, _, _ in traj:
episode_return += rew
return episode_return
trajs.sort(key=compute_returns)
dataset.rewards /= compute_returns(trajs[-1]) - compute_returns(trajs[0])
dataset.rewards *= 1000.0
def make_dataset(dataset, env_name, zero_reward=False):
if zero_reward:
dataset['reward'] = np.zeros_like(dataset['rewards'])
if not env_name in ENV_TO_HORIZON_MAP:
dataset = OfflineDataset(dataset)
if 'antmaze' in env_name:
dataset.dataset_dict['rewards'] *= 100
elif env_name.split('-')[0] in ['hopper', 'halfcheetah', 'walker2d']:
dataset.normalize_returns(scaling=1000)
return dataset
def main(_):
variant = get_user_flags(FLAGS, FLAGS_DEF)
wandb_logger = WandBLogger(config=FLAGS.logging, variant=variant)
set_random_seed(FLAGS.seed)
if FLAGS.env in ENV_TO_HORIZON_MAP:
dataset_path = f'./robomimic/datasets/{FLAGS.env}/low_dim_v141.hdf5'
seq_dataset = SequenceDataset(hdf5_path=dataset_path,
obs_keys=OBS_KEYS,
dataset_keys=("actions", "rewards", "dones"),
hdf5_cache_mode="all",
load_next_obs=True)
|
FLAGS = flags.FLAGS
FLAGS_DEF = define_flags_with_default(
env='pen-human-v1',
dataset_dir = '',
seed=42,
save_model=False,
zero_reward=False,
reward_scale=1.0,
reward_bias=0.0,
max_traj_length=200,
eval_n_trajs=10,
eval_period=10,
batch_size=256,
vqvae_n_epochs=500,
n_epochs=1000,
n_pi_beta_epochs=2000,
n_train_step_per_epoch=50,
tqdm=True,
embedding_dim=128,
codebook_size=64,
commitment_cost=1.0,
quantization_cost=1.0,
entropy_loss_ratio=0.0,
entropy_loss_type="softmax",
entropy_temperature=1.0,
vqvae_arch='512-512',
sample_action=True,
policy_weight_decay=0.0,
kl_divergence_weight=0.0,
qf_weight_decay=0.0,
qf_arch='256-256',
iql_expectile=0.8,
iql_temperature=0.1,
iql_bc_loss_weight=0.0,
logging=WandBLogger.get_default_config(),
)
OBS_KEYS = ("robot0_eef_pos", "robot0_eef_quat", "robot0_gripper_qpos", "object")
ENV_TO_HORIZON_MAP = {'lift': 400,
'can': 400,
'square': 400,
'transport': 700,
'tool_hang': 700}
def normalize(dataset):
trajs = split_into_trajectories(dataset.observations, dataset.actions,
dataset.rewards, dataset.masks,
dataset.dones_float,
dataset.next_observations)
def compute_returns(traj):
episode_return = 0
for _, _, rew, _, _, _ in traj:
episode_return += rew
return episode_return
trajs.sort(key=compute_returns)
dataset.rewards /= compute_returns(trajs[-1]) - compute_returns(trajs[0])
dataset.rewards *= 1000.0
def make_dataset(dataset, env_name, zero_reward=False):
if zero_reward:
dataset['reward'] = np.zeros_like(dataset['rewards'])
if not env_name in ENV_TO_HORIZON_MAP:
dataset = OfflineDataset(dataset)
if 'antmaze' in env_name:
dataset.dataset_dict['rewards'] *= 100
elif env_name.split('-')[0] in ['hopper', 'halfcheetah', 'walker2d']:
dataset.normalize_returns(scaling=1000)
return dataset
def main(_):
variant = get_user_flags(FLAGS, FLAGS_DEF)
wandb_logger = WandBLogger(config=FLAGS.logging, variant=variant)
set_random_seed(FLAGS.seed)
if FLAGS.env in ENV_TO_HORIZON_MAP:
dataset_path = f'./robomimic/datasets/{FLAGS.env}/low_dim_v141.hdf5'
seq_dataset = SequenceDataset(hdf5_path=dataset_path,
obs_keys=OBS_KEYS,
dataset_keys=("actions", "rewards", "dones"),
hdf5_cache_mode="all",
load_next_obs=True) | dataset = process_robomimic_dataset(seq_dataset) | 6 | 2023-10-18 06:31:20+00:00 | 8k |
naver-ai/dual-teacher | tools/train.py | [
{
"identifier": "__version__",
"path": "mmseg/version.py",
"snippet": "def parse_version_info(version_str):"
},
{
"identifier": "set_random_seed",
"path": "mmseg/apis/train.py",
"snippet": "def set_random_seed(seed, deterministic=False):\n \"\"\"Set random seed.\n Args:\n se... | import argparse
import copy
import os
import os.path as osp
import time
import logging
import mmcv
import torch
import numpy as np
import seg_core.eval_seg as eval_seg
import torch.nn.functional as F
import warnings
import torch.distributed as dist
import random
import tempfile
from mmcv.runner import init_dist
from mmcv.utils import Config, DictAction, get_git_hash
from torchvision.transforms import ToTensor
from mmseg import __version__
from mmseg.apis import set_random_seed, train_segmentor
from mmseg.datasets import build_dataset, build_dataloader
from mmseg.models import build_segmentor
from mmseg.utils import collect_env, get_root_logger
from seg_core.model import MiT_SegFormer
from seg_core.optimizer import PolyWarmupAdamW
from seg_core.augmentations import ClassMixLoss, compute_classmix, compute_cutmix, compute_ic
from torchvision.utils import save_image
from dist_helper import setup_distributed
from mmseg.apis import single_gpu_test
from mmcv.image import tensor2imgs
from PIL import Image, ImageOps, ImageFilter
from torchvision import transforms
from copy import deepcopy | 6,075 | """
Dual-Teacher
Copyright (c) 2023-present NAVER Cloud Corp.
distributed under NVIDIA Source Code License for SegFormer
--------------------------------------------------------
References:
SegFormer: https://github.com/NVlabs/SegFormer
--------------------------------------------------------
"""
warnings.filterwarnings("ignore")
criterion_u = torch.nn.CrossEntropyLoss(reduction='none').cuda()
def train_sup(args, model, optimizer, train_loader, val_loader, criterion, max_iters, print_iters, eval_iters):
train_iterator = iter(train_loader)
if args.ddp:
rank, world_size = dist.get_rank(), dist.get_world_size()
else:
rank = 0
for epoch in range(200):
for i in range(len(train_loader)):
model.train()
try:
batch_data = next(train_iterator)
except:
train_iterator = iter(train_loader)
batch_data = next(train_iterator)
image = batch_data['img'].data[0].cuda(non_blocking=True)
label = batch_data['gt_semantic_seg'].data[0].squeeze(dim=1).cuda(non_blocking=True)
outputs = model(image)
outputs = F.interpolate(outputs, size=label.shape[1:], mode='bilinear', align_corners=False)
seg_loss = criterion(outputs, label.type(torch.long))
optimizer.zero_grad()
seg_loss.backward()
optimizer.step()
if rank == 0:
lr = optimizer.param_groups[0]['lr']
logging.info("save_path:{}".format(args.save_path))
logging.info("Iter: %d; LR: %.3e; seg_loss: %f" % (i + 1, lr, seg_loss.item()))
print("Iter: %d; LR: %.3e; seg_loss: %f" % (i + 1, lr, seg_loss.item()))
logging.info('[iter:{}] Validation:'.format(i + 1))
print('[iter:{}] Validation:'.format(i + 1))
val_score = val(model.module, val_loader)
logging.info('mIoU:{:.5f}'.format(val_score['Mean IoU'] * 100))
print('mIoU:{:.5f}'.format(val_score['Mean IoU'] * 100))
model.train()
def train_dual(args, model, model_teacher, model_teacher2, optimizer, train_loader, train_loader_u, val_loader, criterion, cm_loss_fn, max_iters, print_iters, eval_iters):
if args.ddp:
rank, world_size = dist.get_rank(), dist.get_world_size()
else:
rank = 0
best_miou, best_epoch = 0, 0
for epoch in range(200):
model.train()
train_loader.sampler.set_epoch(epoch)
train_loader_u.sampler.set_epoch(epoch)
train_iterator = iter(train_loader)
train_iterator_u = iter(train_loader_u)
if epoch % 2 == 0:
ema_model = model_teacher
do_cut_mix = True
do_class_mix = False
else:
ema_model = model_teacher2
do_cut_mix = False
do_class_mix = True
ema_model.train()
for i in range(len(train_loader)):
try:
batch_data_u = next(train_iterator_u)
except:
train_iterator_u = iter(train_loader_u)
batch_data_u = next(train_iterator_u)
try:
batch_data = next(train_iterator)
except:
train_iterator = iter(train_loader)
batch_data = next(train_iterator)
image = batch_data['img'].data[0].cuda(non_blocking=True)
label = batch_data['gt_semantic_seg'].data[0].squeeze(dim=1).cuda(non_blocking=True)
image_u = batch_data_u['img'].data[0].cuda(non_blocking=True)
label_u = batch_data['gt_semantic_seg'].data[0].squeeze(dim=1).cuda(non_blocking=True)
b, _, h, w = image.shape
image_u_strong = deepcopy(image_u)
image_u_strong = transforms.ColorJitter(0.5, 0.5, 0.5, 0.25)(image_u_strong)
image_u_strong = transforms.RandomGrayscale(p=0.2)(image_u_strong)
if do_class_mix:
loss = compute_classmix(b, h, w, criterion, cm_loss_fn, model, ema_model, image, label, image_u, image_u_strong, threshold=0.95)
if do_cut_mix:
| """
Dual-Teacher
Copyright (c) 2023-present NAVER Cloud Corp.
distributed under NVIDIA Source Code License for SegFormer
--------------------------------------------------------
References:
SegFormer: https://github.com/NVlabs/SegFormer
--------------------------------------------------------
"""
warnings.filterwarnings("ignore")
criterion_u = torch.nn.CrossEntropyLoss(reduction='none').cuda()
def train_sup(args, model, optimizer, train_loader, val_loader, criterion, max_iters, print_iters, eval_iters):
train_iterator = iter(train_loader)
if args.ddp:
rank, world_size = dist.get_rank(), dist.get_world_size()
else:
rank = 0
for epoch in range(200):
for i in range(len(train_loader)):
model.train()
try:
batch_data = next(train_iterator)
except:
train_iterator = iter(train_loader)
batch_data = next(train_iterator)
image = batch_data['img'].data[0].cuda(non_blocking=True)
label = batch_data['gt_semantic_seg'].data[0].squeeze(dim=1).cuda(non_blocking=True)
outputs = model(image)
outputs = F.interpolate(outputs, size=label.shape[1:], mode='bilinear', align_corners=False)
seg_loss = criterion(outputs, label.type(torch.long))
optimizer.zero_grad()
seg_loss.backward()
optimizer.step()
if rank == 0:
lr = optimizer.param_groups[0]['lr']
logging.info("save_path:{}".format(args.save_path))
logging.info("Iter: %d; LR: %.3e; seg_loss: %f" % (i + 1, lr, seg_loss.item()))
print("Iter: %d; LR: %.3e; seg_loss: %f" % (i + 1, lr, seg_loss.item()))
logging.info('[iter:{}] Validation:'.format(i + 1))
print('[iter:{}] Validation:'.format(i + 1))
val_score = val(model.module, val_loader)
logging.info('mIoU:{:.5f}'.format(val_score['Mean IoU'] * 100))
print('mIoU:{:.5f}'.format(val_score['Mean IoU'] * 100))
model.train()
def train_dual(args, model, model_teacher, model_teacher2, optimizer, train_loader, train_loader_u, val_loader, criterion, cm_loss_fn, max_iters, print_iters, eval_iters):
if args.ddp:
rank, world_size = dist.get_rank(), dist.get_world_size()
else:
rank = 0
best_miou, best_epoch = 0, 0
for epoch in range(200):
model.train()
train_loader.sampler.set_epoch(epoch)
train_loader_u.sampler.set_epoch(epoch)
train_iterator = iter(train_loader)
train_iterator_u = iter(train_loader_u)
if epoch % 2 == 0:
ema_model = model_teacher
do_cut_mix = True
do_class_mix = False
else:
ema_model = model_teacher2
do_cut_mix = False
do_class_mix = True
ema_model.train()
for i in range(len(train_loader)):
try:
batch_data_u = next(train_iterator_u)
except:
train_iterator_u = iter(train_loader_u)
batch_data_u = next(train_iterator_u)
try:
batch_data = next(train_iterator)
except:
train_iterator = iter(train_loader)
batch_data = next(train_iterator)
image = batch_data['img'].data[0].cuda(non_blocking=True)
label = batch_data['gt_semantic_seg'].data[0].squeeze(dim=1).cuda(non_blocking=True)
image_u = batch_data_u['img'].data[0].cuda(non_blocking=True)
label_u = batch_data['gt_semantic_seg'].data[0].squeeze(dim=1).cuda(non_blocking=True)
b, _, h, w = image.shape
image_u_strong = deepcopy(image_u)
image_u_strong = transforms.ColorJitter(0.5, 0.5, 0.5, 0.25)(image_u_strong)
image_u_strong = transforms.RandomGrayscale(p=0.2)(image_u_strong)
if do_class_mix:
loss = compute_classmix(b, h, w, criterion, cm_loss_fn, model, ema_model, image, label, image_u, image_u_strong, threshold=0.95)
if do_cut_mix: | loss = compute_cutmix(h, w, image, label, criterion, model, ema_model, image_u, threshold=0.95) | 12 | 2023-10-19 04:04:31+00:00 | 8k |
Azure/azure-openai-benchmark | benchmark/loadcmd.py | [
{
"identifier": "AsyncHTTPExecuter",
"path": "benchmark/asynchttpexecuter.py",
"snippet": "class AsyncHTTPExecuter:\n \"\"\"\n An implementation of an async HTTP executer class with rate limiting and\n concurrency control.\n \"\"\"\n def __init__(self, async_http_func: Callable[[aiohttp.C... | import logging
import math
import os
import sys
import time
import aiohttp
import wonderwords
from typing import Iterable, Iterator
from .asynchttpexecuter import AsyncHTTPExecuter
from .oairequester import OAIRequester
from .oaitokenizer import num_tokens_from_messages
from .ratelimiting import NoRateLimiter, RateLimiter
from .statsaggregator import _StatsAggregator | 5,318 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
class _RequestBuilder:
"""
Wrapper iterator class to build request payloads.
"""
def __init__(self, model:str, context_tokens:int,
max_tokens:None,
completions:None,
frequence_penalty:None,
presence_penalty:None,
temperature:None,
top_p:None):
self.model = model
self.context_tokens = context_tokens
self.max_tokens = max_tokens
self.completions = completions
self.frequency_penalty = frequence_penalty
self.presence_penalty = presence_penalty
self.temperature = temperature
self.top_p = top_p
logging.info("warming up prompt cache")
_generate_messages(self.model, self.context_tokens, self.max_tokens)
def __iter__(self) -> Iterator[dict]:
return self
def __next__(self) -> (dict, int):
messages, messages_tokens = _generate_messages(self.model, self.context_tokens, self.max_tokens)
body = {"messages":messages}
if self.max_tokens is not None:
body["max_tokens"] = self.max_tokens
if self.completions is not None:
body["n"] = self.completions
if self.frequency_penalty is not None:
body["frequency_penalty"] = self.frequency_penalty
if self.presence_penalty is not None:
body["presenece_penalty"] = self.presence_penalty
if self.temperature is not None:
body["temperature"] = self.temperature
if self.top_p is not None:
body["top_p"] = self.top_p
return body, messages_tokens
def load(args):
try:
_validate(args)
except ValueError as e:
print(f"invalid argument(s): {e}")
sys.exit(1)
api_key = os.getenv(args.api_key_env)
url = args.api_base_endpoint[0] + "/openai/deployments/" + args.deployment + "/chat/completions"
url += "?api-version=" + args.api_version
rate_limiter = NoRateLimiter()
if args.rate is not None and args.rate > 0:
| # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
class _RequestBuilder:
"""
Wrapper iterator class to build request payloads.
"""
def __init__(self, model:str, context_tokens:int,
max_tokens:None,
completions:None,
frequence_penalty:None,
presence_penalty:None,
temperature:None,
top_p:None):
self.model = model
self.context_tokens = context_tokens
self.max_tokens = max_tokens
self.completions = completions
self.frequency_penalty = frequence_penalty
self.presence_penalty = presence_penalty
self.temperature = temperature
self.top_p = top_p
logging.info("warming up prompt cache")
_generate_messages(self.model, self.context_tokens, self.max_tokens)
def __iter__(self) -> Iterator[dict]:
return self
def __next__(self) -> (dict, int):
messages, messages_tokens = _generate_messages(self.model, self.context_tokens, self.max_tokens)
body = {"messages":messages}
if self.max_tokens is not None:
body["max_tokens"] = self.max_tokens
if self.completions is not None:
body["n"] = self.completions
if self.frequency_penalty is not None:
body["frequency_penalty"] = self.frequency_penalty
if self.presence_penalty is not None:
body["presenece_penalty"] = self.presence_penalty
if self.temperature is not None:
body["temperature"] = self.temperature
if self.top_p is not None:
body["top_p"] = self.top_p
return body, messages_tokens
def load(args):
try:
_validate(args)
except ValueError as e:
print(f"invalid argument(s): {e}")
sys.exit(1)
api_key = os.getenv(args.api_key_env)
url = args.api_base_endpoint[0] + "/openai/deployments/" + args.deployment + "/chat/completions"
url += "?api-version=" + args.api_version
rate_limiter = NoRateLimiter()
if args.rate is not None and args.rate > 0: | rate_limiter = RateLimiter(args.rate, 60) | 4 | 2023-10-19 00:52:26+00:00 | 8k |
pytest-visual/pytest-visual | visual/interface.py | [
{
"identifier": "correct_layout",
"path": "visual/lib/convenience.py",
"snippet": "def correct_layout(image: np.ndarray, layout: str) -> np.ndarray:\n if layout[0] == \"1\":\n image = np.squeeze(image, axis=0)\n layout = layout[1:]\n if layout[0] == \"c\":\n image = np.moveaxi... | import os
import random
import tempfile
import numpy as np
import pytest
import torchview # isort: skip
import numpy as np
import torch
import tensorflow as tf
from typing import Generator, List, Optional
from _pytest.fixtures import FixtureRequest
from PIL import Image
from plotly.graph_objs import Figure
from visual.lib.convenience import (
correct_layout,
create_plot_from_images,
get_grid_shape,
get_image_max_value_from_type,
get_layout_from_image,
)
from visual.lib.flags import get_visualization_flags, pytest_addoption
from visual.lib.storage import (
Statement,
clear_statements,
get_storage_path,
load_statements,
store_statements,
)
from visual.lib.ui import UI, Location, visual_UI | 4,711 | """
Show text within a visualization case.
Parameters:
- text (str): The text to show.
"""
self.statements.append(["print", text])
def show_figure(self, figure: Figure) -> None:
"""
Show a plotly figure within a visualization case.
Parameters:
- fig (Figure): The figure to show.
"""
self.statements.append(["show", str(figure.to_json())])
# Convenience interface
def show_images(
self,
images: List[np.ndarray],
labels: Optional[List[str]] = None,
max_cols: int = 3,
height_per_row: float = 300,
) -> None:
"""
Convenience method to show a grid of images. Only accepts standardized numpy images.
Parameters:
- images (List[np.ndarray]): A list of images to show.
- labels (Optional[List[str]]): A list of labels for each image.
- max_cols (int): Maximum number of columns in the grid.
- height_per_row (float): The height of each row in the grid.
"""
assert all(isinstance(image, np.ndarray) for image in images), "Images must be numpy arrays"
assert len(images) > 0, "At least one image must be specified"
grid_shape = get_grid_shape(len(images), max_cols)
total_height = None if height_per_row is None else height_per_row * grid_shape[0]
figure = create_plot_from_images(images, labels, grid_shape, total_height)
self.show_figure(figure)
def show_image(
self,
image: np.ndarray,
label: Optional[str] = None,
height: float = 600,
) -> None:
"""
Convenience method to show a single image. Only accepts standardized numpy images.
Parameters:
- image (np.ndarray): The image to show.
- label (Optional[str]): A label for the image.
- height (float): The height of the image.
"""
labels = None if label is None else [label]
self.show_images([image], labels, max_cols=1, height_per_row=height)
def show_model(
self,
model,
input_size,
depth: int = 100,
height: float = 1500,
) -> None:
"""
Convenience method to show a PyTorch model. Requires the torchview package.
Parameters:
- model (torch.nn.Module): The model to show.
- input_size (Tuple[int, ...]): The input size of the model.
- depth (int): The maximum depth of the model to show.
- height (float): The height of the image.
"""
plot = torchview.draw_graph(model, input_size=input_size, depth=depth)
# Create temporary file path
tempfile_path = tempfile.mktemp()
plot.visual_graph.render(tempfile_path, format="png")
# Read image and show
image = np.array(Image.open(tempfile_path + ".png"))
self.show_image(image, height=height)
# Remove temporary file
os.remove(tempfile_path)
os.remove(tempfile_path + ".png")
@pytest.fixture
def visual(request: FixtureRequest, visual_UI: UI) -> Generator[VisualFixture, None, None]:
"""
A pytest fixture that manages the visualization process during test execution.
Parameters:
- request (FixtureRequest): The current pytest request.
- visual_UI (UI): An instance of the UI class for user interaction.
Yields:
- VisualFixture: An object to collect visualization statements.
"""
run_visualization, yes_all, reset_all = get_visualization_flags(request)
visualizer = VisualFixture()
storage_path = get_storage_path(request)
if run_visualization:
failed_tests1 = request.session.testsfailed
yield visualizer # Run test
failed_tests2 = request.session.testsfailed
if failed_tests2 > failed_tests1:
return # Test failed, so no visualization
statements = visualizer.statements
if not yes_all:
# Read previous statements
|
class VisualFixture:
def __init__(self):
"""
An object to collect visualization statements.
"""
self.statements: List[Statement] = []
# Core interface
def print(self, text: str) -> None:
"""
Show text within a visualization case.
Parameters:
- text (str): The text to show.
"""
self.statements.append(["print", text])
def show_figure(self, figure: Figure) -> None:
"""
Show a plotly figure within a visualization case.
Parameters:
- fig (Figure): The figure to show.
"""
self.statements.append(["show", str(figure.to_json())])
# Convenience interface
def show_images(
self,
images: List[np.ndarray],
labels: Optional[List[str]] = None,
max_cols: int = 3,
height_per_row: float = 300,
) -> None:
"""
Convenience method to show a grid of images. Only accepts standardized numpy images.
Parameters:
- images (List[np.ndarray]): A list of images to show.
- labels (Optional[List[str]]): A list of labels for each image.
- max_cols (int): Maximum number of columns in the grid.
- height_per_row (float): The height of each row in the grid.
"""
assert all(isinstance(image, np.ndarray) for image in images), "Images must be numpy arrays"
assert len(images) > 0, "At least one image must be specified"
grid_shape = get_grid_shape(len(images), max_cols)
total_height = None if height_per_row is None else height_per_row * grid_shape[0]
figure = create_plot_from_images(images, labels, grid_shape, total_height)
self.show_figure(figure)
def show_image(
self,
image: np.ndarray,
label: Optional[str] = None,
height: float = 600,
) -> None:
"""
Convenience method to show a single image. Only accepts standardized numpy images.
Parameters:
- image (np.ndarray): The image to show.
- label (Optional[str]): A label for the image.
- height (float): The height of the image.
"""
labels = None if label is None else [label]
self.show_images([image], labels, max_cols=1, height_per_row=height)
def show_model(
self,
model,
input_size,
depth: int = 100,
height: float = 1500,
) -> None:
"""
Convenience method to show a PyTorch model. Requires the torchview package.
Parameters:
- model (torch.nn.Module): The model to show.
- input_size (Tuple[int, ...]): The input size of the model.
- depth (int): The maximum depth of the model to show.
- height (float): The height of the image.
"""
plot = torchview.draw_graph(model, input_size=input_size, depth=depth)
# Create temporary file path
tempfile_path = tempfile.mktemp()
plot.visual_graph.render(tempfile_path, format="png")
# Read image and show
image = np.array(Image.open(tempfile_path + ".png"))
self.show_image(image, height=height)
# Remove temporary file
os.remove(tempfile_path)
os.remove(tempfile_path + ".png")
@pytest.fixture
def visual(request: FixtureRequest, visual_UI: UI) -> Generator[VisualFixture, None, None]:
"""
A pytest fixture that manages the visualization process during test execution.
Parameters:
- request (FixtureRequest): The current pytest request.
- visual_UI (UI): An instance of the UI class for user interaction.
Yields:
- VisualFixture: An object to collect visualization statements.
"""
run_visualization, yes_all, reset_all = get_visualization_flags(request)
visualizer = VisualFixture()
storage_path = get_storage_path(request)
if run_visualization:
failed_tests1 = request.session.testsfailed
yield visualizer # Run test
failed_tests2 = request.session.testsfailed
if failed_tests2 > failed_tests1:
return # Test failed, so no visualization
statements = visualizer.statements
if not yes_all:
# Read previous statements | location = Location(request.node.module.__file__, request.node.name) # type: ignore | 9 | 2023-10-18 07:13:37+00:00 | 8k |
SLDGroup/G-CASCADE | test_ISIC2018.py | [
{
"identifier": "PVT_GCASCADE",
"path": "lib/networks.py",
"snippet": "class PVT_GCASCADE(nn.Module):\r\n def __init__(self, n_class=1, img_size=224, k=11, padding=5, conv='mr', gcb_act='gelu', activation='relu', skip_aggregation='additive'):\r\n super(PVT_GCASCADE, self).__init__()\r\n\r\n ... | import torch
import torch.nn.functional as F
import numpy as np
import os, argparse
import sys
import cv2
import pandas as pd
from scipy import misc
from lib.networks import PVT_GCASCADE, MERIT_GCASCADE
from utils.dataloader import test_dataset | 4,902 |
jacard /= len(Y_test)
dice /= len(Y_test)
tanimoto /= len(Y_test)
return jacard, dice, tanimoto
def confusion_matrix_scorer(Y, Y_pred):
Y = Y.astype(np.int8)
Y_pred = Y_pred.astype(np.int8)
P = len(np.where(Y == 1)[0])
N = len(np.where(Y == 0)[0])
#print([P, N])
FP = len(np.where(Y - Y_pred == -1)[0])
FN = len(np.where(Y - Y_pred == 1)[0])
TP = len(np.where(Y + Y_pred ==2)[0])
TN = len(np.where(Y + Y_pred == 0)[0])
return P, N, TN, FP, FN, TP
def get_metrics(Y, pred):
Y = np.reshape(Y, pred.shape)
smooth = 1e-15
P = 0
N = 0
TN = 0
FP = 0
FN = 0
TP = 0
sensitivity = 0
specificity = 0
accuracy = 0
precision = 0
F1 = 0
MCC = 0
for i in range(len(Y)):
_p, _n, _tn, _fp, _fn, _tp = confusion_matrix_scorer(Y[i], pred[i])
P += _p
N += _n
TN += _tn
FP += _fp
FN += _fn
TP += _tp
if (np.sum(Y[i])==0) and (np.sum(pred[i])==0):
sensitivity += 1
specificity += 1
precision += 1
F1 += 1
MCC += 1
else:
if(_tp == 0):
sensitivity += 0
precision += 0
F1 += 0.0
else:
sensitivity += (_tp / (_tp + _fn))
precision += (_tp / (_tp + _fp))
F1 += (2 * ((_tp / (_tp + _fp)) * (_tp / (_tp + _fn))) / ((_tp / (_tp + _fp)) + (_tp / (_tp + _fn))))
if(_tn == 0):
specificity += 0
else:
specificity += (_tn / (_tn + _fp))
MCC += (_tp*_tn - _fp*_fn + smooth)/(np.power((_tp+_fp)*(_tp+_fn)*(_tn+_fp)*(_tn+_fn), 0.5) + smooth)
accuracy += ((_tp + _tn)/(_tp + _fn + _fp + _tn))
return P, N, TN, FP, FN, TP, sensitivity/len(Y), specificity/len(Y), accuracy/len(Y), precision/len(Y), F1/len(Y), MCC/len(Y)
def get_metrics_and_print(Y, yp, method = "PVT-GCASCADE", testset = 'test', threshold = 0.5, show = False, write = False):
rs = []
#yp = preds_test >= threshold #np.round(preds_test,0)
P, N, TN, FP, FN, TP, sensitivity, specificity, accuracy, precision, f1, mcc_cal = get_metrics(Y, yp)
jacard, dice, tanimoto = calculate_metrics(Y, yp)
cmat = [[TN, FP], [FN, TP]]
cmat_score = [[TN/N, FP/N], [FN/P, TP/P]]
print(cmat)
if show:
plt.figure(figsize = (6,6))
sns.heatmap(cmat_score, cmap="Reds", annot=True, fmt = '.2%', square=1, linewidth=2.) #cmat/np.sum(cmat)
plt.xlabel("Predictions")
plt.ylabel("True values")
plt.show()
print("Sensitivity: ", sensitivity)
print("Specificity: ", specificity)
print("Accuracy: ", accuracy)
print("Precision: ", precision)
print("Recall: ", sensitivity)
print("F1 Score: ", f1)
print("MCC: ",mcc_cal)
print('Dice: ', dice)
print('Jacard: ', jacard)
print('Tanimoto: ', tanimoto)
if(write):
results = pd.DataFrame([[method, TN, FP, FN, TP, jacard,
dice, sensitivity, specificity,
accuracy, precision, f1, mcc_cal]],
columns=['Method', 'TN', 'FP', 'FN', 'TP', 'mIoU/Jacard', 'DICE',
'Sensitivity/Recall', 'Specificity', 'Accuracy', 'Precision',
'F-score', 'MCC'])
results.to_csv('results_' + testset + '.csv', mode='a', index=False, header=False)
if __name__ == '__main__':
method_name = 'ISIC2018_811_PVT_GCASCADE_img_size384bs4_Run1'
parser = argparse.ArgumentParser()
parser.add_argument('--encoder', type=str, default='PVT', help='Name of encoder: PVT or MERIT')
parser.add_argument('--skip_aggregation', type=str, default='additive', help='Type of skip-aggregation: additive or concatenation')
parser.add_argument('--testsize', type=int, default=384, help='testing size')
parser.add_argument('--pth_path', type=str, default='./model_pth/'+method_name+'/'+method_name+'.pth')
opt = parser.parse_args()
#torch.cuda.set_device(0) # set your gpu device
if opt.encoder=='PVT':
|
def calculate_metrics(Y_test, yp):
jacard = 0
dice = 0
tanimoto = 0
smooth = 1e-15
for i in range(len(Y_test)):
yp_2 = yp[i].ravel()
y2 = Y_test[i].ravel()
intersection = yp_2 * y2
union = yp_2 + y2 - intersection
only_neg = y2 * (1-yp_2)
only_pos = (1-y2)*yp_2
if (np.sum(y2)==0) and (np.sum(yp_2)==0):
tanimoto += 1.0
jacard += 1.0
dice += 1.0
elif(np.sum(intersection)==0):
tanimoto += 0.0
jacard += 0.0
dice += 0.0
else:
tanimoto += ((np.sum(intersection) + smooth)/(np.sum(intersection) + np.sum(only_neg) + np.sum(only_pos) + smooth))
jacard += ((np.sum(intersection) + smooth)/(np.sum(union) + smooth))
dice += (2. * np.sum(intersection) + smooth) / (np.sum(yp_2) + np.sum(y2) + smooth)
jacard /= len(Y_test)
dice /= len(Y_test)
tanimoto /= len(Y_test)
return jacard, dice, tanimoto
def confusion_matrix_scorer(Y, Y_pred):
Y = Y.astype(np.int8)
Y_pred = Y_pred.astype(np.int8)
P = len(np.where(Y == 1)[0])
N = len(np.where(Y == 0)[0])
#print([P, N])
FP = len(np.where(Y - Y_pred == -1)[0])
FN = len(np.where(Y - Y_pred == 1)[0])
TP = len(np.where(Y + Y_pred ==2)[0])
TN = len(np.where(Y + Y_pred == 0)[0])
return P, N, TN, FP, FN, TP
def get_metrics(Y, pred):
Y = np.reshape(Y, pred.shape)
smooth = 1e-15
P = 0
N = 0
TN = 0
FP = 0
FN = 0
TP = 0
sensitivity = 0
specificity = 0
accuracy = 0
precision = 0
F1 = 0
MCC = 0
for i in range(len(Y)):
_p, _n, _tn, _fp, _fn, _tp = confusion_matrix_scorer(Y[i], pred[i])
P += _p
N += _n
TN += _tn
FP += _fp
FN += _fn
TP += _tp
if (np.sum(Y[i])==0) and (np.sum(pred[i])==0):
sensitivity += 1
specificity += 1
precision += 1
F1 += 1
MCC += 1
else:
if(_tp == 0):
sensitivity += 0
precision += 0
F1 += 0.0
else:
sensitivity += (_tp / (_tp + _fn))
precision += (_tp / (_tp + _fp))
F1 += (2 * ((_tp / (_tp + _fp)) * (_tp / (_tp + _fn))) / ((_tp / (_tp + _fp)) + (_tp / (_tp + _fn))))
if(_tn == 0):
specificity += 0
else:
specificity += (_tn / (_tn + _fp))
MCC += (_tp*_tn - _fp*_fn + smooth)/(np.power((_tp+_fp)*(_tp+_fn)*(_tn+_fp)*(_tn+_fn), 0.5) + smooth)
accuracy += ((_tp + _tn)/(_tp + _fn + _fp + _tn))
return P, N, TN, FP, FN, TP, sensitivity/len(Y), specificity/len(Y), accuracy/len(Y), precision/len(Y), F1/len(Y), MCC/len(Y)
def get_metrics_and_print(Y, yp, method = "PVT-GCASCADE", testset = 'test', threshold = 0.5, show = False, write = False):
rs = []
#yp = preds_test >= threshold #np.round(preds_test,0)
P, N, TN, FP, FN, TP, sensitivity, specificity, accuracy, precision, f1, mcc_cal = get_metrics(Y, yp)
jacard, dice, tanimoto = calculate_metrics(Y, yp)
cmat = [[TN, FP], [FN, TP]]
cmat_score = [[TN/N, FP/N], [FN/P, TP/P]]
print(cmat)
if show:
plt.figure(figsize = (6,6))
sns.heatmap(cmat_score, cmap="Reds", annot=True, fmt = '.2%', square=1, linewidth=2.) #cmat/np.sum(cmat)
plt.xlabel("Predictions")
plt.ylabel("True values")
plt.show()
print("Sensitivity: ", sensitivity)
print("Specificity: ", specificity)
print("Accuracy: ", accuracy)
print("Precision: ", precision)
print("Recall: ", sensitivity)
print("F1 Score: ", f1)
print("MCC: ",mcc_cal)
print('Dice: ', dice)
print('Jacard: ', jacard)
print('Tanimoto: ', tanimoto)
if(write):
results = pd.DataFrame([[method, TN, FP, FN, TP, jacard,
dice, sensitivity, specificity,
accuracy, precision, f1, mcc_cal]],
columns=['Method', 'TN', 'FP', 'FN', 'TP', 'mIoU/Jacard', 'DICE',
'Sensitivity/Recall', 'Specificity', 'Accuracy', 'Precision',
'F-score', 'MCC'])
results.to_csv('results_' + testset + '.csv', mode='a', index=False, header=False)
if __name__ == '__main__':
method_name = 'ISIC2018_811_PVT_GCASCADE_img_size384bs4_Run1'
parser = argparse.ArgumentParser()
parser.add_argument('--encoder', type=str, default='PVT', help='Name of encoder: PVT or MERIT')
parser.add_argument('--skip_aggregation', type=str, default='additive', help='Type of skip-aggregation: additive or concatenation')
parser.add_argument('--testsize', type=int, default=384, help='testing size')
parser.add_argument('--pth_path', type=str, default='./model_pth/'+method_name+'/'+method_name+'.pth')
opt = parser.parse_args()
#torch.cuda.set_device(0) # set your gpu device
if opt.encoder=='PVT': | model = PVT_GCASCADE(n_class=1, img_size=opt.img_size, k=11, padding=5, conv='mr', gcb_act='gelu', skip_aggregation=opt.skip_aggregation) | 0 | 2023-10-24 17:49:10+00:00 | 8k |
StackTipsLab/bloggy | bloggy/models/post.py | [
{
"identifier": "settings",
"path": "bloggy/settings.py",
"snippet": "BASE_DIR = Path(__file__).resolve().parent.parent\nSECRET_KEY = os.getenv(\"SECRET_KEY\", get_random_secret_key())\nDEBUG = os.getenv(\"DEBUG\", \"False\") == \"True\"\nALLOWED_HOSTS = os.getenv(\"ALLOWED_HOSTS\", \"127.0.0.1, localho... | from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.db.models import TextField
from django.urls import reverse
from django.utils.html import format_html
from django.utils.text import slugify
from hitcount.models import HitCount
from bloggy import settings
from bloggy.models import Category, Bookmark
from bloggy.models.course import Course
from bloggy.models.mixin.Content import Content
from bloggy.utils.string_utils import StringUtils
import bloggy | 3,932 |
def upload_thumbnail_image(self, post_id):
return f'uploads/posts/{post_id}'
class Post(Content):
difficulty = models.CharField(
max_length=20, choices=[
('beginner', 'Beginner'),
('intermediate', 'Intermediate'),
('advance', 'advance'),
],
default='easy', blank=True, null=True,
help_text="Select difficulty",
verbose_name="Difficulty level")
is_featured = models.BooleanField(
default=False,
help_text="Should this story be featured on site?"
)
video_id = models.CharField(
max_length=100,
help_text='YouTube Video ID',
null=True,
blank=True
)
github_link = models.CharField(
max_length=200,
help_text='Github project link',
null=True,
blank=True
)
post_type = models.CharField(
max_length=20, choices=settings.get_post_types(),
default='article', blank=True, null=True,
help_text="Post type",
verbose_name="Post type")
template_type = models.CharField(
max_length=20, choices=[
('standard', 'Standard'),
('cover', 'Cover'),
('naked', 'Naked'),
('full', 'Full'),
],
default='standard', blank=True, null=True,
help_text="Template type",
verbose_name="Template type")
content = TextField(null=True, help_text='Post content')
thumbnail = models.ImageField(upload_to=upload_thumbnail_image, blank=True, null=True)
# This comes from Django HitCount
view_count = GenericRelation(
HitCount,
object_id_field='object_pk',
related_query_name='hit_count_generic_relation'
)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='posts'
)
|
def upload_thumbnail_image(self, post_id):
return f'uploads/posts/{post_id}'
class Post(Content):
difficulty = models.CharField(
max_length=20, choices=[
('beginner', 'Beginner'),
('intermediate', 'Intermediate'),
('advance', 'advance'),
],
default='easy', blank=True, null=True,
help_text="Select difficulty",
verbose_name="Difficulty level")
is_featured = models.BooleanField(
default=False,
help_text="Should this story be featured on site?"
)
video_id = models.CharField(
max_length=100,
help_text='YouTube Video ID',
null=True,
blank=True
)
github_link = models.CharField(
max_length=200,
help_text='Github project link',
null=True,
blank=True
)
post_type = models.CharField(
max_length=20, choices=settings.get_post_types(),
default='article', blank=True, null=True,
help_text="Post type",
verbose_name="Post type")
template_type = models.CharField(
max_length=20, choices=[
('standard', 'Standard'),
('cover', 'Cover'),
('naked', 'Naked'),
('full', 'Full'),
],
default='standard', blank=True, null=True,
help_text="Template type",
verbose_name="Template type")
content = TextField(null=True, help_text='Post content')
thumbnail = models.ImageField(upload_to=upload_thumbnail_image, blank=True, null=True)
# This comes from Django HitCount
view_count = GenericRelation(
HitCount,
object_id_field='object_pk',
related_query_name='hit_count_generic_relation'
)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='posts'
) | category = models.ManyToManyField(Category) | 1 | 2023-10-17 14:50:39+00:00 | 8k |
Iniquitatis/sd-webui-temporal | temporal/image_generation.py | [
{
"identifier": "clear_directory",
"path": "temporal/fs.py",
"snippet": "def clear_directory(path, pattern = None):\n if not path.is_dir():\n return path\n\n for entry in path.iterdir():\n if pattern and not entry.match(pattern):\n continue\n\n if entry.is_file():\n... | from copy import copy, deepcopy
from itertools import count
from math import ceil
from pathlib import Path
from PIL import Image
from modules import images, processing
from modules.shared import opts, prompt_styles, state
from temporal.fs import clear_directory, ensure_directory_exists, remove_directory
from temporal.func_utils import make_func_registerer
from temporal.image_buffer import ImageBuffer
from temporal.image_preprocessing import PREPROCESSORS, preprocess_image
from temporal.image_utils import average_images, ensure_image_dims, generate_value_noise_image, save_image
from temporal.metrics import Metrics
from temporal.object_utils import copy_with_overrides
from temporal.session import get_last_frame_index, load_last_frame, load_session, save_session
from temporal.thread_queue import ThreadQueue
from temporal.time_utils import wait_until | 4,047 |
GENERATION_MODES, generation_mode = make_func_registerer(name = "")
image_save_queue = ThreadQueue()
@generation_mode("image", "Image")
def _(p, ext_params):
opts_backup = opts.data.copy()
_apply_prompt_styles(p)
if not _setup_processing(p, ext_params):
return processing.Processed(p, p.init_images)
image_buffer = _make_image_buffer(p, ext_params)
_apply_relative_params(ext_params, p.denoising_strength)
last_processed = processing.Processed(p, [p.init_images[0]])
for i in range(ext_params.frame_count):
if not (processed := _process_iteration(
p = p,
ext_params = ext_params,
image_buffer = image_buffer,
image = last_processed.images[0],
i = i,
frame_index = i + 1,
)):
break
last_processed = processed
_save_processed_image(
p = p,
processed = last_processed,
output_dir = ext_params.output_dir,
)
opts.data.update(opts_backup)
return last_processed
@generation_mode("sequence", "Sequence")
def _(p, ext_params):
opts_backup = opts.data.copy()
opts.save_to_dirs = False
project_dir = ensure_directory_exists(Path(ext_params.output_dir) / ext_params.project_subdir)
if not ext_params.continue_from_last_frame:
clear_directory(project_dir, "*.png")
remove_directory(project_dir / "session" / "buffer")
remove_directory(project_dir / "metrics")
_apply_prompt_styles(p)
if ext_params.load_parameters:
|
GENERATION_MODES, generation_mode = make_func_registerer(name = "")
image_save_queue = ThreadQueue()
@generation_mode("image", "Image")
def _(p, ext_params):
opts_backup = opts.data.copy()
_apply_prompt_styles(p)
if not _setup_processing(p, ext_params):
return processing.Processed(p, p.init_images)
image_buffer = _make_image_buffer(p, ext_params)
_apply_relative_params(ext_params, p.denoising_strength)
last_processed = processing.Processed(p, [p.init_images[0]])
for i in range(ext_params.frame_count):
if not (processed := _process_iteration(
p = p,
ext_params = ext_params,
image_buffer = image_buffer,
image = last_processed.images[0],
i = i,
frame_index = i + 1,
)):
break
last_processed = processed
_save_processed_image(
p = p,
processed = last_processed,
output_dir = ext_params.output_dir,
)
opts.data.update(opts_backup)
return last_processed
@generation_mode("sequence", "Sequence")
def _(p, ext_params):
opts_backup = opts.data.copy()
opts.save_to_dirs = False
project_dir = ensure_directory_exists(Path(ext_params.output_dir) / ext_params.project_subdir)
if not ext_params.continue_from_last_frame:
clear_directory(project_dir, "*.png")
remove_directory(project_dir / "session" / "buffer")
remove_directory(project_dir / "metrics")
_apply_prompt_styles(p)
if ext_params.load_parameters: | load_session(p, ext_params, project_dir) | 14 | 2023-10-15 18:49:12+00:00 | 8k |
zabbix/python-zabbix-utils | tests/test_zabbix_api.py | [
{
"identifier": "ZabbixAPI",
"path": "zabbix_utils/api.py",
"snippet": "class ZabbixAPI():\n \"\"\"Provide interface for working with Zabbix API.\n\n Args:\n url (str, optional): Zabbix API URL. Defaults to `http://localhost/zabbix/api_jsonrpc.php`.\n token (str, optional): Zabbix AP... | import json
import unittest
from unittest.mock import patch
from zabbix_utils.api import ZabbixAPI, APIVersion
from zabbix_utils.common import ModuleUtils
from zabbix_utils.version import __min_supported__, __max_supported__
from zabbix_utils.exceptions import APINotSupported, ProcessingError | 5,048 | # zabbix_utils
#
# Copyright (C) 2001-2023 Zabbix SIA
#
# 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.
DEFAULT_VALUES = {
'user': 'Admin',
'password': 'zabbix',
'token': 'oTmtWu',
'session': 'cc364fb50199c5e305aa91785b7e49a0',
| # zabbix_utils
#
# Copyright (C) 2001-2023 Zabbix SIA
#
# 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.
DEFAULT_VALUES = {
'user': 'Admin',
'password': 'zabbix',
'token': 'oTmtWu',
'session': 'cc364fb50199c5e305aa91785b7e49a0', | 'max_version': "{}.0".format(__max_supported__ + .2), | 3 | 2023-10-16 12:49:35+00:00 | 8k |
miccunifi/TAPE | models/swin_transformer_3d.py | [
{
"identifier": "compute_mask_3D",
"path": "utils/utils_models.py",
"snippet": "def compute_mask_3D(D: int, H: int, W: int, window_size: Tuple[int], shift_size: Tuple[int], device: torch.device)\\\n -> torch.Tensor:\n \"\"\"\n Compute 3D mask for window-based multi-head self-attention\n ... | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import numpy as np
from typing import Tuple
from einops import rearrange
from utils.utils_models import (compute_mask_3D, window_partition_3D, window_reverse_3D, get_window_size, DropPath, Mlp,
trunc_normal_) | 4,391 | # define a parameter table of relative position bias
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1) * (2 * window_size[2] - 1),
num_heads)) # 2*Wd-1 * 2*Wh-1 * 2*Ww-1, nH
# get pair-wise relative position index for each token inside the window
coords_d = torch.arange(self.window_size[0])
coords_h = torch.arange(self.window_size[1])
coords_w = torch.arange(self.window_size[2])
coords = torch.stack(torch.meshgrid(coords_d, coords_h, coords_w)) # 3, Wd, Wh, Ww
coords_flatten = torch.flatten(coords, 1) # 3, Wd*Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 3, Wd*Wh*Ww, Wd*Wh*Ww
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wd*Wh*Ww, Wd*Wh*Ww, 3
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
relative_coords[:, :, 1] += self.window_size[1] - 1
relative_coords[:, :, 2] += self.window_size[2] - 1
relative_coords[:, :, 0] *= (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1)
relative_coords[:, :, 1] *= (2 * self.window_size[2] - 1)
relative_position_index = relative_coords.sum(-1) # Wd*Wh*Ww, Wd*Wh*Ww
self.register_buffer("relative_position_index", relative_position_index)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
trunc_normal_(self.relative_position_bias_table, std=.02)
self.softmax = nn.Softmax(dim=-1)
def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
""" Forward function.
Args:
x (torch.Tensor): input features with shape of (num_windows*B, N, C)
mask (torch.Tensor): (0/-inf) mask with shape of (num_windows, N, N) or None
"""
B_, N, C = x.shape
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # B_, nH, N, C
q = q * self.scale
attn = q @ k.transpose(-2, -1)
relative_position_bias = self.relative_position_bias_table[
self.relative_position_index[:N, :N].reshape(-1)].reshape(
N, N, -1) # Wd*Wh*Ww,Wd*Wh*Ww,nH
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wd*Wh*Ww, Wd*Wh*Ww
attn = attn + relative_position_bias.unsqueeze(0) # B_, nH, N, N
if mask is not None:
nW = mask.shape[0]
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
attn = attn.view(-1, self.num_heads, N, N)
attn = self.softmax(attn)
else:
attn = self.softmax(attn)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class SwinTransformerBlock3D(nn.Module):
""" Swin Transformer Block.
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads.
window_size (tuple[int]): Window size.
shift_size (tuple[int]): Shift size for SW-MSA.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
drop (float, optional): Dropout rate. Default: 0.0
attn_drop (float, optional): Attention dropout rate. Default: 0.0
drop_path (float, optional): Stochastic depth rate. Default: 0.0
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
use_checkpoint (bool): Whether to use gradient checkpointing to save memory. Default: False.
"""
def __init__(self, dim: int,
num_heads: int,
window_size: Tuple[int] = (2, 7, 7),
shift_size: Tuple[int] = (0, 0, 0),
mlp_ratio: float = 4.,
qkv_bias: bool = True,
qk_scale: float = None,
drop: float = 0.,
attn_drop: float = 0.,
drop_path: float = 0.,
act_layer: nn.Module = nn.GELU,
norm_layer: nn.Module = nn.LayerNorm,
use_checkpoint: bool = False):
super().__init__()
self.dim = dim
self.num_heads = num_heads
self.window_size = window_size
self.shift_size = shift_size
self.mlp_ratio = mlp_ratio
self.use_checkpoint = use_checkpoint
assert 0 <= self.shift_size[0] < self.window_size[0], "shift_size must in 0-window_size"
assert 0 <= self.shift_size[1] < self.window_size[1], "shift_size must in 0-window_size"
assert 0 <= self.shift_size[2] < self.window_size[2], "shift_size must in 0-window_size"
self.norm1 = norm_layer(dim)
self.attn = WindowAttention3D(
dim, window_size=self.window_size, num_heads=num_heads,
qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
def forward_part1(self, x: torch.Tensor, mask_matrix: torch.Tensor) -> torch.Tensor:
B, D, H, W, C = x.shape
|
class PatchMerging(nn.Module):
"""
Patch Merging Layer
Args:
dim (int): Number of input channels.
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
"""
def __init__(self, dim: int, norm_layer: nn.Module = nn.LayerNorm):
super().__init__()
self.dim = dim
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
self.norm = norm_layer(4 * dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward function
Args:
x: Input feature, tensor size (B, D, H, W, C).
"""
B, D, H, W, C = x.shape
# padding
pad_input = (H % 2 == 1) or (W % 2 == 1)
if pad_input:
x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
x0 = x[:, :, 0::2, 0::2, :] # B D H/2 W/2 C
x1 = x[:, :, 1::2, 0::2, :] # B D H/2 W/2 C
x2 = x[:, :, 0::2, 1::2, :] # B D H/2 W/2 C
x3 = x[:, :, 1::2, 1::2, :] # B D H/2 W/2 C
x = torch.cat([x0, x1, x2, x3], -1) # B D H/2 W/2 4*C
x = self.norm(x)
x = self.reduction(x)
return x
class PatchExpand(nn.Module):
"""
Patch Expand Layer
Args:
embed_dim (int): Embedding dimension.
"""
def __init__(self, embed_dim: int):
super().__init__()
self.before_conv = nn.Conv2d(embed_dim, embed_dim * 2, 3, 1, 1)
self.pixel_shuffle = nn.PixelShuffle(upscale_factor=2)
self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
self.after_conv = nn.Conv2d(embed_dim // 2, embed_dim // 2, 3, 1, 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, C, T, H, W = x.shape
x = rearrange(x, 'b c t h w -> b t c h w').reshape(B * T, C, H, W)
x = self.before_conv(x)
x = self.pixel_shuffle(x)
x = self.after_conv(self.lrelu(x))
_, C, H, W = x.shape
x = rearrange(x.reshape(B, T, C, H, W), 'b t c h w -> b c t h w')
return x
class WindowAttention3D(nn.Module):
"""
Window based 3D multi-head self attention (W-MSA) module with relative position bias.
It supports both shifted and non-shifted window.
Args:
dim (int): Number of input channels.
window_size (tuple[int]): The temporal length, height and width of the window.
num_heads (int): Number of attention heads.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
"""
def __init__(self,
dim: int,
window_size: Tuple[int],
num_heads: int,
qkv_bias: bool = False,
qk_scale: float = None,
attn_drop: float = 0.,
proj_drop: float = 0.):
super().__init__()
self.dim = dim
self.window_size = window_size # Wd, Wh, Ww
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
# define a parameter table of relative position bias
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1) * (2 * window_size[2] - 1),
num_heads)) # 2*Wd-1 * 2*Wh-1 * 2*Ww-1, nH
# get pair-wise relative position index for each token inside the window
coords_d = torch.arange(self.window_size[0])
coords_h = torch.arange(self.window_size[1])
coords_w = torch.arange(self.window_size[2])
coords = torch.stack(torch.meshgrid(coords_d, coords_h, coords_w)) # 3, Wd, Wh, Ww
coords_flatten = torch.flatten(coords, 1) # 3, Wd*Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 3, Wd*Wh*Ww, Wd*Wh*Ww
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wd*Wh*Ww, Wd*Wh*Ww, 3
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
relative_coords[:, :, 1] += self.window_size[1] - 1
relative_coords[:, :, 2] += self.window_size[2] - 1
relative_coords[:, :, 0] *= (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1)
relative_coords[:, :, 1] *= (2 * self.window_size[2] - 1)
relative_position_index = relative_coords.sum(-1) # Wd*Wh*Ww, Wd*Wh*Ww
self.register_buffer("relative_position_index", relative_position_index)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
trunc_normal_(self.relative_position_bias_table, std=.02)
self.softmax = nn.Softmax(dim=-1)
def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
""" Forward function.
Args:
x (torch.Tensor): input features with shape of (num_windows*B, N, C)
mask (torch.Tensor): (0/-inf) mask with shape of (num_windows, N, N) or None
"""
B_, N, C = x.shape
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # B_, nH, N, C
q = q * self.scale
attn = q @ k.transpose(-2, -1)
relative_position_bias = self.relative_position_bias_table[
self.relative_position_index[:N, :N].reshape(-1)].reshape(
N, N, -1) # Wd*Wh*Ww,Wd*Wh*Ww,nH
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wd*Wh*Ww, Wd*Wh*Ww
attn = attn + relative_position_bias.unsqueeze(0) # B_, nH, N, N
if mask is not None:
nW = mask.shape[0]
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
attn = attn.view(-1, self.num_heads, N, N)
attn = self.softmax(attn)
else:
attn = self.softmax(attn)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class SwinTransformerBlock3D(nn.Module):
""" Swin Transformer Block.
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads.
window_size (tuple[int]): Window size.
shift_size (tuple[int]): Shift size for SW-MSA.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
drop (float, optional): Dropout rate. Default: 0.0
attn_drop (float, optional): Attention dropout rate. Default: 0.0
drop_path (float, optional): Stochastic depth rate. Default: 0.0
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
use_checkpoint (bool): Whether to use gradient checkpointing to save memory. Default: False.
"""
def __init__(self, dim: int,
num_heads: int,
window_size: Tuple[int] = (2, 7, 7),
shift_size: Tuple[int] = (0, 0, 0),
mlp_ratio: float = 4.,
qkv_bias: bool = True,
qk_scale: float = None,
drop: float = 0.,
attn_drop: float = 0.,
drop_path: float = 0.,
act_layer: nn.Module = nn.GELU,
norm_layer: nn.Module = nn.LayerNorm,
use_checkpoint: bool = False):
super().__init__()
self.dim = dim
self.num_heads = num_heads
self.window_size = window_size
self.shift_size = shift_size
self.mlp_ratio = mlp_ratio
self.use_checkpoint = use_checkpoint
assert 0 <= self.shift_size[0] < self.window_size[0], "shift_size must in 0-window_size"
assert 0 <= self.shift_size[1] < self.window_size[1], "shift_size must in 0-window_size"
assert 0 <= self.shift_size[2] < self.window_size[2], "shift_size must in 0-window_size"
self.norm1 = norm_layer(dim)
self.attn = WindowAttention3D(
dim, window_size=self.window_size, num_heads=num_heads,
qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
def forward_part1(self, x: torch.Tensor, mask_matrix: torch.Tensor) -> torch.Tensor:
B, D, H, W, C = x.shape | window_size, shift_size = get_window_size((D, H, W), self.window_size, self.shift_size) | 3 | 2023-10-19 09:14:40+00:00 | 8k |
OPTML-Group/Diffusion-MU-Attack | src/tasks/classifier_.py | [
{
"identifier": "calculate_clip_score",
"path": "src/tasks/utils/metrics/clip_score.py",
"snippet": "def calculate_clip_score(images, prompts,device):\n clip_score = clip_score_fn(torch.from_numpy(images).to(device), prompts).detach()\n return round(float(clip_score), 4)"
},
{
"identifier"... | import os
import torch
import torch.nn.functional as F
from copy import deepcopy
from diffusers import AutoencoderKL, UNet2DConditionModel, LMSDiscreteScheduler
from transformers import CLIPTextModel, CLIPTokenizer
from PIL import Image
from uuid import uuid4
from .utils.metrics.clip_score import calculate_clip_score
from .utils.metrics.nudity_eval import if_nude, detectNudeClasses
from .utils.metrics.harm_eval import q16_binary_classifier, harm_eval
from .utils.metrics.style_eval import style_eval,init_classifier
from .utils.metrics.object_eval import imagenet_ResNet50, object_eval
from .utils.text_encoder import CustomTextEncoder
from .utils.datasets import get as get_dataset
from tqdm.auto import tqdm | 4,886 | self.scheduler.set_timesteps(num_inference_steps)
# Hyperparameters for different SLD Modes
safety_momentum = None
if self.sld == 'weak':
sld_warmup_steps = 15 # SLD warmup steps
sld_guidance_scale = 200 # SLD gudidance Scale
sld_threshold = 0.0 # SLD threshold
sld_momentum_scale = 0.0 # SLD momentum scale
sld_mom_beta = 0.0 # SLD momentum beta
elif self.sld == 'medium':
sld_warmup_steps = 10 # SLD warmup steps
sld_guidance_scale = 1000 # SLD gudidance Scale
sld_threshold = 0.01 # SLD threshold
sld_momentum_scale = 0.3 # SLD momentum scale
sld_mom_beta = 0.4 # SLD momentum beta
elif self.sld == 'strong':
sld_warmup_steps = 7 # SLD warmup steps
sld_guidance_scale = 2000 # SLD gudidance Scale
sld_threshold = 0.025 # SLD threshold
sld_momentum_scale = 0.5 # SLD momentum scale
sld_mom_beta = 0.7 # SLD momentum beta
elif self.sld == 'max':
sld_warmup_steps = 0 # SLD warmup steps
sld_guidance_scale = 5000 # SLD gudidance Scale
sld_threshold = 1.0 # SLD threshold
sld_momentum_scale = 0.5 # SLD momentum scale
sld_mom_beta = 0.7 # SLD momentum beta
for t in tqdm(self.scheduler.timesteps):
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
latent_model_input = latents
latent_model_input = self.scheduler.scale_model_input(latent_model_input, timestep=t)
# predict the noise residual
with torch.no_grad():
noise_pred_uncond = self.target_unet_sd(latent_model_input, t, encoder_hidden_states=uncond_embeddings).sample
noise_pred_text = self.target_unet_sd(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
# perform guidance
# noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
# Perform SLD guidance
if self.sld is not None:
noise_guidance = noise_pred_text - noise_pred_uncond
with torch.no_grad():
noise_pred_safety_concept = self.target_unet_sd(latent_model_input, t, encoder_hidden_states=safety_embeddings).sample
if safety_momentum is None:
safety_momentum = torch.zeros_like(noise_pred_text)
# Equation 6
scale = torch.clamp(
torch.abs((noise_pred_text - noise_pred_safety_concept)) * sld_guidance_scale, max=1.)
# Equation 6
safety_concept_scale = torch.where(
(noise_pred_text - noise_pred_safety_concept) >= sld_threshold,
torch.zeros_like(scale), scale)
# Equation 4
noise_guidance_safety = torch.mul(
(noise_pred_safety_concept - noise_pred_uncond), safety_concept_scale)
# Equation 7
noise_guidance_safety = noise_guidance_safety + sld_momentum_scale * safety_momentum
# Equation 8
safety_momentum = sld_mom_beta * safety_momentum + (1 - sld_mom_beta) * noise_guidance_safety
if t >= sld_warmup_steps: # Warmup
# Equation 3
noise_guidance = noise_guidance - noise_guidance_safety
noise_pred = noise_pred_uncond + guidance_scale * noise_guidance
else:
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
# scale and decode the image latents with vae
latents = 1 / 0.18215 * latents
with torch.no_grad():
image = self.vae.decode(latents).sample
image = (image / 2 + 0.5).clamp(0, 1)
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
images = (image * 255).round().astype("uint8")
return images[0]
def eval(self,input_ids,prompt,seed=0,batch_size=1,height=512,width=512,guidance_scale=7.5):
results = {}
text_input = self.tokenizer(
prompt, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt",truncation=True
)
text_embeddings = self.id2embedding(text_input.input_ids.to(self.device))
image = self.sampling(input_ids,text_embeddings,batch_size=batch_size,seed=seed,height=height,width=width,num_inference_steps=self.sampling_step_num,guidance_scale=guidance_scale)
# results['clipscore'] = calculate_clip_score(image, prompt,self.device)
results['image'] = Image.fromarray(image)
img_tmp_path = os.path.join(self.cache_path, f'{uuid4()}.png')
# store in the local cache for detectNudeClasses
results['image'].save(img_tmp_path)
if self.concept == 'nudity':
results['nude'] = detectNudeClasses([img_tmp_path], threshold=0.)[0]
results['success'] = if_nude(results['nude'], threshold=0.45)
if len(results['nude']) != 0:
results['score'] = max(results['nude'].values())
else:
results['score'] = 0
elif self.concept == 'vangogh':
results['style'] = style_eval(self.classifier,results['image'])[:10]
# results['style'].sort(key=lambda x: x['score'], reverse=True)
# results['score'] = next(filter(lambda x: x['label'] == 'vincent-van-gogh', results['style']))['score']
# results['success'] = 'vincent-van-gogh' in list(map(lambda x: x['label'], results['style'][:10]))
elif self.concept in self.object_list:
|
class ClassifierTask:
def __init__(
self,
concept,
sld,
sld_concept,
negative_prompt,
model_name_or_path,
target_ckpt,
cache_path,
dataset_path,
criterion,
sampling_step_num,
n_samples = 50,
classifier_dir = None,
):
self.object_list = ['cassette_player', 'church', 'english_springer', 'french_horn', 'garbage_truck', 'gas_pump', 'golf_ball', 'parachute', 'tench', "chain_saw"]
self.object_labels = [482, 497, 217, 566, 569, 571, 574, 701, 0, 491]
self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
self.concept = concept
self.sld = sld
self.sld_concept = sld_concept
self.negative_prompt = negative_prompt
self.cache_path = cache_path
self.sampling_step_num = sampling_step_num
self.dataset = get_dataset(dataset_path)
self.criterion = torch.nn.L1Loss() if criterion == 'l1' else torch.nn.MSELoss()
self.vae = AutoencoderKL.from_pretrained(model_name_or_path, subfolder="vae", cache_dir=cache_path).to(self.device)
self.tokenizer = CLIPTokenizer.from_pretrained(model_name_or_path, subfolder="tokenizer", cache_dir=cache_path)
self.text_encoder = CLIPTextModel.from_pretrained(model_name_or_path, subfolder="text_encoder", cache_dir=cache_path).to(self.device)
self.custom_text_encoder = CustomTextEncoder(self.text_encoder).to(self.device)
self.all_embeddings = self.custom_text_encoder.get_all_embedding().unsqueeze(0)
self.unet_sd = UNet2DConditionModel.from_pretrained(model_name_or_path, subfolder="unet", cache_dir=cache_path).to(self.device)
self.target_unet_sd = deepcopy(self.unet_sd)
if self.sld is None:
self.target_unet_sd.load_state_dict(torch.load(target_ckpt, map_location=self.device))
if classifier_dir is not None:
self.classifier = init_classifier(self.device,classifier_dir)
elif self.concept in self.object_list:
self.processor, self.classifier = imagenet_ResNet50(self.device)
elif self.concept == 'harm':
self.clip_model, self.classifier = q16_binary_classifier(self.device)
self.scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
self.T = 1000
self.n_samples = n_samples
start = self.T // self.n_samples // 2
self.sampled_t = list(range(start, self.T, self.T // self.n_samples))[:self.n_samples]
for m in [self.vae, self.text_encoder, self.custom_text_encoder, self.unet_sd, self.target_unet_sd]:
m.eval()
m.requires_grad_(False)
def get_loss(self,x0,t,input_ids,input_embeddings,**kwargs):
x0 = x0.to(self.device)
x0 = x0.repeat(input_embeddings.shape[0], 1, 1, 1)
noise = torch.randn((1, 4, 64, 64), device=self.device)
noise = noise.repeat(input_embeddings.shape[0], 1, 1, 1)
noised_latent = x0 * (self.scheduler.alphas_cumprod[t] ** 0.5).view(-1, 1, 1, 1).to(self.device) + \
noise * ((1 - self.scheduler.alphas_cumprod[t]) ** 0.5).view(-1, 1, 1, 1).to(self.device)
encoder_hidden_states = self.custom_text_encoder(input_ids = input_ids,inputs_embeds=input_embeddings)[0]
noise_pred = self.target_unet_sd(noised_latent,t,encoder_hidden_states=encoder_hidden_states).sample
error = self.criterion(noise,noise_pred)
return error
def str2id(self,prompt):
text_input = self.tokenizer(
prompt, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt",truncation=True
)
return text_input.input_ids.to(self.device)
def img2latent(self,image):
with torch.no_grad():
img_input = image.unsqueeze(0).to(self.device)
x0 = self.vae.encode(img_input).latent_dist.mean
x0 *= 0.18215
return x0
def id2embedding(self,input_ids):
input_one_hot = F.one_hot(input_ids.view(-1), num_classes = len(self.tokenizer.get_vocab())).float()
input_one_hot = torch.unsqueeze(input_one_hot,0).to(self.device)
input_embeds = input_one_hot @ self.all_embeddings
return input_embeds
def sampling(self,input_ids,text_embeddings,batch_size=1,seed=0,height=512,width=512,num_inference_steps=50,guidance_scale=7.5):
text_embeddings = self.custom_text_encoder(input_ids = input_ids, inputs_embeds=text_embeddings)[0]
# Negative prompt or Not
if self.negative_prompt is not None:
uncond_input = self.tokenizer(
[self.negative_prompt] * batch_size, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt"
)
else:
uncond_input = self.tokenizer(
[""] * batch_size, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt"
)
uncond_embeddings = self.id2embedding(uncond_input.input_ids.to(self.device))
uncond_embeddings = self.custom_text_encoder(input_ids = uncond_input.input_ids.to(self.device), inputs_embeds=uncond_embeddings)[0]
# Generate safety embedding for SLD
if self.sld is not None:
if self.sld_concept is not None:
safety_concept = str(self.sld_concept)
else:
safety_concept = 'hate, harassment, violence, suffering, humiliation, harm, suicide, ' \
'sexual, nudity, bodily fluids, blood, obscene gestures, illegal activity, ' \
'drug use, theft, vandalism, weapons, child abuse, brutality, cruelty'
safety_input = self.tokenizer(
[safety_concept] * batch_size, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt"
)
safety_embeddings = self.id2embedding(safety_input.input_ids.to(self.device))
safety_embeddings = self.custom_text_encoder(input_ids = safety_input.input_ids.to(self.device), inputs_embeds=safety_embeddings)[0]
generator = torch.manual_seed(seed)
latents = torch.randn(
(batch_size, self.target_unet_sd.config.in_channels, height // 8, width // 8),
generator=generator,
)
latents = latents.to(self.device)
self.scheduler.set_timesteps(num_inference_steps)
latents = latents * self.scheduler.init_noise_sigma
self.scheduler.set_timesteps(num_inference_steps)
# Hyperparameters for different SLD Modes
safety_momentum = None
if self.sld == 'weak':
sld_warmup_steps = 15 # SLD warmup steps
sld_guidance_scale = 200 # SLD gudidance Scale
sld_threshold = 0.0 # SLD threshold
sld_momentum_scale = 0.0 # SLD momentum scale
sld_mom_beta = 0.0 # SLD momentum beta
elif self.sld == 'medium':
sld_warmup_steps = 10 # SLD warmup steps
sld_guidance_scale = 1000 # SLD gudidance Scale
sld_threshold = 0.01 # SLD threshold
sld_momentum_scale = 0.3 # SLD momentum scale
sld_mom_beta = 0.4 # SLD momentum beta
elif self.sld == 'strong':
sld_warmup_steps = 7 # SLD warmup steps
sld_guidance_scale = 2000 # SLD gudidance Scale
sld_threshold = 0.025 # SLD threshold
sld_momentum_scale = 0.5 # SLD momentum scale
sld_mom_beta = 0.7 # SLD momentum beta
elif self.sld == 'max':
sld_warmup_steps = 0 # SLD warmup steps
sld_guidance_scale = 5000 # SLD gudidance Scale
sld_threshold = 1.0 # SLD threshold
sld_momentum_scale = 0.5 # SLD momentum scale
sld_mom_beta = 0.7 # SLD momentum beta
for t in tqdm(self.scheduler.timesteps):
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
latent_model_input = latents
latent_model_input = self.scheduler.scale_model_input(latent_model_input, timestep=t)
# predict the noise residual
with torch.no_grad():
noise_pred_uncond = self.target_unet_sd(latent_model_input, t, encoder_hidden_states=uncond_embeddings).sample
noise_pred_text = self.target_unet_sd(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
# perform guidance
# noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
# Perform SLD guidance
if self.sld is not None:
noise_guidance = noise_pred_text - noise_pred_uncond
with torch.no_grad():
noise_pred_safety_concept = self.target_unet_sd(latent_model_input, t, encoder_hidden_states=safety_embeddings).sample
if safety_momentum is None:
safety_momentum = torch.zeros_like(noise_pred_text)
# Equation 6
scale = torch.clamp(
torch.abs((noise_pred_text - noise_pred_safety_concept)) * sld_guidance_scale, max=1.)
# Equation 6
safety_concept_scale = torch.where(
(noise_pred_text - noise_pred_safety_concept) >= sld_threshold,
torch.zeros_like(scale), scale)
# Equation 4
noise_guidance_safety = torch.mul(
(noise_pred_safety_concept - noise_pred_uncond), safety_concept_scale)
# Equation 7
noise_guidance_safety = noise_guidance_safety + sld_momentum_scale * safety_momentum
# Equation 8
safety_momentum = sld_mom_beta * safety_momentum + (1 - sld_mom_beta) * noise_guidance_safety
if t >= sld_warmup_steps: # Warmup
# Equation 3
noise_guidance = noise_guidance - noise_guidance_safety
noise_pred = noise_pred_uncond + guidance_scale * noise_guidance
else:
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
# scale and decode the image latents with vae
latents = 1 / 0.18215 * latents
with torch.no_grad():
image = self.vae.decode(latents).sample
image = (image / 2 + 0.5).clamp(0, 1)
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
images = (image * 255).round().astype("uint8")
return images[0]
def eval(self,input_ids,prompt,seed=0,batch_size=1,height=512,width=512,guidance_scale=7.5):
results = {}
text_input = self.tokenizer(
prompt, padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt",truncation=True
)
text_embeddings = self.id2embedding(text_input.input_ids.to(self.device))
image = self.sampling(input_ids,text_embeddings,batch_size=batch_size,seed=seed,height=height,width=width,num_inference_steps=self.sampling_step_num,guidance_scale=guidance_scale)
# results['clipscore'] = calculate_clip_score(image, prompt,self.device)
results['image'] = Image.fromarray(image)
img_tmp_path = os.path.join(self.cache_path, f'{uuid4()}.png')
# store in the local cache for detectNudeClasses
results['image'].save(img_tmp_path)
if self.concept == 'nudity':
results['nude'] = detectNudeClasses([img_tmp_path], threshold=0.)[0]
results['success'] = if_nude(results['nude'], threshold=0.45)
if len(results['nude']) != 0:
results['score'] = max(results['nude'].values())
else:
results['score'] = 0
elif self.concept == 'vangogh':
results['style'] = style_eval(self.classifier,results['image'])[:10]
# results['style'].sort(key=lambda x: x['score'], reverse=True)
# results['score'] = next(filter(lambda x: x['label'] == 'vincent-van-gogh', results['style']))['score']
# results['success'] = 'vincent-van-gogh' in list(map(lambda x: x['label'], results['style'][:10]))
elif self.concept in self.object_list: | results['object'], logits = object_eval(self.classifier,results['image'], processor=self.processor, device=self.device) | 8 | 2023-10-17 13:54:37+00:00 | 8k |
YefanZhou/TempBalance | object_detection/src/YOLOv8/ultralytics/nn/modules/transformer.py | [
{
"identifier": "Conv",
"path": "object_detection/src/YOLOv8/ultralytics/nn/modules/conv.py",
"snippet": "class Conv(nn.Module):\n \"\"\"Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation).\"\"\"\n default_act = nn.SiLU() # default activation\n\n ... | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import constant_, xavier_uniform_
from .conv import Conv
from .utils import _get_clones, inverse_sigmoid, multi_scale_deformable_attn_pytorch | 4,455 | xavier_uniform_(self.value_proj.weight.data)
constant_(self.value_proj.bias.data, 0.)
xavier_uniform_(self.output_proj.weight.data)
constant_(self.output_proj.bias.data, 0.)
def forward(self, query, reference_points, value, value_spatial_shapes, value_mask=None):
"""
https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
Args:
query (Tensor): [bs, query_length, C]
reference_points (Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),
bottom-right (1, 1), including padding area
value (Tensor): [bs, value_length, C]
value_spatial_shapes (List): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
value_mask (Tensor): [bs, value_length], True for non-padding elements, False for padding elements
Returns:
output (Tensor): [bs, Length_{query}, C]
"""
bs, len_q = query.shape[:2]
_, len_v = value.shape[:2]
assert sum(s[0] * s[1] for s in value_spatial_shapes) == len_v
value = self.value_proj(value)
if value_mask is not None:
value = value.masked_fill(value_mask[..., None], float(0))
value = value.view(bs, len_v, self.n_heads, self.d_model // self.n_heads)
sampling_offsets = self.sampling_offsets(query).view(bs, len_q, self.n_heads, self.n_levels, self.n_points, 2)
attention_weights = self.attention_weights(query).view(bs, len_q, self.n_heads, self.n_levels * self.n_points)
attention_weights = F.softmax(attention_weights, -1).view(bs, len_q, self.n_heads, self.n_levels, self.n_points)
# N, Len_q, n_heads, n_levels, n_points, 2
n = reference_points.shape[-1]
if n == 2:
offset_normalizer = torch.as_tensor(value_spatial_shapes, dtype=query.dtype, device=query.device).flip(-1)
add = sampling_offsets / offset_normalizer[None, None, None, :, None, :]
sampling_locations = reference_points[:, :, None, :, None, :] + add
elif n == 4:
add = sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
sampling_locations = reference_points[:, :, None, :, None, :2] + add
else:
raise ValueError(f'Last dim of reference_points must be 2 or 4, but got {n}.')
output = multi_scale_deformable_attn_pytorch(value, value_spatial_shapes, sampling_locations, attention_weights)
output = self.output_proj(output)
return output
class DeformableTransformerDecoderLayer(nn.Module):
"""
https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py
"""
def __init__(self, d_model=256, n_heads=8, d_ffn=1024, dropout=0., act=nn.ReLU(), n_levels=4, n_points=4):
super().__init__()
# self attention
self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
# cross attention
self.cross_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points)
self.dropout2 = nn.Dropout(dropout)
self.norm2 = nn.LayerNorm(d_model)
# ffn
self.linear1 = nn.Linear(d_model, d_ffn)
self.act = act
self.dropout3 = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ffn, d_model)
self.dropout4 = nn.Dropout(dropout)
self.norm3 = nn.LayerNorm(d_model)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward_ffn(self, tgt):
tgt2 = self.linear2(self.dropout3(self.act(self.linear1(tgt))))
tgt = tgt + self.dropout4(tgt2)
tgt = self.norm3(tgt)
return tgt
def forward(self,
tgt,
reference_points,
src,
src_spatial_shapes,
src_padding_mask=None,
attn_mask=None,
query_pos=None):
# self attention
q = k = self.with_pos_embed(tgt, query_pos)
if attn_mask is not None:
attn_mask = torch.where(attn_mask.astype('bool'), torch.zeros(attn_mask.shape, tgt.dtype),
torch.full(attn_mask.shape, float('-inf'), tgt.dtype))
tgt2 = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), tgt.transpose(0, 1))[0].transpose(0, 1)
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
# cross attention
tgt2 = self.cross_attn(self.with_pos_embed(tgt, query_pos), reference_points, src, src_spatial_shapes,
src_padding_mask)
tgt = tgt + self.dropout2(tgt2)
tgt = self.norm2(tgt)
# ffn
tgt = self.forward_ffn(tgt)
return tgt
class DeformableTransformerDecoder(nn.Module):
"""
https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
"""
def __init__(self, hidden_dim, decoder_layer, num_layers, eval_idx=-1):
super().__init__()
| # Ultralytics YOLO 🚀, AGPL-3.0 license
"""
Transformer modules
"""
__all__ = [
'TransformerEncoderLayer', 'TransformerLayer', 'TransformerBlock', 'MLPBlock', 'LayerNorm2d', 'AIFI',
'DeformableTransformerDecoder', 'DeformableTransformerDecoderLayer', 'MSDeformAttn', 'MLP']
class TransformerEncoderLayer(nn.Module):
"""Transformer Encoder."""
def __init__(self, c1, cm=2048, num_heads=8, dropout=0.0, act=nn.GELU(), normalize_before=False):
super().__init__()
self.ma = nn.MultiheadAttention(c1, num_heads, dropout=dropout, batch_first=True)
# Implementation of Feedforward model
self.fc1 = nn.Linear(c1, cm)
self.fc2 = nn.Linear(cm, c1)
self.norm1 = nn.LayerNorm(c1)
self.norm2 = nn.LayerNorm(c1)
self.dropout = nn.Dropout(dropout)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.act = act
self.normalize_before = normalize_before
def with_pos_embed(self, tensor, pos=None):
"""Add position embeddings if given."""
return tensor if pos is None else tensor + pos
def forward_post(self, src, src_mask=None, src_key_padding_mask=None, pos=None):
q = k = self.with_pos_embed(src, pos)
src2 = self.ma(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]
src = src + self.dropout1(src2)
src = self.norm1(src)
src2 = self.fc2(self.dropout(self.act(self.fc1(src))))
src = src + self.dropout2(src2)
src = self.norm2(src)
return src
def forward_pre(self, src, src_mask=None, src_key_padding_mask=None, pos=None):
src2 = self.norm1(src)
q = k = self.with_pos_embed(src2, pos)
src2 = self.ma(q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]
src = src + self.dropout1(src2)
src2 = self.norm2(src)
src2 = self.fc2(self.dropout(self.act(self.fc1(src2))))
src = src + self.dropout2(src2)
return src
def forward(self, src, src_mask=None, src_key_padding_mask=None, pos=None):
"""Forward propagates the input through the encoder module."""
if self.normalize_before:
return self.forward_pre(src, src_mask, src_key_padding_mask, pos)
return self.forward_post(src, src_mask, src_key_padding_mask, pos)
class AIFI(TransformerEncoderLayer):
def __init__(self, c1, cm=2048, num_heads=8, dropout=0, act=nn.GELU(), normalize_before=False):
super().__init__(c1, cm, num_heads, dropout, act, normalize_before)
def forward(self, x):
c, h, w = x.shape[1:]
pos_embed = self.build_2d_sincos_position_embedding(w, h, c)
# flatten [B, C, H, W] to [B, HxW, C]
x = super().forward(x.flatten(2).permute(0, 2, 1), pos=pos_embed.to(device=x.device, dtype=x.dtype))
return x.permute((0, 2, 1)).view([-1, c, h, w])
@staticmethod
def build_2d_sincos_position_embedding(w, h, embed_dim=256, temperature=10000.):
grid_w = torch.arange(int(w), dtype=torch.float32)
grid_h = torch.arange(int(h), dtype=torch.float32)
grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing='ij')
assert embed_dim % 4 == 0, \
'Embed dimension must be divisible by 4 for 2D sin-cos position embedding'
pos_dim = embed_dim // 4
omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim
omega = 1. / (temperature ** omega)
out_w = grid_w.flatten()[..., None] @ omega[None]
out_h = grid_h.flatten()[..., None] @ omega[None]
return torch.concat([torch.sin(out_w), torch.cos(out_w),
torch.sin(out_h), torch.cos(out_h)], axis=1)[None, :, :]
class TransformerLayer(nn.Module):
"""Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)."""
def __init__(self, c, num_heads):
"""Initializes a self-attention mechanism using linear transformations and multi-head attention."""
super().__init__()
self.q = nn.Linear(c, c, bias=False)
self.k = nn.Linear(c, c, bias=False)
self.v = nn.Linear(c, c, bias=False)
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
self.fc1 = nn.Linear(c, c, bias=False)
self.fc2 = nn.Linear(c, c, bias=False)
def forward(self, x):
"""Apply a transformer block to the input x and return the output."""
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
x = self.fc2(self.fc1(x)) + x
return x
class TransformerBlock(nn.Module):
"""Vision Transformer https://arxiv.org/abs/2010.11929."""
def __init__(self, c1, c2, num_heads, num_layers):
"""Initialize a Transformer module with position embedding and specified number of heads and layers."""
super().__init__()
self.conv = None
if c1 != c2:
self.conv = Conv(c1, c2)
self.linear = nn.Linear(c2, c2) # learnable position embedding
self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))
self.c2 = c2
def forward(self, x):
"""Forward propagates the input through the bottleneck module."""
if self.conv is not None:
x = self.conv(x)
b, _, w, h = x.shape
p = x.flatten(2).permute(2, 0, 1)
return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)
class MLPBlock(nn.Module):
def __init__(self, embedding_dim, mlp_dim, act=nn.GELU):
super().__init__()
self.lin1 = nn.Linear(embedding_dim, mlp_dim)
self.lin2 = nn.Linear(mlp_dim, embedding_dim)
self.act = act()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.lin2(self.act(self.lin1(x)))
class MLP(nn.Module):
""" Very simple multi-layer perceptron (also called FFN)"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
class LayerNorm2d(nn.Module):
def __init__(self, num_channels, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(num_channels))
self.bias = nn.Parameter(torch.zeros(num_channels))
self.eps = eps
def forward(self, x):
u = x.mean(1, keepdim=True)
s = (x - u).pow(2).mean(1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.eps)
x = self.weight[:, None, None] * x + self.bias[:, None, None]
return x
class MSDeformAttn(nn.Module):
"""
Original Multi-Scale Deformable Attention Module.
https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py
"""
def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4):
super().__init__()
if d_model % n_heads != 0:
raise ValueError(f'd_model must be divisible by n_heads, but got {d_model} and {n_heads}')
_d_per_head = d_model // n_heads
# you'd better set _d_per_head to a power of 2 which is more efficient in our CUDA implementation
assert _d_per_head * n_heads == d_model, '`d_model` must be divisible by `n_heads`'
self.im2col_step = 64
self.d_model = d_model
self.n_levels = n_levels
self.n_heads = n_heads
self.n_points = n_points
self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)
self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points)
self.value_proj = nn.Linear(d_model, d_model)
self.output_proj = nn.Linear(d_model, d_model)
self._reset_parameters()
def _reset_parameters(self):
constant_(self.sampling_offsets.weight.data, 0.)
thetas = torch.arange(self.n_heads, dtype=torch.float32) * (2.0 * math.pi / self.n_heads)
grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
grid_init = (grid_init / grid_init.abs().max(-1, keepdim=True)[0]).view(self.n_heads, 1, 1, 2).repeat(
1, self.n_levels, self.n_points, 1)
for i in range(self.n_points):
grid_init[:, :, i, :] *= i + 1
with torch.no_grad():
self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))
constant_(self.attention_weights.weight.data, 0.)
constant_(self.attention_weights.bias.data, 0.)
xavier_uniform_(self.value_proj.weight.data)
constant_(self.value_proj.bias.data, 0.)
xavier_uniform_(self.output_proj.weight.data)
constant_(self.output_proj.bias.data, 0.)
def forward(self, query, reference_points, value, value_spatial_shapes, value_mask=None):
"""
https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
Args:
query (Tensor): [bs, query_length, C]
reference_points (Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),
bottom-right (1, 1), including padding area
value (Tensor): [bs, value_length, C]
value_spatial_shapes (List): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
value_mask (Tensor): [bs, value_length], True for non-padding elements, False for padding elements
Returns:
output (Tensor): [bs, Length_{query}, C]
"""
bs, len_q = query.shape[:2]
_, len_v = value.shape[:2]
assert sum(s[0] * s[1] for s in value_spatial_shapes) == len_v
value = self.value_proj(value)
if value_mask is not None:
value = value.masked_fill(value_mask[..., None], float(0))
value = value.view(bs, len_v, self.n_heads, self.d_model // self.n_heads)
sampling_offsets = self.sampling_offsets(query).view(bs, len_q, self.n_heads, self.n_levels, self.n_points, 2)
attention_weights = self.attention_weights(query).view(bs, len_q, self.n_heads, self.n_levels * self.n_points)
attention_weights = F.softmax(attention_weights, -1).view(bs, len_q, self.n_heads, self.n_levels, self.n_points)
# N, Len_q, n_heads, n_levels, n_points, 2
n = reference_points.shape[-1]
if n == 2:
offset_normalizer = torch.as_tensor(value_spatial_shapes, dtype=query.dtype, device=query.device).flip(-1)
add = sampling_offsets / offset_normalizer[None, None, None, :, None, :]
sampling_locations = reference_points[:, :, None, :, None, :] + add
elif n == 4:
add = sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
sampling_locations = reference_points[:, :, None, :, None, :2] + add
else:
raise ValueError(f'Last dim of reference_points must be 2 or 4, but got {n}.')
output = multi_scale_deformable_attn_pytorch(value, value_spatial_shapes, sampling_locations, attention_weights)
output = self.output_proj(output)
return output
class DeformableTransformerDecoderLayer(nn.Module):
"""
https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py
"""
def __init__(self, d_model=256, n_heads=8, d_ffn=1024, dropout=0., act=nn.ReLU(), n_levels=4, n_points=4):
super().__init__()
# self attention
self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
# cross attention
self.cross_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points)
self.dropout2 = nn.Dropout(dropout)
self.norm2 = nn.LayerNorm(d_model)
# ffn
self.linear1 = nn.Linear(d_model, d_ffn)
self.act = act
self.dropout3 = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ffn, d_model)
self.dropout4 = nn.Dropout(dropout)
self.norm3 = nn.LayerNorm(d_model)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward_ffn(self, tgt):
tgt2 = self.linear2(self.dropout3(self.act(self.linear1(tgt))))
tgt = tgt + self.dropout4(tgt2)
tgt = self.norm3(tgt)
return tgt
def forward(self,
tgt,
reference_points,
src,
src_spatial_shapes,
src_padding_mask=None,
attn_mask=None,
query_pos=None):
# self attention
q = k = self.with_pos_embed(tgt, query_pos)
if attn_mask is not None:
attn_mask = torch.where(attn_mask.astype('bool'), torch.zeros(attn_mask.shape, tgt.dtype),
torch.full(attn_mask.shape, float('-inf'), tgt.dtype))
tgt2 = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), tgt.transpose(0, 1))[0].transpose(0, 1)
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
# cross attention
tgt2 = self.cross_attn(self.with_pos_embed(tgt, query_pos), reference_points, src, src_spatial_shapes,
src_padding_mask)
tgt = tgt + self.dropout2(tgt2)
tgt = self.norm2(tgt)
# ffn
tgt = self.forward_ffn(tgt)
return tgt
class DeformableTransformerDecoder(nn.Module):
"""
https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py
"""
def __init__(self, hidden_dim, decoder_layer, num_layers, eval_idx=-1):
super().__init__() | self.layers = _get_clones(decoder_layer, num_layers) | 1 | 2023-10-24 00:45:55+00:00 | 8k |
zhaojw1998/AccoMontage-3 | train_QA.py | [
{
"identifier": "Query_and_reArrange",
"path": "orchestrator/QA_model.py",
"snippet": "class Query_and_reArrange(nn.Module):\n \"\"\"Q&A model for multi-track rearrangement\"\"\"\n def __init__(self, name, device, trf_layers=2):\n super(Query_and_reArrange, self).__init__()\n\n self.... | import os
import time
import torch
from torch import optim
from orchestrator.QA_model import Query_and_reArrange
from orchestrator.QA_dataset import Slakh2100_Pop909_Dataset, collate_fn
from torch.utils.data import DataLoader
from orchestrator.utils.scheduler import MinExponentialLR, OptimizerScheduler, TeacherForcingScheduler, ConstantScheduler, ParameterScheduler
from orchestrator.utils.training import kl_anealing, SummaryWriters, LogPathManager, epoch_time
from tqdm import tqdm | 6,288 | os.environ['CUDA_VISIBLE_DEVICES']= '0'
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
DEVICE = 'cuda:0'
BATCH_SIZE = 64
TRF_LAYERS = 2
N_EPOCH = 30
CLIP = 3
WEIGHTS = [1, 0.5]
BETA = 1e-2
TFR = [(0.6, 0), (0.5, 0)]
LR = 1e-3
MODEL_NAME = 'VQ-Q&A-T'
SAVE_ROOT = '/data1/zhaojw/AccoMontage3/'
DEBUG = 0
| os.environ['CUDA_VISIBLE_DEVICES']= '0'
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
DEVICE = 'cuda:0'
BATCH_SIZE = 64
TRF_LAYERS = 2
N_EPOCH = 30
CLIP = 3
WEIGHTS = [1, 0.5]
BETA = 1e-2
TFR = [(0.6, 0), (0.5, 0)]
LR = 1e-3
MODEL_NAME = 'VQ-Q&A-T'
SAVE_ROOT = '/data1/zhaojw/AccoMontage3/'
DEBUG = 0
| model = Query_and_reArrange(name=MODEL_NAME, trf_layers=TRF_LAYERS, device=DEVICE) | 0 | 2023-10-23 12:36:57+00:00 | 8k |
zcczhang/UVD | uvd/envs/evaluator/vec_envs/vec_env.py | [
{
"identifier": "EnvWorker",
"path": "uvd/envs/evaluator/vec_envs/workers.py",
"snippet": "class EnvWorker(ABC):\n \"\"\"An abstract worker for an environment.\"\"\"\n\n def __init__(self, env_fn: Callable[[], gym.Env]) -> None:\n self._env_fn = env_fn\n self.is_closed = False\n ... | from typing import Any, Callable, List, Optional, Tuple, Union
from .workers import EnvWorker, RayEnvWorker, SubprocEnvWorker
import gym
import numpy as np
import ray | 5,043 | ready_conns: List[EnvWorker] = []
while not ready_conns:
ready_conns = self.worker_class.wait(
self.waiting_conn, self.wait_num, self.timeout
)
result = []
for conn in ready_conns:
waiting_index = self.waiting_conn.index(conn)
self.waiting_conn.pop(waiting_index)
env_id = self.waiting_id.pop(waiting_index)
obs, rew, done, info = conn.recv()
info["env_id"] = env_id
result.append((obs, rew, done, info))
self.ready_id.append(env_id)
obs_list, rew_list, done_list, info_list = zip(*result)
try:
obs_stack = np.stack(obs_list)
except ValueError: # different len(obs)
obs_stack = np.array(obs_list, dtype=object)
rew_stack, done_stack, info_stack = map(
np.stack, [rew_list, done_list, info_list]
)
return obs_stack, rew_stack, done_stack, info_stack
def seed(
self,
seed: Optional[Union[int, List[int]]] = None,
) -> List[Optional[List[int]]]:
"""Set the seed for all environments.
Accept ``None``, an int (which will extend ``i`` to
``[i, i + 1, i + 2, ...]``) or a list.
:return: The list of seeds used in this env's random number generators.
The first value in the list should be the "main" seed, or the value
which a reproducer pass to "seed".
"""
self._assert_is_not_closed()
seed_list: Union[List[None], List[int]]
if seed is None:
seed_list = [seed] * self.env_num
elif isinstance(seed, int):
seed_list = [seed + i for i in range(self.env_num)]
else:
seed_list = seed
return [w.seed(s) for w, s in zip(self.workers, seed_list)]
def render(self, **kwargs: Any) -> List[Any]:
"""Render all of the environments."""
self._assert_is_not_closed()
if self.is_async and len(self.waiting_id) > 0:
raise RuntimeError(
f"Environments {self.waiting_id} are still stepping, cannot "
"render them now."
)
return [w.render(**kwargs) for w in self.workers]
def close(self) -> None:
"""Close all of the environments.
This function will be called only once (if not, it will be
called during garbage collected). This way, ``close`` of all
workers can be assured.
"""
self._assert_is_not_closed()
for w in self.workers:
w.close()
self.is_closed = True
class SubprocVectorEnv(BaseVectorEnv):
"""Vectorized environment wrapper based on subprocess.
.. seealso::
Please refer to :class:`~tianshou.env.BaseVectorEnv` for other APIs' usage.
"""
def __init__(self, env_fns: List[Callable[[], gym.Env]], **kwargs: Any) -> None:
def worker_fn(fn: Callable[[], gym.Env]) -> SubprocEnvWorker:
return SubprocEnvWorker(fn, share_memory=False)
super().__init__(env_fns, worker_fn, **kwargs)
class ShmemVectorEnv(BaseVectorEnv):
"""Optimized SubprocVectorEnv with shared buffers to exchange observations.
ShmemVectorEnv has exactly the same API as SubprocVectorEnv.
.. seealso::
Please refer to :class:`~tianshou.env.BaseVectorEnv` for other APIs' usage.
"""
def __init__(self, env_fns: List[Callable[[], gym.Env]], **kwargs: Any) -> None:
def worker_fn(fn: Callable[[], gym.Env]) -> SubprocEnvWorker:
return SubprocEnvWorker(fn, share_memory=True)
super().__init__(env_fns, worker_fn, **kwargs)
class RayVectorEnv(BaseVectorEnv):
"""Vectorized environment wrapper based on ray.
This is a choice to run distributed environments in a cluster.
.. seealso::
Please refer to :class:`~tianshou.env.BaseVectorEnv` for other APIs' usage.
"""
def __init__(self, env_fns: List[Callable[[], gym.Env]], **kwargs: Any) -> None:
try:
except ImportError as exception:
raise ImportError(
"Please install ray to support RayVectorEnv: pip install ray"
) from exception
if not ray.is_initialized():
ray.init()
| """Modified from `tianshou`"""
GYM_RESERVED_KEYS = [
"metadata",
"reward_range",
"spec",
"action_space",
"observation_space",
]
class BaseVectorEnv(object):
"""Base class for vectorized environments.
Usage:
::
env_num = 8
envs = DummyVectorEnv([lambda: gym.make(task) for _ in range(env_num)])
assert len(envs) == env_num
It accepts a list of environment generators. In other words, an environment
generator ``efn`` of a specific task means that ``efn()`` returns the
environment of the given task, for example, ``gym.make(task)``.
All of the VectorEnv must inherit :class:`~tianshou.env.BaseVectorEnv`.
Here are some other usages:
::
envs.seed(2) # which is equal to the next line
envs.seed([2, 3, 4, 5, 6, 7, 8, 9]) # set specific seed for each env
obs = envs.reset() # reset all environments
obs = envs.reset([0, 5, 7]) # reset 3 specific environments
obs, rew, done, info = envs.step([1] * 8) # step synchronously
envs.render() # render all environments
envs.close() # close all environments
.. warning::
If you use your own environment, please make sure the ``seed`` method
is set up properly, e.g.,
::
def seed(self, seed):
np.random.seed(seed)
Otherwise, the outputs of these envs may be the same with each other.
:param env_fns: a list of callable envs, ``env_fns[i]()`` generates the i-th env.
:param worker_fn: a callable worker, ``worker_fn(env_fns[i])`` generates a
worker which contains the i-th env.
:param int wait_num: use in asynchronous simulation if the time cost of
``env.step`` varies with time and synchronously waiting for all
environments to finish a step is time-wasting. In that case, we can
return when ``wait_num`` environments finish a step and keep on
simulation in these environments. If ``None``, asynchronous simulation
is disabled; else, ``1 <= wait_num <= env_num``.
:param float timeout: use in asynchronous simulation same as above, in each
vectorized step it only deal with those environments spending time
within ``timeout`` seconds.
"""
def __init__(
self,
env_fns: List[Callable[[], gym.Env]],
worker_fn: Callable[[Callable[[], gym.Env]], EnvWorker],
wait_num: Optional[int] = None,
timeout: Optional[float] = None,
) -> None:
self._env_fns = env_fns
# A VectorEnv contains a pool of EnvWorkers, which corresponds to
# interact with the given envs (one worker <-> one env).
self.workers = [worker_fn(fn) for fn in env_fns]
self.worker_class = type(self.workers[0])
assert issubclass(self.worker_class, EnvWorker)
assert all([isinstance(w, self.worker_class) for w in self.workers])
self.env_num = len(env_fns)
self.wait_num = wait_num or len(env_fns)
assert (
1 <= self.wait_num <= len(env_fns)
), f"wait_num should be in [1, {len(env_fns)}], but got {wait_num}"
self.timeout = timeout
assert (
self.timeout is None or self.timeout > 0
), f"timeout is {timeout}, it should be positive if provided!"
self.is_async = self.wait_num != len(env_fns) or timeout is not None
self.waiting_conn: List[EnvWorker] = []
# environments in self.ready_id is actually ready
# but environments in self.waiting_id are just waiting when checked,
# and they may be ready now, but this is not known until we check it
# in the step() function
self.waiting_id: List[int] = []
# all environments are ready in the beginning
self.ready_id = list(range(self.env_num))
self.is_closed = False
def _assert_is_not_closed(self) -> None:
assert (
not self.is_closed
), f"Methods of {self.__class__.__name__} cannot be called after close."
def __len__(self) -> int:
"""Return len(self), which is the number of environments."""
return self.env_num
def __getattribute__(self, key: str) -> Any:
"""Switch the attribute getter depending on the key.
Any class who inherits ``gym.Env`` will inherit some attributes,
like ``action_space``. However, we would like the attribute
lookup to go straight into the worker (in fact, this vector
env's action_space is always None).
"""
if key in GYM_RESERVED_KEYS: # reserved keys in gym.Env
return self.get_env_attr(key)
else:
return super().__getattribute__(key)
def get_env_attr(
self,
key: str,
id: Optional[Union[int, List[int], np.ndarray]] = None,
) -> List[Any]:
"""Get an attribute from the underlying environments.
If id is an int, retrieve the attribute denoted by key from the
environment underlying the worker at index id. The result is
returned as a list with one element. Otherwise, retrieve the
attribute for all workers at indices id and return a list that
is ordered correspondingly to id.
:param str key: The key of the desired attribute.
:param id: Indice(s) of the desired worker(s). Default to None
for all env_id.
:return list: The list of environment attributes.
"""
self._assert_is_not_closed()
id = self._wrap_id(id)
if self.is_async:
self._assert_id(id)
return [self.workers[j].get_env_attr(key) for j in id]
def set_env_attr(
self,
key: str,
value: Any,
id: Optional[Union[int, List[int], np.ndarray]] = None,
diff_value: bool = False,
) -> None:
"""Set an attribute in the underlying environments.
If id is an int, set the attribute denoted by key from the
environment underlying the worker at index id to value.
Otherwise, set the attribute for all workers at indices id.
:param str key: The key of the desired attribute.
:param Any value: The new value of the attribute.
:param id: Indice(s) of the desired worker(s). Default to None
for all env_id.
"""
self._assert_is_not_closed()
id = self._wrap_id(id)
if diff_value:
assert len(value) == len(id)
if self.is_async:
self._assert_id(id)
for i, j in enumerate(id):
if diff_value:
self.workers[j].set_env_attr(key, value[i])
else:
self.workers[j].set_env_attr(key, value)
def _wrap_id(
self,
id: Optional[Union[int, List[int], np.ndarray]] = None,
) -> Union[List[int], np.ndarray]:
if id is None:
return list(range(self.env_num))
return [id] if np.isscalar(id) else id # type: ignore
def _assert_id(self, id: Union[List[int], np.ndarray]) -> None:
for i in id:
assert (
i not in self.waiting_id
), f"Cannot interact with environment {i} which is stepping now."
assert (
i in self.ready_id
), f"Can only interact with ready environments {self.ready_id}."
# TODO: compatible issue with reset -> (obs, info)
def reset(
self, id: Optional[Union[int, List[int], np.ndarray]] = None
) -> np.ndarray:
"""Reset the state of some envs and return initial observations.
If id is None, reset the state of all the environments and
return initial observations, otherwise reset the specific
environments with the given id, either an int or a list.
"""
self._assert_is_not_closed()
id = self._wrap_id(id)
if self.is_async:
self._assert_id(id)
# send(None) == reset() in worker
for i in id:
self.workers[i].send(None)
obs_list = [self.workers[i].recv() for i in id]
try:
obs = np.stack(obs_list)
except ValueError: # different len(obs)
obs = np.array(obs_list, dtype=object)
return obs
def step(
self,
action: np.ndarray,
id: Optional[Union[int, List[int], np.ndarray]] = None,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Run one timestep of some environments' dynamics.
If id is None, run one timestep of all the environments’ dynamics;
otherwise run one timestep for some environments with given id, either
an int or a list. When the end of episode is reached, you are
responsible for calling reset(id) to reset this environment’s state.
Accept a batch of action and return a tuple (batch_obs, batch_rew,
batch_done, batch_info) in numpy format.
:param numpy.ndarray action: a batch of action provided by the agent.
:return: A tuple including four items:
* ``obs`` a numpy.ndarray, the agent's observation of current environments
* ``rew`` a numpy.ndarray, the amount of rewards returned after \
previous actions
* ``done`` a numpy.ndarray, whether these episodes have ended, in \
which case further step() calls will return undefined results
* ``info`` a numpy.ndarray, contains auxiliary diagnostic \
information (helpful for debugging, and sometimes learning)
For the async simulation:
Provide the given action to the environments. The action sequence
should correspond to the ``id`` argument, and the ``id`` argument
should be a subset of the ``env_id`` in the last returned ``info``
(initially they are env_ids of all the environments). If action is
None, fetch unfinished step() calls instead.
"""
self._assert_is_not_closed()
id = self._wrap_id(id)
if not self.is_async:
assert len(action) == len(id)
for i, j in enumerate(id):
self.workers[j].send(action[i])
result = []
for j in id:
obs, rew, done, info = self.workers[j].recv()
info["env_id"] = j
result.append((obs, rew, done, info))
else:
if action is not None:
self._assert_id(id)
assert len(action) == len(id)
for act, env_id in zip(action, id):
self.workers[env_id].send(act)
self.waiting_conn.append(self.workers[env_id])
self.waiting_id.append(env_id)
self.ready_id = [x for x in self.ready_id if x not in id]
ready_conns: List[EnvWorker] = []
while not ready_conns:
ready_conns = self.worker_class.wait(
self.waiting_conn, self.wait_num, self.timeout
)
result = []
for conn in ready_conns:
waiting_index = self.waiting_conn.index(conn)
self.waiting_conn.pop(waiting_index)
env_id = self.waiting_id.pop(waiting_index)
obs, rew, done, info = conn.recv()
info["env_id"] = env_id
result.append((obs, rew, done, info))
self.ready_id.append(env_id)
obs_list, rew_list, done_list, info_list = zip(*result)
try:
obs_stack = np.stack(obs_list)
except ValueError: # different len(obs)
obs_stack = np.array(obs_list, dtype=object)
rew_stack, done_stack, info_stack = map(
np.stack, [rew_list, done_list, info_list]
)
return obs_stack, rew_stack, done_stack, info_stack
def seed(
self,
seed: Optional[Union[int, List[int]]] = None,
) -> List[Optional[List[int]]]:
"""Set the seed for all environments.
Accept ``None``, an int (which will extend ``i`` to
``[i, i + 1, i + 2, ...]``) or a list.
:return: The list of seeds used in this env's random number generators.
The first value in the list should be the "main" seed, or the value
which a reproducer pass to "seed".
"""
self._assert_is_not_closed()
seed_list: Union[List[None], List[int]]
if seed is None:
seed_list = [seed] * self.env_num
elif isinstance(seed, int):
seed_list = [seed + i for i in range(self.env_num)]
else:
seed_list = seed
return [w.seed(s) for w, s in zip(self.workers, seed_list)]
def render(self, **kwargs: Any) -> List[Any]:
"""Render all of the environments."""
self._assert_is_not_closed()
if self.is_async and len(self.waiting_id) > 0:
raise RuntimeError(
f"Environments {self.waiting_id} are still stepping, cannot "
"render them now."
)
return [w.render(**kwargs) for w in self.workers]
def close(self) -> None:
"""Close all of the environments.
This function will be called only once (if not, it will be
called during garbage collected). This way, ``close`` of all
workers can be assured.
"""
self._assert_is_not_closed()
for w in self.workers:
w.close()
self.is_closed = True
class SubprocVectorEnv(BaseVectorEnv):
"""Vectorized environment wrapper based on subprocess.
.. seealso::
Please refer to :class:`~tianshou.env.BaseVectorEnv` for other APIs' usage.
"""
def __init__(self, env_fns: List[Callable[[], gym.Env]], **kwargs: Any) -> None:
def worker_fn(fn: Callable[[], gym.Env]) -> SubprocEnvWorker:
return SubprocEnvWorker(fn, share_memory=False)
super().__init__(env_fns, worker_fn, **kwargs)
class ShmemVectorEnv(BaseVectorEnv):
"""Optimized SubprocVectorEnv with shared buffers to exchange observations.
ShmemVectorEnv has exactly the same API as SubprocVectorEnv.
.. seealso::
Please refer to :class:`~tianshou.env.BaseVectorEnv` for other APIs' usage.
"""
def __init__(self, env_fns: List[Callable[[], gym.Env]], **kwargs: Any) -> None:
def worker_fn(fn: Callable[[], gym.Env]) -> SubprocEnvWorker:
return SubprocEnvWorker(fn, share_memory=True)
super().__init__(env_fns, worker_fn, **kwargs)
class RayVectorEnv(BaseVectorEnv):
"""Vectorized environment wrapper based on ray.
This is a choice to run distributed environments in a cluster.
.. seealso::
Please refer to :class:`~tianshou.env.BaseVectorEnv` for other APIs' usage.
"""
def __init__(self, env_fns: List[Callable[[], gym.Env]], **kwargs: Any) -> None:
try:
except ImportError as exception:
raise ImportError(
"Please install ray to support RayVectorEnv: pip install ray"
) from exception
if not ray.is_initialized():
ray.init() | super().__init__(env_fns, RayEnvWorker, **kwargs) | 1 | 2023-10-17 19:08:14+00:00 | 8k |
bytedance/ColTrack | models/dino/deformable_transformer.py | [
{
"identifier": "inverse_sigmoid",
"path": "util/misc.py",
"snippet": "def inverse_sigmoid(x, eps=1e-3):\n if x.shape[-1] == 4:\n x = torch.cat(((x[..., :2] + 1) / 3, x[..., 2:] / 2), dim=-1)\n elif x.shape[-1] == 2:\n x = (x + 1) / 3\n else:\n raise ValueError\n x = x.c... | import math, random
import copy
import torch
from typing import Optional
from util.misc import inverse_sigmoid, scale_sigmoid
from torch import nn, Tensor
from .utils import gen_encoder_output_proposals, MLP,_get_activation_fn, gen_sineembed_for_position
from .ops.modules import MSDeformAttn
from .utils import RandomBoxPerturber | 5,652 | raise NotImplementedError
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(
encoder_layer, num_encoder_layers,
encoder_norm, d_model=d_model,
num_queries=num_queries,
deformable_encoder=deformable_encoder,
enc_layer_share=enc_layer_share,
two_stage_type=two_stage_type
)
# choose decoder layer type
if deformable_decoder:
decoder_layer = DeformableTransformerDecoderLayer(d_model, dim_feedforward,
dropout, activation,
num_feature_levels, nhead, dec_n_points, use_deformable_box_attn=use_deformable_box_attn, box_attn_type=box_attn_type,
key_aware_type=key_aware_type,
decoder_sa_type=decoder_sa_type,
module_seq=module_seq)
else:
raise NotImplementedError
decoder_norm = nn.LayerNorm(d_model)
self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm,
return_intermediate=return_intermediate_dec,
d_model=d_model, query_dim=query_dim,
modulate_hw_attn=modulate_hw_attn,
num_feature_levels=num_feature_levels,
deformable_decoder=deformable_decoder,
decoder_query_perturber=decoder_query_perturber,
dec_layer_number=dec_layer_number, rm_dec_query_scale=rm_dec_query_scale,
dec_layer_share=dec_layer_share,
use_detached_boxes_dec_out=use_detached_boxes_dec_out
)
self.d_model = d_model
self.nhead = nhead
self.dec_layers = num_decoder_layers
self.num_queries = num_queries # useful for single stage model only
self.num_patterns = num_patterns
if not isinstance(num_patterns, int):
Warning("num_patterns should be int but {}".format(type(num_patterns)))
self.num_patterns = 0
if num_feature_levels > 1:
if self.num_encoder_layers > 0:
self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
else:
self.level_embed = None
self.learnable_tgt_init = learnable_tgt_init
assert learnable_tgt_init, "why not learnable_tgt_init"
self.embed_init_tgt = embed_init_tgt
if (two_stage_type != 'no' and embed_init_tgt) or (two_stage_type == 'no'):
self.tgt_embed = nn.Embedding(self.num_queries, d_model)
nn.init.normal_(self.tgt_embed.weight.data)
else:
self.tgt_embed = None
# for two stage
self.two_stage_type = two_stage_type
self.two_stage_pat_embed = two_stage_pat_embed
self.two_stage_add_query_num = two_stage_add_query_num
self.two_stage_learn_wh = two_stage_learn_wh
assert two_stage_type in ['no', 'standard'], "unknown param {} of two_stage_type".format(two_stage_type)
if two_stage_type =='standard':
# anchor selection at the output of encoder
self.enc_output = nn.Linear(d_model, d_model)
self.enc_output_norm = nn.LayerNorm(d_model)
if two_stage_pat_embed > 0:
self.pat_embed_for_2stage = nn.Parameter(torch.Tensor(two_stage_pat_embed, d_model))
nn.init.normal_(self.pat_embed_for_2stage)
if two_stage_add_query_num > 0:
self.tgt_embed = nn.Embedding(self.two_stage_add_query_num, d_model)
if two_stage_learn_wh:
# import ipdb; ipdb.set_trace()
self.two_stage_wh_embedding = nn.Embedding(1, 2)
else:
self.two_stage_wh_embedding = None
if two_stage_type == 'no':
self.init_ref_points(num_queries) # init self.refpoint_embed
self.enc_out_class_embed = None
self.enc_out_bbox_embed = None
# evolution of anchors
self.dec_layer_number = dec_layer_number
if dec_layer_number is not None:
if self.two_stage_type != 'no' or num_patterns == 0:
assert dec_layer_number[0] == num_queries, f"dec_layer_number[0]({dec_layer_number[0]}) != num_queries({num_queries})"
else:
assert dec_layer_number[0] == num_queries * num_patterns, f"dec_layer_number[0]({dec_layer_number[0]}) != num_queries({num_queries}) * num_patterns({num_patterns})"
self._reset_parameters()
self.rm_self_attn_layers = rm_self_attn_layers
if rm_self_attn_layers is not None:
# assert len(rm_self_attn_layers) == num_decoder_layers
print("Removing the self-attn in {} decoder layers".format(rm_self_attn_layers))
for lid, dec_layer in enumerate(self.decoder.layers):
if lid in rm_self_attn_layers:
dec_layer.rm_self_attn_modules()
self.rm_detach = rm_detach
if self.rm_detach:
assert isinstance(rm_detach, list)
assert any([i in ['enc_ref', 'enc_tgt', 'dec'] for i in rm_detach])
self.decoder.rm_detach = rm_detach
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
for m in self.modules():
| # ------------------------------------------------------------------------
# DINO
# Copyright (c) 2022 IDEA. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Conditional DETR Transformer class.
# Copyright (c) 2021 Microsoft. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# ------------------------------------------------------------------------
class DeformableTransformer(nn.Module):
def __init__(self, d_model=256, nhead=8,
num_queries=300,
num_encoder_layers=6,
num_unicoder_layers=0,
num_decoder_layers=6,
dim_feedforward=2048, dropout=0.0,
activation="relu", normalize_before=False,
return_intermediate_dec=False, query_dim=4,
num_patterns=0,
modulate_hw_attn=False,
# for deformable encoder
deformable_encoder=False,
deformable_decoder=False,
num_feature_levels=1,
enc_n_points=4,
dec_n_points=4,
use_deformable_box_attn=False,
box_attn_type='roi_align',
# init query
learnable_tgt_init=False,
decoder_query_perturber=None,
add_channel_attention=False,
add_pos_value=False,
random_refpoints_xy=False,
# two stage
two_stage_type='no', # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1']
two_stage_pat_embed=0,
two_stage_add_query_num=0,
two_stage_learn_wh=False,
two_stage_keep_all_tokens=False,
# evo of #anchors
dec_layer_number=None,
rm_enc_query_scale=True,
rm_dec_query_scale=True,
rm_self_attn_layers=None,
key_aware_type=None,
# layer share
layer_share_type=None,
# for detach
rm_detach=None,
decoder_sa_type='ca',
module_seq=['sa', 'ca', 'ffn'],
# for dn
embed_init_tgt=False,
use_detached_boxes_dec_out=False,
):
super().__init__()
self.num_feature_levels = num_feature_levels
self.num_encoder_layers = num_encoder_layers
self.num_unicoder_layers = num_unicoder_layers
self.num_decoder_layers = num_decoder_layers
self.deformable_encoder = deformable_encoder
self.deformable_decoder = deformable_decoder
self.two_stage_keep_all_tokens = two_stage_keep_all_tokens
self.num_queries = num_queries
self.random_refpoints_xy = random_refpoints_xy
self.use_detached_boxes_dec_out = use_detached_boxes_dec_out
assert query_dim == 4
if num_feature_levels > 1:
assert deformable_encoder, "only support deformable_encoder for num_feature_levels > 1"
if use_deformable_box_attn:
assert deformable_encoder or deformable_encoder
assert layer_share_type in [None, 'encoder', 'decoder', 'both']
if layer_share_type in ['encoder', 'both']:
enc_layer_share = True
else:
enc_layer_share = False
if layer_share_type in ['decoder', 'both']:
dec_layer_share = True
else:
dec_layer_share = False
assert layer_share_type is None
self.decoder_sa_type = decoder_sa_type
assert decoder_sa_type in ['sa', 'ca_label', 'ca_content']
# choose encoder layer type
if deformable_encoder:
encoder_layer = DeformableTransformerEncoderLayer(d_model, dim_feedforward,
dropout, activation,
num_feature_levels, nhead, enc_n_points, add_channel_attention=add_channel_attention, use_deformable_box_attn=use_deformable_box_attn, box_attn_type=box_attn_type)
else:
raise NotImplementedError
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(
encoder_layer, num_encoder_layers,
encoder_norm, d_model=d_model,
num_queries=num_queries,
deformable_encoder=deformable_encoder,
enc_layer_share=enc_layer_share,
two_stage_type=two_stage_type
)
# choose decoder layer type
if deformable_decoder:
decoder_layer = DeformableTransformerDecoderLayer(d_model, dim_feedforward,
dropout, activation,
num_feature_levels, nhead, dec_n_points, use_deformable_box_attn=use_deformable_box_attn, box_attn_type=box_attn_type,
key_aware_type=key_aware_type,
decoder_sa_type=decoder_sa_type,
module_seq=module_seq)
else:
raise NotImplementedError
decoder_norm = nn.LayerNorm(d_model)
self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm,
return_intermediate=return_intermediate_dec,
d_model=d_model, query_dim=query_dim,
modulate_hw_attn=modulate_hw_attn,
num_feature_levels=num_feature_levels,
deformable_decoder=deformable_decoder,
decoder_query_perturber=decoder_query_perturber,
dec_layer_number=dec_layer_number, rm_dec_query_scale=rm_dec_query_scale,
dec_layer_share=dec_layer_share,
use_detached_boxes_dec_out=use_detached_boxes_dec_out
)
self.d_model = d_model
self.nhead = nhead
self.dec_layers = num_decoder_layers
self.num_queries = num_queries # useful for single stage model only
self.num_patterns = num_patterns
if not isinstance(num_patterns, int):
Warning("num_patterns should be int but {}".format(type(num_patterns)))
self.num_patterns = 0
if num_feature_levels > 1:
if self.num_encoder_layers > 0:
self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
else:
self.level_embed = None
self.learnable_tgt_init = learnable_tgt_init
assert learnable_tgt_init, "why not learnable_tgt_init"
self.embed_init_tgt = embed_init_tgt
if (two_stage_type != 'no' and embed_init_tgt) or (two_stage_type == 'no'):
self.tgt_embed = nn.Embedding(self.num_queries, d_model)
nn.init.normal_(self.tgt_embed.weight.data)
else:
self.tgt_embed = None
# for two stage
self.two_stage_type = two_stage_type
self.two_stage_pat_embed = two_stage_pat_embed
self.two_stage_add_query_num = two_stage_add_query_num
self.two_stage_learn_wh = two_stage_learn_wh
assert two_stage_type in ['no', 'standard'], "unknown param {} of two_stage_type".format(two_stage_type)
if two_stage_type =='standard':
# anchor selection at the output of encoder
self.enc_output = nn.Linear(d_model, d_model)
self.enc_output_norm = nn.LayerNorm(d_model)
if two_stage_pat_embed > 0:
self.pat_embed_for_2stage = nn.Parameter(torch.Tensor(two_stage_pat_embed, d_model))
nn.init.normal_(self.pat_embed_for_2stage)
if two_stage_add_query_num > 0:
self.tgt_embed = nn.Embedding(self.two_stage_add_query_num, d_model)
if two_stage_learn_wh:
# import ipdb; ipdb.set_trace()
self.two_stage_wh_embedding = nn.Embedding(1, 2)
else:
self.two_stage_wh_embedding = None
if two_stage_type == 'no':
self.init_ref_points(num_queries) # init self.refpoint_embed
self.enc_out_class_embed = None
self.enc_out_bbox_embed = None
# evolution of anchors
self.dec_layer_number = dec_layer_number
if dec_layer_number is not None:
if self.two_stage_type != 'no' or num_patterns == 0:
assert dec_layer_number[0] == num_queries, f"dec_layer_number[0]({dec_layer_number[0]}) != num_queries({num_queries})"
else:
assert dec_layer_number[0] == num_queries * num_patterns, f"dec_layer_number[0]({dec_layer_number[0]}) != num_queries({num_queries}) * num_patterns({num_patterns})"
self._reset_parameters()
self.rm_self_attn_layers = rm_self_attn_layers
if rm_self_attn_layers is not None:
# assert len(rm_self_attn_layers) == num_decoder_layers
print("Removing the self-attn in {} decoder layers".format(rm_self_attn_layers))
for lid, dec_layer in enumerate(self.decoder.layers):
if lid in rm_self_attn_layers:
dec_layer.rm_self_attn_modules()
self.rm_detach = rm_detach
if self.rm_detach:
assert isinstance(rm_detach, list)
assert any([i in ['enc_ref', 'enc_tgt', 'dec'] for i in rm_detach])
self.decoder.rm_detach = rm_detach
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
for m in self.modules(): | if isinstance(m, MSDeformAttn): | 6 | 2023-10-16 02:18:33+00:00 | 8k |
alm0ra/mockafka-py | tests/test_consumer.py | [
{
"identifier": "FakeAdminClientImpl",
"path": "mockafka/admin_client.py",
"snippet": "class FakeAdminClientImpl:\n \"\"\"\n Mock implementation of the Confluent Kafka AdminClient for testing purposes.\n\n Attributes:\n - kafka (KafkaStore): The in-memory storage for simulating Kafka behavio... | from unittest import TestCase
from mockafka.admin_client import FakeAdminClientImpl
from mockafka.conumser import FakeConsumer
from mockafka.kafka_store import KafkaStore, KafkaException
from mockafka.producer import FakeProducer
import pytest | 5,179 |
class TestFakeConsumer(TestCase):
def setUp(self) -> None:
self.kafka = KafkaStore(clean=True)
self.producer = FakeProducer()
|
class TestFakeConsumer(TestCase):
def setUp(self) -> None:
self.kafka = KafkaStore(clean=True)
self.producer = FakeProducer() | self.consumer = FakeConsumer() | 1 | 2023-10-24 13:27:12+00:00 | 8k |
CuriseJia/FreeStyleRet | test.py | [
{
"identifier": "ShallowStyleRetrieval",
"path": "src/models/style_retrieval.py",
"snippet": "class ShallowStyleRetrieval(nn.Module):\n def __init__(self, model_args):\n super(ShallowStyleRetrieval, self).__init__()\n self.args = model_args\n self.openclip, self.pre_process_train... | import argparse
import torch
import torch.nn.functional as F
from tqdm import tqdm
from torch.utils.data import DataLoader
from src.models import ShallowStyleRetrieval, DeepStyleRetrieval, BLIP_Retrieval
from src.dataset.data import T2ITestDataset, I2ITestDataset, X2ITestDataset
from src.utils.utils import setup_seed, getR1Accuary, getR5Accuary | 7,072 |
def parse_args():
parser = argparse.ArgumentParser(description='Parse args for FreeStyleRet Training.')
# project settings
parser.add_argument('--resume', default='', type=str, help='load checkpoints from given path')
parser.add_argument('--origin_resume', default='model_large_retrieval_coco.pth', type=str, help='load checkpoints from given path')
parser.add_argument('--gram_encoder_path', default='pretrained/vgg_normalised.pth', type=str, help='load vgg from given path')
parser.add_argument('--style_cluster_path', default='pretrained/style_cluster.npy', type=str, help='load style prompt from given npy')
parser.add_argument('--device', default='cuda:0')
parser.add_argument('--seed', default=42, type=int)
parser.add_argument('--num_workers', default=6, type=int)
# data settings
parser.add_argument("--type", type=str, default='style2image', help='choose train text2image or style2image.')
parser.add_argument("--style", type=str, default='sketch', help='choose sketch, art or mosaic.')
parser.add_argument("--test_dataset_path", type=str, default='DSR/')
parser.add_argument("--test_json_path", type=str, default='DSR/test.json')
parser.add_argument("--batch_size", type=int, default=24)
# model settings
parser.add_argument('--prompt', type=str, default='DeepPrompt', help='ShallowPrompt or DeepPrompt')
parser.add_argument('--gram_prompts', type=int, default=4)
parser.add_argument('--gram_prompt_dim', type=int, default=1024)
parser.add_argument('--style_prompts', type=int, default=4)
parser.add_argument('--style_prompt_dim', type=int, default=1024)
args = parser.parse_args()
return args
def eval(args, model, dataloader):
model.eval()
r1 = []
r5 = []
if args.type == 'text2image':
for data in enumerate(tqdm(dataloader)):
if args.prompt == 'BLIP_Retrieval':
caption = data[1][0]
else:
caption = model.tokenizer(data[1][0]).to(args.device, non_blocking=True)
image = data[1][1].to(args.device, non_blocking=True)
image_feature = model(image, dtype='image')
text_feature = model(caption, dtype='text')
image_feature = F.normalize(image_feature, dim=-1)
text_feature = F.normalize(text_feature, dim=-1)
prob = torch.softmax((100.0 * text_feature @ image_feature.T), dim=-1)
r1.append(getR1Accuary(prob))
|
def parse_args():
parser = argparse.ArgumentParser(description='Parse args for FreeStyleRet Training.')
# project settings
parser.add_argument('--resume', default='', type=str, help='load checkpoints from given path')
parser.add_argument('--origin_resume', default='model_large_retrieval_coco.pth', type=str, help='load checkpoints from given path')
parser.add_argument('--gram_encoder_path', default='pretrained/vgg_normalised.pth', type=str, help='load vgg from given path')
parser.add_argument('--style_cluster_path', default='pretrained/style_cluster.npy', type=str, help='load style prompt from given npy')
parser.add_argument('--device', default='cuda:0')
parser.add_argument('--seed', default=42, type=int)
parser.add_argument('--num_workers', default=6, type=int)
# data settings
parser.add_argument("--type", type=str, default='style2image', help='choose train text2image or style2image.')
parser.add_argument("--style", type=str, default='sketch', help='choose sketch, art or mosaic.')
parser.add_argument("--test_dataset_path", type=str, default='DSR/')
parser.add_argument("--test_json_path", type=str, default='DSR/test.json')
parser.add_argument("--batch_size", type=int, default=24)
# model settings
parser.add_argument('--prompt', type=str, default='DeepPrompt', help='ShallowPrompt or DeepPrompt')
parser.add_argument('--gram_prompts', type=int, default=4)
parser.add_argument('--gram_prompt_dim', type=int, default=1024)
parser.add_argument('--style_prompts', type=int, default=4)
parser.add_argument('--style_prompt_dim', type=int, default=1024)
args = parser.parse_args()
return args
def eval(args, model, dataloader):
model.eval()
r1 = []
r5 = []
if args.type == 'text2image':
for data in enumerate(tqdm(dataloader)):
if args.prompt == 'BLIP_Retrieval':
caption = data[1][0]
else:
caption = model.tokenizer(data[1][0]).to(args.device, non_blocking=True)
image = data[1][1].to(args.device, non_blocking=True)
image_feature = model(image, dtype='image')
text_feature = model(caption, dtype='text')
image_feature = F.normalize(image_feature, dim=-1)
text_feature = F.normalize(text_feature, dim=-1)
prob = torch.softmax((100.0 * text_feature @ image_feature.T), dim=-1)
r1.append(getR1Accuary(prob)) | r5.append(getR5Accuary(prob)) | 8 | 2023-10-17 09:32:57+00:00 | 8k |
liuqidong07/MOELoRA-peft | run_mlora.py | [
{
"identifier": "main",
"path": "src/MLoRA/main.py",
"snippet": "def main(parser):\n\n if len(sys.argv) == 2 and sys.argv[1].endswith(\".json\"):\n # If we pass only one argument to the script and it's the path to a json file,\n # let's parse it to get our arguments.\n model_args... | import os
from src.MLoRA.main import main
from transformers import HfArgumentParser, Seq2SeqTrainingArguments
from src.MLoRA.arguments import ModelArguments, DataTrainingArguments | 6,142 | # -*- encoding: utf-8 -*-
# here put the import lib
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
if __name__ == "__main__":
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
| # -*- encoding: utf-8 -*-
# here put the import lib
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3"
if __name__ == "__main__":
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments))
| main(parser) | 0 | 2023-10-19 10:55:50+00:00 | 8k |
voyage-ai/voyageai-python | voyageai/api_resources/abstract/engine_api_resource.py | [
{
"identifier": "error",
"path": "voyageai/error.py",
"snippet": "class VoyageError(Exception):\nclass APIError(VoyageError):\nclass TryAgain(VoyageError):\nclass Timeout(VoyageError):\nclass APIConnectionError(VoyageError):\nclass InvalidRequestError(VoyageError):\nclass MalformedRequestError(VoyageErr... | import time
from pydoc import apropos
from typing import Optional
from urllib.parse import quote_plus
from voyageai import error, util
from voyageai.api_resources import api_requestor
from voyageai.api_resources.abstract.api_resource import APIResource
from voyageai.util import ApiType | 3,720 |
MAX_TIMEOUT = 20
class EngineAPIResource(APIResource):
plain_old_data = False
def __init__(self, engine: Optional[str] = None, **kwargs):
super().__init__(engine=engine, **kwargs)
@classmethod
def class_url(
cls,
engine: Optional[str] = None,
api_type: Optional[str] = None,
api_version: Optional[str] = None,
):
# Namespaces are separated in object names with periods (.) and in URLs
# with forward slashes (/), so replace the former with the latter.
base = cls.OBJECT_NAME.replace(".", "/") # type: ignore
return "/%s" % (base)
@classmethod
def __prepare_create_request(
cls,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
deployment_id = params.pop("deployment_id", None)
engine = params.pop("engine", deployment_id)
model = params.get("model", None)
timeout = params.pop("timeout", None)
stream = params.get("stream", False)
headers = params.pop("headers", None)
request_timeout = params.pop("request_timeout", None)
typed_api_type = cls._get_api_type_and_version(api_type=api_type)[0]
if model is None and engine is None:
|
MAX_TIMEOUT = 20
class EngineAPIResource(APIResource):
plain_old_data = False
def __init__(self, engine: Optional[str] = None, **kwargs):
super().__init__(engine=engine, **kwargs)
@classmethod
def class_url(
cls,
engine: Optional[str] = None,
api_type: Optional[str] = None,
api_version: Optional[str] = None,
):
# Namespaces are separated in object names with periods (.) and in URLs
# with forward slashes (/), so replace the former with the latter.
base = cls.OBJECT_NAME.replace(".", "/") # type: ignore
return "/%s" % (base)
@classmethod
def __prepare_create_request(
cls,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
**params,
):
deployment_id = params.pop("deployment_id", None)
engine = params.pop("engine", deployment_id)
model = params.get("model", None)
timeout = params.pop("timeout", None)
stream = params.get("stream", False)
headers = params.pop("headers", None)
request_timeout = params.pop("request_timeout", None)
typed_api_type = cls._get_api_type_and_version(api_type=api_type)[0]
if model is None and engine is None: | raise error.InvalidRequestError( | 0 | 2023-10-17 22:11:18+00:00 | 8k |
YuroFR/freqtrade-modded-crypto-trading-bot | tests/optimize/test_recursive_analysis.py | [
{
"identifier": "start_recursive_analysis",
"path": "freqtrade/commands/optimize_commands.py",
"snippet": "def start_recursive_analysis(args: Dict[str, Any]) -> None:\n \"\"\"\n Start the backtest recursive tester script\n :param args: Cli args from Arguments()\n :return: None\n \"\"\"\n ... | from copy import deepcopy
from pathlib import Path
from unittest.mock import MagicMock, PropertyMock
from freqtrade.commands.optimize_commands import start_recursive_analysis
from freqtrade.data.history import get_timerange
from freqtrade.exceptions import OperationalException
from freqtrade.optimize.analysis.recursive import RecursiveAnalysis
from freqtrade.optimize.analysis.recursive_helpers import RecursiveAnalysisSubFunctions
from tests.conftest import get_args, log_has_re, patch_exchange
import pytest | 3,731 | # pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, unused-argument
@pytest.fixture
def recursive_conf(default_conf_usdt):
default_conf_usdt['timerange'] = '20220101-20220501'
default_conf_usdt['strategy_path'] = str(
Path(__file__).parent.parent / "strategy/strats")
default_conf_usdt['strategy'] = 'strategy_test_v3_recursive_issue'
default_conf_usdt['pairs'] = ['UNITTEST/USDT']
default_conf_usdt['startup_candle'] = [100]
return default_conf_usdt
def test_start_recursive_analysis(mocker):
single_mock = MagicMock()
text_table_mock = MagicMock()
mocker.patch.multiple(
'freqtrade.optimize.analysis.recursive_helpers.RecursiveAnalysisSubFunctions',
initialize_single_recursive_analysis=single_mock,
text_table_recursive_analysis_instances=text_table_mock,
)
args = [
"recursive-analysis",
"--strategy",
"strategy_test_v3_recursive_issue",
"--strategy-path",
str(Path(__file__).parent.parent / "strategy/strats"),
"--pairs",
"UNITTEST/BTC",
"--timerange",
"20220101-20220201"
]
pargs = get_args(args)
pargs['config'] = None
start_recursive_analysis(pargs)
assert single_mock.call_count == 1
assert text_table_mock.call_count == 1
single_mock.reset_mock()
# Missing timerange
args = [
"recursive-analysis",
"--strategy",
"strategy_test_v3_with_recursive_bias",
"--strategy-path",
str(Path(__file__).parent.parent / "strategy/strats"),
"--pairs",
"UNITTEST/BTC"
]
pargs = get_args(args)
pargs['config'] = None
| # pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, unused-argument
@pytest.fixture
def recursive_conf(default_conf_usdt):
default_conf_usdt['timerange'] = '20220101-20220501'
default_conf_usdt['strategy_path'] = str(
Path(__file__).parent.parent / "strategy/strats")
default_conf_usdt['strategy'] = 'strategy_test_v3_recursive_issue'
default_conf_usdt['pairs'] = ['UNITTEST/USDT']
default_conf_usdt['startup_candle'] = [100]
return default_conf_usdt
def test_start_recursive_analysis(mocker):
single_mock = MagicMock()
text_table_mock = MagicMock()
mocker.patch.multiple(
'freqtrade.optimize.analysis.recursive_helpers.RecursiveAnalysisSubFunctions',
initialize_single_recursive_analysis=single_mock,
text_table_recursive_analysis_instances=text_table_mock,
)
args = [
"recursive-analysis",
"--strategy",
"strategy_test_v3_recursive_issue",
"--strategy-path",
str(Path(__file__).parent.parent / "strategy/strats"),
"--pairs",
"UNITTEST/BTC",
"--timerange",
"20220101-20220201"
]
pargs = get_args(args)
pargs['config'] = None
start_recursive_analysis(pargs)
assert single_mock.call_count == 1
assert text_table_mock.call_count == 1
single_mock.reset_mock()
# Missing timerange
args = [
"recursive-analysis",
"--strategy",
"strategy_test_v3_with_recursive_bias",
"--strategy-path",
str(Path(__file__).parent.parent / "strategy/strats"),
"--pairs",
"UNITTEST/BTC"
]
pargs = get_args(args)
pargs['config'] = None | with pytest.raises(OperationalException, | 2 | 2023-10-21 10:02:05+00:00 | 8k |
yanzhh/HGERE | transformers/src/transformers/modeling_utils.py | [
{
"identifier": "get_activation",
"path": "transformers/src/transformers/activations.py",
"snippet": "def get_activation(activation_string):\n if activation_string in ACT2FN:\n return ACT2FN[activation_string]\n else:\n raise KeyError(\n \"function {} not found in ACT2FN m... | import logging
import os
import typing
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.nn import functional as F
from .activations import get_activation
from .configuration_utils import PretrainedConfig
from .file_utils import (
DUMMY_INPUTS,
TF2_WEIGHTS_NAME,
TF_WEIGHTS_NAME,
WEIGHTS_NAME,
cached_path,
hf_bucket_url,
is_remote_url,
)
from torch.nn import Identity
from transformers import load_tf2_checkpoint_in_pytorch_model | 5,881 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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.
"""PyTorch BERT model."""
logger = logging.getLogger(__name__)
try:
except ImportError:
# Older PyTorch compatibility
class Identity(nn.Module):
r"""A placeholder identity operator that is argument-insensitive.
"""
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, input):
return input
class ModuleUtilsMixin:
"""
A few utilities for torch.nn.Modules, to be used as a mixin.
"""
def num_parameters(self, only_trainable: bool = False) -> int:
"""
Get number of (optionally, trainable) parameters in the module.
"""
params = filter(lambda x: x.requires_grad, self.parameters()) if only_trainable else self.parameters()
return sum(p.numel() for p in params)
class PreTrainedModel(nn.Module, ModuleUtilsMixin):
r""" Base class for all models.
:class:`~transformers.PreTrainedModel` takes care of storing the configuration of the models and handles methods for loading/downloading/saving models
as well as a few methods common to all models to (i) resize the input embeddings and (ii) prune heads in the self-attention heads.
Class attributes (overridden by derived classes):
- ``config_class``: a class derived from :class:`~transformers.PretrainedConfig` to use as configuration class for this model architecture.
- ``pretrained_model_archive_map``: a python ``dict`` of with `short-cut-names` (string) as keys and `url` (string) of associated pretrained weights as values.
- ``load_tf_weights``: a python ``method`` for loading a TensorFlow checkpoint in a PyTorch model, taking as arguments:
- ``model``: an instance of the relevant subclass of :class:`~transformers.PreTrainedModel`,
- ``config``: an instance of the relevant subclass of :class:`~transformers.PretrainedConfig`,
- ``path``: a path (string) to the TensorFlow checkpoint.
- ``base_model_prefix``: a string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model.
"""
config_class = None
pretrained_model_archive_map = {}
base_model_prefix = ""
@property
def dummy_inputs(self):
""" Dummy inputs to do a forward pass in the network.
Returns:
torch.Tensor with dummy inputs
"""
return {"input_ids": torch.tensor(DUMMY_INPUTS)}
def __init__(self, config, *inputs, **kwargs):
super().__init__()
| # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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.
"""PyTorch BERT model."""
logger = logging.getLogger(__name__)
try:
except ImportError:
# Older PyTorch compatibility
class Identity(nn.Module):
r"""A placeholder identity operator that is argument-insensitive.
"""
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, input):
return input
class ModuleUtilsMixin:
"""
A few utilities for torch.nn.Modules, to be used as a mixin.
"""
def num_parameters(self, only_trainable: bool = False) -> int:
"""
Get number of (optionally, trainable) parameters in the module.
"""
params = filter(lambda x: x.requires_grad, self.parameters()) if only_trainable else self.parameters()
return sum(p.numel() for p in params)
class PreTrainedModel(nn.Module, ModuleUtilsMixin):
r""" Base class for all models.
:class:`~transformers.PreTrainedModel` takes care of storing the configuration of the models and handles methods for loading/downloading/saving models
as well as a few methods common to all models to (i) resize the input embeddings and (ii) prune heads in the self-attention heads.
Class attributes (overridden by derived classes):
- ``config_class``: a class derived from :class:`~transformers.PretrainedConfig` to use as configuration class for this model architecture.
- ``pretrained_model_archive_map``: a python ``dict`` of with `short-cut-names` (string) as keys and `url` (string) of associated pretrained weights as values.
- ``load_tf_weights``: a python ``method`` for loading a TensorFlow checkpoint in a PyTorch model, taking as arguments:
- ``model``: an instance of the relevant subclass of :class:`~transformers.PreTrainedModel`,
- ``config``: an instance of the relevant subclass of :class:`~transformers.PretrainedConfig`,
- ``path``: a path (string) to the TensorFlow checkpoint.
- ``base_model_prefix``: a string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model.
"""
config_class = None
pretrained_model_archive_map = {}
base_model_prefix = ""
@property
def dummy_inputs(self):
""" Dummy inputs to do a forward pass in the network.
Returns:
torch.Tensor with dummy inputs
"""
return {"input_ids": torch.tensor(DUMMY_INPUTS)}
def __init__(self, config, *inputs, **kwargs):
super().__init__() | if not isinstance(config, PretrainedConfig): | 1 | 2023-10-15 02:31:09+00:00 | 8k |
johnyang101/pmpnndiff | data/datamodules.py | [
{
"identifier": "StructureDatasetJSONL",
"path": "data/utils.py",
"snippet": "class StructureDatasetJSONL():\n def __init__(self, jsonl_file, verbose=True, truncate=None, max_length=100,\n alphabet='ACDEFGHIKLMNPQRSTVWYX-', \n esm=False, esm_cfg=None,\n ):\n alphabet_set =... | import torch
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from data.utils import StructureDatasetJSONL, StructureLoader
from data.utils import StructureDatasetPDB, PDB_dataset, loader_pdb, build_training_clusters, worker_init_fn, get_pdbs | 3,832 |
class Generic_PMPNN_DM(pl.LightningDataModule):
def __init__(self, cfg, debug, truncate=None):
super().__init__()
self.cfg = cfg
self.debug = debug
self.truncate = 100 if debug and truncate is None else truncate
self.memorize = True if self.truncate == 1 else False
self.batch_size = cfg.batch_size
print(f'Debug: {self.debug}')
print(f"Batch size: {self.batch_size}")
|
class Generic_PMPNN_DM(pl.LightningDataModule):
def __init__(self, cfg, debug, truncate=None):
super().__init__()
self.cfg = cfg
self.debug = debug
self.truncate = 100 if debug and truncate is None else truncate
self.memorize = True if self.truncate == 1 else False
self.batch_size = cfg.batch_size
print(f'Debug: {self.debug}')
print(f"Batch size: {self.batch_size}")
| def train_dataloader(self) -> StructureLoader: | 1 | 2023-10-16 08:47:43+00:00 | 8k |
generative-skill-chaining/gsc-code | generative_skill_chaining/envs/pybullet/real/object_tracker.py | [
{
"identifier": "redisgl",
"path": "generative_skill_chaining/envs/pybullet/real/redisgl.py",
"snippet": "KEY_ARGS = \"webapp::simulator::args\"\nKEY_RESOURCES = \"webapp::resources::simulator\"\nclass Pose:\nclass Geometry(abc.ABC):\nclass Box(Geometry):\nclass Capsule(Geometry):\nclass Cylinder(Geomet... | import pathlib
import ctrlutils
import numpy as np
from typing import Dict, Iterable, List, Optional, Sequence, Union
from ctrlutils import eigen
from generative_skill_chaining.envs.pybullet.real import redisgl
from generative_skill_chaining.envs.pybullet.sim import math, shapes
from generative_skill_chaining.envs.pybullet.table.objects import Object, Variant | 4,353 | )
quat = eigen.Quaterniond(shape.pose.quat) * quat_pybullet_to_redisgl
return redisgl.Pose(shape.pose.pos, quat.coeffs)
else:
return redisgl.Pose(shape.pose.pos, shape.pose.quat)
def create_geometry(shape: shapes.Shape) -> redisgl.Geometry:
if isinstance(shape, shapes.Box):
return redisgl.Box(scale=shape.size)
elif isinstance(shape, shapes.Cylinder):
return redisgl.Cylinder(radius=shape.radius, length=shape.length)
elif isinstance(shape, shapes.Sphere):
return redisgl.Sphere(radius=shape.radius)
raise NotImplementedError(f"Shape type {shape} is not supported.")
def create_graphics(object: Object) -> Sequence[redisgl.Graphics]:
if isinstance(object, Variant):
return []
return [
redisgl.Graphics(
name=object.name,
geometry=create_geometry(shape),
T_to_parent=create_pose(shape),
)
for shape in object.shapes
]
def create_object_model(object: Object, key_namespace: str) -> redisgl.ObjectModel:
return redisgl.ObjectModel(
name=object.name,
graphics=create_graphics(object),
key_pos=f"{key_namespace}::objects::{object.name}::pos",
key_ori=f"{key_namespace}::objects::{object.name}::ori",
)
class ObjectTracker:
def __init__(
self,
objects: Dict[str, Object],
redis_host: str,
redis_port: int,
redis_password: str,
key_namespace: str,
object_key_prefix: str,
assets_path: Union[str, pathlib.Path],
):
self._redis = ctrlutils.RedisClient(redis_host, redis_port, redis_password)
self._redis_pipe = self._redis.pipeline()
self._object_key_prefix = object_key_prefix
self._assets_path = str(pathlib.Path(assets_path).absolute())
redisgl.register_resource_path(self._redis_pipe, self._assets_path)
self._model_keys = redisgl.ModelKeys(key_namespace)
redisgl.register_model_keys(self._redis_pipe, self._model_keys)
self._redis_pipe.execute()
self._tracked_objects = [] # self.get_tracked_objects(objects.values())
for object in objects.values():
try:
redisgl.register_object(
self._redis_pipe,
self._model_keys,
object=create_object_model(object, key_namespace),
)
except NotImplementedError:
continue
self._tracked_objects.append(object)
self._redis_pipe.execute()
def __del__(self) -> None:
redisgl.unregister_resource_path(self._redis_pipe, self._assets_path)
redisgl.unregister_model_keys(self._redis_pipe, self._model_keys)
for object in self._tracked_objects:
redisgl.unregister_object(self._redis_pipe, self._model_keys, object.name)
self._redis_pipe.execute()
def get_tracked_objects(self, objects: Iterable[Object]) -> List[Object]:
for object in objects:
self._redis_pipe.get(self._object_key_prefix + object.name + "::pos")
object_models = self._redis_pipe.execute()
return [
object
for object, object_model in zip(objects, object_models)
if object_model is not None
]
def update_poses(
self,
objects: Optional[Iterable[Object]] = None,
exclude: Optional[Sequence[Object]] = None,
) -> List[Object]:
if objects is None:
objects = self._tracked_objects
# Query all object poses.
for object in objects:
self._redis_pipe.get(self._object_key_prefix + object.name + "::pos")
self._redis_pipe.get(self._object_key_prefix + object.name + "::ori")
b_object_poses = self._redis_pipe.execute()
# Set returned poses.
updated_objects = []
for i, object in enumerate(objects):
if exclude is not None and object in exclude:
continue
b_object_pos = b_object_poses[2 * i]
b_object_quat = b_object_poses[2 * i + 1]
if b_object_pos is None or b_object_quat is None:
continue
object_pos = ctrlutils.redis.decode_matlab(b_object_pos)
object_quat = ctrlutils.redis.decode_matlab(b_object_quat)
|
def create_pose(shape: shapes.Shape) -> redisgl.Pose:
if shape.pose is None:
return redisgl.Pose()
elif isinstance(shape, shapes.Cylinder):
quat_pybullet_to_redisgl = eigen.Quaterniond(
eigen.AngleAxisd(np.pi / 2, np.array([1.0, 0.0, 0.0]))
)
quat = eigen.Quaterniond(shape.pose.quat) * quat_pybullet_to_redisgl
return redisgl.Pose(shape.pose.pos, quat.coeffs)
else:
return redisgl.Pose(shape.pose.pos, shape.pose.quat)
def create_geometry(shape: shapes.Shape) -> redisgl.Geometry:
if isinstance(shape, shapes.Box):
return redisgl.Box(scale=shape.size)
elif isinstance(shape, shapes.Cylinder):
return redisgl.Cylinder(radius=shape.radius, length=shape.length)
elif isinstance(shape, shapes.Sphere):
return redisgl.Sphere(radius=shape.radius)
raise NotImplementedError(f"Shape type {shape} is not supported.")
def create_graphics(object: Object) -> Sequence[redisgl.Graphics]:
if isinstance(object, Variant):
return []
return [
redisgl.Graphics(
name=object.name,
geometry=create_geometry(shape),
T_to_parent=create_pose(shape),
)
for shape in object.shapes
]
def create_object_model(object: Object, key_namespace: str) -> redisgl.ObjectModel:
return redisgl.ObjectModel(
name=object.name,
graphics=create_graphics(object),
key_pos=f"{key_namespace}::objects::{object.name}::pos",
key_ori=f"{key_namespace}::objects::{object.name}::ori",
)
class ObjectTracker:
def __init__(
self,
objects: Dict[str, Object],
redis_host: str,
redis_port: int,
redis_password: str,
key_namespace: str,
object_key_prefix: str,
assets_path: Union[str, pathlib.Path],
):
self._redis = ctrlutils.RedisClient(redis_host, redis_port, redis_password)
self._redis_pipe = self._redis.pipeline()
self._object_key_prefix = object_key_prefix
self._assets_path = str(pathlib.Path(assets_path).absolute())
redisgl.register_resource_path(self._redis_pipe, self._assets_path)
self._model_keys = redisgl.ModelKeys(key_namespace)
redisgl.register_model_keys(self._redis_pipe, self._model_keys)
self._redis_pipe.execute()
self._tracked_objects = [] # self.get_tracked_objects(objects.values())
for object in objects.values():
try:
redisgl.register_object(
self._redis_pipe,
self._model_keys,
object=create_object_model(object, key_namespace),
)
except NotImplementedError:
continue
self._tracked_objects.append(object)
self._redis_pipe.execute()
def __del__(self) -> None:
redisgl.unregister_resource_path(self._redis_pipe, self._assets_path)
redisgl.unregister_model_keys(self._redis_pipe, self._model_keys)
for object in self._tracked_objects:
redisgl.unregister_object(self._redis_pipe, self._model_keys, object.name)
self._redis_pipe.execute()
def get_tracked_objects(self, objects: Iterable[Object]) -> List[Object]:
for object in objects:
self._redis_pipe.get(self._object_key_prefix + object.name + "::pos")
object_models = self._redis_pipe.execute()
return [
object
for object, object_model in zip(objects, object_models)
if object_model is not None
]
def update_poses(
self,
objects: Optional[Iterable[Object]] = None,
exclude: Optional[Sequence[Object]] = None,
) -> List[Object]:
if objects is None:
objects = self._tracked_objects
# Query all object poses.
for object in objects:
self._redis_pipe.get(self._object_key_prefix + object.name + "::pos")
self._redis_pipe.get(self._object_key_prefix + object.name + "::ori")
b_object_poses = self._redis_pipe.execute()
# Set returned poses.
updated_objects = []
for i, object in enumerate(objects):
if exclude is not None and object in exclude:
continue
b_object_pos = b_object_poses[2 * i]
b_object_quat = b_object_poses[2 * i + 1]
if b_object_pos is None or b_object_quat is None:
continue
object_pos = ctrlutils.redis.decode_matlab(b_object_pos)
object_quat = ctrlutils.redis.decode_matlab(b_object_quat)
| object.set_pose(math.Pose(object_pos, object_quat)) | 1 | 2023-10-16 00:22:40+00:00 | 8k |
akashgreninja/GreSec | backend/venv/lib/python3.10/site-packages/charset_normalizer/md.py | [
{
"identifier": "COMMON_SAFE_ASCII_CHARACTERS",
"path": "backend/venv/lib/python3.10/site-packages/charset_normalizer/constant.py",
"snippet": "COMMON_SAFE_ASCII_CHARACTERS: Set[str] = {\n \"<\",\n \">\",\n \"=\",\n \":\",\n \"/\",\n \"&\",\n \";\",\n \"{\",\n \"}\",\n \"[\... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_case_variable,
is_cjk,
is_emoticon,
is_hangul,
is_hiragana,
is_katakana,
is_latin,
is_punctuation,
is_separator,
is_symbol,
is_thai,
is_unprintable,
remove_accent,
unicode_range,
) | 3,775 | def ratio(self) -> float:
if self._character_count == 0:
return 0.0
return (self._unprintable_count * 8) / self._character_count
class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._successive_count: int = 0
self._character_count: int = 0
self._last_latin_character: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isalpha() and is_latin(character)
def feed(self, character: str) -> None:
self._character_count += 1
if (
self._last_latin_character is not None
and is_accentuated(character)
and is_accentuated(self._last_latin_character)
):
if character.isupper() and self._last_latin_character.isupper():
self._successive_count += 1
# Worse if its the same char duplicated with different accent.
if remove_accent(character) == remove_accent(self._last_latin_character):
self._successive_count += 1
self._last_latin_character = character
def reset(self) -> None: # pragma: no cover
self._successive_count = 0
self._character_count = 0
self._last_latin_character = None
@property
def ratio(self) -> float:
if self._character_count == 0:
return 0.0
return (self._successive_count * 2) / self._character_count
class SuspiciousRange(MessDetectorPlugin):
def __init__(self) -> None:
self._suspicious_successive_range_count: int = 0
self._character_count: int = 0
self._last_printable_seen: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isprintable()
def feed(self, character: str) -> None:
self._character_count += 1
if (
character.isspace()
or is_punctuation(character)
or character in COMMON_SAFE_ASCII_CHARACTERS
):
self._last_printable_seen = None
return
if self._last_printable_seen is None:
self._last_printable_seen = character
return
unicode_range_a: Optional[str] = unicode_range(self._last_printable_seen)
unicode_range_b: Optional[str] = unicode_range(character)
if is_suspiciously_successive_range(unicode_range_a, unicode_range_b):
self._suspicious_successive_range_count += 1
self._last_printable_seen = character
def reset(self) -> None: # pragma: no cover
self._character_count = 0
self._suspicious_successive_range_count = 0
self._last_printable_seen = None
@property
def ratio(self) -> float:
if self._character_count <= 24:
return 0.0
ratio_of_suspicious_range_usage: float = (
self._suspicious_successive_range_count * 2
) / self._character_count
return ratio_of_suspicious_range_usage
class SuperWeirdWordPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._word_count: int = 0
self._bad_word_count: int = 0
self._foreign_long_count: int = 0
self._is_current_word_bad: bool = False
self._foreign_long_watch: bool = False
self._character_count: int = 0
self._bad_character_count: int = 0
self._buffer: str = ""
self._buffer_accent_count: int = 0
def eligible(self, character: str) -> bool:
return True
def feed(self, character: str) -> None:
if character.isalpha():
self._buffer += character
if is_accentuated(character):
self._buffer_accent_count += 1
if (
self._foreign_long_watch is False
and (is_latin(character) is False or is_accentuated(character))
and is_cjk(character) is False
|
class MessDetectorPlugin:
"""
Base abstract class used for mess detection plugins.
All detectors MUST extend and implement given methods.
"""
def eligible(self, character: str) -> bool:
"""
Determine if given character should be fed in.
"""
raise NotImplementedError # pragma: nocover
def feed(self, character: str) -> None:
"""
The main routine to be executed upon character.
Insert the logic in witch the text would be considered chaotic.
"""
raise NotImplementedError # pragma: nocover
def reset(self) -> None: # pragma: no cover
"""
Permit to reset the plugin to the initial state.
"""
raise NotImplementedError
@property
def ratio(self) -> float:
"""
Compute the chaos ratio based on what your feed() has seen.
Must NOT be lower than 0.; No restriction gt 0.
"""
raise NotImplementedError # pragma: nocover
class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._punctuation_count: int = 0
self._symbol_count: int = 0
self._character_count: int = 0
self._last_printable_char: Optional[str] = None
self._frenzy_symbol_in_word: bool = False
def eligible(self, character: str) -> bool:
return character.isprintable()
def feed(self, character: str) -> None:
self._character_count += 1
if (
character != self._last_printable_char
and character not in COMMON_SAFE_ASCII_CHARACTERS
):
if is_punctuation(character):
self._punctuation_count += 1
elif (
character.isdigit() is False
and is_symbol(character)
and is_emoticon(character) is False
):
self._symbol_count += 2
self._last_printable_char = character
def reset(self) -> None: # pragma: no cover
self._punctuation_count = 0
self._character_count = 0
self._symbol_count = 0
@property
def ratio(self) -> float:
if self._character_count == 0:
return 0.0
ratio_of_punctuation: float = (
self._punctuation_count + self._symbol_count
) / self._character_count
return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
class TooManyAccentuatedPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._character_count: int = 0
self._accentuated_count: int = 0
def eligible(self, character: str) -> bool:
return character.isalpha()
def feed(self, character: str) -> None:
self._character_count += 1
if is_accentuated(character):
self._accentuated_count += 1
def reset(self) -> None: # pragma: no cover
self._character_count = 0
self._accentuated_count = 0
@property
def ratio(self) -> float:
if self._character_count == 0 or self._character_count < 8:
return 0.0
ratio_of_accentuation: float = self._accentuated_count / self._character_count
return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
class UnprintablePlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._unprintable_count: int = 0
self._character_count: int = 0
def eligible(self, character: str) -> bool:
return True
def feed(self, character: str) -> None:
if is_unprintable(character):
self._unprintable_count += 1
self._character_count += 1
def reset(self) -> None: # pragma: no cover
self._unprintable_count = 0
@property
def ratio(self) -> float:
if self._character_count == 0:
return 0.0
return (self._unprintable_count * 8) / self._character_count
class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._successive_count: int = 0
self._character_count: int = 0
self._last_latin_character: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isalpha() and is_latin(character)
def feed(self, character: str) -> None:
self._character_count += 1
if (
self._last_latin_character is not None
and is_accentuated(character)
and is_accentuated(self._last_latin_character)
):
if character.isupper() and self._last_latin_character.isupper():
self._successive_count += 1
# Worse if its the same char duplicated with different accent.
if remove_accent(character) == remove_accent(self._last_latin_character):
self._successive_count += 1
self._last_latin_character = character
def reset(self) -> None: # pragma: no cover
self._successive_count = 0
self._character_count = 0
self._last_latin_character = None
@property
def ratio(self) -> float:
if self._character_count == 0:
return 0.0
return (self._successive_count * 2) / self._character_count
class SuspiciousRange(MessDetectorPlugin):
def __init__(self) -> None:
self._suspicious_successive_range_count: int = 0
self._character_count: int = 0
self._last_printable_seen: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isprintable()
def feed(self, character: str) -> None:
self._character_count += 1
if (
character.isspace()
or is_punctuation(character)
or character in COMMON_SAFE_ASCII_CHARACTERS
):
self._last_printable_seen = None
return
if self._last_printable_seen is None:
self._last_printable_seen = character
return
unicode_range_a: Optional[str] = unicode_range(self._last_printable_seen)
unicode_range_b: Optional[str] = unicode_range(character)
if is_suspiciously_successive_range(unicode_range_a, unicode_range_b):
self._suspicious_successive_range_count += 1
self._last_printable_seen = character
def reset(self) -> None: # pragma: no cover
self._character_count = 0
self._suspicious_successive_range_count = 0
self._last_printable_seen = None
@property
def ratio(self) -> float:
if self._character_count <= 24:
return 0.0
ratio_of_suspicious_range_usage: float = (
self._suspicious_successive_range_count * 2
) / self._character_count
return ratio_of_suspicious_range_usage
class SuperWeirdWordPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._word_count: int = 0
self._bad_word_count: int = 0
self._foreign_long_count: int = 0
self._is_current_word_bad: bool = False
self._foreign_long_watch: bool = False
self._character_count: int = 0
self._bad_character_count: int = 0
self._buffer: str = ""
self._buffer_accent_count: int = 0
def eligible(self, character: str) -> bool:
return True
def feed(self, character: str) -> None:
if character.isalpha():
self._buffer += character
if is_accentuated(character):
self._buffer_accent_count += 1
if (
self._foreign_long_watch is False
and (is_latin(character) is False or is_accentuated(character))
and is_cjk(character) is False | and is_hangul(character) is False | 7 | 2023-10-23 18:09:28+00:00 | 8k |
marmotlab/Context_Aware_Navigation | graph_generator.py | [
{
"identifier": "Node",
"path": "node.py",
"snippet": "class Node():\r\n def __init__(self, coords, frontiers, robot_belief, target_position):\r\n self.coords = coords\r\n self.observable_frontiers = []\r\n self.sensor_range = 80\r\n self.target_position = target_position\... | import numpy as np
import copy
from sklearn.neighbors import NearestNeighbors
from parameter import *
from node import Node
from graph import Graph, a_star
| 4,144 | x = self.node_coords[:, 0] + self.node_coords[:, 1] * 1j
for node in self.route_node:
index = np.argwhere(x.reshape(-1) == node[0] + node[1] * 1j)
self.indicator[index] = 1
return self.node_coords, self.graph.edges, self.node_utility, self.indicator, self.direction_vector
def generate_uniform_points(self):
x = np.linspace(0, self.map_x - 1, 30).round().astype(int)
y = np.linspace(0, self.map_y - 1, 30).round().astype(int)
t1, t2 = np.meshgrid(x, y)
points = np.vstack([t1.T.ravel(), t2.T.ravel()]).T
return points
def free_area(self, robot_belief):
# free area 255
index = np.where(robot_belief == 255)
free = np.asarray([index[1], index[0]]).T
return free
def unique_coords(self, coords):
x = coords[:, 0] + coords[:, 1] * 1j
indices = np.unique(x, return_index=True)[1]
coords = np.array([coords[idx] for idx in sorted(indices)])
return coords
def find_nearest_node_index(self, position):
index = np.argmin(np.linalg.norm(self.node_coords - position, axis=1))
return index
def find_index_from_coords(self, node_coords, p):
return np.argmin(np.linalg.norm(node_coords - p, axis=1))
def find_k_neighbor(self, coords, node_coords, robot_belief):
dist_list = np.linalg.norm((coords - node_coords), axis=-1)
sorted_index = np.argsort(dist_list)
k = 0
neighbor_index_list = []
while k < self.k_size and k < node_coords.shape[0]:
neighbor_index = sorted_index[k]
neighbor_index_list.append(neighbor_index)
start = coords
end = node_coords[neighbor_index]
if not self.check_collision(start, end, robot_belief):
a = str(self.find_index_from_coords(node_coords, start))
b = str(neighbor_index)
dist = np.linalg.norm(start - end)
self.graph.add_node(a)
self.graph.add_edge(a, b, dist)
# test
self.graph.add_node(b)
self.graph.add_edge(b, a, dist)
k += 1
return neighbor_index_list
def find_k_neighbor_all_nodes(self, node_coords, robot_belief, ground_truth=False):
X = node_coords
if len(node_coords) >= self.k_size:
knn = NearestNeighbors(n_neighbors=self.k_size)
else:
knn = NearestNeighbors(n_neighbors=len(node_coords))
knn.fit(X)
distances, indices = knn.kneighbors(X)
for i, p in enumerate(X):
for j, neighbour in enumerate(X[indices[i][:]]):
start = p
end = neighbour
if not self.check_collision(start, end, robot_belief):
a = str(self.find_index_from_coords(node_coords, p))
b = str(self.find_index_from_coords(node_coords, neighbour))
if not ground_truth:
self.graph.add_node(a)
self.graph.add_edge(a, b, distances[i, j])
if self.plot:
self.x.append([p[0], neighbour[0]])
self.y.append([p[1], neighbour[1]])
else:
self.ground_truth_graph.add_node(a)
self.ground_truth_graph.add_edge(a, b, distances[i, j])
def find_index_from_coords(self, node_coords, p):
return np.where(np.linalg.norm(node_coords - p, axis=1) < 1e-5)[0][0]
def check_collision(self, start, end, robot_belief):
# Bresenham line algorithm checking
collision = False
x0 = start[0].round()
y0 = start[1].round()
x1 = end[0].round()
y1 = end[1].round()
dx, dy = abs(x1 - x0), abs(y1 - y0)
x, y = x0, y0
error = dx - dy
x_inc = 1 if x1 > x0 else -1
y_inc = 1 if y1 > y0 else -1
dx *= 2
dy *= 2
while 0 <= x < robot_belief.shape[1] and 0 <= y < robot_belief.shape[0]:
k = robot_belief.item(int(y), int(x))
if x == x1 and y == y1:
break
if k == 1:
collision = True
break
if k == 127:
collision = True
break
if error > 0:
x += x_inc
error -= dy
else:
y += y_inc
error += dx
return collision
def find_shortest_path(self, current, destination, node_coords, graph):
start_node = str(self.find_index_from_coords(node_coords, current))
end_node = str(self.find_index_from_coords(node_coords, destination))
|
class Graph_generator:
def __init__(self, map_size, k_size, sensor_range, target_position, plot=False):
self.k_size = k_size
self.graph = Graph()
self.ground_truth_graph = Graph()
self.node_coords = None
self.plot = plot
self.x = []
self.y = []
self.map_x = map_size[1]
self.map_y = map_size[0]
self.uniform_points = self.generate_uniform_points()
self.sensor_range = sensor_range
self.route_node = []
self.nodes_list = []
self.node_utility = None
self.indicator = None
self.direction_vector = None
self.target_position = target_position
def generate_node_coords(self, robot_location, robot_belief):
free_area = self.free_area(robot_belief)
free_area_to_check = free_area[:, 0] + free_area[:, 1] * 1j
uniform_points_to_check = self.uniform_points[:, 0] + self.uniform_points[:, 1] * 1j
_, _, candidate_indices = np.intersect1d(free_area_to_check, uniform_points_to_check, return_indices=True)
node_coords = self.uniform_points[candidate_indices]
node_coords = np.concatenate((robot_location.reshape(1, 2), self.target_position.reshape(1, 2), node_coords))
return self.unique_coords(node_coords).reshape(-1, 2)
def edge_clear_all_nodes(self):
self.graph = Graph()
self.x = []
self.y = []
def edge_clear(self, coords):
node_index = str(self.find_index_from_coords(self.node_coords, coords))
self.graph.clear_edge(node_index)
def generate_graph(self, robot_location, ground_truth_belief, robot_belief, frontiers):
self.node_coords = self.generate_node_coords(robot_location, robot_belief)
self.ground_truth_node_coords = self.generate_node_coords(robot_location, ground_truth_belief)
self.find_k_neighbor_all_nodes(self.node_coords, robot_belief)
self.find_k_neighbor_all_nodes(self.ground_truth_node_coords, ground_truth_belief, ground_truth=True)
self.node_utility = []
self.direction_vector = []
for coords in self.node_coords:
node = Node(coords, frontiers, robot_belief, self.target_position)
self.nodes_list.append(node)
utility = node.utility
direction_vector = node.direction_vector
self.direction_vector.append(direction_vector)
self.node_utility.append(utility)
self.direction_vector = np.array(self.direction_vector)
self.node_utility = np.array(self.node_utility)
self.indicator = np.zeros((self.node_coords.shape[0], 1))
x = self.node_coords[:,0] + self.node_coords[:,1]*1j
for node in self.route_node:
index = np.argwhere(x.reshape(-1) == node[0]+node[1]*1j)[0]
self.indicator[index] = 1
return self.node_coords, self.graph.edges, self.node_utility, self.indicator, self.direction_vector
def update_graph(self, robot_position, robot_belief, old_robot_belief, frontiers, old_frontiers):
# add uniform points in the new free area to the node coords
new_free_area = self.free_area((robot_belief - old_robot_belief > 0) * 255)
free_area_to_check = new_free_area[:, 0] + new_free_area[:, 1] * 1j
uniform_points_to_check = self.uniform_points[:, 0] + self.uniform_points[:, 1] * 1j
_, _, candidate_indices = np.intersect1d(free_area_to_check, uniform_points_to_check, return_indices=True)
new_node_coords = self.uniform_points[candidate_indices]
old_node_coords = copy.deepcopy(self.node_coords)
self.node_coords = np.concatenate((self.node_coords, new_node_coords, self.target_position.reshape(1, 2)))
self.node_coords = self.unique_coords(self.node_coords).reshape(-1, 2)
self.edge_clear_all_nodes()
self.find_k_neighbor_all_nodes(self.node_coords, robot_belief)
# update the observable frontiers through the change of frontiers
old_frontiers_to_check = old_frontiers[:, 0] + old_frontiers[:, 1] * 1j
new_frontiers_to_check = frontiers[:, 0] + frontiers[:, 1] * 1j
observed_frontiers_index = np.where(
np.isin(old_frontiers_to_check, new_frontiers_to_check, assume_unique=True) == False)
new_frontiers_index = np.where(
np.isin(new_frontiers_to_check, old_frontiers_to_check, assume_unique=True) == False)
observed_frontiers = old_frontiers[observed_frontiers_index]
new_frontiers = frontiers[new_frontiers_index]
for node in self.nodes_list:
if np.linalg.norm(node.coords - robot_position) > 2 * self.sensor_range:
pass
elif node.zero_utility_node is True:
pass
else:
node.update_observable_frontiers(observed_frontiers, new_frontiers, robot_belief)
for new_coords in new_node_coords:
node = Node(new_coords, frontiers, robot_belief, self.target_position)
self.nodes_list.append(node)
self.direction_vector = []
self.node_utility = []
for i, coords in enumerate(self.node_coords):
utility = self.nodes_list[i].utility
node = Node(coords, frontiers, robot_belief, self.target_position)
self.node_utility.append(utility)
direction_vector = node.direction_vector
self.direction_vector.append(direction_vector)
self.direction_vector = np.array(self.direction_vector)
self.node_utility = np.array(self.node_utility)
self.indicator = np.zeros((self.node_coords.shape[0], 1))
x = self.node_coords[:, 0] + self.node_coords[:, 1] * 1j
for node in self.route_node:
index = np.argwhere(x.reshape(-1) == node[0] + node[1] * 1j)
self.indicator[index] = 1
return self.node_coords, self.graph.edges, self.node_utility, self.indicator, self.direction_vector
def generate_uniform_points(self):
x = np.linspace(0, self.map_x - 1, 30).round().astype(int)
y = np.linspace(0, self.map_y - 1, 30).round().astype(int)
t1, t2 = np.meshgrid(x, y)
points = np.vstack([t1.T.ravel(), t2.T.ravel()]).T
return points
def free_area(self, robot_belief):
# free area 255
index = np.where(robot_belief == 255)
free = np.asarray([index[1], index[0]]).T
return free
def unique_coords(self, coords):
x = coords[:, 0] + coords[:, 1] * 1j
indices = np.unique(x, return_index=True)[1]
coords = np.array([coords[idx] for idx in sorted(indices)])
return coords
def find_nearest_node_index(self, position):
index = np.argmin(np.linalg.norm(self.node_coords - position, axis=1))
return index
def find_index_from_coords(self, node_coords, p):
return np.argmin(np.linalg.norm(node_coords - p, axis=1))
def find_k_neighbor(self, coords, node_coords, robot_belief):
dist_list = np.linalg.norm((coords - node_coords), axis=-1)
sorted_index = np.argsort(dist_list)
k = 0
neighbor_index_list = []
while k < self.k_size and k < node_coords.shape[0]:
neighbor_index = sorted_index[k]
neighbor_index_list.append(neighbor_index)
start = coords
end = node_coords[neighbor_index]
if not self.check_collision(start, end, robot_belief):
a = str(self.find_index_from_coords(node_coords, start))
b = str(neighbor_index)
dist = np.linalg.norm(start - end)
self.graph.add_node(a)
self.graph.add_edge(a, b, dist)
# test
self.graph.add_node(b)
self.graph.add_edge(b, a, dist)
k += 1
return neighbor_index_list
def find_k_neighbor_all_nodes(self, node_coords, robot_belief, ground_truth=False):
X = node_coords
if len(node_coords) >= self.k_size:
knn = NearestNeighbors(n_neighbors=self.k_size)
else:
knn = NearestNeighbors(n_neighbors=len(node_coords))
knn.fit(X)
distances, indices = knn.kneighbors(X)
for i, p in enumerate(X):
for j, neighbour in enumerate(X[indices[i][:]]):
start = p
end = neighbour
if not self.check_collision(start, end, robot_belief):
a = str(self.find_index_from_coords(node_coords, p))
b = str(self.find_index_from_coords(node_coords, neighbour))
if not ground_truth:
self.graph.add_node(a)
self.graph.add_edge(a, b, distances[i, j])
if self.plot:
self.x.append([p[0], neighbour[0]])
self.y.append([p[1], neighbour[1]])
else:
self.ground_truth_graph.add_node(a)
self.ground_truth_graph.add_edge(a, b, distances[i, j])
def find_index_from_coords(self, node_coords, p):
return np.where(np.linalg.norm(node_coords - p, axis=1) < 1e-5)[0][0]
def check_collision(self, start, end, robot_belief):
# Bresenham line algorithm checking
collision = False
x0 = start[0].round()
y0 = start[1].round()
x1 = end[0].round()
y1 = end[1].round()
dx, dy = abs(x1 - x0), abs(y1 - y0)
x, y = x0, y0
error = dx - dy
x_inc = 1 if x1 > x0 else -1
y_inc = 1 if y1 > y0 else -1
dx *= 2
dy *= 2
while 0 <= x < robot_belief.shape[1] and 0 <= y < robot_belief.shape[0]:
k = robot_belief.item(int(y), int(x))
if x == x1 and y == y1:
break
if k == 1:
collision = True
break
if k == 127:
collision = True
break
if error > 0:
x += x_inc
error -= dy
else:
y += y_inc
error += dx
return collision
def find_shortest_path(self, current, destination, node_coords, graph):
start_node = str(self.find_index_from_coords(node_coords, current))
end_node = str(self.find_index_from_coords(node_coords, destination))
| route, dist = a_star(int(start_node), int(end_node), node_coords, graph)
| 2 | 2023-10-17 04:32:42+00:00 | 8k |
WestlakeIntelligentRobotics/ConsensusLLM-code | modules/experiment/vector2d_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
import pickle
from .template import Template
from ..llm.agent_2d import Agent2D
from ..llm.api_key import api_keys
from ..llm.role import names
from ..prompt.form import agent_output_form
from ..prompt.personality import stubborn, suggestible
from ..prompt.scenario_2d import agent_role, game_description, round_description
from ..visual.gen_html import gen_html
from ..visual.plot_2d import plot_xy, video | 6,461 |
class Vector2dDebate(Template):
"""
Vector2dDebate is a class that simulates a 2D debate scenario with multiple
agents.
This class provides the framework to conduct 2D debates with agents and
record their trajectories.
Args:
args:
An object containing configuration parameters for the debate
simulation.
connectivity_matrix:
A square matrix defining agent knowledge connectivity.
Raises:
ValueError:
If the sum of stubborn and suggestible agents exceeds the total
number of agents,
if there are insufficient API keys for the agents, or if the
connectivity matrix is not appropriate.
"""
def __init__(self, args, connectivity_matrix):
"""
Initialize the Vector2dDebate instance.
Args:
args: An object containing configuration options.
connectivity_matrix: A matrix defining agent knowledge connectivity.
Raises:
ValueError: If the input parameters are invalid.
"""
super().__init__(args)
self._dt = 0.1
self._n_agents = args.agents
self._init_input = game_description + "\n\n" + agent_output_form
self._round_description = round_description
self._positions = [[]] * args.n_exp
self._output_file = args.out_file
self._n_suggestible = args.n_suggestible
self._n_stubborn = args.n_stubborn
self._trajectory = {"pos": {}, "target": {}} # A dictionary for recording agent trajectories
# np.random.seed(0)
# Define the connectivity matrix for agent knowledge
# m(i, j) = 1 means agent i knows the position of agent j
self._m = connectivity_matrix
# Safety checks for input parameters
if args.n_stubborn + args.n_suggestible > self._n_agents:
raise ValueError("stubborn + suggestible agents is more than "
f"{self._n_agents}")
if len(api_keys) < self._n_agents * args.n_exp:
raise ValueError("api_keys are not enough for "
f"{self._n_agents} agents")
if self._m.shape[0] != self._m.shape[1]:
raise ValueError("connectivity_matrix is not a square matrix, "
f"shape: {self._m.shape}")
if self._m.shape[0] != self._n_agents:
raise ValueError("connectivity_matrix is not enough for "
f"{self._n_agents} agents, shape: {self._m.shape}")
def _generate_agents(self, simulation_ind):
"""Generate agent instances for the simulation.
Args:
simulation_ind: Index of the simulation.
Returns:
List of Agent2D instances.
"""
agents = []
position = (np.array([[20, 20], [80, 20], [50, 80]])
+ np.random.randint(-10, 10, size=(self._n_agents, 2)))
for idx in range(self._n_agents):
position_others = [(x, y) for x, y in position[self._m[idx, :]]]
agent = Agent2D(position=tuple(position[idx]),
other_position=position_others,
key=api_keys[simulation_ind * self._n_agents + idx],
model="gpt-3.5-turbo-0613",
name=names[idx])
# add personality, neutral by default
personality = ""
if idx < self._n_stubborn:
personality = stubborn
elif (self._n_stubborn <= idx
< self._n_stubborn + self._n_suggestible):
personality = suggestible
agent.memories_update(role='system',
content=agent_role + personality)
agents.append(agent)
self._positions[simulation_ind] = position
return agents
def _generate_question(self, agent, round) -> str:
"""Generate a question for an agent in a round.
Args:
agent: An Agent2D instance.
round: The current round.
Returns:
A formatted string containing the question.
"""
input = self._init_input.format(agent.position, agent.other_position)
return input
def _exp_postprocess(self):
"""Post-process the experiment data, including saving and
generating visualizations."""
is_success, filename = self.save_record(self._output_file)
if is_success:
# Call functions to plot and generate HTML
trajectory_file = self._output_file + '/trajectory.p'
plot_xy(trajectory_file)
video(trajectory_file)
| """
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 Vector2dDebate(Template):
"""
Vector2dDebate is a class that simulates a 2D debate scenario with multiple
agents.
This class provides the framework to conduct 2D debates with agents and
record their trajectories.
Args:
args:
An object containing configuration parameters for the debate
simulation.
connectivity_matrix:
A square matrix defining agent knowledge connectivity.
Raises:
ValueError:
If the sum of stubborn and suggestible agents exceeds the total
number of agents,
if there are insufficient API keys for the agents, or if the
connectivity matrix is not appropriate.
"""
def __init__(self, args, connectivity_matrix):
"""
Initialize the Vector2dDebate instance.
Args:
args: An object containing configuration options.
connectivity_matrix: A matrix defining agent knowledge connectivity.
Raises:
ValueError: If the input parameters are invalid.
"""
super().__init__(args)
self._dt = 0.1
self._n_agents = args.agents
self._init_input = game_description + "\n\n" + agent_output_form
self._round_description = round_description
self._positions = [[]] * args.n_exp
self._output_file = args.out_file
self._n_suggestible = args.n_suggestible
self._n_stubborn = args.n_stubborn
self._trajectory = {"pos": {}, "target": {}} # A dictionary for recording agent trajectories
# np.random.seed(0)
# Define the connectivity matrix for agent knowledge
# m(i, j) = 1 means agent i knows the position of agent j
self._m = connectivity_matrix
# Safety checks for input parameters
if args.n_stubborn + args.n_suggestible > self._n_agents:
raise ValueError("stubborn + suggestible agents is more than "
f"{self._n_agents}")
if len(api_keys) < self._n_agents * args.n_exp:
raise ValueError("api_keys are not enough for "
f"{self._n_agents} agents")
if self._m.shape[0] != self._m.shape[1]:
raise ValueError("connectivity_matrix is not a square matrix, "
f"shape: {self._m.shape}")
if self._m.shape[0] != self._n_agents:
raise ValueError("connectivity_matrix is not enough for "
f"{self._n_agents} agents, shape: {self._m.shape}")
def _generate_agents(self, simulation_ind):
"""Generate agent instances for the simulation.
Args:
simulation_ind: Index of the simulation.
Returns:
List of Agent2D instances.
"""
agents = []
position = (np.array([[20, 20], [80, 20], [50, 80]])
+ np.random.randint(-10, 10, size=(self._n_agents, 2)))
for idx in range(self._n_agents):
position_others = [(x, y) for x, y in position[self._m[idx, :]]]
agent = Agent2D(position=tuple(position[idx]),
other_position=position_others,
key=api_keys[simulation_ind * self._n_agents + idx],
model="gpt-3.5-turbo-0613",
name=names[idx])
# add personality, neutral by default
personality = ""
if idx < self._n_stubborn:
personality = stubborn
elif (self._n_stubborn <= idx
< self._n_stubborn + self._n_suggestible):
personality = suggestible
agent.memories_update(role='system',
content=agent_role + personality)
agents.append(agent)
self._positions[simulation_ind] = position
return agents
def _generate_question(self, agent, round) -> str:
"""Generate a question for an agent in a round.
Args:
agent: An Agent2D instance.
round: The current round.
Returns:
A formatted string containing the question.
"""
input = self._init_input.format(agent.position, agent.other_position)
return input
def _exp_postprocess(self):
"""Post-process the experiment data, including saving and
generating visualizations."""
is_success, filename = self.save_record(self._output_file)
if is_success:
# Call functions to plot and generate HTML
trajectory_file = self._output_file + '/trajectory.p'
plot_xy(trajectory_file)
video(trajectory_file) | gen_html(filename, self._output_file) | 7 | 2023-10-20 07:58:07+00:00 | 8k |
inngest/inngest-py | inngest/flask.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 ... | import json
import flask
from ._internal import (
client_lib,
comm,
const,
errors,
execution,
function,
net,
transforms,
types,
) | 3,890 | """Flask integration for Inngest."""
FRAMEWORK = const.Framework.FLASK
def serve(
app: flask.Flask,
client: client_lib.Inngest,
functions: list[function.Function],
*,
serve_origin: str | None = None,
serve_path: str | None = None,
) -> None:
"""
Serve Inngest functions in a Flask app.
Args:
----
app: Flask app.
client: Inngest client.
functions: List of functions to serve.
serve_origin: Origin to serve the functions from.
serve_path: Path to serve the functions from.
"""
| """Flask integration for Inngest."""
FRAMEWORK = const.Framework.FLASK
def serve(
app: flask.Flask,
client: client_lib.Inngest,
functions: list[function.Function],
*,
serve_origin: str | None = None,
serve_path: str | None = None,
) -> None:
"""
Serve Inngest functions in a Flask app.
Args:
----
app: Flask app.
client: Inngest client.
functions: List of functions to serve.
serve_origin: Origin to serve the functions from.
serve_path: Path to serve the functions from.
"""
| handler = comm.CommHandler( | 1 | 2023-10-19 01:02:30+00:00 | 8k |
skleee/GLEN | src/tevatron/modeling/glen_t5_modeling.py | [
{
"identifier": "T5Config",
"path": "src/tevatron/modeling/glen_t5_config.py",
"snippet": "class T5Config(PretrainedConfig):\n r\"\"\"\n This is the configuration class to store the configuration of a :class:`~transformers.T5Model` or a\n :class:`~transformers.TFT5Model`. It is used to instanti... | import copy
import math
import os
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
import re
import numpy as np
import tensorflow as tf
from transformers import logging
from transformers.modeling_utils import (
PreTrainedModel,
find_pruneable_heads_and_indices,
prune_linear_layer,
)
from transformers.file_utils import (
DUMMY_INPUTS,
DUMMY_MASK,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings,
)
from .glen_t5_config import T5Config
from .glen_t5_outputs import BaseModelOutputWithPast, Seq2SeqModelOutput
from tevatron.modeling import (
T5ForConditionalGeneration_GLEN as T5ForConditionalGeneration,
) | 5,751 | `T5 Training <./t5.html#training>`__.
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Mask to avoid performing attention on padding token indices.
Mask values selected in ``[0, 1]``:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
`What are attention masks? <../glossary.html#attention-mask>`__
decoder_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`):
Provide for sequence to sequence training. T5 uses the :obj:`pad_token_id` as the starting token for
:obj:`decoder_input_ids` generation.
If :obj:`past_key_values` is used, optionally only the last :obj:`decoder_input_ids` have to be input (see
:obj:`past_key_values`).
To know more on how to prepare :obj:`decoder_input_ids` for pretraining take a look at
`T5 Training <./t5.html#training>`__. If :obj:`decoder_input_ids` and :obj:`decoder_inputs_embeds` are both
unset, :obj:`decoder_input_ids` takes the value of :obj:`input_ids`.
decoder_attention_mask (:obj:`torch.BoolTensor` of shape :obj:`(batch_size, tgt_seq_len)`, `optional`):
Default behavior: generate a tensor that ignores pad tokens in :obj:`decoder_input_ids`. Causal mask will
also be used by default.
encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`):
Tuple consists of (:obj:`last_hidden_state`, :obj:`optional`: `hidden_states`, :obj:`optional`: `attentions`)
:obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)` is a sequence of
hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
Mask to nullify selected heads of the self-attention modules.
Mask values selected in ``[0, 1]``:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
vectors than the model's internal embedding lookup matrix.
decoder_inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, target_sequence_length, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`decoder_input_ids` you can choose to directly pass an embedded
representation.
If :obj:`past_key_values` is used, optionally only the last :obj:`decoder_inputs_embeds` have to be input
(see :obj:`past_key_values`).
This is useful if you want more control over how to convert :obj:`decoder_input_ids` indices into
associated vectors than the model's internal embedding lookup matrix.
If :obj:`decoder_input_ids` and :obj:`decoder_inputs_embeds` are both
unset, :obj:`decoder_inputs_embeds` takes the value of :obj:`inputs_embeds`.
use_cache (:obj:`bool`, `optional`):
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
decoding (see :obj:`past_key_values`).
output_attentions (:obj:`bool`, `optional`):
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
tensors for more detail.
output_hidden_states (:obj:`bool`, `optional`):
Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
more detail.
return_dict (:obj:`bool`, `optional`):
Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
"""
@add_start_docstrings(
"The bare T5 Model transformer outputting raw hidden-states"
"without any specific head on top.",
T5_START_DOCSTRING,
)
class T5Model(T5PreTrainedModel):
def __init__(self, config: T5Config):
super().__init__(config)
self.shared = nn.Embedding(config.vocab_size, config.d_model)
encoder_config = copy.deepcopy(config)
encoder_config.use_cache = False
encoder_config.is_encoder_decoder = False
self.encoder = T5Stack(encoder_config, self.shared)
decoder_config = copy.deepcopy(config)
decoder_config.is_decoder = True
decoder_config.is_encoder_decoder = False
decoder_config.num_layers = config.num_decoder_layers
if self.multiple_decoder:
self.decoder_list = []
for i in range(self.decoder_num):
self.decoder_list.append(T5Stack(decoder_config, self.shared))
else:
self.decoder = T5Stack(decoder_config, self.shared)
self.init_weights()
def get_input_embeddings(self):
return self.shared
def set_input_embeddings(self, new_embeddings):
self.shared = new_embeddings
self.encoder.set_input_embeddings(new_embeddings)
self.decoder.set_input_embeddings(new_embeddings)
def get_encoder(self):
return self.encoder
def get_decoder(self):
return self.decoder
def _prune_heads(self, heads_to_prune):
"""Prunes heads of the model.
heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
See base class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)
@replace_return_docstrings(
| # coding=utf-8
# Copyright 2018 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
#
# 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.
""" PyTorch T5 model. """
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "T5Config"
####################################################
# This dict contrains shortcut names and associated url
# for the pretrained weights provided with the models
####################################################
T5_PRETRAINED_MODEL_ARCHIVE_LIST = [
"t5-small",
"t5-base",
"t5-large",
"t5-3b",
"t5-11b",
# See all T5 models at https://huggingface.co/models?filter=t5
]
####################################################
# This is a conversion method from TF 1.0 to PyTorch
# More details: https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28
####################################################
def load_tf_weights_in_t5(model, config, tf_checkpoint_path):
"""Load tf checkpoints in a pytorch model."""
try:
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(tf_checkpoint_path)
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
tf_weights = {}
for name, shape in init_vars:
logger.info("Loading TF weight {} with shape {}".format(name, shape))
array = tf.train.load_variable(tf_path, name)
names.append(name)
tf_weights[name] = array
for txt_name in names:
name = txt_name.split("/")
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
# which are not required for using pretrained model
if any(
n
in [
"adam_v",
"adam_m",
"AdamWeightDecayOptimizer",
"AdamWeightDecayOptimizer_1",
"global_step",
]
for n in name
):
logger.info("Skipping {}".format("/".join(name)))
tf_weights.pop(txt_name, None)
continue
if "_slot_" in name[-1]:
logger.info("Skipping {}".format("/".join(name)))
tf_weights.pop(txt_name, None)
continue
pointer = model
array = tf_weights[txt_name]
for m_name in name:
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
scope_names = re.split(r"_(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] in ["kernel", "scale", "embedding"]:
pointer = getattr(pointer, "weight")
# elif scope_names[0] == 'scale':
# pointer = getattr(pointer, 'weight')
# elif scope_names[0] == 'output_bias' or scope_names[0] == 'beta':
# pointer = getattr(pointer, 'bias')
# elif scope_names[0] == 'squad':
# pointer = getattr(pointer, 'classifier')
else:
try:
pointer = getattr(pointer, scope_names[0])
except AttributeError:
logger.info("Skipping {}".format("/".join(name)))
continue
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
if scope_names[0] not in ["kernel", "scale", "embedding"]:
pointer = getattr(pointer, "weight")
if scope_names[0] != "embedding":
logger.info(
"Transposing numpy weight of shape {} for {}".format(array.shape, name)
)
array = np.transpose(array)
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info("Initialize PyTorch weight {}".format(name))
pointer.data = torch.from_numpy(array.astype(np.float32))
tf_weights.pop(txt_name, None)
logger.info(
"Weights not copied to PyTorch model: {}".format(", ".join(tf_weights.keys()))
)
# logger.info("Weights not copied to PyTorch model: {}".format(', '.join(tf_weights.keys())))
return model
####################################################
# PyTorch Models are constructed by sub-classing
# - torch.nn.Module for the layers and
# - PreTrainedModel for the models (it-self a sub-class of torch.nn.Module)
####################################################
class T5LayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""Construct a layernorm module in the T5 style
No bias and no substraction of mean.
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
# layer norm should always be calculated in float32
variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)
x = x / torch.sqrt(variance + self.variance_epsilon)
if self.weight.dtype == torch.float16:
x = x.to(torch.float16)
return self.weight * x
class T5DenseReluDense(nn.Module):
def __init__(self, config):
super().__init__()
self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(self, hidden_states):
h = self.wi(hidden_states)
h = F.relu(h)
h = self.dropout(h)
h = self.wo(h)
return h
class T5LayerFF(nn.Module):
def __init__(self, config):
super().__init__()
self.DenseReluDense = T5DenseReluDense(config)
self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(self, hidden_states):
norm_x = self.layer_norm(hidden_states)
y = self.DenseReluDense(norm_x)
layer_output = hidden_states + self.dropout(y)
return layer_output
class T5Attention(nn.Module):
def __init__(
self,
config: T5Config,
has_relative_attention_bias=False,
is_bidirectional=False,
):
super().__init__()
self.is_bidirectional = is_bidirectional
self.is_decoder = config.is_decoder
self.has_relative_attention_bias = has_relative_attention_bias
self.relative_attention_num_buckets = config.relative_attention_num_buckets
self.d_model = config.d_model
self.d_kv = config.d_kv
self.n_heads = config.num_heads
self.dropout = config.dropout_rate
self.inner_dim = self.n_heads * self.d_kv
# Mesh TensorFlow initialization to avoid scaling before softmax
self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)
self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)
self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)
self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)
if self.has_relative_attention_bias:
self.relative_attention_bias = nn.Embedding(
self.relative_attention_num_buckets, self.n_heads
)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.n_heads, self.d_kv, self.pruned_heads
)
# Prune linear layers
self.q = prune_linear_layer(self.q, index)
self.k = prune_linear_layer(self.k, index)
self.v = prune_linear_layer(self.v, index)
self.o = prune_linear_layer(self.o, index, dim=1)
# Update hyper params
self.n_heads = self.n_heads - len(heads)
self.inner_dim = self.d_kv * self.n_heads
self.pruned_heads = self.pruned_heads.union(heads)
@staticmethod
def _relative_position_bucket(
relative_position, bidirectional=True, num_buckets=32, max_distance=128
):
"""
Adapted from Mesh Tensorflow:
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
Translate relative position to a bucket number for relative attention.
The relative position is defined as memory_position - query_position, i.e.
the distance in tokens from the attending position to the attended-to
position. If bidirectional=False, then positive relative positions are
invalid.
We use smaller buckets for small absolute relative_position and larger buckets
for larger absolute relative_positions. All relative positions >=max_distance
map to the same bucket. All relative positions <=-max_distance map to the
same bucket. This should allow for more graceful generalization to longer
sequences than the model has been trained on.
Args:
relative_position: an int32 Tensor
bidirectional: a boolean - whether the attention is bidirectional
num_buckets: an integer
max_distance: an integer
Returns:
a Tensor with the same shape as relative_position, containing int32
values in the range [0, num_buckets)
"""
ret = 0
n = -relative_position
if bidirectional:
num_buckets //= 2
ret += (n < 0).to(
torch.long
) * num_buckets # mtf.to_int32(mtf.less(n, 0)) * num_buckets
n = torch.abs(n)
else:
n = torch.max(n, torch.zeros_like(n))
# now n is in the range [0, inf)
# half of the buckets are for exact increments in positions
max_exact = num_buckets // 2
is_small = n < max_exact
# The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
val_if_large = max_exact + (
torch.log(n.float() / max_exact)
/ math.log(max_distance / max_exact)
* (num_buckets - max_exact)
).to(torch.long)
val_if_large = torch.min(
val_if_large, torch.full_like(val_if_large, num_buckets - 1)
)
ret += torch.where(is_small, n, val_if_large)
return ret
def compute_bias(self, qlen, klen):
"""Compute binned relative position bias"""
context_position = torch.arange(qlen, dtype=torch.long)[:, None]
memory_position = torch.arange(klen, dtype=torch.long)[None, :]
relative_position = memory_position - context_position # shape (qlen, klen)
rp_bucket = self._relative_position_bucket(
relative_position, # shape (qlen, klen)
bidirectional=self.is_bidirectional,
num_buckets=self.relative_attention_num_buckets,
)
rp_bucket = rp_bucket.to(self.relative_attention_bias.weight.device)
values = self.relative_attention_bias(
rp_bucket
) # shape (qlen, klen, num_heads)
values = values.permute([2, 0, 1]).unsqueeze(
0
) # shape (1, num_heads, qlen, klen)
return values
def forward(
self,
input,
mask=None,
kv=None,
position_bias=None,
past_key_value=None,
head_mask=None,
query_length=None,
use_cache=False,
output_attentions=False,
):
"""
Self-attention (if kv is None) or attention over source sentence (provided by kv).
"""
# Input is (bs, qlen, dim)
# Mask is (bs, klen) (non-causal) or (bs, klen, klen)
# past_key_value[0] is (bs, n_heads, q_len - 1, dim_per_head)
bs, qlen, dim = input.size()
if past_key_value is not None:
assert self.is_decoder is True, "Encoder cannot cache past key value states"
assert (
len(past_key_value) == 2
), "past_key_value should have 2 past states: keys and values. Got {} past states".format(
len(past_key_value)
)
real_qlen = (
qlen + past_key_value[0].shape[2]
if query_length is None
else query_length
)
else:
real_qlen = qlen
if kv is None:
klen = real_qlen
else:
klen = kv.size(1)
def shape(x):
"""projection"""
return x.view(bs, -1, self.n_heads, self.d_kv).transpose(1, 2)
def unshape(x):
"""compute context"""
return x.transpose(1, 2).contiguous().view(bs, -1, self.inner_dim)
q = shape(self.q(input)) # (bs, n_heads, qlen, dim_per_head)
if kv is None:
k = shape(self.k(input)) # (bs, n_heads, qlen, dim_per_head)
v = shape(self.v(input)) # (bs, n_heads, qlen, dim_per_head)
elif past_key_value is None:
k = v = kv
k = shape(self.k(k)) # (bs, n_heads, qlen, dim_per_head)
v = shape(self.v(v)) # (bs, n_heads, qlen, dim_per_head)
if past_key_value is not None:
if kv is None:
k_, v_ = past_key_value
k = torch.cat([k_, k], dim=2) # (bs, n_heads, klen, dim_per_head)
v = torch.cat([v_, v], dim=2) # (bs, n_heads, klen, dim_per_head)
else:
k, v = past_key_value
if self.is_decoder and use_cache is True:
present_key_value_state = ((k, v),)
else:
present_key_value_state = (None,)
# (bs, n_heads, qlen, klen)
scores = torch.matmul(
q, k.transpose(3, 2)
) # equivalent of torch.einsum("bnqd,bnkd->bnqk", q, k), compatible with onnx op>9
if position_bias is None:
if not self.has_relative_attention_bias:
raise ValueError(
"No position_bias provided and no weights to compute position_bias"
)
position_bias = self.compute_bias(real_qlen, klen)
# if key and values are already calculated
# we want only the last query position bias
if past_key_value is not None:
position_bias = position_bias[:, :, -qlen:, :]
if mask is not None:
position_bias = position_bias + mask # (bs, n_heads, qlen, klen)
scores += position_bias
weights = F.softmax(scores.float(), dim=-1).type_as(
scores
) # (bs, n_heads, qlen, klen)
weights = F.dropout(
weights, p=self.dropout, training=self.training
) # (bs, n_heads, qlen, klen)
# Mask heads if we want to
if head_mask is not None:
weights = weights * head_mask
context = torch.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)
context = unshape(context) # (bs, qlen, dim)
context = self.o(context)
outputs = (context,) + present_key_value_state
if output_attentions:
outputs = outputs + (weights,)
if self.has_relative_attention_bias:
outputs = outputs + (position_bias,)
return outputs
class T5LayerSelfAttention(nn.Module):
def __init__(self, config, has_relative_attention_bias=False):
super().__init__()
self.SelfAttention = T5Attention(
config,
has_relative_attention_bias=has_relative_attention_bias,
is_bidirectional=not config.is_decoder,
)
self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(
self,
hidden_states,
attention_mask=None,
position_bias=None,
head_mask=None,
past_key_value=None,
use_cache=False,
output_attentions=False,
):
norm_x = self.layer_norm(hidden_states)
attention_output = self.SelfAttention(
norm_x,
mask=attention_mask,
position_bias=position_bias,
head_mask=head_mask,
past_key_value=past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
)
y = attention_output[0]
layer_output = hidden_states + self.dropout(y)
outputs = (layer_output,) + attention_output[
1:
] # add attentions if we output them
return outputs
class T5LayerCrossAttention(nn.Module):
def __init__(self, config, has_relative_attention_bias=False):
super().__init__()
self.EncDecAttention = T5Attention(
config,
has_relative_attention_bias=has_relative_attention_bias,
is_bidirectional=True,
)
self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(
self,
hidden_states,
kv,
attention_mask=None,
position_bias=None,
head_mask=None,
past_key_value=None,
use_cache=False,
query_length=None,
output_attentions=False,
):
norm_x = self.layer_norm(hidden_states)
attention_output = self.EncDecAttention(
norm_x,
mask=attention_mask,
kv=kv,
position_bias=position_bias,
head_mask=head_mask,
past_key_value=past_key_value,
use_cache=use_cache,
query_length=query_length,
output_attentions=output_attentions,
)
y = attention_output[0]
layer_output = hidden_states + self.dropout(y)
outputs = (layer_output,) + attention_output[
1:
] # add attentions if we output them
return outputs
class T5Block(nn.Module):
def __init__(self, config, has_relative_attention_bias=False):
super().__init__()
self.is_decoder = config.is_decoder
self.layer = nn.ModuleList()
self.layer.append(
T5LayerSelfAttention(
config, has_relative_attention_bias=has_relative_attention_bias
)
)
if self.is_decoder:
self.layer.append(
T5LayerCrossAttention(
config, has_relative_attention_bias=has_relative_attention_bias
)
)
self.layer.append(T5LayerFF(config))
def forward(
self,
hidden_states,
attention_mask=None,
position_bias=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
encoder_decoder_position_bias=None,
head_mask=None,
past_key_value=None,
use_cache=False,
output_attentions=False,
):
if past_key_value is not None:
assert self.is_decoder, "Only decoder can use `past_key_values`"
expected_num_past_key_values = 2 if encoder_hidden_states is None else 4
error_message = "There should be {} past states. 2 (past / key) for self attention.{} Got {} past key / value states".format(
expected_num_past_key_values,
"2 (past / key) for cross attention"
if expected_num_past_key_values == 4
else "",
len(past_key_value),
)
assert len(past_key_value) == expected_num_past_key_values, error_message
self_attn_past_key_value = past_key_value[:2]
cross_attn_past_key_value = past_key_value[2:]
else:
self_attn_past_key_value, cross_attn_past_key_value = None, None
self_attention_outputs = self.layer[0](
hidden_states,
attention_mask=attention_mask,
position_bias=position_bias,
head_mask=head_mask,
past_key_value=self_attn_past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
)
hidden_states, present_key_value_state = self_attention_outputs[:2]
attention_outputs = self_attention_outputs[
2:
] # Keep self-attention outputs and relative position weights
if self.is_decoder and encoder_hidden_states is not None:
# the actual query length is unknown for cross attention
# if using past key value states. Need to inject it here
if present_key_value_state is not None:
query_length = present_key_value_state[0].shape[2]
else:
query_length = None
cross_attention_outputs = self.layer[1](
hidden_states,
kv=encoder_hidden_states,
attention_mask=encoder_attention_mask,
position_bias=encoder_decoder_position_bias,
head_mask=head_mask,
past_key_value=cross_attn_past_key_value,
query_length=query_length,
use_cache=use_cache,
output_attentions=output_attentions,
)
hidden_states = cross_attention_outputs[0]
# Combine self attn and cross attn key value states
if present_key_value_state is not None:
present_key_value_state = (
present_key_value_state + cross_attention_outputs[1]
)
# Keep cross-attention outputs and relative position weights
attention_outputs = attention_outputs + cross_attention_outputs[2:]
# Apply Feed Forward layer
hidden_states = self.layer[-1](hidden_states)
outputs = (hidden_states,)
# Add attentions if we output them
outputs = outputs + (present_key_value_state,) + attention_outputs
return outputs # hidden-states, present_key_value_states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
class T5PreTrainedModel(PreTrainedModel):
"""An abstract class to handle weights initialization and
a simple interface for downloading and loading pretrained models.
"""
config_class = T5Config
load_tf_weights = load_tf_weights_in_t5
base_model_prefix = "transformer"
@property
def dummy_inputs(self):
input_ids = torch.tensor(DUMMY_INPUTS)
input_mask = torch.tensor(DUMMY_MASK)
dummy_inputs = {
"decoder_input_ids": input_ids,
"input_ids": input_ids,
"decoder_attention_mask": input_mask,
}
return dummy_inputs
def _init_weights(self, module):
"""Initialize the weights"""
factor = (
self.config.initializer_factor
) # Used for testing weights initialization
if isinstance(module, T5LayerNorm):
module.weight.data.fill_(factor * 1.0)
elif isinstance(module, (T5Model, T5ForConditionalGeneration)):
# Mesh TensorFlow embeddings initialization
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
elif isinstance(module, T5DenseReluDense):
# Mesh TensorFlow FF initialization
# See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
# and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
module.wi.weight.data.normal_(
mean=0.0, std=factor * ((self.config.d_model) ** -0.5)
)
if hasattr(module.wi, "bias") and module.wi.bias is not None:
module.wi.bias.data.zero_()
module.wo.weight.data.normal_(
mean=0.0, std=factor * ((self.config.d_ff) ** -0.5)
)
if hasattr(module.wo, "bias") and module.wo.bias is not None:
module.wo.bias.data.zero_()
elif isinstance(module, T5Attention):
# Mesh TensorFlow attention initialization to avoid scaling before softmax
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
d_model = self.config.d_model
d_kv = self.config.d_kv
n_heads = self.config.num_heads
module.q.weight.data.normal_(
mean=0.0, std=factor * ((d_model * d_kv) ** -0.5)
)
module.k.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
module.v.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
module.o.weight.data.normal_(
mean=0.0, std=factor * ((n_heads * d_kv) ** -0.5)
)
if module.has_relative_attention_bias:
module.relative_attention_bias.weight.data.normal_(
mean=0.0, std=factor * ((d_model) ** -0.5)
)
def _shift_right(self, input_ids):
decoder_start_token_id = self.config.decoder_start_token_id
pad_token_id = self.config.pad_token_id
assert (
decoder_start_token_id is not None
), "self.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id. See T5 docs for more information"
# shift inputs to the right
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
shifted_input_ids[..., 0] = decoder_start_token_id
assert (
pad_token_id is not None
), "self.model.config.pad_token_id has to be defined."
# replace possible -100 values in labels by `pad_token_id`
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
assert torch.all(
shifted_input_ids >= 0
).item(), "Verify that `shifted_input_ids` has only positive values"
return shifted_input_ids
class T5Stack(T5PreTrainedModel):
def __init__(self, config, embed_tokens=None):
super().__init__(config)
self.embed_tokens = embed_tokens
self.is_decoder = config.is_decoder
self.block = nn.ModuleList(
[
T5Block(config, has_relative_attention_bias=bool(i == 0))
for i in range(config.num_layers)
]
)
self.final_layer_norm = T5LayerNorm(
config.d_model, eps=config.layer_norm_epsilon
)
self.dropout = nn.Dropout(config.dropout_rate)
self.init_weights()
def get_input_embeddings(self):
return self.embed_tokens
def get_output_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, new_embeddings):
self.embed_tokens = new_embeddings
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
inputs_embeds=None,
head_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
use_cache = use_cache if use_cache is not None else self.config.use_cache
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states
)
return_dict = (
return_dict if return_dict is not None else self.config.use_return_dict
)
if input_ids is not None and inputs_embeds is not None:
err_msg_prefix = "decoder_" if self.is_decoder else ""
raise ValueError(
f"You cannot specify both {err_msg_prefix}inputs and {err_msg_prefix}inputs_embeds at the same time"
)
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
err_msg_prefix = "decoder_" if self.is_decoder else ""
raise ValueError(
f"You have to specify either {err_msg_prefix}inputs or {err_msg_prefix}inputs_embeds"
)
if inputs_embeds is None:
assert (
self.embed_tokens is not None
), "You have to intialize the model with valid token embeddings"
if self.training and self.is_decoder and len(input_ids) == 2:
inputs_embeds = self.embed_tokens(input_ids[0])
else:
inputs_embeds = self.embed_tokens(input_ids)
batch_size, seq_length = input_shape
# required mask seq length can be calculated via length of past
mask_seq_length = (
past_key_values[0][0].shape[2] + seq_length
if past_key_values is not None
else seq_length
)
if use_cache is True:
assert (
self.is_decoder
), ":obj:`use_cache` can only be set to `True` if {} is used as a decoder".format(
self
)
if attention_mask is None:
attention_mask = torch.ones(batch_size, mask_seq_length).to(
inputs_embeds.device
)
if (
self.is_decoder
and encoder_attention_mask is None
and encoder_hidden_states is not None
):
encoder_seq_length = encoder_hidden_states.shape[1]
encoder_attention_mask = torch.ones(
batch_size,
encoder_seq_length,
device=inputs_embeds.device,
dtype=torch.long,
)
# initialize past_key_values with `None` if past does not exist
if past_key_values is None:
past_key_values = [None] * len(self.block)
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask = self.get_extended_attention_mask(
attention_mask, input_shape, inputs_embeds.device
)
# print(f"extended_attention_mask: {extended_attention_mask.shape}")
if self.is_decoder and encoder_attention_mask is not None:
encoder_extended_attention_mask = self.invert_attention_mask(
encoder_attention_mask
)
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
head_mask = self.get_head_mask(head_mask, self.config.num_layers)
present_key_value_states = () if use_cache else None
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
position_bias = None
encoder_decoder_position_bias = None
hidden_states = self.dropout(inputs_embeds)
for i, (layer_module, past_key_value) in enumerate(
zip(self.block, past_key_values)
):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_outputs = layer_module(
hidden_states,
attention_mask=extended_attention_mask,
position_bias=position_bias,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
encoder_decoder_position_bias=encoder_decoder_position_bias,
head_mask=head_mask[i],
past_key_value=past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
)
# layer_outputs is a tuple with:
# hidden-states, key-value-states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
hidden_states, present_key_value_state = layer_outputs[:2]
if i == 0:
# We share the position biases between the layers - the first layer store them
# layer_outputs = hidden-states, key-value-states (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
position_bias = layer_outputs[3 if output_attentions else 2]
if self.is_decoder and encoder_hidden_states is not None:
encoder_decoder_position_bias = layer_outputs[
5 if output_attentions else 3
]
# append next layer key value states
if use_cache:
present_key_value_states = present_key_value_states + (
present_key_value_state,
)
if output_attentions:
all_attentions = all_attentions + (
layer_outputs[2],
) # We keep only self-attention weights for now
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.dropout(hidden_states)
# Add last layer
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [
hidden_states,
present_key_value_states,
all_hidden_states,
all_attentions,
]
if v is not None
)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=present_key_value_states,
hidden_states=all_hidden_states,
attentions=all_attentions,
)
T5_START_DOCSTRING = r"""
The T5 model was proposed in `Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
<https://arxiv.org/abs/1910.10683>`__ by Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang,
Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu.
It's an encoder decoder transformer pre-trained in a text-to-text denoising generative setting.
This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
pruning heads etc.)
This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
usage and behavior.
Parameters:
config (:class:`~transformers.T5Config`): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the configuration.
Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
"""
T5_INPUTS_DOCSTRING = r"""
Args:
input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right
and the left.
Indices can be obtained using :class:`~transformers.T5Tokenizer`.
See :meth:`transformers.PreTrainedTokenizer.encode` and
:meth:`transformers.PreTrainedTokenizer.__call__` for detail.
To know more on how to prepare :obj:`input_ids` for pretraining take a look a
`T5 Training <./t5.html#training>`__.
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Mask to avoid performing attention on padding token indices.
Mask values selected in ``[0, 1]``:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
`What are attention masks? <../glossary.html#attention-mask>`__
decoder_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`):
Provide for sequence to sequence training. T5 uses the :obj:`pad_token_id` as the starting token for
:obj:`decoder_input_ids` generation.
If :obj:`past_key_values` is used, optionally only the last :obj:`decoder_input_ids` have to be input (see
:obj:`past_key_values`).
To know more on how to prepare :obj:`decoder_input_ids` for pretraining take a look at
`T5 Training <./t5.html#training>`__. If :obj:`decoder_input_ids` and :obj:`decoder_inputs_embeds` are both
unset, :obj:`decoder_input_ids` takes the value of :obj:`input_ids`.
decoder_attention_mask (:obj:`torch.BoolTensor` of shape :obj:`(batch_size, tgt_seq_len)`, `optional`):
Default behavior: generate a tensor that ignores pad tokens in :obj:`decoder_input_ids`. Causal mask will
also be used by default.
encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`):
Tuple consists of (:obj:`last_hidden_state`, :obj:`optional`: `hidden_states`, :obj:`optional`: `attentions`)
:obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)` is a sequence of
hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
(those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
Mask to nullify selected heads of the self-attention modules.
Mask values selected in ``[0, 1]``:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
vectors than the model's internal embedding lookup matrix.
decoder_inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, target_sequence_length, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`decoder_input_ids` you can choose to directly pass an embedded
representation.
If :obj:`past_key_values` is used, optionally only the last :obj:`decoder_inputs_embeds` have to be input
(see :obj:`past_key_values`).
This is useful if you want more control over how to convert :obj:`decoder_input_ids` indices into
associated vectors than the model's internal embedding lookup matrix.
If :obj:`decoder_input_ids` and :obj:`decoder_inputs_embeds` are both
unset, :obj:`decoder_inputs_embeds` takes the value of :obj:`inputs_embeds`.
use_cache (:obj:`bool`, `optional`):
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
decoding (see :obj:`past_key_values`).
output_attentions (:obj:`bool`, `optional`):
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
tensors for more detail.
output_hidden_states (:obj:`bool`, `optional`):
Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
more detail.
return_dict (:obj:`bool`, `optional`):
Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
"""
@add_start_docstrings(
"The bare T5 Model transformer outputting raw hidden-states"
"without any specific head on top.",
T5_START_DOCSTRING,
)
class T5Model(T5PreTrainedModel):
def __init__(self, config: T5Config):
super().__init__(config)
self.shared = nn.Embedding(config.vocab_size, config.d_model)
encoder_config = copy.deepcopy(config)
encoder_config.use_cache = False
encoder_config.is_encoder_decoder = False
self.encoder = T5Stack(encoder_config, self.shared)
decoder_config = copy.deepcopy(config)
decoder_config.is_decoder = True
decoder_config.is_encoder_decoder = False
decoder_config.num_layers = config.num_decoder_layers
if self.multiple_decoder:
self.decoder_list = []
for i in range(self.decoder_num):
self.decoder_list.append(T5Stack(decoder_config, self.shared))
else:
self.decoder = T5Stack(decoder_config, self.shared)
self.init_weights()
def get_input_embeddings(self):
return self.shared
def set_input_embeddings(self, new_embeddings):
self.shared = new_embeddings
self.encoder.set_input_embeddings(new_embeddings)
self.decoder.set_input_embeddings(new_embeddings)
def get_encoder(self):
return self.encoder
def get_decoder(self):
return self.decoder
def _prune_heads(self, heads_to_prune):
"""Prunes heads of the model.
heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
See base class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)
@replace_return_docstrings( | output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC | 2 | 2023-10-18 09:40:42+00:00 | 8k |
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.