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 |
|---|---|---|---|---|---|---|---|---|---|---|
liebrandapps/FindMyGUI | api.py | [
{
"identifier": "AirTag",
"path": "airTag.py",
"snippet": "class AirTag:\n\n def __init__(self, ctx, jsonFile=None):\n self.log = ctx.log\n self.cfg = ctx.cfg\n self.__id = uuid.uuid4().hex\n self._name = \"\"\n self._privateKey = None\n self._advertisementKe... | import json
import time
import requests.exceptions
from airTag import AirTag
from findmy.request_reports import FindMy | 3,610 | """
Mark Liebrand 2024
This file is part of FindMyGUI which is released under the Apache 2.0 License
See file LICENSE or go to for full license details https://github.com/liebrandapps/FindMyGUI
"""
class API:
def __init__(self, ctx):
self.ctx = ctx
self.log = ctx.log
def call(self, cmd, params=None):
self.log.debug(f"[API] Handling API command <{cmd}>")
result = {}
if cmd == "listTags":
result = self._listTags()
if cmd == 'getPos':
result = self._getPos()
if cmd == 'refresh':
result = self._refresh()
if cmd == 'getTagData':
result = self._getTagData(params['id'][0])
if cmd == 'editTag':
result = self._editTag(params['id'][0], params['name'][0], params['privateKey'][0],
params['advertisementKey'][0], params['imgId'][0])
if cmd == 'addTag':
result = self._addTag(params['id'][0], params['name'][0], params['privateKey'][0],
params['advertisementKey'][0], params['imgId'][0])
if cmd == 'signInStatus':
result = self._signInStatus(int(params['timeStamp'][0]))
if cmd == 'creds':
result = self._creds(params['userName'][0], params['password'][0])
if cmd == 'auth':
result = self._auth(params['ndFactor'][0])
if cmd == 'lastLocationUpdate':
result = self._lastLocationUpdate()
return json.dumps(result if result is not None else {})
def _listTags(self):
dct = {}
for id in self.ctx.airtags.keys():
dct[id] = self.ctx.airtags[id].toDict()
return dct
def _getPos(self):
findMy = FindMy(self.ctx)
data = findMy.retrieveLocations()
return data
def _refresh(self):
self.ctx.signInDone = False
findMy = FindMy(self.ctx)
try:
data = findMy.retrieveLocations()
except requests.exceptions.ConnectTimeout as e:
msg = f"[API] Anisette Server not running: {str(e)}"
self.ctx.errMsg = msg
self.ctx.log.error(msg)
data = {"status": "fail", "msg": msg}
return data
def _getTagData(self, id):
self.log.debug(f"[API] Cmds' getTagData parameter is id={id}")
if id in self.ctx.airtags.keys():
tag = self.ctx.airtags[id]
dct = tag.toDict()
dct['status'] = 'ok'
else:
dct = {'status': 'fail', 'msg': 'tag not found', 'id': id}
return dct
def _editTag(self, id, name, privKey, advKey, imgId):
self.log.debug(f"[API] Cmds' editTag parameter are id={id}, name={name}, private Key={privKey}, "
f"advertisementKey={advKey}")
if id in self.ctx.airtags.keys():
tag = self.ctx.airtags[id]
tag.name = name
tag.privateKey = privKey
tag.advertisementKey = advKey
tag.imgId = imgId
if tag.needsSave:
tag.save()
dct = {'status': 'ok', 'dataChanged': str(tag.needsSave)}
else:
dct = {'status': 'fail', 'msg': 'tag not found', 'id': id}
return dct
def _addTag(self, id, name, privKey, advKey, imgId):
self.log.debug(f"[API] Cmds' addTag parameter are id={id}, name={name}, private Key={privKey}, "
f"advertisementKey={advKey}")
| """
Mark Liebrand 2024
This file is part of FindMyGUI which is released under the Apache 2.0 License
See file LICENSE or go to for full license details https://github.com/liebrandapps/FindMyGUI
"""
class API:
def __init__(self, ctx):
self.ctx = ctx
self.log = ctx.log
def call(self, cmd, params=None):
self.log.debug(f"[API] Handling API command <{cmd}>")
result = {}
if cmd == "listTags":
result = self._listTags()
if cmd == 'getPos':
result = self._getPos()
if cmd == 'refresh':
result = self._refresh()
if cmd == 'getTagData':
result = self._getTagData(params['id'][0])
if cmd == 'editTag':
result = self._editTag(params['id'][0], params['name'][0], params['privateKey'][0],
params['advertisementKey'][0], params['imgId'][0])
if cmd == 'addTag':
result = self._addTag(params['id'][0], params['name'][0], params['privateKey'][0],
params['advertisementKey'][0], params['imgId'][0])
if cmd == 'signInStatus':
result = self._signInStatus(int(params['timeStamp'][0]))
if cmd == 'creds':
result = self._creds(params['userName'][0], params['password'][0])
if cmd == 'auth':
result = self._auth(params['ndFactor'][0])
if cmd == 'lastLocationUpdate':
result = self._lastLocationUpdate()
return json.dumps(result if result is not None else {})
def _listTags(self):
dct = {}
for id in self.ctx.airtags.keys():
dct[id] = self.ctx.airtags[id].toDict()
return dct
def _getPos(self):
findMy = FindMy(self.ctx)
data = findMy.retrieveLocations()
return data
def _refresh(self):
self.ctx.signInDone = False
findMy = FindMy(self.ctx)
try:
data = findMy.retrieveLocations()
except requests.exceptions.ConnectTimeout as e:
msg = f"[API] Anisette Server not running: {str(e)}"
self.ctx.errMsg = msg
self.ctx.log.error(msg)
data = {"status": "fail", "msg": msg}
return data
def _getTagData(self, id):
self.log.debug(f"[API] Cmds' getTagData parameter is id={id}")
if id in self.ctx.airtags.keys():
tag = self.ctx.airtags[id]
dct = tag.toDict()
dct['status'] = 'ok'
else:
dct = {'status': 'fail', 'msg': 'tag not found', 'id': id}
return dct
def _editTag(self, id, name, privKey, advKey, imgId):
self.log.debug(f"[API] Cmds' editTag parameter are id={id}, name={name}, private Key={privKey}, "
f"advertisementKey={advKey}")
if id in self.ctx.airtags.keys():
tag = self.ctx.airtags[id]
tag.name = name
tag.privateKey = privKey
tag.advertisementKey = advKey
tag.imgId = imgId
if tag.needsSave:
tag.save()
dct = {'status': 'ok', 'dataChanged': str(tag.needsSave)}
else:
dct = {'status': 'fail', 'msg': 'tag not found', 'id': id}
return dct
def _addTag(self, id, name, privKey, advKey, imgId):
self.log.debug(f"[API] Cmds' addTag parameter are id={id}, name={name}, private Key={privKey}, "
f"advertisementKey={advKey}") | tag = AirTag(self.ctx) | 0 | 2023-12-16 12:39:52+00:00 | 8k |
Samuel-Effiong/Django-Dynamic-Table | django_dynamic_table/tests.py | [
{
"identifier": "DynamicTable",
"path": "django_dynamic_table/models.py",
"snippet": "class DynamicTable(models.Model):\r\n\r\n table_name = models.CharField(_('Table Name'), max_length=255, unique=True)\r\n table_description = models.TextField(_('Table Description'), blank=True)\r\n date_creat... | import datetime
from typing import List
from django.test import TestCase
from django.utils import timezone
from .models import DynamicTable, TableColumn, TableRow, CellValue
from .errors import (
TableHaveNoRow, TableHaveNoColumn, ColumnNotInTable,
RowNotInTable, DuplicateColumnInTable, DynamicTableError,
UnSupportedDataType, CantParseValueToDataType, CellDoesNotExist
)
| 4,108 |
# Create your tests here.
class DynamicTableTest(TestCase):
def setUp(self) -> None:
self.name = 'Employee Records'
self.description = "Contains company employee personal information"
self.date_created = timezone.now().date()
self.column_name = 'First Name'
self.data_type = 'char'
self.supported_data_type = ['int', 'char', 'textfield', 'float', 'bool', 'date']
self.table = DynamicTable(
table_name=self.name,
table_description=self.description
)
self.table.save()
def test_table_creation_with_no_columns_and_rows(self):
self.assertEqual(self.name, str(self.table))
self.assertEqual(self.description, self.table.table_description)
self.assertEqual(self.date_created, self.table.date_created.date())
default_value = {
'rows': 0,
'columns': 0
}
self.assertDictEqual(default_value, self.table.table_info())
# Delete columns test
self.assertRaises(ColumnNotInTable, self.table.delete_column, column_name='Name')
# Delete rows test
self.assertRaises(RowNotInTable, self.table.delete_row, row_index=1)
self.assertRaises(TypeError, self.table.delete_row, row_index='1')
self.assertTrue(self.table.is_empty())
# ensures that rows can't be added to an empty table
self.assertRaises(TableHaveNoColumn, self.table.add_row, value={})
self.assertRaises(ValueError, self.table.add_row, value='love')
self.assertRaises(ValueError, self.table.add_row, value=[1, 2, 3])
self.assertRaises(ValueError, self.table.add_row, value=(1, 2, 3))
self.assertRaises(TableHaveNoColumn, self.table.bulk_add_rows, values=[{}, {}])
self.assertRaises(ValueError, self.table.bulk_add_rows, values={})
self.assertRaises(ValueError, self.table.bulk_add_rows, values='love')
self.assertRaises(ValueError, self.table.bulk_add_rows, values=(1, 2))
self.assertRaises(ValueError, self.table.bulk_add_rows, values=[1, '2'])
def test_supported_data_types(self):
self.assertListEqual(sorted(self.supported_data_type), sorted(self.table.get_supported_data_types()))
self.assertTrue(self.table.data_type_is_supported(' CHAR'))
self.assertTrue(self.table.data_type_is_supported('DaTe '))
self.assertTrue(self.table.data_type_is_supported(' bool '))
self.assertFalse(self.table.data_type_is_supported('File'))
self.assertFalse(self.table.data_type_is_supported('timE'))
self.assertIsInstance(self.table.data_type_is_supported(['file', 'char']), list)
self.assertListEqual([True, False, True, False], self.table.data_type_is_supported(['cHar', 'file', 'DATE', 'time']))
self.assertListEqual([True, True], self.table.data_type_is_supported(['cHar', 'DATE',]))
self.assertListEqual([False, False], self.table.data_type_is_supported(['File', 'time']))
def test_adding_column_with_incorrect_parameters(self):
|
# Create your tests here.
class DynamicTableTest(TestCase):
def setUp(self) -> None:
self.name = 'Employee Records'
self.description = "Contains company employee personal information"
self.date_created = timezone.now().date()
self.column_name = 'First Name'
self.data_type = 'char'
self.supported_data_type = ['int', 'char', 'textfield', 'float', 'bool', 'date']
self.table = DynamicTable(
table_name=self.name,
table_description=self.description
)
self.table.save()
def test_table_creation_with_no_columns_and_rows(self):
self.assertEqual(self.name, str(self.table))
self.assertEqual(self.description, self.table.table_description)
self.assertEqual(self.date_created, self.table.date_created.date())
default_value = {
'rows': 0,
'columns': 0
}
self.assertDictEqual(default_value, self.table.table_info())
# Delete columns test
self.assertRaises(ColumnNotInTable, self.table.delete_column, column_name='Name')
# Delete rows test
self.assertRaises(RowNotInTable, self.table.delete_row, row_index=1)
self.assertRaises(TypeError, self.table.delete_row, row_index='1')
self.assertTrue(self.table.is_empty())
# ensures that rows can't be added to an empty table
self.assertRaises(TableHaveNoColumn, self.table.add_row, value={})
self.assertRaises(ValueError, self.table.add_row, value='love')
self.assertRaises(ValueError, self.table.add_row, value=[1, 2, 3])
self.assertRaises(ValueError, self.table.add_row, value=(1, 2, 3))
self.assertRaises(TableHaveNoColumn, self.table.bulk_add_rows, values=[{}, {}])
self.assertRaises(ValueError, self.table.bulk_add_rows, values={})
self.assertRaises(ValueError, self.table.bulk_add_rows, values='love')
self.assertRaises(ValueError, self.table.bulk_add_rows, values=(1, 2))
self.assertRaises(ValueError, self.table.bulk_add_rows, values=[1, '2'])
def test_supported_data_types(self):
self.assertListEqual(sorted(self.supported_data_type), sorted(self.table.get_supported_data_types()))
self.assertTrue(self.table.data_type_is_supported(' CHAR'))
self.assertTrue(self.table.data_type_is_supported('DaTe '))
self.assertTrue(self.table.data_type_is_supported(' bool '))
self.assertFalse(self.table.data_type_is_supported('File'))
self.assertFalse(self.table.data_type_is_supported('timE'))
self.assertIsInstance(self.table.data_type_is_supported(['file', 'char']), list)
self.assertListEqual([True, False, True, False], self.table.data_type_is_supported(['cHar', 'file', 'DATE', 'time']))
self.assertListEqual([True, True], self.table.data_type_is_supported(['cHar', 'DATE',]))
self.assertListEqual([False, False], self.table.data_type_is_supported(['File', 'time']))
def test_adding_column_with_incorrect_parameters(self):
| self.assertRaises(DynamicTableError, self.table.add_column, ['first name'], ['char'])
| 9 | 2023-12-19 15:50:38+00:00 | 8k |
mohame54/Speech-Transcriber-App | whisper/whisper.py | [
{
"identifier": "Inference",
"path": "whisper/decoding.py",
"snippet": "class Inference:\n \"\"\"\n Class for handling sequence generation inference.\n\n Attributes:\n encoder: ONNX runtime inference session for the encoder.\n decoder: ONNX runtime inference session for the decode... | from typing import Literal, Union, Tuple, Optional, List
from transformers import WhisperFeatureExtractor, WhisperTokenizer
from dataclasses import dataclass
from .decoding import Inference, GreedyDecoding, BeamSearchDecoding, Hypothesis
import soxr
import soundfile as sf
import numpy as np
import wget
import os | 3,745 |
# LOCAL
@dataclass
class WhisperConfig:
"""
Configuration class for the WhisperInference module.
Attributes:
- encoder_path: Path to the encoder model.
- decoder_path: Path to the decoder model.
- model_id: Model identifier, default is "openai/whisper-base" this is the only one supported for now.
- transcribption_mode: Language mode, default is "English".
- decoding: Decoding mode, default is "greedy".
- beam_size: Beam size for beam search decoding, default is 5.
- eos_id: End-of-sequence token ID, default is 50257.
- temperature: Temperature for decoding, default is 1.0.
- top_p: Top-p sampling parameter, default is 0.98.
- length_penalty: Length penalty for beam search decoding, default is 2.0.
"""
encoder_path: str
decoder_path: str
model_id: str = "openai/whisper-base"
transcribption_mode: Literal["English", "Arabic"] = "English"
decoding: Literal["greedy", "beam"] = "greedy"
beam_size: int = 5
eos_id: int = 50257
temperature: float = 1.0
top_p: float = 0.98
length_penalty: float = 2.0
class WhisperInference:
"""
Inference module for transcribing audio using the Whisper model.
Attributes:
- processor: WhisperFeatureExtractor for extracting features from audio.
- tokenizer: WhisperTokenizer for tokenizing transcriptions.
- decoding: Decoding strategy based on the selected mode.
"""
def __init__(
self,
config: WhisperConfig
):
"""
Initializes the WhisperInference module.
Args:
- config: WhisperConfig object containing model configuration.
"""
# Initialize feature extractor and tokenizer
self.processor = WhisperFeatureExtractor.from_pretrained(config.model_id)
self.tokenizer = WhisperTokenizer.from_pretrained(
config.model_id,
language=config.transcribption_mode,
task="transcribe",
)
self.config = config
self.inference = Inference(
self.config.encoder_path,
self.config.decoder_path,
self.config.transcribption_mode,
)
self.set_decoding()
def set_decoding(self, decoding: Optional[str]= None):
# Initialize inference and decoding strategy based on the selected mode
decoding = decoding if decoding is not None else self.config.decoding
if decoding == "greedy":
self.decoding = GreedyDecoding(
self.inference,
self.config.eos_id,
self.config.temperature,
self.config.top_p
)
else:
self.decoding = BeamSearchDecoding(
self.inference,
self.config.eos_id,
self.config.beam_size,
self.config.length_penalty,
self.config.top_p,
self.config.temperature,
)
def _extract_feats(self, audio)-> np.ndarray:
"""
Extracts features from the input audio using the feature extractor.
Args:
- audio: Input audio as a numpy array.
Returns:
- feats: Extracted log mel spectrogram.
"""
feats = self.processor(audio, sampling_rate=16_000)['input_features']
return feats
def __call__(
self,
audio: Union[np.ndarray, str],
max_len: int = 50,
return_multiple: bool = False,
return_hyps: bool = False,
**generation_kwargs,
|
# LOCAL
@dataclass
class WhisperConfig:
"""
Configuration class for the WhisperInference module.
Attributes:
- encoder_path: Path to the encoder model.
- decoder_path: Path to the decoder model.
- model_id: Model identifier, default is "openai/whisper-base" this is the only one supported for now.
- transcribption_mode: Language mode, default is "English".
- decoding: Decoding mode, default is "greedy".
- beam_size: Beam size for beam search decoding, default is 5.
- eos_id: End-of-sequence token ID, default is 50257.
- temperature: Temperature for decoding, default is 1.0.
- top_p: Top-p sampling parameter, default is 0.98.
- length_penalty: Length penalty for beam search decoding, default is 2.0.
"""
encoder_path: str
decoder_path: str
model_id: str = "openai/whisper-base"
transcribption_mode: Literal["English", "Arabic"] = "English"
decoding: Literal["greedy", "beam"] = "greedy"
beam_size: int = 5
eos_id: int = 50257
temperature: float = 1.0
top_p: float = 0.98
length_penalty: float = 2.0
class WhisperInference:
"""
Inference module for transcribing audio using the Whisper model.
Attributes:
- processor: WhisperFeatureExtractor for extracting features from audio.
- tokenizer: WhisperTokenizer for tokenizing transcriptions.
- decoding: Decoding strategy based on the selected mode.
"""
def __init__(
self,
config: WhisperConfig
):
"""
Initializes the WhisperInference module.
Args:
- config: WhisperConfig object containing model configuration.
"""
# Initialize feature extractor and tokenizer
self.processor = WhisperFeatureExtractor.from_pretrained(config.model_id)
self.tokenizer = WhisperTokenizer.from_pretrained(
config.model_id,
language=config.transcribption_mode,
task="transcribe",
)
self.config = config
self.inference = Inference(
self.config.encoder_path,
self.config.decoder_path,
self.config.transcribption_mode,
)
self.set_decoding()
def set_decoding(self, decoding: Optional[str]= None):
# Initialize inference and decoding strategy based on the selected mode
decoding = decoding if decoding is not None else self.config.decoding
if decoding == "greedy":
self.decoding = GreedyDecoding(
self.inference,
self.config.eos_id,
self.config.temperature,
self.config.top_p
)
else:
self.decoding = BeamSearchDecoding(
self.inference,
self.config.eos_id,
self.config.beam_size,
self.config.length_penalty,
self.config.top_p,
self.config.temperature,
)
def _extract_feats(self, audio)-> np.ndarray:
"""
Extracts features from the input audio using the feature extractor.
Args:
- audio: Input audio as a numpy array.
Returns:
- feats: Extracted log mel spectrogram.
"""
feats = self.processor(audio, sampling_rate=16_000)['input_features']
return feats
def __call__(
self,
audio: Union[np.ndarray, str],
max_len: int = 50,
return_multiple: bool = False,
return_hyps: bool = False,
**generation_kwargs, | )-> Union[Hypothesis, List[Hypothesis]]: | 3 | 2023-12-16 13:35:51+00:00 | 8k |
zhcui/polar_preview | polar/lang_firsov/lang_firsov.py | [
{
"identifier": "grad",
"path": "polar/lang_firsov/grad.py",
"snippet": "def get_grad_lf(mylf, params=None, rdm1=None, mo_coeff=None, mo_occ=None,\n scf_max_cycle=50, fci=False, beta=np.inf):\ndef get_grad_lf_full(mylf, params=None, rdm1=None, mo_coeff=None, mo_occ=None):\ndef get_grad_gl... | from functools import partial
from scipy import linalg as la
from scipy import optimize as opt
from pyscf import gto, scf, ao2mo, lib
from pyscf.scf import hf
from pyscf.lib import logger
from polar.lang_firsov import grad
from polar.lang_firsov import thermal_average as ta
from polar.fci.fci import fc_factor
from pyscf.pbc.scf.addons import smearing_
from pyscf import fci, ao2mo
from polar.lang_firsov import mp as lfmp
from polar.lang_firsov import mp_glf
import numpy as np | 3,637 | lams = np.zeros(nmode, dtype=params.dtype)
else:
raise ValueError("unknown lf type %s"%(self))
else:
if uniform:
l, z = params
zs = np.zeros(nmode, dtype=params.dtype)
zs[:] = z
if isinstance(self, GGLangFirsov):
lams = np.zeros((nmode, nao, nao), dtype=params.dtype)
lams[range(nmode), range(nao), range(nao)] = l
elif isinstance(self, GLangFirsov):
lams = np.zeros((nmode, nao), dtype=params.dtype)
lams[range(nmode), range(nao)] = l
elif isinstance(self, LangFirsov):
lams = np.zeros(nmode, dtype=params.dtype)
lams[:] = l
else:
raise ValueError("unknown lf type %s"%(self))
else:
zs = np.array(params[-nmode:], copy=True)
lams = np.array(params[:-nmode].reshape(nmode, -1), copy=True)
if isinstance(self, GGLangFirsov):
lams = lib.unpack_tril(lams)
if lams.shape != (nmode, nao, nao):
raise ValueError("lams shape %s does not match %s"
%(str(lams.shape), (nmode, nao, nao)))
elif isinstance(self, GLangFirsov):
pass
elif isinstance(self, LangFirsov):
lams = lams.reshape(nmode)
else:
raise ValueError("unknown lf type %s"%(self))
return lams, zs
def pack_params(self, lams, zs):
if self.lams_only:
if self.uniform:
params = np.array((lams[0],))
else:
params = np.hstack((lams.ravel(),))
elif self.zs_only:
if self.uniform:
params = np.array((zs[0],))
else:
params = np.hstack((zs.ravel(),))
else:
if self.uniform:
params = np.array((lams[0], zs[0]))
else:
params = np.hstack((lams.ravel(), zs.ravel()))
return params
def unpack_params_full(self, params, uniform=None):
nocc = self.nelec_a
nvir = self.nao - nocc
kappa = params[:nvir*nocc]
lams, zs = self.unpack_params(params[nvir*nocc:])
return kappa, lams, zs
def pack_params_full(self, kappa, lams, zs):
return np.hstack((kappa.ravel(), self.pack_params(lams, zs).ravel()))
@property
def nlams(self):
if self.zs_only:
nlams = 0
elif self.uniform:
nlams = 1
else:
nlams = self.nmode
return nlams
@property
def nzs(self):
if self.lams_only:
nzs = 0
elif self.uniform:
nzs = 1
else:
nzs = self.nmode
return nzs
@property
def nparam(self):
nparam = self.nlams + self.nzs
return nparam
@property
def nkappa(self):
nocc = self.nelec_a
nvir = self.nao - nocc
nparam = nvir * nocc
return nparam
@property
def nparam_full(self):
nparam = int(self.nkappa)
nparam += self.nparam
return nparam
def get_lams_zs(self, opt=True):
if opt:
return self.unpack_params(self.params_opt)
else:
return self.unpack_params(self.params)
get_lf_ham = get_lf_ham
solve_lf_ham = solve_lf_ham
solve_lf_ham_full = solve_lf_ham_full
get_grad = grad.get_grad_lf
get_grad_full = grad.get_grad_lf_full
kernel = kernel
@staticmethod
| #!/usr/bin/env python
"""
Variational Lang-Firsov.
Authors:
Zhi-Hao Cui <zhcui0408@gmail.com>
"""
einsum = partial(np.einsum, optimize=True)
# ****************************************************************************
# Variational Lang-Firsov
# ****************************************************************************
def get_lf_ham(mylf, params=None, h0=None, h1=None, h2=None,
h_ep=None, w_p=None):
"""
Get h0, h1, h_ep, h2 of variational Lang-Firsov Hamiltonian.
Args:
mylf: LF object.
lams: (nmode,)
zs: (nmode,)
h0: energy constant
h1: (nao, nao)
h2: (nao, nao, nao, nao), TODO, compact
h_ep: constant
w_p: (nmode,) or constant.
Returns:
H0: constant
H1: (nao, nao)
H_ep: (nmode, nao, nao)
H2: (nao, nao, nao, nao)
"""
if params is None:
params = mylf.params
if h0 is None:
h0 = mylf.h0
if h1 is None:
h1 = mylf.h1
if h2 is None:
h2 = mylf.h2
if h_ep is None:
h_ep = mylf.h_ep
if w_p is None:
w_p = mylf.w_p
lams, zs = mylf.unpack_params(params)
nmode = mylf.nmode
nao = mylf.nao
g = h_ep
fac = np.exp(-0.5 * lams**2)
h1_diag = w_p*lams**2 - (2.0*g)*lams + (2.0*g)*zs - 2.0*w_p*zs*lams + h1[range(nao), range(nao)]
H1 = einsum("ij, i, j -> ij", h1, fac, fac)
H1[range(nao), range(nao)] = h1_diag
H_ep = np.zeros((nmode, nao, nao))
H_ep[range(nmode), range(nao), range(nao)] = g - w_p * lams
H0 = h0 + (w_p * zs**2).sum()
if h2 is not None:
fac2 = np.exp(-2.0 * lams**2)
H2_diag = (-4.0*g) * lams + (2.0 * w_p) * lams**2 + h2[range(nao), range(nao), range(nao), range(nao)]
H2 = np.empty((nao, nao, nao, nao))
for i in range(nao):
for j in range(nao):
for k in range(nao):
for l in range(nao):
if i == j and i == l and i == k:
# i = j = k = l
H2[i, j, k, l] = h2[i, j, k, l]
elif i == j and i == k:
# i = j = k != l
H2[i, j, k, l] = h2[i, j, k, l] * fac[l] * fac[k]
elif i == j and i == l:
# i = j = l != k
H2[i, j, k, l] = h2[i, j, k, l] * fac[l] * fac[k]
elif i == l and i == k:
# i = l = k != j
H2[i, j, k, l] = h2[i, j, k, l] * fac[i] * fac[j]
elif j == l and j == k:
# i != j = k = l
H2[i, j, k, l] = h2[i, j, k, l] * fac[i] * fac[j]
elif i == j:
if k == l:
H2[i, j, k, l] = h2[i, j, k, l]
else:
H2[i, j, k, l] = h2[i, j, k, l] * fac[k] * fac[l]
elif i == k:
if j == l:
H2[i, j, k, l] = h2[i, j, k, l] * fac2[i] * fac2[j]
else:
H2[i, j, k, l] = h2[i, j, k, l] * fac2[i] * fac[j] * fac[l]
elif i == l:
if j == k:
H2[i, j, k, l] = h2[i, j, k, l]
else:
H2[i, j, k, l] = h2[i, j, k, l] * fac[j] * fac[k]
elif j == k:
if i == l:
H2[i, j, k, l] = h2[i, j, k, l]
else:
H2[i, j, k, l] = h2[i, j, k, l] * fac[i] * fac[l]
elif j == l:
if i == k:
H2[i, j, k, l] = h2[i, j, k, l] * fac2[i] * fac2[j]
else:
H2[i, j, k, l] = h2[i, j, k, l] * fac[i] * fac[k] * fac2[j]
elif k == l:
if i == j:
H2[i, j, k, l] = h2[i, j, k, l]
else:
H2[i, j, k, l] = h2[i, j, k, l] * fac[i] * fac[j]
else:
H2[i, j, k, l] = h2[i, j, k, l] * fac[i] * fac[j] * fac[k] * fac[l]
H2[range(nao), range(nao), range(nao), range(nao)] = H2_diag
else:
H2 = h2
return H0, H1, H2, H_ep, w_p
def solve_lf_ham(mylf, params=None, nelec=None, mp2=False, mp3=False, mp4=False,
nph=9, verbose=False, scf_newton=False, beta=np.inf, dm0=None,
scf_max_cycle=50, fci=False):
H0, H1, H2, H_ep, w_p = mylf.get_lf_ham(params=params)
ovlp = mylf.get_ovlp()
nao = mylf.nao
h1 = mylf.get_h1()
h_ep_bare = mylf.get_h_ep()
if nelec is None:
nelec = mylf.nelec
if params is None:
params = mylf.params
lams, zs = mylf.unpack_params(params)
if H2 is not None:
mf = hf.RHF(mylf.mol)
mf.energy_nuc = lambda *args: H0
mf.get_hcore = lambda *args: H1
mf.get_ovlp = lambda *args: ovlp
mf._eri = H2
mf.direct_scf = False
mf.max_cycle = scf_max_cycle
mf.conv_tol = mylf.conv_tol * 0.1
if scf_newton:
mf = mf.newton()
if beta < np.inf:
mf = smearing_(mf, sigma=1.0/beta, method='fermi')
e_tot = mf.kernel(dm0=dm0)
rdm1 = mf.make_rdm1()
mylf._scf = mf
mylf.mo_energy = mf.mo_energy
mylf.mo_coeff = mf.mo_coeff
mylf.mo_occ = mf.mo_occ
mylf.e_hf = float(e_tot)
conv = mf.converged
if fci:
cisolver = fci.direct_nosym.FCI()
cisolver.max_cycle = 100
cisolver.conv_tol = 1e-8
C = mf.mo_coeff
h1_mo = C.conj().T @ mf.get_hcore() @ C
h2_mo = ao2mo.kernel(mf._eri, C)
e_tot, fcivec = cisolver.kernel(h1_mo, h2_mo, C.shape[-1], nelec, ecore=mf.energy_nuc())
rdm1 = cisolver.make_rdm1(fcivec, C.shape[-1], (mylf.nelec_a, mylf.nelec_b))
rdm1 = C @ rdm1 @ C.conj().T
else:
ew, ev = la.eigh(H1, ovlp)
mo_occ = np.zeros(nao)
if nelec == 1:
nocc = nelec
mo_occ[:nocc] = 1.0
else:
nocc = nelec_a
mo_occ[:nocc] = 2.0
e_tot = np.sum(ew * mo_occ) + H0
nao, nmo = ev.shape
rdm1 = np.dot(ev * mo_occ, ev.conj().T)
mylf.mo_energy = ew
mylf.mo_coeff = ev
mylf.mo_occ = mo_occ
mylf.e_hf = float(e_tot)
conv = True
if mp2 or mp3 or mp4:
nocc = (np.asarray(mo_occ > 0.5)).sum()
mo_energy = ew
mo_coeff = ev
if lams.ndim == 1:
lf = 'lf'
elif lams.ndim == 2:
lf = 'glf'
else:
raise ValueError
logger.info(mylf, "PT number of phonon: %d", nph)
logger.info(mylf, "e_hf %15.8f", e_tot)
logger.info(mylf, "LF type %s", lf)
if mp4:
e_mp1, e_mp2, e_mp3, e_mp4 = lfmp.get_e_mp4(mylf.mol, h1, H_ep, w_p, lams, zs,
mo_coeff, mo_occ, mo_energy, nph,
lf=lf, h_ep_bare=h_ep_bare)
e_tot += e_mp1
e_tot += e_mp2
e_tot += e_mp3
e_tot += e_mp4
mylf.e_mp1 = e_mp1
mylf.e_mp2 = e_mp2
mylf.e_mp3 = e_mp3
mylf.e_mp4 = e_mp4
logger.info(mylf, "e_mp1 %15.8f", e_mp1)
logger.info(mylf, "e_mp2 %15.8f", e_mp2)
logger.info(mylf, "e_mp3 %15.8f", e_mp3)
logger.info(mylf, "e_mp4 %15.8f", e_mp4)
elif mp3:
e_mp1, e_mp2, e_mp3 = lfmp.get_e_mp3(mylf.mol, h1, H_ep, w_p, lams, zs,
mo_coeff, mo_occ, mo_energy, nph,
lf=lf, h_ep_bare=h_ep_bare)
e_tot += e_mp1
e_tot += e_mp2
e_tot += e_mp3
mylf.e_mp1 = e_mp1
mylf.e_mp2 = e_mp2
mylf.e_mp3 = e_mp3
logger.info(mylf, "e_mp1 %15.8f", e_mp1)
logger.info(mylf, "e_mp2 %15.8f", e_mp2)
logger.info(mylf, "e_mp3 %15.8f", e_mp3)
elif mp2 == 'slow':
e_mp1, e_mp2 = lfmp.get_e_mp2_slow(mylf.mol, h1, H_ep, w_p, lams, zs,
mo_coeff, mo_occ, mo_energy, nph,
lf=lf, h_ep_bare=h_ep_bare)
e_tot += e_mp1
e_tot += e_mp2
mylf.e_mp1 = e_mp1
mylf.e_mp2 = e_mp2
logger.info(mylf, "e_mp1 %15.8f", e_mp1)
logger.info(mylf, "e_mp2 %15.8f", e_mp2)
elif mp2:
e_mp2 = lfmp.get_e_mp2(h1, H_ep, w_p, lams, zs, mo_coeff, mo_occ,
mo_energy, nph)
e_tot += e_mp2
mylf.e_mp2 = e_mp2
logger.info(mylf, "e_mp2 %15.8f", e_mp2)
if verbose:
logger.info(mylf, "e_tot %15.8f", e_tot)
logger.info(mylf, "lams\n%s", lams)
logger.info(mylf, "zs\n%s", zs)
logger.info(mylf, "rdm1\n%s", rdm1)
mylf.e_tot = e_tot
return e_tot, rdm1
def solve_lf_ham_full(mylf, params=None, nelec=None, mp2=False, mp3=False, mp4=False,
nph=9, verbose=False, scf_newton=False, beta=np.inf, dm0=None,
scf_max_cycle=50, mo_coeff=None, mo_occ=None, canonicalization=True):
if params is None:
params = mylf.params_full
kappa, lams, zs = mylf.unpack_params_full(params)
params_p = mylf.pack_params(lams, zs)
H0, H1, H2, H_ep, w_p = mylf.get_lf_ham(params=params_p)
ovlp = mylf.get_ovlp()
nao = mylf.nao
h1 = mylf.get_h1()
if nelec is None:
nelec = mylf.nelec
if H2 is not None:
mf = hf.RHF(mylf.mol)
mf.energy_nuc = lambda *args: H0
mf.get_hcore = lambda *args: H1
mf.get_ovlp = lambda *args: ovlp
# ZHC FIXME NOTE the transformed H2 may not have the 4-fold symmetry,
# it is only 2-fold. pqrs = rspq
#mf._eri = ao2mo.restore(4, H2, nao)
mf._eri = H2
mf.direct_scf = False
mf.max_cycle = scf_max_cycle
mf.conv_tol = mylf.conv_tol * 0.1
dr = hf.unpack_uniq_var(kappa, mo_occ)
mo_coeff = np.dot(mo_coeff, la.expm(dr))
rdm1 = mf.make_rdm1(mo_coeff, mo_occ)
e_tot = mf.energy_elec(dm=rdm1)[0] + mf.energy_nuc()
fock = mf.get_fock(dm=rdm1)
if canonicalization:
print("-" * 79)
mo_energy, mo_coeff = mf.canonicalize(mo_coeff, mo_occ, fock)
homo = lumo = None
mo_e_occ = mo_energy[mo_occ >= 1.0]
mo_e_vir = mo_energy[mo_occ < 1.0]
if len(mo_e_occ) > 0:
homo = mo_e_occ.max()
if len(mo_e_vir) > 0:
lumo = mo_e_vir.min()
if homo is not None:
print ('HOMO = %15.8g'%(homo))
if lumo is not None:
print ('LUMO = %15.8g'%(lumo))
if homo is not None:
print ("gap = %15.8g"%(lumo - homo))
if (lumo is not None) and (homo is not None) and (homo > lumo):
print ('WARN: HOMO %s > LUMO %s was found in the canonicalized orbitals.'%(homo, lumo))
print ("mo_energy:\n%s"%mo_energy)
grad = mf.get_grad(mo_coeff, mo_occ, fock)
grad_norm = la.norm(grad)
print("-" * 79)
print ("|g| = %15.8g" % grad_norm)
print("-" * 79)
else:
mo_energy = einsum("pm, pq, qm -> m", mo_coeff.conj(), fock, mo_coeff)
mylf._scf = mf
mylf.e_hf = float(e_tot)
conv = mf.converged
mylf.mo_coeff = mf.mo_coeff = mo_coeff
mylf.mo_occ = mf.mo_occ = mo_occ
mylf.mo_energy = mf.mo_energy = mo_energy
if mp2:
logger.info(mylf, "LF-MP2 start, nph = %d", nph)
ovlp_g = la.block_diag(ovlp, ovlp)
hcore_g = la.block_diag(H1, H1)
mylf._scf = mf = mf.to_ghf()
mf.get_ovlp = lambda *args: ovlp_g
mf.get_hcore = lambda *args: hcore_g
e_mp2 = mp_glf.get_e_mp2(mylf, lams=lams, zs=zs, nph=nph)
e_tot += e_mp2
mylf.e_mp2 = e_mp2
logger.info(mylf, "e_mp2 %15.8f", mylf.e_mp2)
return e_tot, rdm1
def kernel(mylf, params=None, nelec=None, method='BFGS', conv_tol=None,
max_cycle=None, gtol=None, mp2=False, mp3=False, mp4=False, nph=9,
ntrial=None, use_num_grad=True, full_opt=False, mo_coeff=None,
mo_occ=None, fci=False, scf_max_cycle=50, beta=np.inf):
mylf.dump_flags()
if params is None:
if full_opt:
params = mylf.params_full
else:
params = mylf.params
if nelec is None:
nelec = mylf.nelec
if conv_tol is None:
conv_tol = mylf.conv_tol
if gtol is None:
gtol = np.sqrt(conv_tol)
if max_cycle is None:
max_cycle = mylf.max_cycle
if ntrial is None:
ntrial = mylf.ntrial
if use_num_grad:
jac = None
else:
if full_opt:
def jac(params):
return mylf.get_grad_full(params, mo_coeff=mo_coeff, mo_occ=mo_occ)
else:
def jac(params):
return mylf.get_grad(params, scf_max_cycle=scf_max_cycle, fci=fci, beta=beta)
if full_opt:
def cost_func(params):
return mylf.solve_lf_ham_full(params, nelec, mo_coeff=mo_coeff,
mo_occ=mo_occ, canonicalization=False)[0]
else:
def cost_func(params):
return mylf.solve_lf_ham(params, nelec, scf_max_cycle=scf_max_cycle,
fci=fci, beta=beta)[0]
params_opt = None
e_tot = 1e+9
for i in range(ntrial):
print ("trial %5d / %5d"%(i, ntrial), flush=True)
if i == 1:
params = np.zeros_like(params)
elif i >= 2:
params = (np.random.random(params.shape) - 0.5) * (np.max(mylf.get_h_ep()) / np.max(mylf.get_w_p()))
if i % 2== 0:
params *= 0.1
res = opt.minimize(cost_func, params, jac=jac, method=method, tol=conv_tol,
options={"disp": True, "maxiter": max_cycle,
"gtol": gtol})
if res.fun < e_tot:
params_opt = res.x
e_tot = res.fun
mylf.params_full_opt = params_opt
mylf.params_opt = np.array(params_opt[-mylf.nparam:], copy=True)
mylf.e_tot = e_tot
if full_opt:
mylf.e_tot, rdm1 = mylf.solve_lf_ham_full(params_opt, nelec, mp2=mp2, mp3=mp3, mp4=mp4,
nph=nph, verbose=True, mo_coeff=mo_coeff,
mo_occ=mo_occ)
kappa, lams, zs = mylf.unpack_params_full(mylf.params_full_opt)
else:
mylf.e_tot, rdm1 = mylf.solve_lf_ham(params_opt, nelec, mp2=mp2, mp3=mp3, mp4=mp4,
nph=nph, verbose=True,
fci=fci, scf_max_cycle=scf_max_cycle, beta=beta)
lams, zs = mylf.unpack_params(mylf.params_opt)
kappa = None
logger.info(mylf, "e_tot %15.8f", mylf.e_tot)
logger.info(mylf, "kappa\n%s", kappa)
logger.info(mylf, "lams\n%s", lams)
logger.info(mylf, "zs\n%s", zs)
logger.info(mylf, "rdm1\n%s", rdm1)
return mylf.e_tot
class LangFirsov(object):
conv_tol = 1e-8
conv_tol_grad = None
max_cycle = 1000
ntrial = 5
def __init__(self, h0, h1, h2, h_ep, w_p, nelec, spin=0, params=None,
uniform=False, lams_only=False, zs_only=False, verbose=4, mol=None):
self.mol = gto.Mole(verbose=verbose)
self.mol.build(dump_input=False)
self.verbose = verbose
self.max_memory = self.mol.max_memory
self.stdout = self.mol.stdout
self.h0 = h0
self.h1 = h1
self.h2 = h2
self.h_ep = h_ep
self.w_p = w_p
self.nelec = nelec
self.mol.nelectron = nelec
self.mol.tot_electrons = lambda *args: self.nelec
self.mol.incore_anyway = True
if self.nelec == 1:
self.spin = self.mol.spin = 1
else:
self.spin = self.mol.spin = spin
self.nelec_a = (self.nelec + self.spin) // 2
self.nelec_b = (self.nelec - self.spin) // 2
assert self.nelec_a + self.nelec_b == self.nelec
self.nmode = len(self.w_p)
self.nao = self.h1.shape[-1]
self.ovlp = np.eye(self.nao)
self.uniform = uniform
self.lams_only = lams_only
self.zs_only = zs_only
self.lf_type = 'lf'
if params is None:
self.params = self.get_init_params()
else:
self.params = params
assert len(self.params) == self.nparam
self.params_full = np.zeros(self.nparam_full)
self.params_full[-self.nparam:] = self.params
# results:
self.chkfile = None
self.params_opt = None
self.params_full_opt = None
self.e_tot = None
self.e_hf = None
self.e_mp1 = None
self.e_mp2 = None
self.e_mp3 = None
self.e_mp4 = None
self.mo_energy = None
self.mo_coeff = None
self.mo_occ = None
def dump_flags(self, verbose=None):
log = logger.new_logger(self, verbose)
if log.verbose < logger.INFO:
return self
log.info('\n')
log.info('******** %s ********', self.__class__)
method = [self.__class__.__name__]
log.info('method = %s', '-'.join(method))
log.info("uniform = %s", self.uniform)
log.info("nao = %10d", self.nao)
log.info("nelec = %10s", self.nelec)
log.info("nmode = %10d", self.nmode)
log.info("nparam = %10d", self.nparam)
log.info('conv_tol = %g', self.conv_tol)
log.info('conv_tol_grad = %s', self.conv_tol_grad)
log.info('max_cycles = %d', self.max_cycle)
log.info("ntrial: %d", self.ntrial)
if isinstance(self.h_ep, np.ndarray) and (self.nao > 16 or self.nmode > 16):
log.info("h_ep:\n%s min %15.6f max %15.6f",
str(self.h_ep.shape), np.min(self.h_ep), np.max(self.h_ep))
else:
log.info("h_ep:\n%s", self.h_ep)
if self.nmode > 16:
log.info("w_p:\n%s min %15.6f max %15.6f",
str(self.w_p.shape), np.min(self.w_p), np.max(self.w_p))
else:
log.info("w_p:\n%s", self.w_p)
lams, zs = self.unpack_params(self.params)
log.info("lams shape: %s", str(lams.shape))
log.info("lams:\n%s", lams)
log.info("zs shape: %s", str(zs.shape))
log.info("zs:\n%s", zs)
if self.chkfile:
log.info('chkfile to save SCF result = %s', self.chkfile)
log.info('max_memory %d MB (current use %d MB)',
self.max_memory, lib.current_memory()[0])
return self
def get_h0(self):
return self.h0
def energy_nuc(self):
return self.h0
def get_ovlp(self):
return self.ovlp
def get_h1(self):
return self.h1
def get_hcore(self):
return self.h1
def get_h2(self):
return self.h2
def get_h_ep(self):
return self.h_ep
def get_w_p(self):
return self.w_p
def get_dm0(self, key='minao'):
"""
get initial rdm1.
"""
if self.mol.natm == 0:
h1e = self.get_h1()
s1e = self.get_ovlp()
mo_energy, mo_coeff = la.eigh(h1e, s1e)
mo_occ = np.zeros_like(mo_energy)
mo_occ[:self.nelec_a] = 2.0
dm0 = np.dot(mo_coeff * mo_occ, mo_coeff.conj().T)
else:
if key == 'minao':
dm0 = hf.init_guess_by_minao(self.mol)
elif key == 'atom':
dm0 = hf.init_guess_by_atom(self.mol)
else:
raise ValueError
return dm0
def get_init_params(self, scale=0.1):
h_ep = self.h_ep
w_p = self.w_p
if self.zs_only:
lams = np.array([])
elif self.uniform:
lams = np.zeros(self.nmode)
lams[:] = (np.random.random() - 0.5) * (np.max(h_ep) / np.max(w_p) * scale)
else:
lams = (np.random.random(self.nlams) - 0.5) * (np.max(h_ep) / np.max(w_p) * scale)
if self.lams_only:
zs = np.array([])
elif self.zs_only:
zs = np.random.random(self.nzs)
else:
dm0 = self.get_dm0()
zs = np.einsum("p, pp -> p", lams, dm0)
params = np.append(lams, zs)
if self.uniform:
if self.lams_only or self.zs_only:
params = params[[-1]]
else:
params = params[[0, self.nlams]]
return params
def unpack_params(self, params, uniform=None, lams_only=None, zs_only=None):
if lams_only is None:
lams_only = self.lams_only
if zs_only is None:
zs_only = self.zs_only
if uniform is None:
uniform = self.uniform
nmode = self.nmode
nao = self.nao
if lams_only:
zs = np.array([], dtype=params.dtype)
if uniform:
l = params
if isinstance(self, GGLangFirsov):
lams = np.zeros((nmode, nao, nao), dtype=params.dtype)
lams[range(nmode), range(nao), range(nao)] = l
elif isinstance(self, GLangFirsov):
lams = np.zeros((nmode, nao), dtype=params.dtype)
lams[range(nmode), range(nao)] = l
elif isinstance(self, LangFirsov):
lams = np.zeros(nmode, dtype=params.dtype)
lams[:] = l
else:
raise ValueError("unknown lf type %s"%(self))
else:
lams = np.array(params.reshape(nmode, -1), copy=True)
if isinstance(self, GGLangFirsov):
lams = lib.unpack_tril(lams)
if lams.shape != (nmode, nao, nao):
raise ValueError("lams shape %s does not match %s"
%(str(lams.shape), (nmode, nao, nao)))
elif isinstance(self, GLangFirsov):
pass
elif isinstance(self, LangFirsov):
lams = lams.reshape(nmode)
else:
raise ValueError("unknown lf type %s"%(self))
elif zs_only:
if uniform:
z = params
zs = np.zeros(nmode, dtype=params.dtype)
zs[:] = z
else:
zs = np.array(params[-nmode:], copy=True)
if isinstance(self, GGLangFirsov):
lams = np.zeros((nmode, nao, nao), dtype=params.dtype)
elif isinstance(self, GLangFirsov):
lams = np.zeros((nmode, nao), dtype=params.dtype)
elif isinstance(self, LangFirsov):
lams = np.zeros(nmode, dtype=params.dtype)
else:
raise ValueError("unknown lf type %s"%(self))
else:
if uniform:
l, z = params
zs = np.zeros(nmode, dtype=params.dtype)
zs[:] = z
if isinstance(self, GGLangFirsov):
lams = np.zeros((nmode, nao, nao), dtype=params.dtype)
lams[range(nmode), range(nao), range(nao)] = l
elif isinstance(self, GLangFirsov):
lams = np.zeros((nmode, nao), dtype=params.dtype)
lams[range(nmode), range(nao)] = l
elif isinstance(self, LangFirsov):
lams = np.zeros(nmode, dtype=params.dtype)
lams[:] = l
else:
raise ValueError("unknown lf type %s"%(self))
else:
zs = np.array(params[-nmode:], copy=True)
lams = np.array(params[:-nmode].reshape(nmode, -1), copy=True)
if isinstance(self, GGLangFirsov):
lams = lib.unpack_tril(lams)
if lams.shape != (nmode, nao, nao):
raise ValueError("lams shape %s does not match %s"
%(str(lams.shape), (nmode, nao, nao)))
elif isinstance(self, GLangFirsov):
pass
elif isinstance(self, LangFirsov):
lams = lams.reshape(nmode)
else:
raise ValueError("unknown lf type %s"%(self))
return lams, zs
def pack_params(self, lams, zs):
if self.lams_only:
if self.uniform:
params = np.array((lams[0],))
else:
params = np.hstack((lams.ravel(),))
elif self.zs_only:
if self.uniform:
params = np.array((zs[0],))
else:
params = np.hstack((zs.ravel(),))
else:
if self.uniform:
params = np.array((lams[0], zs[0]))
else:
params = np.hstack((lams.ravel(), zs.ravel()))
return params
def unpack_params_full(self, params, uniform=None):
nocc = self.nelec_a
nvir = self.nao - nocc
kappa = params[:nvir*nocc]
lams, zs = self.unpack_params(params[nvir*nocc:])
return kappa, lams, zs
def pack_params_full(self, kappa, lams, zs):
return np.hstack((kappa.ravel(), self.pack_params(lams, zs).ravel()))
@property
def nlams(self):
if self.zs_only:
nlams = 0
elif self.uniform:
nlams = 1
else:
nlams = self.nmode
return nlams
@property
def nzs(self):
if self.lams_only:
nzs = 0
elif self.uniform:
nzs = 1
else:
nzs = self.nmode
return nzs
@property
def nparam(self):
nparam = self.nlams + self.nzs
return nparam
@property
def nkappa(self):
nocc = self.nelec_a
nvir = self.nao - nocc
nparam = nvir * nocc
return nparam
@property
def nparam_full(self):
nparam = int(self.nkappa)
nparam += self.nparam
return nparam
def get_lams_zs(self, opt=True):
if opt:
return self.unpack_params(self.params_opt)
else:
return self.unpack_params(self.params)
get_lf_ham = get_lf_ham
solve_lf_ham = solve_lf_ham
solve_lf_ham_full = solve_lf_ham_full
get_grad = grad.get_grad_lf
get_grad_full = grad.get_grad_lf_full
kernel = kernel
@staticmethod | def fc_factor(n, l, m): | 2 | 2023-12-18 07:39:51+00:00 | 8k |
YaoFANGUK/video-subtitle-remover | backend/scenedetect/backends/opencv.py | [
{
"identifier": "FrameTimecode",
"path": "backend/scenedetect/frame_timecode.py",
"snippet": "class FrameTimecode:\n \"\"\"Object for frame-based timecodes, using the video framerate to compute back and\n forth between frame number and seconds/timecode.\n\n A timecode is valid only if it compli... | from logging import getLogger
from typing import AnyStr, Tuple, Union, Optional
from numpy import ndarray
from backend.scenedetect.frame_timecode import FrameTimecode, MAX_FPS_DELTA
from backend.scenedetect.platform import get_file_name
from backend.scenedetect.video_stream import VideoStream, SeekError, VideoOpenFailure, FrameRateUnavailable
import math
import os.path
import cv2 | 6,526 | # -*- coding: utf-8 -*-
#
# PySceneDetect: Python-Based Video Scene Detector
# -------------------------------------------------------------------
# [ Site: https://scenedetect.com ]
# [ Docs: https://scenedetect.com/docs/ ]
# [ Github: https://github.com/Breakthrough/PySceneDetect/ ]
#
# Copyright (C) 2014-2023 Brandon Castellano <http://www.bcastell.com>.
# PySceneDetect is licensed under the BSD 3-Clause License; see the
# included LICENSE file, or visit one of the above pages for details.
#
""":class:`VideoStreamCv2` is backed by the OpenCV `VideoCapture` object. This is the default
backend. Works with video files, image sequences, and network streams/URLs.
For wrapping input devices or pipes, there is also :class:`VideoCaptureAdapter` which can be
constructed from an existing `cv2.VideoCapture`. This allows performing scene detection on inputs
which do not support seeking.
"""
logger = getLogger('pyscenedetect')
IMAGE_SEQUENCE_IDENTIFIER = '%'
NON_VIDEO_FILE_INPUT_IDENTIFIERS = (
IMAGE_SEQUENCE_IDENTIFIER, # image sequence
'://', # URL/network stream
' ! ', # gstreamer pipe
)
def _get_aspect_ratio(cap: cv2.VideoCapture, epsilon: float = 0.0001) -> float:
"""Display/pixel aspect ratio of the VideoCapture as a float (1.0 represents square pixels)."""
# Versions of OpenCV < 3.4.1 do not support this, so we fall back to 1.0.
if not 'CAP_PROP_SAR_NUM' in dir(cv2):
return 1.0
num: float = cap.get(cv2.CAP_PROP_SAR_NUM)
den: float = cap.get(cv2.CAP_PROP_SAR_DEN)
# If numerator or denominator are close to zero, so we fall back to 1.0.
if abs(num) < epsilon or abs(den) < epsilon:
return 1.0
return num / den
| # -*- coding: utf-8 -*-
#
# PySceneDetect: Python-Based Video Scene Detector
# -------------------------------------------------------------------
# [ Site: https://scenedetect.com ]
# [ Docs: https://scenedetect.com/docs/ ]
# [ Github: https://github.com/Breakthrough/PySceneDetect/ ]
#
# Copyright (C) 2014-2023 Brandon Castellano <http://www.bcastell.com>.
# PySceneDetect is licensed under the BSD 3-Clause License; see the
# included LICENSE file, or visit one of the above pages for details.
#
""":class:`VideoStreamCv2` is backed by the OpenCV `VideoCapture` object. This is the default
backend. Works with video files, image sequences, and network streams/URLs.
For wrapping input devices or pipes, there is also :class:`VideoCaptureAdapter` which can be
constructed from an existing `cv2.VideoCapture`. This allows performing scene detection on inputs
which do not support seeking.
"""
logger = getLogger('pyscenedetect')
IMAGE_SEQUENCE_IDENTIFIER = '%'
NON_VIDEO_FILE_INPUT_IDENTIFIERS = (
IMAGE_SEQUENCE_IDENTIFIER, # image sequence
'://', # URL/network stream
' ! ', # gstreamer pipe
)
def _get_aspect_ratio(cap: cv2.VideoCapture, epsilon: float = 0.0001) -> float:
"""Display/pixel aspect ratio of the VideoCapture as a float (1.0 represents square pixels)."""
# Versions of OpenCV < 3.4.1 do not support this, so we fall back to 1.0.
if not 'CAP_PROP_SAR_NUM' in dir(cv2):
return 1.0
num: float = cap.get(cv2.CAP_PROP_SAR_NUM)
den: float = cap.get(cv2.CAP_PROP_SAR_DEN)
# If numerator or denominator are close to zero, so we fall back to 1.0.
if abs(num) < epsilon or abs(den) < epsilon:
return 1.0
return num / den
| class VideoStreamCv2(VideoStream): | 3 | 2023-10-25 02:50:01+00:00 | 8k |
Genesis-Embodied-AI/RoboGen | gpt_4/prompts/utils.py | [
{
"identifier": "decompose_and_generate_reward_or_primitive",
"path": "gpt_4/prompts/prompt_manipulation_reward_primitive.py",
"snippet": "def decompose_and_generate_reward_or_primitive(task_name, task_description, initial_config, articulation_tree, semantics, \n involved_li... | import copy
import os
import yaml
from gpt_4.prompts.prompt_manipulation_reward_primitive import decompose_and_generate_reward_or_primitive
from gpt_4.prompts.prompt_set_joint_angle import query_joint_angle
from gpt_4.prompts.prompt_spatial_relationship import query_spatial_relationship
from gpt_4.query import query
from gpt_4.adjust_size import adjust_size_v2 | 6,421 | joints = []
task_response = task_response.split("\n")
for l_idx, line in enumerate(task_response):
if line.lower().startswith("task name:"):
task_name = line.split(":")[1].strip()
task_name = task_name.replace("/", " or ").replace(".", "").replace("'", "").replace('"', "")
task_names.append(task_name)
task_description = task_response[l_idx+1].split(":")[1].strip()
task_description = task_description.replace("/", " or ").replace(".", "").replace("'", "").replace('"', "").replace(")", ".").replace("(", ".")
task_descriptions.append(task_description)
additional_objects.append(task_response[l_idx+2].split(":")[1].strip())
involved_links = ""
for link_idx in range(l_idx+4, len(task_response)):
if task_response[link_idx].lower().startswith("joints:"):
break
else:
# involved_links.append(task_response[link_idx].split(":")[0][2:])
involved_links += (task_response[link_idx][2:])
links.append(involved_links)
involved_joints = ""
for joint_idx in range(link_idx+1, len(task_response)):
if not task_response[joint_idx].lower().startswith("- "):
break
else:
# involved_joints.append(task_response[joint_idx].split(":")[0][2:])
involved_joints += (task_response[joint_idx][2:])
joints.append(involved_joints)
return task_names, task_descriptions, additional_objects, links, joints
def build_task_given_text(object_category, task_name, task_description, additional_object, involved_links, involved_joints,
articulation_tree_filled, semantics_filled, object_path, save_folder, temperature_dict, model_dict=None):
if model_dict is None:
model_dict = {
"task_generation": "gpt-4",
"reward": "gpt-4",
"yaml": "gpt-4",
"size": "gpt-4",
"joint": "gpt-4",
"spatial_relationship": "gpt-4"
}
task_yaml_config_prompt_filled = copy.deepcopy(task_yaml_config_prompt)
if additional_object.lower() == "none":
task_object = object_category
else:
task_object = "{}, {}".format(object_category, additional_object)
task_yaml_config_prompt_filled = task_yaml_config_prompt_filled.format(task_name, task_description, task_object)
task_yaml_config_prompt_filled += articulation_tree_filled + semantics_filled
system = "You are a helpful assistant."
save_path = os.path.join(save_folder, "gpt_response/task_yaml_config_{}.json".format(task_name))
print("=" * 50)
print("=" * 20, "generating task yaml config", "=" * 20)
print("=" * 50)
task_yaml_response = query(system, [task_yaml_config_prompt_filled], [], save_path=save_path, debug=False,
temperature=temperature_dict["yaml"], model=model_dict["yaml"])
# NOTE: parse the yaml file and generate the task in the simulator.
description = f"{task_name}_{task_description}".replace(" ", "_").replace(".", "").replace(",", "")
task_yaml_response = task_yaml_response.split("\n")
size_save_path = os.path.join(save_folder, "gpt_response/size_{}.json".format(task_name))
parsed_yaml, save_name = parse_response_to_get_yaml(task_yaml_response, description, save_path=size_save_path,
temperature=temperature_dict["size"], model=model_dict["size"])
# NOTE: post-process such that articulated object is urdf.
# NOTE: post-process to include the reward asset path for reward generation.
for obj in parsed_yaml:
if "name" in obj and obj['name'] == object_category:
obj['type'] = 'urdf'
obj['reward_asset_path'] = object_path
# config_path = "gpt_4/data/parsed_configs_semantic_articulated/{}-{}".format(object_category, time_string)
config_path = save_folder
with open(os.path.join(config_path, save_name), 'w') as f:
yaml.dump(parsed_yaml, f, indent=4)
input_to_reward_config = copy.deepcopy(parsed_yaml)
for obj in input_to_reward_config:
if "reward_asset_path" in obj:
input_to_reward_config.remove(obj)
initial_config = yaml.safe_dump(parsed_yaml)
### decompose and generate reward
yaml_file_path = os.path.join(config_path, save_name)
reward_save_path = os.path.join(save_folder, "gpt_response/reward_{}.json".format(task_name))
print("=" * 50)
print("=" * 20, "generating reward", "=" * 20)
print("=" * 50)
solution_path = decompose_and_generate_reward_or_primitive(task_name, task_description, initial_config,
articulation_tree_filled, semantics_filled,
involved_links, involved_joints, object_path,
yaml_file_path, save_path=reward_save_path,
temperature=temperature_dict["reward"],
model=model_dict["reward"])
### generate joint angle
save_path = os.path.join(save_folder, "gpt_response/joint_angle_{}.json".format(task_name))
substep_file_path = os.path.join(solution_path, "substeps.txt")
with open(substep_file_path, 'r') as f:
substeps = f.readlines()
print("=" * 50)
print("=" * 20, "generating initial joint angle", "=" * 20)
print("=" * 50)
joint_angle_values = query_joint_angle(task_name, task_description, articulation_tree_filled, semantics_filled,
involved_links, involved_joints, substeps, save_path=save_path,
temperature=temperature_dict['joint'], model=model_dict["joint"])
joint_angle_values["set_joint_angle_object_name"] = object_category
involved_objects = []
config = yaml.safe_load(initial_config)
for obj in config:
if "name" in obj:
involved_objects.append(obj["name"])
involved_objects = ", ".join(involved_objects)
save_path = os.path.join(save_folder, "gpt_response/spatial_relationships_{}.json".format(task_name))
print("=" * 50)
print("=" * 20, "generating initial spatial relationship", "=" * 20)
print("=" * 50)
|
task_yaml_config_prompt = """
I need you to describe the initial scene configuration for a given task in the following format, using a yaml file. This yaml file will help build the task in a simulator. The task is for a mobile Franka panda robotic arm to learn a manipulation skill in the simulator. The Franka panda arm is mounted on a floor, at location (1, 1, 0). It can move freely on the floor. The z axis is the gravity axis.
The format is as follows:
```yaml
- use_table: whether the task requires using a table. This should be decided based on common sense. If a table is used, its location will be fixed at (0, 0, 0). The height of the table will be 0.6m. Usually, if the objects invovled in the task are usually placed on a table (not directly on the ground), then the task requires using a table.
# for each object involved in the task, we need to specify the following fields for it.
- type: mesh
name: name of the object, so it can be referred to in the simulator
size: describe the scale of the object mesh using 1 number in meters. The scale should match real everyday objects. E.g., an apple is of scale 0.08m. You can think of the scale to be the longest dimension of the object.
lang: this should be a language description of the mesh. The language should be a concise description of the obejct, such that the language description can be used to search an existing database of objects to find the object.
path: this can be a string showing the path to the mesh of the object.
on_table: whether the object needs to be placed on the table (if there is a table needed for the task). This should be based on common sense and the requirement of the task. E.g., a microwave is usually placed on the table.
center: the location of the object center. If there isn't a table needed for the task or the object does not need to be on the table, this center should be expressed in the world coordinate system. If there is a table in the task and the object needs to be placed on the table, this center should be expressed in terms of the table coordinate, where (0, 0, 0) is the lower corner of the table, and (1, 1, 1) is the higher corner of the table. In either case, you should try to specify a location such that there is no collision between objects.
movable: if the object is movable or not in the simulator due to robot actions. This option should be falsed for most tasks; it should be true only if the task specifically requires the robot to move the object. This value can also be missing, which means the object is not movable.
```
An example input includes the task names, task descriptions, and objects involved in the task. I will also provide with you the articulation tree and semantics of the articulated object.
This can be useful for knowing what parts are already in the articulated object, and thus you do not need to repeat those parts as separate objects in the yaml file.
Your task includes two parts:
1. Output the yaml configuration of the task.
2. Sometimes, the task description / objects involved will refer to generic/placeholder objects, e.g., to place an "item" into the drawer, and to heat "food" in the microwave. In the generated yaml config, you should change these placeholder objects to be concrete objects in the lang field, e.g., change "item" to be a toy or a pencil, and "food" to be a hamburger, a bowl of soup, etc.
Example input:
Task Name: Insert Bread Slice
Description: The robotic arm will insert a bread slice into the toaster.
Objects involved: Toaster, bread slice. Only the objects specified here should be included in the yaml file.
```Toaster articulation tree
links:
base
link_0
link_1
link_2
link_3
link_4
link_5
joints:
joint_name: joint_0 joint_type: continuous parent_link: link_5 child_link: link_0
joint_name: joint_1 joint_type: prismatic parent_link: link_5 child_link: link_1
joint_name: joint_2 joint_type: prismatic parent_link: link_5 child_link: link_2
joint_name: joint_3 joint_type: prismatic parent_link: link_5 child_link: link_3
joint_name: joint_4 joint_type: prismatic parent_link: link_5 child_link: link_4
joint_name: joint_5 joint_type: fixed parent_link: base child_link: link_5
```
```Toaster semantics
link_0 hinge knob
link_1 slider slider
link_2 slider button
link_3 slider button
link_4 slider button
link_5 free toaster_body
```
An example output:
```yaml
- use_table: True ### Toaster and bread are usually put on a table.
- type: mesh
name: "Toaster"
on_table: True # Toasters are usually put on a table.
center: (0.1, 0.1, 0) # Remember that when an object is placed on the table, the center is expressed in the table coordinate, where (0, 0, 0) is the lower corner and (1, 1, 1) is the higher corner of the table. Here we put the toaster near the lower corner of the table.
size: 0.35 # the size of a toaster is roughly 0.35m
lang: "a common toaster"
path: "toaster.urdf"
- type: mesh
name: "bread slice"
on_table: True # Bread is usually placed on the table as well.
center: (0.8, 0.7, 0) # Remember that when an object is placed on the table, the center is expressed in the table coordinate, where (0, 0, 0) is the lower corner and (1, 1, 1) is the higher corner of the table. Here we put the bread slice near the higher corner of the table.
size: 0.1 # common size of a bread slice
lang: "a slice of bread"
Path: "bread_slice.obj"
```
Another example input:
Task Name: Removing Lid From Pot
Description: The robotic arm will remove the lid from the pot.
Objects involved: KitchenPot. Only the objects specified here should be included in the yaml file.
```KitchenPot articulation tree
links:
base
link_0
link_1
joints:
joint_name: joint_0 joint_type: prismatic parent_link: link_1 child_link: link_0
joint_name: joint_1 joint_type: fixed parent_link: base child_link: link_1
```
```KitchenPot semantics
link_0 slider lid
link_1 free pot_body
```
Output:
```yaml
- use_table: True # A kitchen pot is usually placed on the table.
- type: mesh
name: "KitchenPot"
on_table: True # kitchen pots are usually placed on a table.
center: (0.3, 0.6, 0) # Remember that when an object is placed on the table, the center is expressed in the table coordinate, where (0, 0, 0) is the lower corner and (1, 1, 1) is the higher corner of the table. Here we put the kitchen pot just at a random location on the table.
size: 0.28 # the size of a common kitchen pot is roughly 0.28m
lang: "a common kitchen pot"
path: "kitchen_pot.urdf"
```
Note in this example, the kitchen pot already has a lid from the semantics file. Therefore, you do not need to include a separate lid in the yaml file.
One more example input:
Task Name: Push the chair.
Description: The robotic arm will push and move the chair to a target location.
Objects involved: A chair. Only the objects here should be included in the yaml file.
```Chair articulation tree
links:
base
link_0
link_1
joints:
joint_name: joint_0 joint_type: revolute parent_link: link_1 child_link: link_0
joint_name: joint_1 joint_type: fixed parent_link: base child_link: link_1
```
```Chair semantics
link_0 hinge seat
link_1 free leg
```
Output:
```yaml
- use_table: False # A chair is usually just on the ground
- type: mesh
name: "Chair"
on_table: False # An oven is usually just placed on the floor.
center: (1.0, 0, 0) # Remember that when not on a table, the center is expressed in the world coordinate. Since the robot is at (1, 1, 0) and the table is at (0, 0, 0), we place the oven at (1.8, 2, 0) to avoid collision with the table and the robot.
size: 1.2 # the size of an oven is roughly 0.9m
lang: "a standard chair"
path: "chair.urdf"
movable: True # here the task requires the robot to push the chair, so the chair has to be moveable.
```
Note in the above example we set the chair to be moveable so the robot can push it for executing the task.
Another example:
Task Name: Put an item into the box drawer
Description: The robot will open the drawer of the box, and put an item into it.
Objects involved: A box with drawer, an item to be placed in the drawer.
```Box articulation tree
links:
base
link_0
link_1
link_2
joints:
joint_name: joint_0 joint_type: revolute parent_link: link_2 child_link: link_0
joint_name: joint_1 joint_type: prismatic parent_link: link_2 child_link: link_1
joint_name: joint_2 joint_type: fixed parent_link: base child_link: link_2
```
```Box semantics
link_0 hinge rotation_lid
link_1 slider drawer
link_2 free box_body
```
Output:
```yaml
- use_table: true
- center: (0.5, 0.5, 0)
lang: "a wooden box"
name: "Box"
on_table: true
path: "box.urdf"
size: 0.3
type: urdf
- path: "item.obj"
center: (0.2, 0.4, 0)
lang: "A toy" # Note here, we changed the generic/placeholder "item" object to be a more concrete object: a toy.
name: "Item"
on_table: true
size: 0.05
type: mesh
```
One more example:
Task Name: Fetch item from refrigerator
Description: The robot will open the refrigerator door, and fetch an item from the refrigerator.
Objects involved: A refrigerator, an item to be fetched from the refrigerator.
```Refirgerator articulation tree
links:
base
link_0
link_1
link_2
joints:
joint_name: joint_0 joint_type: fixed parent_link: base child_link: link_0
joint_name: joint_1 joint_type: revolute parent_link: link_0 child_link: link_1
joint_name: joint_2 joint_type: revolute parent_link: link_0 child_link: link_2
```
```Refrigerator semantics
link_0 heavy refrigerator_body
link_1 hinge door
link_2 hinge door
```
Output:
```yaml
- use_table: true # the fetched item should be placed on the table, after it's moved out of the refrigerator.
- center: (1.0, 0.2, 0) # Remember that when not on a table, the center is expressed in the world coordinate. Since the robot is at (1, 1, 0) and the table is at (0, 0, 0), we place the oven at (1.8, 2, 0) to avoid collision with the table and the robot.
lang: a common two-door refrigerator
name: Refrigerator
on_table: false # the refrigerator is usually placed on the floor.
path: refrigerator.urdf
reward_asset_path: '10612'
size: 1.8
type: urdf
- center: (1.0, 0.2, 0.5) # the soda can is initially placed inside the refrigerator.
lang: a can of soda
name: Item
on_table: false # the item is initially placed inside the refrigerator
path: soda_can.obj
size: 0.2
type: mesh
```
Rules:
- You do not need to include the robot in the yaml file.
- The yaml file should only include the objects listed in "Objects involved".
- Sometimes, the task description / objects involved will refer to generic/placeholder objects, e.g., to place an "item" into the drawer, and to heat "food" in the microwave. In the generated yaml config, you should change these placeholder objects to be concrete objects in the lang field, e.g., change "item" to be a toy or a pencil, and "food" to be a hamburger, a bowl of soup, etc.
Can you do this for the following task:
Task Name: {}
Description: {}
Objects involved: {}
"""
def parse_response_to_get_yaml(response, task_description, save_path, temperature=0.2, model='gpt-4'):
yaml_string = []
for l_idx, line in enumerate(response):
if "```yaml" in line:
for l_idx_2 in range(l_idx + 1, len(response)):
if response[l_idx_2].lstrip().startswith("```"):
break
yaml_string.append(response[l_idx_2])
yaml_string = '\n'.join(yaml_string)
description = f"{task_description}".replace(" ", "_").replace(".", "").replace(",", "").replace("(", "").replace(")", "")
save_name = description + '.yaml'
print("=" * 30)
print("querying GPT to adjust the size of the objects")
print("=" * 30)
parsed_size_yaml = adjust_size_v2(description, yaml_string, save_path, temperature, model=model)
return parsed_size_yaml, save_name
def parse_task_response(task_response):
task_names = []
task_descriptions = []
additional_objects = []
links = []
joints = []
task_response = task_response.split("\n")
for l_idx, line in enumerate(task_response):
if line.lower().startswith("task name:"):
task_name = line.split(":")[1].strip()
task_name = task_name.replace("/", " or ").replace(".", "").replace("'", "").replace('"', "")
task_names.append(task_name)
task_description = task_response[l_idx+1].split(":")[1].strip()
task_description = task_description.replace("/", " or ").replace(".", "").replace("'", "").replace('"', "").replace(")", ".").replace("(", ".")
task_descriptions.append(task_description)
additional_objects.append(task_response[l_idx+2].split(":")[1].strip())
involved_links = ""
for link_idx in range(l_idx+4, len(task_response)):
if task_response[link_idx].lower().startswith("joints:"):
break
else:
# involved_links.append(task_response[link_idx].split(":")[0][2:])
involved_links += (task_response[link_idx][2:])
links.append(involved_links)
involved_joints = ""
for joint_idx in range(link_idx+1, len(task_response)):
if not task_response[joint_idx].lower().startswith("- "):
break
else:
# involved_joints.append(task_response[joint_idx].split(":")[0][2:])
involved_joints += (task_response[joint_idx][2:])
joints.append(involved_joints)
return task_names, task_descriptions, additional_objects, links, joints
def build_task_given_text(object_category, task_name, task_description, additional_object, involved_links, involved_joints,
articulation_tree_filled, semantics_filled, object_path, save_folder, temperature_dict, model_dict=None):
if model_dict is None:
model_dict = {
"task_generation": "gpt-4",
"reward": "gpt-4",
"yaml": "gpt-4",
"size": "gpt-4",
"joint": "gpt-4",
"spatial_relationship": "gpt-4"
}
task_yaml_config_prompt_filled = copy.deepcopy(task_yaml_config_prompt)
if additional_object.lower() == "none":
task_object = object_category
else:
task_object = "{}, {}".format(object_category, additional_object)
task_yaml_config_prompt_filled = task_yaml_config_prompt_filled.format(task_name, task_description, task_object)
task_yaml_config_prompt_filled += articulation_tree_filled + semantics_filled
system = "You are a helpful assistant."
save_path = os.path.join(save_folder, "gpt_response/task_yaml_config_{}.json".format(task_name))
print("=" * 50)
print("=" * 20, "generating task yaml config", "=" * 20)
print("=" * 50)
task_yaml_response = query(system, [task_yaml_config_prompt_filled], [], save_path=save_path, debug=False,
temperature=temperature_dict["yaml"], model=model_dict["yaml"])
# NOTE: parse the yaml file and generate the task in the simulator.
description = f"{task_name}_{task_description}".replace(" ", "_").replace(".", "").replace(",", "")
task_yaml_response = task_yaml_response.split("\n")
size_save_path = os.path.join(save_folder, "gpt_response/size_{}.json".format(task_name))
parsed_yaml, save_name = parse_response_to_get_yaml(task_yaml_response, description, save_path=size_save_path,
temperature=temperature_dict["size"], model=model_dict["size"])
# NOTE: post-process such that articulated object is urdf.
# NOTE: post-process to include the reward asset path for reward generation.
for obj in parsed_yaml:
if "name" in obj and obj['name'] == object_category:
obj['type'] = 'urdf'
obj['reward_asset_path'] = object_path
# config_path = "gpt_4/data/parsed_configs_semantic_articulated/{}-{}".format(object_category, time_string)
config_path = save_folder
with open(os.path.join(config_path, save_name), 'w') as f:
yaml.dump(parsed_yaml, f, indent=4)
input_to_reward_config = copy.deepcopy(parsed_yaml)
for obj in input_to_reward_config:
if "reward_asset_path" in obj:
input_to_reward_config.remove(obj)
initial_config = yaml.safe_dump(parsed_yaml)
### decompose and generate reward
yaml_file_path = os.path.join(config_path, save_name)
reward_save_path = os.path.join(save_folder, "gpt_response/reward_{}.json".format(task_name))
print("=" * 50)
print("=" * 20, "generating reward", "=" * 20)
print("=" * 50)
solution_path = decompose_and_generate_reward_or_primitive(task_name, task_description, initial_config,
articulation_tree_filled, semantics_filled,
involved_links, involved_joints, object_path,
yaml_file_path, save_path=reward_save_path,
temperature=temperature_dict["reward"],
model=model_dict["reward"])
### generate joint angle
save_path = os.path.join(save_folder, "gpt_response/joint_angle_{}.json".format(task_name))
substep_file_path = os.path.join(solution_path, "substeps.txt")
with open(substep_file_path, 'r') as f:
substeps = f.readlines()
print("=" * 50)
print("=" * 20, "generating initial joint angle", "=" * 20)
print("=" * 50)
joint_angle_values = query_joint_angle(task_name, task_description, articulation_tree_filled, semantics_filled,
involved_links, involved_joints, substeps, save_path=save_path,
temperature=temperature_dict['joint'], model=model_dict["joint"])
joint_angle_values["set_joint_angle_object_name"] = object_category
involved_objects = []
config = yaml.safe_load(initial_config)
for obj in config:
if "name" in obj:
involved_objects.append(obj["name"])
involved_objects = ", ".join(involved_objects)
save_path = os.path.join(save_folder, "gpt_response/spatial_relationships_{}.json".format(task_name))
print("=" * 50)
print("=" * 20, "generating initial spatial relationship", "=" * 20)
print("=" * 50) | spatial_relationships = query_spatial_relationship(task_name, task_description, involved_objects, articulation_tree_filled, semantics_filled, | 2 | 2023-10-31 19:44:09+00:00 | 8k |
junhoyeo/BetterOCR | betterocr/engines/easy_pororo_ocr/pororo/models/brainOCR/brainocr.py | [
{
"identifier": "get_detector",
"path": "betterocr/engines/easy_pororo_ocr/pororo/models/brainOCR/detection.py",
"snippet": "def get_detector(det_model_ckpt_fp: str, device: str = \"cpu\"):\n net = CRAFT()\n\n net.load_state_dict(\n copy_state_dict(torch.load(det_model_ckpt_fp, map_location... | import ast
import cv2
import numpy as np
from logging import getLogger
from typing import List
from PIL import Image
from .detection import get_detector, get_textbox
from .recognition import get_recognizer, get_text
from .utils import (
diff,
get_image_list,
get_paragraph,
group_text_box,
reformat_input,
) | 5,737 | """
this code is adapted from https://github.com/black7375/korean_ocr_using_pororo
Apache License 2.0 @yunwoong7
Apache License 2.0 @black7375
"""
"""
This code is primarily based on the following:
https://github.com/JaidedAI/EasyOCR/blob/8af936ba1b2f3c230968dc1022d0cd3e9ca1efbb/easyocr/easyocr.py
Basic usage:
>>> from pororo import Pororo
>>> ocr = Pororo(task="ocr", lang="ko")
>>> ocr("IMAGE_FILE")
"""
LOGGER = getLogger(__name__)
class Reader(object):
def __init__(
self,
lang: str,
det_model_ckpt_fp: str,
rec_model_ckpt_fp: str,
opt_fp: str,
device: str,
) -> None:
"""
TODO @karter: modify this such that you download the pretrained checkpoint files
Parameters:
lang: language code. e.g, "en" or "ko"
det_model_ckpt_fp: Detection model's checkpoint path e.g., 'craft_mlt_25k.pth'
rec_model_ckpt_fp: Recognition model's checkpoint path
opt_fp: option file path
"""
# Plug options in the dictionary
opt2val = self.parse_options(opt_fp) # e.g., {"imgH": 64, ...}
opt2val["vocab"] = self.build_vocab(opt2val["character"])
opt2val["vocab_size"] = len(opt2val["vocab"])
opt2val["device"] = device
opt2val["lang"] = lang
opt2val["det_model_ckpt_fp"] = det_model_ckpt_fp
opt2val["rec_model_ckpt_fp"] = rec_model_ckpt_fp
# Get model objects
self.detector = get_detector(det_model_ckpt_fp, opt2val["device"])
self.recognizer, self.converter = get_recognizer(opt2val)
self.opt2val = opt2val
@staticmethod
def parse_options(opt_fp: str) -> dict:
opt2val = dict()
for line in open(opt_fp, "r", encoding="utf8"):
line = line.strip()
if ": " in line:
opt, val = line.split(": ", 1)
try:
opt2val[opt] = ast.literal_eval(val)
except:
opt2val[opt] = val
return opt2val
@staticmethod
def build_vocab(character: str) -> List[str]:
"""Returns vocabulary (=list of characters)"""
vocab = ["[blank]"] + list(
character
) # dummy '[blank]' token for CTCLoss (index 0)
return vocab
def detect(self, img: np.ndarray, opt2val: dict):
"""
:return:
horizontal_list (list): e.g., [[613, 1496, 51, 190], [136, 1544, 134, 508]]
free_list (list): e.g., []
"""
text_box = get_textbox(self.detector, img, opt2val)
horizontal_list, free_list = group_text_box(
text_box,
opt2val["slope_ths"],
opt2val["ycenter_ths"],
opt2val["height_ths"],
opt2val["width_ths"],
opt2val["add_margin"],
)
min_size = opt2val["min_size"]
if min_size:
horizontal_list = [
i for i in horizontal_list if max(i[1] - i[0], i[3] - i[2]) > min_size
]
free_list = [
i
for i in free_list
| """
this code is adapted from https://github.com/black7375/korean_ocr_using_pororo
Apache License 2.0 @yunwoong7
Apache License 2.0 @black7375
"""
"""
This code is primarily based on the following:
https://github.com/JaidedAI/EasyOCR/blob/8af936ba1b2f3c230968dc1022d0cd3e9ca1efbb/easyocr/easyocr.py
Basic usage:
>>> from pororo import Pororo
>>> ocr = Pororo(task="ocr", lang="ko")
>>> ocr("IMAGE_FILE")
"""
LOGGER = getLogger(__name__)
class Reader(object):
def __init__(
self,
lang: str,
det_model_ckpt_fp: str,
rec_model_ckpt_fp: str,
opt_fp: str,
device: str,
) -> None:
"""
TODO @karter: modify this such that you download the pretrained checkpoint files
Parameters:
lang: language code. e.g, "en" or "ko"
det_model_ckpt_fp: Detection model's checkpoint path e.g., 'craft_mlt_25k.pth'
rec_model_ckpt_fp: Recognition model's checkpoint path
opt_fp: option file path
"""
# Plug options in the dictionary
opt2val = self.parse_options(opt_fp) # e.g., {"imgH": 64, ...}
opt2val["vocab"] = self.build_vocab(opt2val["character"])
opt2val["vocab_size"] = len(opt2val["vocab"])
opt2val["device"] = device
opt2val["lang"] = lang
opt2val["det_model_ckpt_fp"] = det_model_ckpt_fp
opt2val["rec_model_ckpt_fp"] = rec_model_ckpt_fp
# Get model objects
self.detector = get_detector(det_model_ckpt_fp, opt2val["device"])
self.recognizer, self.converter = get_recognizer(opt2val)
self.opt2val = opt2val
@staticmethod
def parse_options(opt_fp: str) -> dict:
opt2val = dict()
for line in open(opt_fp, "r", encoding="utf8"):
line = line.strip()
if ": " in line:
opt, val = line.split(": ", 1)
try:
opt2val[opt] = ast.literal_eval(val)
except:
opt2val[opt] = val
return opt2val
@staticmethod
def build_vocab(character: str) -> List[str]:
"""Returns vocabulary (=list of characters)"""
vocab = ["[blank]"] + list(
character
) # dummy '[blank]' token for CTCLoss (index 0)
return vocab
def detect(self, img: np.ndarray, opt2val: dict):
"""
:return:
horizontal_list (list): e.g., [[613, 1496, 51, 190], [136, 1544, 134, 508]]
free_list (list): e.g., []
"""
text_box = get_textbox(self.detector, img, opt2val)
horizontal_list, free_list = group_text_box(
text_box,
opt2val["slope_ths"],
opt2val["ycenter_ths"],
opt2val["height_ths"],
opt2val["width_ths"],
opt2val["add_margin"],
)
min_size = opt2val["min_size"]
if min_size:
horizontal_list = [
i for i in horizontal_list if max(i[1] - i[0], i[3] - i[2]) > min_size
]
free_list = [
i
for i in free_list | if max(diff([c[0] for c in i]), diff([c[1] for c in i])) > min_size | 4 | 2023-10-26 11:26:25+00:00 | 8k |
KoeAI/LLVC | minimal_rvc/pipeline.py | [
{
"identifier": "SynthesizerTrnMs256NSFSid",
"path": "minimal_rvc/models.py",
"snippet": "class SynthesizerTrnMs256NSFSid(nn.Module):\n def __init__(\n self,\n spec_channels,\n segment_size,\n inter_channels,\n hidden_channels,\n filter_channels,\n n_h... | import os
import traceback
import faiss
import numpy as np
import pyworld
import scipy.signal as signal
import torch
import torch.nn.functional as F
import torchcrepe
from typing import *
from fairseq.models.hubert import HubertModel
from torch import Tensor
from .models import SynthesizerTrnMs256NSFSid
from .rmvpe import RMVPE | 4,751 | source[source < 0.001] = np.nan
target = np.interp(
np.arange(0, len(source) * p_len, len(source)) / p_len,
np.arange(0, len(source)),
source
)
f0 = np.nan_to_num(target)
return f0 # Resized f0
def get_f0_official_crepe_computation(
self,
x,
f0_min,
f0_max,
model="full",
):
# Pick a batch size that doesn't cause memory errors on your gpu
batch_size = 512
# Compute pitch using first gpu
audio = torch.tensor(np.copy(x))[None].float()
f0, pd = torchcrepe.predict(
audio,
self.sr,
self.window,
f0_min,
f0_max,
model,
batch_size=batch_size,
device=self.device,
return_periodicity=True,
)
pd = torchcrepe.filter.median(pd, 3)
f0 = torchcrepe.filter.mean(f0, 3)
f0[pd < 0.1] = 0
f0 = f0[0].cpu().numpy()
return f0
def get_f0(
self,
x: np.ndarray,
p_len: int,
f0_up_key: int,
f0_method: str,
f0_relative: bool,
inp_f0: np.ndarray = None,
):
f0_min = 50
f0_max = 1100
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
if f0_method == "harvest":
f0, t = pyworld.harvest(
x.astype(np.double),
fs=self.sr,
f0_ceil=f0_max,
f0_floor=f0_min,
frame_period=10,
)
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
f0 = signal.medfilt(f0, 3)
elif f0_method == "dio":
f0, t = pyworld.dio(
x.astype(np.double),
fs=self.sr,
f0_ceil=f0_max,
f0_floor=f0_min,
frame_period=10,
)
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
f0 = signal.medfilt(f0, 3)
elif f0_method == "mangio-crepe":
f0 = self.get_f0_crepe_computation(
x, f0_min, f0_max, p_len, 160, "full")
elif f0_method == "crepe":
f0 = self.get_f0_official_crepe_computation(
x, f0_min, f0_max, "full")
elif f0_method == "rmvpe":
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
if f0_relative:
if f0_method == "rmvpe" or f0_method == "rmvpe_onnx":
# this is the average f0 of /test_wavs/2086-149214-0000.wav
# by calculating f0 relative to this wav, we can ensure
# consistent output pitch when converting from different speakers
rel_f0 = 126.21
else:
raise ValueError("TODO: find rel_f0 for " + f0_method)
mean_f0 = np.mean(f0[f0 > 0])
offset = np.round(12 * np.log2(mean_f0 / rel_f0))
# print("offset: " + str(offset))
f0_up_key = f0_up_key - offset
f0 *= pow(2, f0_up_key / 12)
tf0 = self.sr // self.window # f0 points per second
if inp_f0 is not None:
delta_t = np.round(
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
).astype("int16")
replace_f0 = np.interp(
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
)
shape = f0[self.x_pad * tf0: self.x_pad *
tf0 + len(replace_f0)].shape[0]
f0[self.x_pad * tf0: self.x_pad * tf0 + len(replace_f0)] = replace_f0[
:shape
]
f0bak = f0.copy()
f0_mel = 1127 * np.log(1 + f0 / 700)
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
f0_mel_max - f0_mel_min
) + 1
f0_mel[f0_mel <= 1] = 1
f0_mel[f0_mel > 255] = 255
f0_coarse = np.rint(f0_mel).astype(int)
return f0_coarse, f0bak # 1-0
def _convert(
self,
model: HubertModel,
embedding_output_layer: int,
| # This module is based on code from ddPn08, liujing04, and teftef6220
# https://github.com/ddPn08/rvc-webui
# https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI
# https://github.com/teftef6220/Voice_Separation_and_Selection
# These modules are licensed under the MIT License.
# from faiss.swigfaiss_avx2 import IndexIVFFlat # cause crash on windows' faiss-cpu installed from pip
class VocalConvertPipeline(object):
def __init__(self, tgt_sr: int, device: Union[str, torch.device], is_half: bool, no_pad: bool = False):
if isinstance(device, str):
device = torch.device(device)
if device.type == "cuda":
vram = torch.cuda.get_device_properties(
device).total_memory / 1024**3
else:
vram = None
if vram is not None and vram <= 4:
self.x_pad = 1
self.x_query = 5
self.x_center = 30
self.x_max = 32
elif vram is not None and vram <= 5:
self.x_pad = 1
self.x_query = 6
self.x_center = 38
self.x_max = 41
else:
self.x_pad = 3
self.x_query = 10
self.x_center = 60
self.x_max = 65
if no_pad:
self.x_pad = 0
self.sr = 16000 # hubert input sample rate
self.window = 160 # hubert input window
self.t_pad = self.sr * self.x_pad # padding time for each utterance
self.t_pad_tgt = tgt_sr * self.x_pad
self.t_pad2 = self.t_pad * 2
self.t_query = self.sr * self.x_query # query time before and after query point
self.t_center = self.sr * self.x_center # query cut point position
self.t_max = self.sr * self.x_max # max time for no query
self.device = device
self.is_half = is_half
self.model_rmvpe = RMVPE(
f"llvc_models/models/f0/rmvpe.pt",
is_half=self.is_half,
device=self.device,
)
def get_optimal_torch_device(self, index: int = 0) -> torch.device:
# Get cuda device
if torch.cuda.is_available():
# Very fast
return torch.device(f"cuda:{index % torch.cuda.device_count()}")
elif torch.backends.mps.is_available():
return torch.device("mps")
# Insert an else here to grab "xla" devices if available. TO DO later. Requires the torch_xla.core.xla_model library
# Else wise return the "cpu" as a torch device,
return torch.device("cpu")
def get_f0_crepe_computation(
self,
x,
f0_min,
f0_max,
p_len,
# 512 before. Hop length changes the speed that the voice jumps to a different dramatic pitch. Lower hop lengths means more pitch accuracy but longer inference time.
hop_length=64,
model="full", # Either use crepe-tiny "tiny" or crepe "full". Default is full
):
# fixes the F.conv2D exception. We needed to convert double to float.
x = x.astype(np.float32)
x /= np.quantile(np.abs(x), 0.999)
torch_device = self.get_optimal_torch_device()
audio = torch.from_numpy(x).to(torch_device, copy=True)
audio = torch.unsqueeze(audio, dim=0)
if audio.ndim == 2 and audio.shape[0] > 1:
audio = torch.mean(audio, dim=0, keepdim=True).detach()
audio = audio.detach()
print("Initiating prediction with a crepe_hop_length of: " + str(hop_length))
pitch: Tensor = torchcrepe.predict(
audio,
self.sr,
hop_length,
f0_min,
f0_max,
model,
batch_size=hop_length * 2,
device=torch_device,
pad=True
)
p_len = p_len or x.shape[0] // hop_length
# Resize the pitch for final f0
source = np.array(pitch.squeeze(0).cpu().float().numpy())
source[source < 0.001] = np.nan
target = np.interp(
np.arange(0, len(source) * p_len, len(source)) / p_len,
np.arange(0, len(source)),
source
)
f0 = np.nan_to_num(target)
return f0 # Resized f0
def get_f0_official_crepe_computation(
self,
x,
f0_min,
f0_max,
model="full",
):
# Pick a batch size that doesn't cause memory errors on your gpu
batch_size = 512
# Compute pitch using first gpu
audio = torch.tensor(np.copy(x))[None].float()
f0, pd = torchcrepe.predict(
audio,
self.sr,
self.window,
f0_min,
f0_max,
model,
batch_size=batch_size,
device=self.device,
return_periodicity=True,
)
pd = torchcrepe.filter.median(pd, 3)
f0 = torchcrepe.filter.mean(f0, 3)
f0[pd < 0.1] = 0
f0 = f0[0].cpu().numpy()
return f0
def get_f0(
self,
x: np.ndarray,
p_len: int,
f0_up_key: int,
f0_method: str,
f0_relative: bool,
inp_f0: np.ndarray = None,
):
f0_min = 50
f0_max = 1100
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
if f0_method == "harvest":
f0, t = pyworld.harvest(
x.astype(np.double),
fs=self.sr,
f0_ceil=f0_max,
f0_floor=f0_min,
frame_period=10,
)
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
f0 = signal.medfilt(f0, 3)
elif f0_method == "dio":
f0, t = pyworld.dio(
x.astype(np.double),
fs=self.sr,
f0_ceil=f0_max,
f0_floor=f0_min,
frame_period=10,
)
f0 = pyworld.stonemask(x.astype(np.double), f0, t, self.sr)
f0 = signal.medfilt(f0, 3)
elif f0_method == "mangio-crepe":
f0 = self.get_f0_crepe_computation(
x, f0_min, f0_max, p_len, 160, "full")
elif f0_method == "crepe":
f0 = self.get_f0_official_crepe_computation(
x, f0_min, f0_max, "full")
elif f0_method == "rmvpe":
f0 = self.model_rmvpe.infer_from_audio(x, thred=0.03)
if f0_relative:
if f0_method == "rmvpe" or f0_method == "rmvpe_onnx":
# this is the average f0 of /test_wavs/2086-149214-0000.wav
# by calculating f0 relative to this wav, we can ensure
# consistent output pitch when converting from different speakers
rel_f0 = 126.21
else:
raise ValueError("TODO: find rel_f0 for " + f0_method)
mean_f0 = np.mean(f0[f0 > 0])
offset = np.round(12 * np.log2(mean_f0 / rel_f0))
# print("offset: " + str(offset))
f0_up_key = f0_up_key - offset
f0 *= pow(2, f0_up_key / 12)
tf0 = self.sr // self.window # f0 points per second
if inp_f0 is not None:
delta_t = np.round(
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
).astype("int16")
replace_f0 = np.interp(
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
)
shape = f0[self.x_pad * tf0: self.x_pad *
tf0 + len(replace_f0)].shape[0]
f0[self.x_pad * tf0: self.x_pad * tf0 + len(replace_f0)] = replace_f0[
:shape
]
f0bak = f0.copy()
f0_mel = 1127 * np.log(1 + f0 / 700)
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
f0_mel_max - f0_mel_min
) + 1
f0_mel[f0_mel <= 1] = 1
f0_mel[f0_mel > 255] = 255
f0_coarse = np.rint(f0_mel).astype(int)
return f0_coarse, f0bak # 1-0
def _convert(
self,
model: HubertModel,
embedding_output_layer: int, | net_g: SynthesizerTrnMs256NSFSid, | 0 | 2023-10-28 01:58:49+00:00 | 8k |
aurelio-labs/semantic-router | tests/unit/test_hybrid_layer.py | [
{
"identifier": "BaseEncoder",
"path": "semantic_router/encoders/base.py",
"snippet": "class BaseEncoder(BaseModel):\n name: str\n score_threshold: float\n type: str = Field(default=\"base\")\n\n class Config:\n arbitrary_types_allowed = True\n\n def __call__(self, docs: List[str])... | import pytest
from semantic_router.encoders import (
AzureOpenAIEncoder,
BaseEncoder,
BM25Encoder,
CohereEncoder,
OpenAIEncoder,
TfidfEncoder,
)
from semantic_router.hybrid_layer import HybridRouteLayer
from semantic_router.route import Route | 6,069 |
def mock_encoder_call(utterances):
# Define a mapping of utterances to return values
mock_responses = {
"Hello": [0.1, 0.2, 0.3],
"Hi": [0.4, 0.5, 0.6],
"Goodbye": [0.7, 0.8, 0.9],
"Bye": [1.0, 1.1, 1.2],
"Au revoir": [1.3, 1.4, 1.5],
}
return [mock_responses.get(u, [0, 0, 0]) for u in utterances]
@pytest.fixture
def base_encoder(mocker):
mock_base_encoder = BaseEncoder(name="test-encoder", score_threshold=0.5)
mocker.patch.object(BaseEncoder, "__call__", return_value=[[0.1, 0.2, 0.3]])
return mock_base_encoder
@pytest.fixture
def cohere_encoder(mocker):
mocker.patch.object(CohereEncoder, "__call__", side_effect=mock_encoder_call)
return CohereEncoder(name="test-cohere-encoder", cohere_api_key="test_api_key")
@pytest.fixture
def openai_encoder(mocker):
mocker.patch.object(OpenAIEncoder, "__call__", side_effect=mock_encoder_call)
return OpenAIEncoder(name="test-openai-encoder", openai_api_key="test_api_key")
@pytest.fixture
def azure_encoder(mocker):
|
def mock_encoder_call(utterances):
# Define a mapping of utterances to return values
mock_responses = {
"Hello": [0.1, 0.2, 0.3],
"Hi": [0.4, 0.5, 0.6],
"Goodbye": [0.7, 0.8, 0.9],
"Bye": [1.0, 1.1, 1.2],
"Au revoir": [1.3, 1.4, 1.5],
}
return [mock_responses.get(u, [0, 0, 0]) for u in utterances]
@pytest.fixture
def base_encoder(mocker):
mock_base_encoder = BaseEncoder(name="test-encoder", score_threshold=0.5)
mocker.patch.object(BaseEncoder, "__call__", return_value=[[0.1, 0.2, 0.3]])
return mock_base_encoder
@pytest.fixture
def cohere_encoder(mocker):
mocker.patch.object(CohereEncoder, "__call__", side_effect=mock_encoder_call)
return CohereEncoder(name="test-cohere-encoder", cohere_api_key="test_api_key")
@pytest.fixture
def openai_encoder(mocker):
mocker.patch.object(OpenAIEncoder, "__call__", side_effect=mock_encoder_call)
return OpenAIEncoder(name="test-openai-encoder", openai_api_key="test_api_key")
@pytest.fixture
def azure_encoder(mocker): | mocker.patch.object(AzureOpenAIEncoder, "__call__", side_effect=mock_encoder_call) | 5 | 2023-10-30 12:12:45+00:00 | 8k |
baaivision/JudgeLM | judgelm/serve/gradio_web_server_multi.py | [
{
"identifier": "SESSION_EXPIRATION_TIME",
"path": "judgelm/constants.py",
"snippet": "SESSION_EXPIRATION_TIME = 3600"
},
{
"identifier": "build_side_by_side_ui_anony",
"path": "judgelm/serve/gradio_block_arena_anony.py",
"snippet": "def build_side_by_side_ui_anony(models):\n notice_m... | import argparse
import pickle
import time
import gradio as gr
from judgelm.constants import (
SESSION_EXPIRATION_TIME,
)
from judgelm.serve.gradio_block_arena_anony import (
build_side_by_side_ui_anony,
load_demo_side_by_side_anony,
set_global_vars_anony,
)
from judgelm.serve.gradio_block_arena_named import (
build_side_by_side_ui_named,
load_demo_side_by_side_named,
set_global_vars_named,
)
from judgelm.serve.gradio_web_server import (
set_global_vars,
block_css,
build_single_model_ui,
get_model_list,
load_demo_single,
ip_expiration_dict,
)
from judgelm.serve.monitor.monitor import build_leaderboard_tab
from judgelm.utils import (
build_logger,
get_window_url_params_js,
parse_gradio_auth_creds,
) | 6,231 | """
The gradio demo server with multiple tabs.
It supports chatting with a single model or chatting with two models side-by-side.
"""
logger = build_logger("gradio_web_server_multi", "gradio_web_server_multi.log")
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
selected = 0
if "arena" in url_params:
selected = 1
elif "compare" in url_params:
selected = 2
elif "leaderboard" in url_params:
selected = 3
if args.model_list_mode == "reload":
if args.anony_only_for_proprietary_model:
models = get_model_list(args.controller_url, False, False, False)
else:
models = get_model_list(
args.controller_url, args.add_chatgpt, args.add_claude, args.add_palm
)
single_updates = load_demo_single(models, url_params)
models_anony = list(models)
if args.anony_only_for_proprietary_model:
# Only enable these models in anony battles.
if args.add_chatgpt:
models_anony += ["gpt-4", "gpt-3.5-turbo"]
if args.add_claude:
models_anony += ["claude-2", "claude-instant-1"]
if args.add_palm:
models_anony += ["palm-2"]
| """
The gradio demo server with multiple tabs.
It supports chatting with a single model or chatting with two models side-by-side.
"""
logger = build_logger("gradio_web_server_multi", "gradio_web_server_multi.log")
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
selected = 0
if "arena" in url_params:
selected = 1
elif "compare" in url_params:
selected = 2
elif "leaderboard" in url_params:
selected = 3
if args.model_list_mode == "reload":
if args.anony_only_for_proprietary_model:
models = get_model_list(args.controller_url, False, False, False)
else:
models = get_model_list(
args.controller_url, args.add_chatgpt, args.add_claude, args.add_palm
)
single_updates = load_demo_single(models, url_params)
models_anony = list(models)
if args.anony_only_for_proprietary_model:
# Only enable these models in anony battles.
if args.add_chatgpt:
models_anony += ["gpt-4", "gpt-3.5-turbo"]
if args.add_claude:
models_anony += ["claude-2", "claude-instant-1"]
if args.add_palm:
models_anony += ["palm-2"]
| side_by_side_anony_updates = load_demo_side_by_side_anony(models_anony, url_params) | 2 | 2023-10-26 19:41:07+00:00 | 8k |
EulerSearch/embedding_studio | embedding_studio/embeddings/data/loaders/s3/s3_loader.py | [
{
"identifier": "settings",
"path": "embedding_studio/core/config.py",
"snippet": "class Settings(BaseSettings):\n API_V1_STR: str = \"/api/v1\"\n SECRET_KEY: str = secrets.token_urlsafe(32)\n ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8\n BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []\n F... | import io
import logging
import uuid
import boto3
from typing import Dict, Iterable, List, Optional
from botocore import UNSIGNED
from botocore.client import Config
from botocore.exceptions import ClientError, EndpointConnectionError
from datasets import Dataset
from PIL import Image
from pydantic import BaseModel
from embedding_studio.core.config import settings
from embedding_studio.embeddings.data.loaders.data_loader import DataLoader
from embedding_studio.embeddings.data.loaders.s3.exceptions.failed_to_load_anything_from_s3 import (
FailedToLoadAnythingFromAWSS3,
)
from embedding_studio.embeddings.data.loaders.s3.item_meta import S3FileMeta
from embedding_studio.workers.fine_tuning.utils.config import (
RetryConfig,
RetryParams,
)
from embedding_studio.workers.fine_tuning.utils.retry import retry_method | 4,465 | return Image.open(outfile)
except ClientError as e:
if e.response["Error"]["Code"] == "404":
logger.error(f"Object {file} not found in bucket {bucket}")
return None
else:
# Raise the exception for any other unexpected errors
raise e
class AWSS3DataLoader(DataLoader):
def __init__(self, retry_config: Optional[RetryConfig] = None, **kwargs):
"""Items loader from AWS S3.
:param max_attempts: maximum number of attempts (default: 10)
:param wait_time_seconds: time to wait between (default: 10)
:param kwargs: dict data for AWSS3Credentials
"""
super(AWSS3DataLoader, self).__init__(**kwargs)
self.retry_config = (
retry_config
if retry_config
else AWSS3DataLoader._get_default_retry_config()
)
self.credentials = AWSS3Credentials(**kwargs)
self.attempt_exception_types = [EndpointConnectionError]
@staticmethod
def _get_default_retry_config() -> RetryConfig:
default_retry_params = RetryParams(
max_attempts=settings.DEFAULT_MAX_ATTEMPTS,
wait_time_seconds=settings.DEFAULT_WAIT_TIME_SECONDS,
)
config = RetryConfig(default_params=default_retry_params)
config["credentials"] = RetryParams(
max_attempts=settings.S3_READ_CREDENTIALS_ATTEMPTS,
wait_time_seconds=settings.S3_READ_WAIT_TIME_SECONDS,
)
config["download_data"] = RetryParams(
max_attempts=settings.S3_DOWNLOAD_DATA_ATTEMPTS,
wait_time_seconds=settings.S3_DOWNLOAD_DATA_WAIT_TIME_SECONDS,
)
return config
@retry_method(name="download_data")
def _read_from_s3(self, client, bucket: str, file: str) -> Image:
return read_from_s3(client, bucket, file)
@retry_method(name="credentials")
def _get_client(self, task_id: str):
if (
self.credentials.aws_access_key_id is None
or self.credentials.aws_secret_access_key is None
) and not self.credentials.use_system_info:
logger.warning(
"No specific AWS credentials, use Anonymous session"
)
s3_client = boto3.client(
"s3", config=Config(signature_version=UNSIGNED)
)
else:
sts_client = boto3.client(
"sts",
aws_access_key_id=self.credentials.aws_access_key_id,
aws_secret_access_key=self.credentials.aws_secret_access_key,
)
if self.credentials.external_id:
assumed_role_object = sts_client.assume_role(
RoleArn=self.credentials.role_arn,
RoleSessionName=task_id,
ExternalId=self.credentials.external_id,
)
else:
assumed_role_object = sts_client.assume_role(
RoleArn=self.credentials.role_arn,
RoleSessionName=task_id,
)
credentials = assumed_role_object["Credentials"]
s3_client = boto3.client(
"s3",
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
return s3_client
def _generate_dataset_from_s3(
self, files: List[S3FileMeta]
) -> Iterable[Dict]:
if len(files) == 0:
logger.warning("Nothing to download")
else:
logger.info("Connecting to aws s3...")
task_id: str = str(uuid.uuid4())
try:
s3_client = self._get_client(task_id)
logger.info("Start downloading data from S3...")
bad_items_count = 0
for val in files:
image = None
try:
image: Image = read_from_s3(
s3_client, val.bucket, val.file
)
except Exception as e:
logger.exception(
f"Unable to download an item: {val.bucket}/{val.file} Exception: {str(e)}"
)
if image is None:
logger.error(
f"Unable to download {val.file} from {val.bucket}"
)
bad_items_count += 1
continue
yield {"item": image, "item_id": val.id}
if bad_items_count == len(files):
|
logger = logging.getLogger(__name__)
class AWSS3Credentials(BaseModel):
role_arn: Optional[str] = None
aws_access_key_id: Optional[str] = None
aws_secret_access_key: Optional[str] = None
external_id: Optional[str] = None
use_system_info: bool = False
def read_from_s3(client, bucket: str, file: str) -> Image:
if not isinstance(bucket, str) or len(bucket) == 0:
raise ValueError("bucket value should be not empty string")
if not isinstance(file, str) or len(file) == 0:
raise ValueError("file value should be not empty string")
outfile = io.BytesIO()
try:
client.download_fileobj(bucket, file, outfile)
outfile.seek(0)
return Image.open(outfile)
except ClientError as e:
if e.response["Error"]["Code"] == "404":
logger.error(f"Object {file} not found in bucket {bucket}")
return None
else:
# Raise the exception for any other unexpected errors
raise e
class AWSS3DataLoader(DataLoader):
def __init__(self, retry_config: Optional[RetryConfig] = None, **kwargs):
"""Items loader from AWS S3.
:param max_attempts: maximum number of attempts (default: 10)
:param wait_time_seconds: time to wait between (default: 10)
:param kwargs: dict data for AWSS3Credentials
"""
super(AWSS3DataLoader, self).__init__(**kwargs)
self.retry_config = (
retry_config
if retry_config
else AWSS3DataLoader._get_default_retry_config()
)
self.credentials = AWSS3Credentials(**kwargs)
self.attempt_exception_types = [EndpointConnectionError]
@staticmethod
def _get_default_retry_config() -> RetryConfig:
default_retry_params = RetryParams(
max_attempts=settings.DEFAULT_MAX_ATTEMPTS,
wait_time_seconds=settings.DEFAULT_WAIT_TIME_SECONDS,
)
config = RetryConfig(default_params=default_retry_params)
config["credentials"] = RetryParams(
max_attempts=settings.S3_READ_CREDENTIALS_ATTEMPTS,
wait_time_seconds=settings.S3_READ_WAIT_TIME_SECONDS,
)
config["download_data"] = RetryParams(
max_attempts=settings.S3_DOWNLOAD_DATA_ATTEMPTS,
wait_time_seconds=settings.S3_DOWNLOAD_DATA_WAIT_TIME_SECONDS,
)
return config
@retry_method(name="download_data")
def _read_from_s3(self, client, bucket: str, file: str) -> Image:
return read_from_s3(client, bucket, file)
@retry_method(name="credentials")
def _get_client(self, task_id: str):
if (
self.credentials.aws_access_key_id is None
or self.credentials.aws_secret_access_key is None
) and not self.credentials.use_system_info:
logger.warning(
"No specific AWS credentials, use Anonymous session"
)
s3_client = boto3.client(
"s3", config=Config(signature_version=UNSIGNED)
)
else:
sts_client = boto3.client(
"sts",
aws_access_key_id=self.credentials.aws_access_key_id,
aws_secret_access_key=self.credentials.aws_secret_access_key,
)
if self.credentials.external_id:
assumed_role_object = sts_client.assume_role(
RoleArn=self.credentials.role_arn,
RoleSessionName=task_id,
ExternalId=self.credentials.external_id,
)
else:
assumed_role_object = sts_client.assume_role(
RoleArn=self.credentials.role_arn,
RoleSessionName=task_id,
)
credentials = assumed_role_object["Credentials"]
s3_client = boto3.client(
"s3",
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
return s3_client
def _generate_dataset_from_s3(
self, files: List[S3FileMeta]
) -> Iterable[Dict]:
if len(files) == 0:
logger.warning("Nothing to download")
else:
logger.info("Connecting to aws s3...")
task_id: str = str(uuid.uuid4())
try:
s3_client = self._get_client(task_id)
logger.info("Start downloading data from S3...")
bad_items_count = 0
for val in files:
image = None
try:
image: Image = read_from_s3(
s3_client, val.bucket, val.file
)
except Exception as e:
logger.exception(
f"Unable to download an item: {val.bucket}/{val.file} Exception: {str(e)}"
)
if image is None:
logger.error(
f"Unable to download {val.file} from {val.bucket}"
)
bad_items_count += 1
continue
yield {"item": image, "item_id": val.id}
if bad_items_count == len(files): | raise FailedToLoadAnythingFromAWSS3() | 2 | 2023-10-31 00:33:13+00:00 | 8k |
facebookresearch/minimax | src/minimax/envs/maze/maze_ood.py | [
{
"identifier": "DIR_TO_VEC",
"path": "src/minimax/envs/maze/common.py",
"snippet": "DIR_TO_VEC = jnp.array([\n\t# Pointing right (positive X)\n\t(1, 0), # right\n\t(0, 1), # down\n\t(-1, 0), # left\n\t(0, -1), # up\n], dtype=jnp.int8)"
},
{
"identifier": "OBJECT_TO_INDEX",
"path": "src/mini... | from typing import Tuple, Optional
from flax import struct
from minimax.envs.registration import register
from .common import (
DIR_TO_VEC,
OBJECT_TO_INDEX,
COLOR_TO_INDEX,
make_maze_map,
)
from .maze import (
Maze,
EnvParams,
EnvState,
Actions
)
import jax
import jax.numpy as jnp
import chex | 5,667 | """
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.
"""
# ======== Singleton mazes ========
class MazeSingleton(Maze):
def __init__(
self,
height=15,
width=15,
wall_map=None,
goal_pos=None,
agent_pos=None,
agent_dir_idx=None,
agent_view_size=5,
see_through_walls=True,
see_agent=False,
normalize_obs=False,
obs_agent_pos=False,
max_episode_steps=None,
singleton_seed=-1,
):
super().__init__(
height=height,
width=width,
agent_view_size=agent_view_size,
see_through_walls=see_through_walls,
see_agent=see_agent,
normalize_obs=normalize_obs,
obs_agent_pos=obs_agent_pos,
max_episode_steps=max_episode_steps,
singleton_seed=singleton_seed
)
if wall_map is None:
self.wall_map = jnp.zeros((height,width), dtype=jnp.bool_)
else:
self.wall_map = \
jnp.array(
[[int(x) for x in row.split()]
for row in wall_map], dtype=jnp.bool_)
height, width = self.wall_map.shape
if max_episode_steps is None:
max_episode_steps = 2*(height+2)*(width+2) # Match original eval steps
self.goal_pos_choices = None
if goal_pos is None:
self.goal_pos = jnp.array([height, width]) - jnp.ones(2, dtype=jnp.uint32)
elif isinstance(goal_pos, (tuple, list)) \
and isinstance(goal_pos[0], (tuple, list)):
self.goal_pos_choices = jnp.array(goal_pos, dtype=jnp.uint32)
self.goal_pos = goal_pos[0]
else:
self.goal_pos = jnp.array(goal_pos, dtype=jnp.uint32)
if agent_pos is None:
self.agent_pos = jnp.zeros(2, dtype=jnp.uint32)
else:
self.agent_pos = jnp.array(agent_pos, dtype=jnp.uint32)
self.agent_dir_idx = agent_dir_idx
if self.agent_dir_idx is None:
self.agent_dir_idx = 0
self.params = EnvParams(
height=height,
width=width,
agent_view_size=agent_view_size,
see_through_walls=see_through_walls,
see_agent=see_agent,
normalize_obs=normalize_obs,
obs_agent_pos=obs_agent_pos,
max_episode_steps=max_episode_steps,
singleton_seed=-1,
)
self.maze_map = make_maze_map(
self.params,
self.wall_map,
self.goal_pos,
self.agent_pos,
self.agent_dir_idx,
pad_obs=True)
@property
def default_params(self) -> EnvParams:
# Default environment parameters
return EnvParams()
def reset_env(
self,
key: chex.PRNGKey,
| """
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.
"""
# ======== Singleton mazes ========
class MazeSingleton(Maze):
def __init__(
self,
height=15,
width=15,
wall_map=None,
goal_pos=None,
agent_pos=None,
agent_dir_idx=None,
agent_view_size=5,
see_through_walls=True,
see_agent=False,
normalize_obs=False,
obs_agent_pos=False,
max_episode_steps=None,
singleton_seed=-1,
):
super().__init__(
height=height,
width=width,
agent_view_size=agent_view_size,
see_through_walls=see_through_walls,
see_agent=see_agent,
normalize_obs=normalize_obs,
obs_agent_pos=obs_agent_pos,
max_episode_steps=max_episode_steps,
singleton_seed=singleton_seed
)
if wall_map is None:
self.wall_map = jnp.zeros((height,width), dtype=jnp.bool_)
else:
self.wall_map = \
jnp.array(
[[int(x) for x in row.split()]
for row in wall_map], dtype=jnp.bool_)
height, width = self.wall_map.shape
if max_episode_steps is None:
max_episode_steps = 2*(height+2)*(width+2) # Match original eval steps
self.goal_pos_choices = None
if goal_pos is None:
self.goal_pos = jnp.array([height, width]) - jnp.ones(2, dtype=jnp.uint32)
elif isinstance(goal_pos, (tuple, list)) \
and isinstance(goal_pos[0], (tuple, list)):
self.goal_pos_choices = jnp.array(goal_pos, dtype=jnp.uint32)
self.goal_pos = goal_pos[0]
else:
self.goal_pos = jnp.array(goal_pos, dtype=jnp.uint32)
if agent_pos is None:
self.agent_pos = jnp.zeros(2, dtype=jnp.uint32)
else:
self.agent_pos = jnp.array(agent_pos, dtype=jnp.uint32)
self.agent_dir_idx = agent_dir_idx
if self.agent_dir_idx is None:
self.agent_dir_idx = 0
self.params = EnvParams(
height=height,
width=width,
agent_view_size=agent_view_size,
see_through_walls=see_through_walls,
see_agent=see_agent,
normalize_obs=normalize_obs,
obs_agent_pos=obs_agent_pos,
max_episode_steps=max_episode_steps,
singleton_seed=-1,
)
self.maze_map = make_maze_map(
self.params,
self.wall_map,
self.goal_pos,
self.agent_pos,
self.agent_dir_idx,
pad_obs=True)
@property
def default_params(self) -> EnvParams:
# Default environment parameters
return EnvParams()
def reset_env(
self,
key: chex.PRNGKey, | ) -> Tuple[chex.Array, EnvState]: | 6 | 2023-10-28 12:12:01+00:00 | 8k |
reworkd/bananalyzer | bananalyzer/__main__.py | [
{
"identifier": "AgentRunner",
"path": "bananalyzer/runner/agent_runner.py",
"snippet": "class AgentRunner(ABC):\n \"\"\"\n Wrapper class clients must implement to run an agent against the evaluations\n \"\"\"\n\n @abstractmethod\n async def run(\n self,\n page: Page,\n ... | import argparse
import ast
import importlib.util
import sys
from pathlib import Path
from typing import List
from urllib.parse import urlparse
from bananalyzer import AgentRunner
from bananalyzer.data.examples import (
get_test_examples,
get_training_examples,
download_examples,
)
from bananalyzer.runner.generator import PytestTestGenerator
from bananalyzer.runner.runner import run_tests
from bananalyzer.schema import AgentRunnerClass, Args, PytestArgs, XDistArgs | 3,708 | help="The distribution mode for pytest-xdist",
)
args = parser.parse_args()
if args.download and not args.path:
args.path = "DOWNLOAD_ONLY"
if not args.path:
print(
f"Please provide the path to a {file_name} file. "
f"Use the --help flag for more information."
)
exit(1)
return Args(
path=args.path,
headless=args.headless,
intent=args.intent,
id=args.id,
domain=args.domain,
category=args.category,
subcategory=args.subcategory,
skip=args.skip,
single_browser_instance=args.single_browser_instance,
type=args.type,
test=args.test,
download=args.download,
count=args.count,
pytest_args=PytestArgs(
s=args.s,
n=args.n,
q=args.quiet,
xml=args.junitxml,
dist=args.dist,
),
xdist_args=XDistArgs(
n=args.n,
dist=args.dist,
),
)
def find_agents(file_path: Path) -> List[AgentRunnerClass]:
with open(file_path, "r") as source:
node = ast.parse(source.read())
runners: List[AgentRunnerClass] = []
for clazz in [n for n in node.body if isinstance(n, ast.ClassDef)]:
if "AgentRunner" in [getattr(base, "id", "") for base in clazz.bases]:
runners.append(
AgentRunnerClass(
class_name=clazz.name,
class_path=str(file_path),
)
)
return runners
def load_agent_from_path(path: Path) -> AgentRunnerClass:
if path.is_dir():
files = [p for p in path.glob("**/*.py") if "venv" not in p.parts]
else:
files = [path]
runners: List[AgentRunnerClass] = []
for file in files:
runners.extend(find_agents(file))
if len(runners) == 0:
raise RuntimeError(f"Could not find any agent runners in {path}")
if len(runners) > 1:
raise RuntimeError(f"Found multiple agent runners in {path}")
runner = runners[0]
runner_file = Path(runner.class_path)
module_name = path.stem
spec = importlib.util.spec_from_file_location(module_name, runner_file)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load module from path {runner_file}")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
agent = getattr(module, runner.class_name)()
if not isinstance(agent, AgentRunner):
raise TypeError("User defined agent is is not an instance of AgentRunner")
return runner
def main() -> int:
"""
Load the agent from the provided path and run it against the benchmark
Note that pytest creates a new global context when running tests.
Because of this, we first load the agent and validate that it is of the correct type here.
Then we pass the path to the agent runner and let it load it within the pytest context.
Note your AgentRunner must be concurrency safe.
"""
print_intro()
# Load the agent
args = parse_args()
if args.download:
print("##################################################")
print("# Downloading examples, this may take a while... #")
print("##################################################")
download_examples()
if args.path == "DOWNLOAD_ONLY":
return 0
agent = load_agent_from_path(Path(args.path))
print(f"Loaded agent {agent.class_name} from {agent.class_name}")
# Filter examples based on args
| # Separate banana-lyzer args from pytest args
# Look for an instance of Banana-lyzer in the current directory
# If it doesn't exist, error
def print_intro() -> None:
# https://www.asciiart.eu/food-and-drinks/bananas
print(
r"""
//\
V \
\ \_
\,'.`-.
|\ `. `.
( \ `. `-. _,.-:\
\ \ `. `-._ __..--' ,-';/
\ `. `-. `-..___..---' _.--' ,'/
`. `. `-._ __..--' ,' /
`. `-_ ``--..'' _.-' ,'
`-_ `-.___ __,--' ,'
`-.__ `----''' __.-'
`--..____..--'
"""
)
print("Bananalyzing... 🍌")
def parse_args() -> Args:
file_name = "bananalyzer-agent.py"
parser = argparse.ArgumentParser(
description="Run the agent inside a bananalyzer agent definition file "
"against the benchmark",
)
parser.add_argument(
"path", type=str, nargs="?", default=None, help=f"Path to the {file_name} file"
)
parser.add_argument(
"--headless", action="store_true", help="Whether to run headless or not"
)
parser.add_argument(
"-s",
"--s",
action="store_true",
help="Shortcut for --capture=no in pytest. Will print stdout and stderr",
)
parser.add_argument(
"-id",
"--id",
type=str,
default=None,
help="Filter tests by id. "
"Ids could be of shape a4c8292a_079c_4e49_bca1_cf7c9da205ec or a4c8292a-079c-4e49-bca1-cf7c9da205ec",
)
parser.add_argument(
"-d",
"--domain",
type=str,
default=None,
help="Filter tests by a particular URL domain",
)
parser.add_argument(
"-i",
"--intent",
type=str,
default=None,
help="Filter tests by a particular intent",
)
parser.add_argument(
"-c",
"--category",
type=str,
default=None,
help="Filter tests by a particular category",
)
parser.add_argument(
"--subcategory",
type=str,
default=None,
help="Filter tests by a particular subcategory",
)
parser.add_argument(
"-n",
"--n",
type=str,
default="logical",
help="Number of test workers to use. The default is 1",
)
parser.add_argument(
"-skip",
"--skip",
type=lambda s: s.split(","),
default=[],
help="A list of ids to skip tests on, separated by commas",
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
help="Will decrease the verbosity of pytest. By default we run with the `--v` pytest param.",
)
parser.add_argument(
"--single_browser_instance",
action="store_true",
help="Run tests in a single browser instance as opposed to creating a browser "
"instance per test. This is faster but less reliable as test contexts can "
"occasionally bleed into each other, causing tests to fail",
)
parser.add_argument(
"--type",
type=str,
default=None,
help="Filter tests by a particular type",
)
parser.add_argument(
"--download",
action="store_true",
help="Will re-download training and test examples",
)
parser.add_argument(
"--test",
action="store_true",
help="Use test set examples instead of training set examples",
)
parser.add_argument(
"--count",
type=int,
default=None,
help="The number of times to run an individual test. Won't work for detail pages",
)
parser.add_argument(
"--junitxml",
type=str,
default=None,
help="The path for the junitxml report file",
)
parser.add_argument(
"--dist",
type=str,
default="loadscope",
help="The distribution mode for pytest-xdist",
)
args = parser.parse_args()
if args.download and not args.path:
args.path = "DOWNLOAD_ONLY"
if not args.path:
print(
f"Please provide the path to a {file_name} file. "
f"Use the --help flag for more information."
)
exit(1)
return Args(
path=args.path,
headless=args.headless,
intent=args.intent,
id=args.id,
domain=args.domain,
category=args.category,
subcategory=args.subcategory,
skip=args.skip,
single_browser_instance=args.single_browser_instance,
type=args.type,
test=args.test,
download=args.download,
count=args.count,
pytest_args=PytestArgs(
s=args.s,
n=args.n,
q=args.quiet,
xml=args.junitxml,
dist=args.dist,
),
xdist_args=XDistArgs(
n=args.n,
dist=args.dist,
),
)
def find_agents(file_path: Path) -> List[AgentRunnerClass]:
with open(file_path, "r") as source:
node = ast.parse(source.read())
runners: List[AgentRunnerClass] = []
for clazz in [n for n in node.body if isinstance(n, ast.ClassDef)]:
if "AgentRunner" in [getattr(base, "id", "") for base in clazz.bases]:
runners.append(
AgentRunnerClass(
class_name=clazz.name,
class_path=str(file_path),
)
)
return runners
def load_agent_from_path(path: Path) -> AgentRunnerClass:
if path.is_dir():
files = [p for p in path.glob("**/*.py") if "venv" not in p.parts]
else:
files = [path]
runners: List[AgentRunnerClass] = []
for file in files:
runners.extend(find_agents(file))
if len(runners) == 0:
raise RuntimeError(f"Could not find any agent runners in {path}")
if len(runners) > 1:
raise RuntimeError(f"Found multiple agent runners in {path}")
runner = runners[0]
runner_file = Path(runner.class_path)
module_name = path.stem
spec = importlib.util.spec_from_file_location(module_name, runner_file)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot load module from path {runner_file}")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
agent = getattr(module, runner.class_name)()
if not isinstance(agent, AgentRunner):
raise TypeError("User defined agent is is not an instance of AgentRunner")
return runner
def main() -> int:
"""
Load the agent from the provided path and run it against the benchmark
Note that pytest creates a new global context when running tests.
Because of this, we first load the agent and validate that it is of the correct type here.
Then we pass the path to the agent runner and let it load it within the pytest context.
Note your AgentRunner must be concurrency safe.
"""
print_intro()
# Load the agent
args = parse_args()
if args.download:
print("##################################################")
print("# Downloading examples, this may take a while... #")
print("##################################################")
download_examples()
if args.path == "DOWNLOAD_ONLY":
return 0
agent = load_agent_from_path(Path(args.path))
print(f"Loaded agent {agent.class_name} from {agent.class_name}")
# Filter examples based on args | examples = get_test_examples() if args.test else get_training_examples() | 1 | 2023-10-30 16:40:57+00:00 | 8k |
innnky/ar-vits | AR/modules/transformer.py | [
{
"identifier": "MultiheadAttention",
"path": "AR/modules/activation.py",
"snippet": "class MultiheadAttention(Module):\n r\"\"\"Allows the model to jointly attend to information\n from different representation subspaces as described in the paper:\n `Attention Is All You Need <https://arxiv.org... | import copy
import numbers
import torch
from functools import partial
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from AR.modules.activation import MultiheadAttention
from AR.modules.scaling import BalancedDoubleSwish
from torch import nn
from torch import Tensor
from torch.nn import functional as F | 6,112 | assert embedding is None
return F.layer_norm(input, self.normalized_shape, self.weight,
self.bias, self.eps)
def extra_repr(self) -> str:
return (
"{normalized_shape}, eps={eps}, "
"elementwise_affine={elementwise_affine}".format(**self.__dict__))
class IdentityNorm(nn.Module):
def __init__(
self,
d_model: int,
eps: float=1e-5,
device=None,
dtype=None, ) -> None:
super(IdentityNorm, self).__init__()
def forward(self, input: Tensor, embedding: Any=None) -> Tensor:
if isinstance(input, tuple):
return input
assert embedding is None
return input
class TransformerEncoder(nn.Module):
r"""TransformerEncoder is a stack of N encoder layers. Users can build the
BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
Args:
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
num_layers: the number of sub-encoder-layers in the encoder (required).
norm: the layer normalization component (optional).
enable_nested_tensor: if True, input will automatically convert to nested tensor
(and convert back on output). This will improve the overall performance of
TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
Examples::
>>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
>>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
>>> src = torch.rand(10, 32, 512)
>>> out = transformer_encoder(src)
"""
__constants__ = ["norm"]
def __init__(self, encoder_layer, num_layers, norm=None):
super(TransformerEncoder, self).__init__()
self.layers = _get_clones(encoder_layer, num_layers)
self.num_layers = num_layers
self.norm = norm
def forward(
self,
src: Tensor,
mask: Optional[Tensor]=None,
src_key_padding_mask: Optional[Tensor]=None,
return_layer_states: bool=False, ) -> Tensor:
r"""Pass the input through the encoder layers in turn.
Args:
src: the sequence to the encoder (required).
mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
return_layer_states: return layers' state (optional).
Shape:
see the docs in Transformer class.
"""
if return_layer_states:
layer_states = [] # layers' output
output = src
for mod in self.layers:
output = mod(
output,
src_mask=mask,
src_key_padding_mask=src_key_padding_mask, )
layer_states.append(output[0])
if self.norm is not None:
output = self.norm(output)
return layer_states, output
output = src
for mod in self.layers:
output = mod(output,
src_mask=mask,
src_key_padding_mask=src_key_padding_mask)
if self.norm is not None:
output = self.norm(output)
return output
class TransformerEncoderLayer(nn.Module):
__constants__ = ["batch_first", "norm_first"]
def __init__(
self,
d_model: int,
nhead: int,
dim_feedforward: int=2048,
dropout: float=0.1,
activation: Union[str, Callable[[Tensor], Tensor]]=F.relu,
batch_first: bool=False,
norm_first: bool=False,
device=None,
dtype=None,
linear1_self_attention_cls: nn.Module=nn.Linear,
linear2_self_attention_cls: nn.Module=nn.Linear,
linear1_feedforward_cls: nn.Module=nn.Linear,
linear2_feedforward_cls: nn.Module=nn.Linear,
layer_norm_cls: nn.Module=LayerNorm,
layer_norm_eps: float=1e-5,
adaptive_layer_norm=False, ) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
super(TransformerEncoderLayer, self).__init__()
| # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/transformer.py
_shape_t = Union[int, List[int], torch.Size]
class LayerNorm(nn.Module):
__constants__ = ["normalized_shape", "eps", "elementwise_affine"]
normalized_shape: Tuple[int, ...]
eps: float
elementwise_affine: bool
def __init__(
self,
normalized_shape: _shape_t,
eps: float=1e-5,
elementwise_affine: bool=True,
device=None,
dtype=None, ) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
super(LayerNorm, self).__init__()
if isinstance(normalized_shape, numbers.Integral):
# mypy error: incompatible types in assignment
normalized_shape = (normalized_shape, ) # type: ignore[assignment]
self.normalized_shape = tuple(
normalized_shape) # type: ignore[arg-type]
self.eps = eps
self.elementwise_affine = elementwise_affine
if self.elementwise_affine:
self.weight = nn.Parameter(
torch.empty(self.normalized_shape, **factory_kwargs))
self.bias = nn.Parameter(
torch.empty(self.normalized_shape, **factory_kwargs))
else:
self.register_parameter("weight", None)
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self) -> None:
if self.elementwise_affine:
nn.init.ones_(self.weight)
nn.init.zeros_(self.bias)
def forward(self, input: Tensor, embedding: Any=None) -> Tensor:
if isinstance(input, tuple):
input, embedding = input
return (F.layer_norm(
input,
self.normalized_shape,
self.weight,
self.bias,
self.eps, ), embedding, )
assert embedding is None
return F.layer_norm(input, self.normalized_shape, self.weight,
self.bias, self.eps)
def extra_repr(self) -> str:
return (
"{normalized_shape}, eps={eps}, "
"elementwise_affine={elementwise_affine}".format(**self.__dict__))
class IdentityNorm(nn.Module):
def __init__(
self,
d_model: int,
eps: float=1e-5,
device=None,
dtype=None, ) -> None:
super(IdentityNorm, self).__init__()
def forward(self, input: Tensor, embedding: Any=None) -> Tensor:
if isinstance(input, tuple):
return input
assert embedding is None
return input
class TransformerEncoder(nn.Module):
r"""TransformerEncoder is a stack of N encoder layers. Users can build the
BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
Args:
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
num_layers: the number of sub-encoder-layers in the encoder (required).
norm: the layer normalization component (optional).
enable_nested_tensor: if True, input will automatically convert to nested tensor
(and convert back on output). This will improve the overall performance of
TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
Examples::
>>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
>>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
>>> src = torch.rand(10, 32, 512)
>>> out = transformer_encoder(src)
"""
__constants__ = ["norm"]
def __init__(self, encoder_layer, num_layers, norm=None):
super(TransformerEncoder, self).__init__()
self.layers = _get_clones(encoder_layer, num_layers)
self.num_layers = num_layers
self.norm = norm
def forward(
self,
src: Tensor,
mask: Optional[Tensor]=None,
src_key_padding_mask: Optional[Tensor]=None,
return_layer_states: bool=False, ) -> Tensor:
r"""Pass the input through the encoder layers in turn.
Args:
src: the sequence to the encoder (required).
mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
return_layer_states: return layers' state (optional).
Shape:
see the docs in Transformer class.
"""
if return_layer_states:
layer_states = [] # layers' output
output = src
for mod in self.layers:
output = mod(
output,
src_mask=mask,
src_key_padding_mask=src_key_padding_mask, )
layer_states.append(output[0])
if self.norm is not None:
output = self.norm(output)
return layer_states, output
output = src
for mod in self.layers:
output = mod(output,
src_mask=mask,
src_key_padding_mask=src_key_padding_mask)
if self.norm is not None:
output = self.norm(output)
return output
class TransformerEncoderLayer(nn.Module):
__constants__ = ["batch_first", "norm_first"]
def __init__(
self,
d_model: int,
nhead: int,
dim_feedforward: int=2048,
dropout: float=0.1,
activation: Union[str, Callable[[Tensor], Tensor]]=F.relu,
batch_first: bool=False,
norm_first: bool=False,
device=None,
dtype=None,
linear1_self_attention_cls: nn.Module=nn.Linear,
linear2_self_attention_cls: nn.Module=nn.Linear,
linear1_feedforward_cls: nn.Module=nn.Linear,
linear2_feedforward_cls: nn.Module=nn.Linear,
layer_norm_cls: nn.Module=LayerNorm,
layer_norm_eps: float=1e-5,
adaptive_layer_norm=False, ) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
super(TransformerEncoderLayer, self).__init__() | self.self_attn = MultiheadAttention( | 0 | 2023-10-30 04:40:19+00:00 | 8k |
nv-tlabs/vid2player3d | embodied_pose/utils/torch_transform.py | [
{
"identifier": "angle_axis_to_quaternion",
"path": "embodied_pose/utils/konia_transform.py",
"snippet": "@torch.jit.script\ndef angle_axis_to_quaternion(\n angle_axis: torch.Tensor, eps: float = 1.0e-6, order: QuaternionCoeffOrder = QuaternionCoeffOrder.WXYZ\n) -> torch.Tensor:\n r\"\"\"Convert a... | import numpy as np
import torch
from .konia_transform import angle_axis_to_quaternion, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion, rotation_matrix_to_angle_axis, angle_axis_to_rotation_matrix | 6,730 | cos[..., 0] * sin[..., 1] * cos[..., 2] + sin[..., 0] * cos[..., 1] * sin[..., 2],
cos[..., 0] * cos[..., 1] * sin[..., 2] - sin[..., 0] * sin[..., 1] * cos[..., 2]
], dim=-1)
return q
def quat_between_two_vec(v1, v2, eps: float = 1e-6):
"""
quaternion for rotating v1 to v2
"""
orig_shape = v1.shape
v1 = v1.reshape(-1, 3)
v2 = v2.reshape(-1, 3)
dot = (v1 * v2).sum(-1)
cross = torch.cross(v1, v2, dim=-1)
out = torch.cat([(1 + dot).unsqueeze(-1), cross], dim=-1)
# handle v1 & v2 with same direction
sind = dot > 1 - eps
out[sind] = torch.tensor([1., 0., 0., 0.], device=v1.device)
# handle v1 & v2 with opposite direction
nind = dot < -1 + eps
if torch.any(nind):
vx = torch.tensor([1., 0., 0.], device=v1.device)
vxdot = (v1 * vx).sum(-1).abs()
nxind = nind & (vxdot < 1 - eps)
if torch.any(nxind):
out[nxind] = angle_axis_to_quaternion(normalize(torch.cross(vx.expand_as(v1[nxind]), v1[nxind], dim=-1)) * np.pi)
# handle v1 & v2 with opposite direction and they are parallel to x axis
pind = nind & (vxdot >= 1 - eps)
if torch.any(pind):
vy = torch.tensor([0., 1., 0.], device=v1.device)
out[pind] = angle_axis_to_quaternion(normalize(torch.cross(vy.expand_as(v1[pind]), v1[pind], dim=-1)) * np.pi)
# normalize and reshape
out = normalize(out).view(orig_shape[:-1] + (4,))
return out
@torch.jit.script
def get_yaw(q, eps: float = 1e-6):
yaw_atany = 2 * (q[..., 0] * q[..., 3] + q[..., 1] * q[..., 2])
yaw_atanx = 1 - 2 * (q[..., 2] * q[..., 2] + q[..., 3] * q[..., 3])
yaw = torch_safe_atan2(yaw_atany, yaw_atanx, eps)
return yaw
@torch.jit.script
def get_yaw_q(q):
yaw = get_yaw(q)
angle_axis = torch.cat([torch.zeros(yaw.shape + (2,), device=q.device), yaw.unsqueeze(-1)], dim=-1)
heading_q = angle_axis_to_quaternion(angle_axis)
return heading_q
@torch.jit.script
def get_heading(q, eps: float = 1e-6):
heading_atany = q[..., 3]
heading_atanx = q[..., 0]
heading = 2 * torch_safe_atan2(heading_atany, heading_atanx, eps)
return heading
def get_heading_q(q):
q_new = q.clone()
q_new[..., 1] = 0
q_new[..., 2] = 0
q_new = normalize(q_new)
return q_new
@torch.jit.script
def heading_to_vec(h_theta):
v = torch.stack([torch.cos(h_theta), torch.sin(h_theta)], dim=-1)
return v
@torch.jit.script
def vec_to_heading(h_vec):
h_theta = torch_safe_atan2(h_vec[..., 1], h_vec[..., 0])
return h_theta
@torch.jit.script
def heading_to_quat(h_theta):
angle_axis = torch.cat([torch.zeros(h_theta.shape + (2,), device=h_theta.device), h_theta.unsqueeze(-1)], dim=-1)
heading_q = angle_axis_to_quaternion(angle_axis)
return heading_q
def deheading_quat(q, heading_q=None):
if heading_q is None:
heading_q = get_heading_q(q)
dq = quat_mul(quat_conjugate(heading_q), q)
return dq
@torch.jit.script
def rotmat_to_rot6d(mat):
rot6d = torch.cat([mat[..., 0], mat[..., 1]], dim=-1)
return rot6d
@torch.jit.script
def rot6d_to_rotmat(rot6d, eps: float = 1e-8):
a1 = rot6d[..., :3].clone()
a2 = rot6d[..., 3:].clone()
ind = torch.norm(a1, dim=-1) < eps
a1[ind] = torch.tensor([1.0, 0.0, 0.0], device=a1.device)
b1 = normalize(a1)
b2 = normalize(a2 - (b1 * a2).sum(dim=-1).unsqueeze(-1) * b1)
ind = torch.norm(b2, dim=-1) < eps
b2[ind] = torch.tensor([0.0, 1.0, 0.0], device=b2.device)
b3 = torch.cross(b1, b2, dim=-1)
mat = torch.stack([b1, b2, b3], dim=-1)
return mat
@torch.jit.script
def angle_axis_to_rot6d(aa):
|
def normalize(x, eps: float = 1e-9):
return x / x.norm(p=2, dim=-1).clamp(min=eps, max=None).unsqueeze(-1)
@torch.jit.script
def quat_mul(a, b):
assert a.shape == b.shape
shape = a.shape
a = a.reshape(-1, 4)
b = b.reshape(-1, 4)
w1, x1, y1, z1 = a[:, 0], a[:, 1], a[:, 2], a[:, 3]
w2, x2, y2, z2 = b[:, 0], b[:, 1], b[:, 2], b[:, 3]
ww = (z1 + x1) * (x2 + y2)
yy = (w1 - y1) * (w2 + z2)
zz = (w1 + y1) * (w2 - z2)
xx = ww + yy + zz
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
w = qq - ww + (z1 - y1) * (y2 - z2)
x = qq - xx + (x1 + w1) * (x2 + w2)
y = qq - yy + (w1 - x1) * (y2 + z2)
z = qq - zz + (z1 + y1) * (w2 - x2)
return torch.stack([w, x, y, z], dim=-1).view(shape)
@torch.jit.script
def quat_conjugate(a):
shape = a.shape
a = a.reshape(-1, 4)
return torch.cat((a[:, 0:1], -a[:, 1:]), dim=-1).view(shape)
@torch.jit.script
def quat_apply(a, b):
shape = b.shape
a = a.reshape(-1, 4)
b = b.reshape(-1, 3)
xyz = a[:, 1:].clone()
t = xyz.cross(b, dim=-1) * 2
return (b + a[:, 0:1].clone() * t + xyz.cross(t, dim=-1)).view(shape)
@torch.jit.script
def quat_angle(a, eps: float = 1e-6):
shape = a.shape
a = a.reshape(-1, 4)
s = 2 * (a[:, 0] ** 2) - 1
s = s.clamp(-1 + eps, 1 - eps)
s = s.acos()
return s.view(shape[:-1])
@torch.jit.script
def quat_angle_diff(quat1, quat2):
return quat_angle(quat_mul(quat1, quat_conjugate(quat2)))
@torch.jit.script
def torch_safe_atan2(y, x, eps: float = 1e-8):
y = y.clone()
y[(y.abs() < eps) & (x.abs() < eps)] += eps
return torch.atan2(y, x)
@torch.jit.script
def ypr_euler_from_quat(q, handle_singularity: bool = False, eps: float = 1e-6, singular_eps: float = 1e-6):
"""
convert quaternion to yaw-pitch-roll euler angles
"""
yaw_atany = 2 * (q[..., 0] * q[..., 3] + q[..., 1] * q[..., 2])
yaw_atanx = 1 - 2 * (q[..., 2] * q[..., 2] + q[..., 3] * q[..., 3])
roll_atany = 2 * (q[..., 0] * q[..., 1] + q[..., 2] * q[..., 3])
roll_atanx = 1 - 2 * (q[..., 1] * q[..., 1] + q[..., 2] * q[..., 2])
yaw = torch_safe_atan2(yaw_atany, yaw_atanx, eps)
pitch = torch.asin(torch.clamp(2 * (q[..., 0] * q[..., 2] - q[..., 1] * q[..., 3]), min=-1 + eps, max=1 - eps))
roll = torch_safe_atan2(roll_atany, roll_atanx, eps)
if handle_singularity:
""" handle two special cases """
test = q[..., 0] * q[..., 2] - q[..., 1] * q[..., 3]
# north pole, pitch ~= 90 degrees
np_ind = test > 0.5 - singular_eps
if torch.any(np_ind):
# print('ypr_euler_from_quat singularity -- north pole!')
roll[np_ind] = 0.0
pitch[np_ind].clamp_max_(0.5 * np.pi)
yaw_atany = q[..., 3][np_ind]
yaw_atanx = q[..., 0][np_ind]
yaw[np_ind] = 2 * torch_safe_atan2(yaw_atany, yaw_atanx, eps)
# south pole, pitch ~= -90 degrees
sp_ind = test < -0.5 + singular_eps
if torch.any(sp_ind):
# print('ypr_euler_from_quat singularity -- south pole!')
roll[sp_ind] = 0.0
pitch[sp_ind].clamp_min_(-0.5 * np.pi)
yaw_atany = q[..., 3][sp_ind]
yaw_atanx = q[..., 0][sp_ind]
yaw[sp_ind] = 2 * torch_safe_atan2(yaw_atany, yaw_atanx, eps)
return torch.stack([roll, pitch, yaw], dim=-1)
@torch.jit.script
def quat_from_ypr_euler(angles):
"""
convert yaw-pitch-roll euler angles to quaternion
"""
half_ang = angles * 0.5
sin = torch.sin(half_ang)
cos = torch.cos(half_ang)
q = torch.stack([
cos[..., 0] * cos[..., 1] * cos[..., 2] + sin[..., 0] * sin[..., 1] * sin[..., 2],
sin[..., 0] * cos[..., 1] * cos[..., 2] - cos[..., 0] * sin[..., 1] * sin[..., 2],
cos[..., 0] * sin[..., 1] * cos[..., 2] + sin[..., 0] * cos[..., 1] * sin[..., 2],
cos[..., 0] * cos[..., 1] * sin[..., 2] - sin[..., 0] * sin[..., 1] * cos[..., 2]
], dim=-1)
return q
def quat_between_two_vec(v1, v2, eps: float = 1e-6):
"""
quaternion for rotating v1 to v2
"""
orig_shape = v1.shape
v1 = v1.reshape(-1, 3)
v2 = v2.reshape(-1, 3)
dot = (v1 * v2).sum(-1)
cross = torch.cross(v1, v2, dim=-1)
out = torch.cat([(1 + dot).unsqueeze(-1), cross], dim=-1)
# handle v1 & v2 with same direction
sind = dot > 1 - eps
out[sind] = torch.tensor([1., 0., 0., 0.], device=v1.device)
# handle v1 & v2 with opposite direction
nind = dot < -1 + eps
if torch.any(nind):
vx = torch.tensor([1., 0., 0.], device=v1.device)
vxdot = (v1 * vx).sum(-1).abs()
nxind = nind & (vxdot < 1 - eps)
if torch.any(nxind):
out[nxind] = angle_axis_to_quaternion(normalize(torch.cross(vx.expand_as(v1[nxind]), v1[nxind], dim=-1)) * np.pi)
# handle v1 & v2 with opposite direction and they are parallel to x axis
pind = nind & (vxdot >= 1 - eps)
if torch.any(pind):
vy = torch.tensor([0., 1., 0.], device=v1.device)
out[pind] = angle_axis_to_quaternion(normalize(torch.cross(vy.expand_as(v1[pind]), v1[pind], dim=-1)) * np.pi)
# normalize and reshape
out = normalize(out).view(orig_shape[:-1] + (4,))
return out
@torch.jit.script
def get_yaw(q, eps: float = 1e-6):
yaw_atany = 2 * (q[..., 0] * q[..., 3] + q[..., 1] * q[..., 2])
yaw_atanx = 1 - 2 * (q[..., 2] * q[..., 2] + q[..., 3] * q[..., 3])
yaw = torch_safe_atan2(yaw_atany, yaw_atanx, eps)
return yaw
@torch.jit.script
def get_yaw_q(q):
yaw = get_yaw(q)
angle_axis = torch.cat([torch.zeros(yaw.shape + (2,), device=q.device), yaw.unsqueeze(-1)], dim=-1)
heading_q = angle_axis_to_quaternion(angle_axis)
return heading_q
@torch.jit.script
def get_heading(q, eps: float = 1e-6):
heading_atany = q[..., 3]
heading_atanx = q[..., 0]
heading = 2 * torch_safe_atan2(heading_atany, heading_atanx, eps)
return heading
def get_heading_q(q):
q_new = q.clone()
q_new[..., 1] = 0
q_new[..., 2] = 0
q_new = normalize(q_new)
return q_new
@torch.jit.script
def heading_to_vec(h_theta):
v = torch.stack([torch.cos(h_theta), torch.sin(h_theta)], dim=-1)
return v
@torch.jit.script
def vec_to_heading(h_vec):
h_theta = torch_safe_atan2(h_vec[..., 1], h_vec[..., 0])
return h_theta
@torch.jit.script
def heading_to_quat(h_theta):
angle_axis = torch.cat([torch.zeros(h_theta.shape + (2,), device=h_theta.device), h_theta.unsqueeze(-1)], dim=-1)
heading_q = angle_axis_to_quaternion(angle_axis)
return heading_q
def deheading_quat(q, heading_q=None):
if heading_q is None:
heading_q = get_heading_q(q)
dq = quat_mul(quat_conjugate(heading_q), q)
return dq
@torch.jit.script
def rotmat_to_rot6d(mat):
rot6d = torch.cat([mat[..., 0], mat[..., 1]], dim=-1)
return rot6d
@torch.jit.script
def rot6d_to_rotmat(rot6d, eps: float = 1e-8):
a1 = rot6d[..., :3].clone()
a2 = rot6d[..., 3:].clone()
ind = torch.norm(a1, dim=-1) < eps
a1[ind] = torch.tensor([1.0, 0.0, 0.0], device=a1.device)
b1 = normalize(a1)
b2 = normalize(a2 - (b1 * a2).sum(dim=-1).unsqueeze(-1) * b1)
ind = torch.norm(b2, dim=-1) < eps
b2[ind] = torch.tensor([0.0, 1.0, 0.0], device=b2.device)
b3 = torch.cross(b1, b2, dim=-1)
mat = torch.stack([b1, b2, b3], dim=-1)
return mat
@torch.jit.script
def angle_axis_to_rot6d(aa): | return rotmat_to_rot6d(angle_axis_to_rotation_matrix(aa)) | 4 | 2023-10-30 20:43:43+00:00 | 8k |
vLAR-group/RayDF | run_mv.py | [
{
"identifier": "config_parser",
"path": "config.py",
"snippet": "def config_parser():\n parser = configargparse.ArgumentParser()\n parser.add_argument('--config', is_config_file=True,\n help='config file path')\n parser.add_argument(\"--eval_only\", action='store_true',\... | import os
import torch
import numpy as np
import imageio
import trimesh
import open3d as o3d
import wandb
from tqdm import trange
from config import config_parser
from open3d import pipelines
from wandb import AlertLevel
from utils import log
from utils.math import convert_d
from utils.dataloader import Dataloader
from utils.ray import get_ray_param
from net_multiview.network import create_net
from net_multiview.sampler import get_multiview_rays
from utils.math import get_surface_gradient, get_surface_normal
from torchmetrics.functional import peak_signal_noise_ratio as PSNR
from torchmetrics.functional import structural_similarity_index_measure as SSIM
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from chamfer_distance import ChamferDistance | 5,148 |
# normalize query gt distance and query surface point
target_dict['dist_norm'] = (target_dict['dist'] - d0) / (args.radius * 2.)
batch_pts = batch_rays[..., :3] + target_dict['dist'] * batch_rays[..., 3:]
for c in range(batch_pts.shape[-1]):
batch_pts[..., c] -= dataloader.scene_info['sphere_center'][c]
target_dict['pts_norm'] = batch_pts / dataloader.scene_info['sphere_radius']
# ================= Multiview Rays =====================
# Sample multiview rays and get their ray parameters
mv_rays, mv_targets = get_multiview_rays(args, query_rays=batch_rays, query_gts=target_dict)
mv_inputs, mv_d0, _ = get_ray_param(ray_fn, mv_rays)
mv_targets['dist_norm'] = (mv_targets['dist'] - mv_d0) / (args.radius * 2.)
# Compute visibility
with torch.no_grad():
cls_inputs = [torch.tile(batch_inputs[:, None], (1, args.N_views, 1)).reshape(-1, batch_inputs.shape[-1]),
mv_inputs,
torch.tile(target_dict['pts_norm'][:, None], (1, args.N_views, 1)).reshape(-1, 3)]
vis = model_cls(cls_inputs)
mv_targets['vis_score'] = torch.sigmoid(vis).reshape(args.N_rand, args.N_views)
reweigh = 0.5
mv_targets['vis_score'] = mv_targets['vis_score'] ** reweigh / (mv_targets['vis_score'] ** reweigh +
(1. - mv_targets['vis_score']) ** reweigh)
# Multiview forward
mv_batch_inputs = torch.cat([batch_inputs, mv_inputs], dim=0)
mv_outputs = model(mv_batch_inputs)
# ================= Optimization =====================
loss_d_query = torch.abs(mv_outputs['dist'][:args.N_rand] - target_dict['dist_norm'])[:, 0]
loss_d_mv = torch.abs(mv_outputs['dist'][args.N_rand:] - mv_targets['dist_norm']).reshape(args.N_rand, args.N_views)
loss_d = loss_d_query + (mv_targets['vis_score'] * loss_d_mv).sum(-1)
loss_d = (loss_d / (1. + mv_targets['vis_score'].sum(-1))).mean()
loss_rgb = torch.tensor(0.).to(device)
if 'rgb' in mv_outputs:
mv_outputs['rgb_pred'] = torch.sigmoid(mv_outputs['rgb'])
loss_rgb_query = ((mv_outputs['rgb_pred'][:args.N_rand] - target_dict['image'])**2).mean(-1)
loss_rgb_mv = ((mv_outputs['rgb_pred'][args.N_rand:] - mv_targets['image'])**2).reshape(args.N_rand, args.N_views, 3).mean(-1)
loss_rgb = loss_rgb_query + (mv_targets['vis_score'] * loss_rgb_mv).sum(-1)
loss_rgb = (loss_rgb / (1. + mv_targets['vis_score'].sum(-1))).mean()
loss = loss_d + args.w_rgb * loss_rgb
loss.backward()
if args.grad_clip > 0.:
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=args.grad_clip)
optimizer.step()
new_lrate = optimizer.param_groups[0]['lr']
scheduler.step()
# ================= Logging ==========================
if i % args.i_print == 0 and i != start:
wandb.log({
'train/_ep': ep,
'train/_lr': new_lrate,
'train/loss': loss.item(),
'train/loss_d': loss_d.item(),
'train/loss_rgb': loss_rgb.item()
})
# ================= Evaluation =====================
if i % args.i_img == 0 and i != start:
torch.cuda.empty_cache()
eval(args, dataloader, ray_fn, model, mode='train')
eval(args, dataloader, ray_fn, model, mode='test')
# Save checkpoints
if (i % args.i_weights == 0 and i != start) or (i + 1) == args.N_iters:
path = os.path.join(args.logdir, args.expname, '{:07d}.tar'.format(i))
ckpt_dict = {
'global_step': global_step,
'network_fn': model.state_dict(),
'optimizer': optimizer.state_dict(),
'scheduler': scheduler.state_dict()
}
torch.save(ckpt_dict, path)
print('Saved checkpoints at', path)
# a quick evaluation on the whole dataset
evaluate_all(args, dataloader, ray_fn, model, global_step=global_step, mode='train')
evaluate_all(args, dataloader, ray_fn, model, global_step=global_step, mode='test')
global_step += 1
wandb.alert(
title='Training Finished',
text=f'Start to evaluate.',
level=AlertLevel.WARN)
args.eval_only = True
args.denoise = True
args.grad_normal = True
evaluate(args)
def eval(args, dataloader, ray_fn, model, img_i=None, mode='test', log_level=2):
# log_level - 0: return metrics, 1: return metrics and maps, otherwise: wandb logging
H = dataloader.scene_info['H']
W = dataloader.scene_info['W']
if img_i is None:
i_split = dataloader.i_test if mode.startswith('test') else dataloader.i_train
img_i = np.random.choice(np.arange(0, len(i_split)))
inds = img_i * H * W + np.arange(0, H * W)
rays, targets = dataloader(inds, mode=mode) # (H*W, C)
targets['dist_norm'] = torch.zeros_like(targets['dist'])
# Forward network
outputs = {}
with torch.enable_grad():
for i in range(0, len(rays), args.N_rand):
batch_inputs, d0, batch_raydirs = get_ray_param(ray_fn, rays[i:i+args.N_rand])
targets['dist_norm'][i:i+args.N_rand] = (targets['dist'][i:i+args.N_rand] - d0) / (args.radius * 2.)
outs = model(batch_inputs)
outs['dist_abs'] = outs['dist'] * (2.*args.radius) + d0
if 'rgb' in outs:
outs['rgb_pred'] = torch.sigmoid(outs['rgb'])
if args.denoise:
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.backends.cudnn.benchmark = True
np.random.seed(0)
LPIPS = LearnedPerceptualImagePatchSimilarity(net_type='alex').to(device)
CD = ChamferDistance().to(device)
def train(args):
# Load dataset
dataloader = Dataloader(args, device)
# Create rayparam function and network
ray_fn, global_step, model, model_cls, optimizer, scheduler = create_net(args, dataloader.scene_info, device)
# Create experiment logger
wandb.init(project="RayDF-RaySurfDNet")
wandb.run.name = args.expname
wandb.watch(model, log="all")
start = global_step
train_num = len(dataloader.dists['train_fg'])
inds = np.random.permutation(train_num)
step_batch = train_num // args.N_rand
for i in trange(start, args.N_iters):
optimizer.zero_grad()
j = i % step_batch
ep = i // step_batch
# re-random train indices after one epoch
if j == 0 and i != start:
inds = np.random.permutation(train_num)
# =================== Query Rays ========================
# Random rays from all images
train_i = inds[j * args.N_rand: (j+1) * args.N_rand]
# load query rays
batch_rays, target_dict = dataloader(inds=train_i, mode='train_fg')
batch_inputs, d0, _ = get_ray_param(ray_fn, batch_rays)
# normalize query gt distance and query surface point
target_dict['dist_norm'] = (target_dict['dist'] - d0) / (args.radius * 2.)
batch_pts = batch_rays[..., :3] + target_dict['dist'] * batch_rays[..., 3:]
for c in range(batch_pts.shape[-1]):
batch_pts[..., c] -= dataloader.scene_info['sphere_center'][c]
target_dict['pts_norm'] = batch_pts / dataloader.scene_info['sphere_radius']
# ================= Multiview Rays =====================
# Sample multiview rays and get their ray parameters
mv_rays, mv_targets = get_multiview_rays(args, query_rays=batch_rays, query_gts=target_dict)
mv_inputs, mv_d0, _ = get_ray_param(ray_fn, mv_rays)
mv_targets['dist_norm'] = (mv_targets['dist'] - mv_d0) / (args.radius * 2.)
# Compute visibility
with torch.no_grad():
cls_inputs = [torch.tile(batch_inputs[:, None], (1, args.N_views, 1)).reshape(-1, batch_inputs.shape[-1]),
mv_inputs,
torch.tile(target_dict['pts_norm'][:, None], (1, args.N_views, 1)).reshape(-1, 3)]
vis = model_cls(cls_inputs)
mv_targets['vis_score'] = torch.sigmoid(vis).reshape(args.N_rand, args.N_views)
reweigh = 0.5
mv_targets['vis_score'] = mv_targets['vis_score'] ** reweigh / (mv_targets['vis_score'] ** reweigh +
(1. - mv_targets['vis_score']) ** reweigh)
# Multiview forward
mv_batch_inputs = torch.cat([batch_inputs, mv_inputs], dim=0)
mv_outputs = model(mv_batch_inputs)
# ================= Optimization =====================
loss_d_query = torch.abs(mv_outputs['dist'][:args.N_rand] - target_dict['dist_norm'])[:, 0]
loss_d_mv = torch.abs(mv_outputs['dist'][args.N_rand:] - mv_targets['dist_norm']).reshape(args.N_rand, args.N_views)
loss_d = loss_d_query + (mv_targets['vis_score'] * loss_d_mv).sum(-1)
loss_d = (loss_d / (1. + mv_targets['vis_score'].sum(-1))).mean()
loss_rgb = torch.tensor(0.).to(device)
if 'rgb' in mv_outputs:
mv_outputs['rgb_pred'] = torch.sigmoid(mv_outputs['rgb'])
loss_rgb_query = ((mv_outputs['rgb_pred'][:args.N_rand] - target_dict['image'])**2).mean(-1)
loss_rgb_mv = ((mv_outputs['rgb_pred'][args.N_rand:] - mv_targets['image'])**2).reshape(args.N_rand, args.N_views, 3).mean(-1)
loss_rgb = loss_rgb_query + (mv_targets['vis_score'] * loss_rgb_mv).sum(-1)
loss_rgb = (loss_rgb / (1. + mv_targets['vis_score'].sum(-1))).mean()
loss = loss_d + args.w_rgb * loss_rgb
loss.backward()
if args.grad_clip > 0.:
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=args.grad_clip)
optimizer.step()
new_lrate = optimizer.param_groups[0]['lr']
scheduler.step()
# ================= Logging ==========================
if i % args.i_print == 0 and i != start:
wandb.log({
'train/_ep': ep,
'train/_lr': new_lrate,
'train/loss': loss.item(),
'train/loss_d': loss_d.item(),
'train/loss_rgb': loss_rgb.item()
})
# ================= Evaluation =====================
if i % args.i_img == 0 and i != start:
torch.cuda.empty_cache()
eval(args, dataloader, ray_fn, model, mode='train')
eval(args, dataloader, ray_fn, model, mode='test')
# Save checkpoints
if (i % args.i_weights == 0 and i != start) or (i + 1) == args.N_iters:
path = os.path.join(args.logdir, args.expname, '{:07d}.tar'.format(i))
ckpt_dict = {
'global_step': global_step,
'network_fn': model.state_dict(),
'optimizer': optimizer.state_dict(),
'scheduler': scheduler.state_dict()
}
torch.save(ckpt_dict, path)
print('Saved checkpoints at', path)
# a quick evaluation on the whole dataset
evaluate_all(args, dataloader, ray_fn, model, global_step=global_step, mode='train')
evaluate_all(args, dataloader, ray_fn, model, global_step=global_step, mode='test')
global_step += 1
wandb.alert(
title='Training Finished',
text=f'Start to evaluate.',
level=AlertLevel.WARN)
args.eval_only = True
args.denoise = True
args.grad_normal = True
evaluate(args)
def eval(args, dataloader, ray_fn, model, img_i=None, mode='test', log_level=2):
# log_level - 0: return metrics, 1: return metrics and maps, otherwise: wandb logging
H = dataloader.scene_info['H']
W = dataloader.scene_info['W']
if img_i is None:
i_split = dataloader.i_test if mode.startswith('test') else dataloader.i_train
img_i = np.random.choice(np.arange(0, len(i_split)))
inds = img_i * H * W + np.arange(0, H * W)
rays, targets = dataloader(inds, mode=mode) # (H*W, C)
targets['dist_norm'] = torch.zeros_like(targets['dist'])
# Forward network
outputs = {}
with torch.enable_grad():
for i in range(0, len(rays), args.N_rand):
batch_inputs, d0, batch_raydirs = get_ray_param(ray_fn, rays[i:i+args.N_rand])
targets['dist_norm'][i:i+args.N_rand] = (targets['dist'][i:i+args.N_rand] - d0) / (args.radius * 2.)
outs = model(batch_inputs)
outs['dist_abs'] = outs['dist'] * (2.*args.radius) + d0
if 'rgb' in outs:
outs['rgb_pred'] = torch.sigmoid(outs['rgb'])
if args.denoise: | gn = get_surface_gradient(outs['dist'], batch_raydirs) | 7 | 2023-10-30 14:05:51+00:00 | 8k |
snap-stanford/relbench | test/external/test_nn.py | [
{
"identifier": "TaskType",
"path": "relbench/data/task.py",
"snippet": "class TaskType(Enum):\n r\"\"\"The type of the task.\n\n Attributes:\n REGRESSION: Regression task.\n MULTICLASS_CLASSIFICATION: Multi-class classification task.\n BINARY_CLASSIFICATION: Binary classifica... | from typing import Dict
from torch_frame.config.text_embedder import TextEmbedderConfig
from torch_frame.testing.text_embedder import HashTextEmbedder
from torch_geometric.loader import NeighborLoader
from torch_geometric.nn import MLP
from relbench.data.task import TaskType
from relbench.datasets import FakeDataset
from relbench.external.graph import (
get_stype_proposal,
get_train_table_input,
make_pkey_fkey_graph,
)
from relbench.external.nn import HeteroEncoder, HeteroGraphSAGE
import torch
import torch.nn.functional as F | 3,942 |
def test_train_fake_product_dataset(tmp_path):
dataset = FakeDataset()
data = make_pkey_fkey_graph(
dataset.db,
get_stype_proposal(dataset.db),
text_embedder_cfg=TextEmbedderConfig(
text_embedder=HashTextEmbedder(8), batch_size=None
),
cache_dir=tmp_path,
)
node_to_col_names_dict = { # TODO Expose as method in `HeteroData`.
node_type: data[node_type].tf.col_names_dict for node_type in data.node_types
}
# Ensure that full-batch model works as expected ##########################
encoder = HeteroEncoder(64, node_to_col_names_dict, data.col_stats_dict)
gnn = HeteroGraphSAGE(data.node_types, data.edge_types, 64)
head = MLP(64, out_channels=1, num_layers=1)
x_dict = encoder(data.tf_dict)
x_dict = gnn(x_dict, data.edge_index_dict)
x = head(x_dict["customer"])
assert len(x_dict) == 3
assert x_dict["customer"].size() == (100, 64)
assert x_dict["review"].size() == (450, 64)
assert x_dict["product"].size() == (30, 64)
assert x.size() == (100, 1)
# Ensure that neighbor loading works on train/val/test splits ############
task = dataset.get_task("rel-amazon-churn", process=True)
|
def test_train_fake_product_dataset(tmp_path):
dataset = FakeDataset()
data = make_pkey_fkey_graph(
dataset.db,
get_stype_proposal(dataset.db),
text_embedder_cfg=TextEmbedderConfig(
text_embedder=HashTextEmbedder(8), batch_size=None
),
cache_dir=tmp_path,
)
node_to_col_names_dict = { # TODO Expose as method in `HeteroData`.
node_type: data[node_type].tf.col_names_dict for node_type in data.node_types
}
# Ensure that full-batch model works as expected ##########################
encoder = HeteroEncoder(64, node_to_col_names_dict, data.col_stats_dict)
gnn = HeteroGraphSAGE(data.node_types, data.edge_types, 64)
head = MLP(64, out_channels=1, num_layers=1)
x_dict = encoder(data.tf_dict)
x_dict = gnn(x_dict, data.edge_index_dict)
x = head(x_dict["customer"])
assert len(x_dict) == 3
assert x_dict["customer"].size() == (100, 64)
assert x_dict["review"].size() == (450, 64)
assert x_dict["product"].size() == (30, 64)
assert x.size() == (100, 1)
# Ensure that neighbor loading works on train/val/test splits ############
task = dataset.get_task("rel-amazon-churn", process=True) | assert task.task_type == TaskType.BINARY_CLASSIFICATION | 0 | 2023-10-29 18:29:52+00:00 | 8k |
francescofugazzi/3dgsconverter | gsconverter/main.py | [
{
"identifier": "Utility",
"path": "gsconverter/utils/utility.py",
"snippet": "class Utility:\n @staticmethod\n def text_based_detect_format(file_path):\n debug_print(\"[DEBUG] Executing 'text_based_detect_format' function...\")\n\n \"\"\"Detect if the given file is in '3dgs' or 'cc'... | import argparse
import os
import sys
import numpy as np
from .utils.utility import Utility
from .utils.conversion_functions import convert
from plyfile import PlyData, PlyElement
from multiprocessing import Pool
from .utils import config
from .utils.utility_functions import init_worker
from .utils.argument_actions import DensityFilterAction, RemoveFlyersAction, AboutAction
from .utils.base_converter import BaseConverter | 6,440 | """
3D Gaussian Splatting Converter
Copyright (c) 2023 Francesco Fugazzi
This software is released under the MIT License.
For more information about the license, please see the LICENSE file.
"""
__version__ = '0.1'
def main():
print(f"3D Gaussian Splatting Converter: {__version__}")
parser = argparse.ArgumentParser(description="Convert between standard 3D Gaussian Splat and Cloud Compare formats.")
# Arguments for input and output
parser.add_argument("--input", "-i", required=True, help="Path to the source point cloud file.")
parser.add_argument("--output", "-o", required=True, help="Path to save the converted point cloud file.")
parser.add_argument("--target_format", "-f", choices=["3dgs", "cc"], required=True, help="Target point cloud format.")
parser.add_argument("--debug", "-d", action="store_true", help="Enable debug prints.")
parser.add_argument('--about', action=AboutAction, help='Show copyright and license info')
# Other flags
parser.add_argument("--rgb", action="store_true", help="Add RGB values to the output file based on f_dc values (only applicable when converting to Cloud Compare format).")
parser.add_argument("--bbox", nargs=6, type=float, metavar=('minX', 'minY', 'minZ', 'maxX', 'maxY', 'maxZ'), help="Specify the 3D bounding box to crop the point cloud.")
parser.add_argument("--density_filter", nargs='*', action=DensityFilterAction, help="Filter the points to keep only regions with higher point density. Optionally provide 'voxel_size' and 'threshold_percentage' as two numbers (e.g., --density_filter 0.5 0.25). If no numbers are provided, defaults of 1.0 and 0.32 are used.")
parser.add_argument("--remove_flyers", nargs='*', action=RemoveFlyersAction, help="Remove flyers based on k-nearest neighbors. Requires two numbers: 'k' (number of neighbors) and 'threshold_factor'.")
args = parser.parse_args()
config.DEBUG = args.debug
# Check and append ".ply" extension if absent
if not args.output.lower().endswith('.ply'):
args.output += '.ply'
# Now check if the file exists after potentially appending the extension
if os.path.exists(args.output):
user_response = input(f"File {args.output} already exists. Do you want to overwrite it? (y/N): ").lower()
if user_response != 'y':
print("Operation aborted by the user.")
return
# Detect the format of the input file
if args.input.lower().endswith('.parquet'):
source_format = 'parquet'
else:
| """
3D Gaussian Splatting Converter
Copyright (c) 2023 Francesco Fugazzi
This software is released under the MIT License.
For more information about the license, please see the LICENSE file.
"""
__version__ = '0.1'
def main():
print(f"3D Gaussian Splatting Converter: {__version__}")
parser = argparse.ArgumentParser(description="Convert between standard 3D Gaussian Splat and Cloud Compare formats.")
# Arguments for input and output
parser.add_argument("--input", "-i", required=True, help="Path to the source point cloud file.")
parser.add_argument("--output", "-o", required=True, help="Path to save the converted point cloud file.")
parser.add_argument("--target_format", "-f", choices=["3dgs", "cc"], required=True, help="Target point cloud format.")
parser.add_argument("--debug", "-d", action="store_true", help="Enable debug prints.")
parser.add_argument('--about', action=AboutAction, help='Show copyright and license info')
# Other flags
parser.add_argument("--rgb", action="store_true", help="Add RGB values to the output file based on f_dc values (only applicable when converting to Cloud Compare format).")
parser.add_argument("--bbox", nargs=6, type=float, metavar=('minX', 'minY', 'minZ', 'maxX', 'maxY', 'maxZ'), help="Specify the 3D bounding box to crop the point cloud.")
parser.add_argument("--density_filter", nargs='*', action=DensityFilterAction, help="Filter the points to keep only regions with higher point density. Optionally provide 'voxel_size' and 'threshold_percentage' as two numbers (e.g., --density_filter 0.5 0.25). If no numbers are provided, defaults of 1.0 and 0.32 are used.")
parser.add_argument("--remove_flyers", nargs='*', action=RemoveFlyersAction, help="Remove flyers based on k-nearest neighbors. Requires two numbers: 'k' (number of neighbors) and 'threshold_factor'.")
args = parser.parse_args()
config.DEBUG = args.debug
# Check and append ".ply" extension if absent
if not args.output.lower().endswith('.ply'):
args.output += '.ply'
# Now check if the file exists after potentially appending the extension
if os.path.exists(args.output):
user_response = input(f"File {args.output} already exists. Do you want to overwrite it? (y/N): ").lower()
if user_response != 'y':
print("Operation aborted by the user.")
return
# Detect the format of the input file
if args.input.lower().endswith('.parquet'):
source_format = 'parquet'
else: | source_format = Utility.text_based_detect_format(args.input) | 0 | 2023-10-28 15:09:50+00:00 | 8k |
masked-spacetime-hashing/msth | nerfstudio/fields/semantic_nerf_field.py | [
{
"identifier": "RaySamples",
"path": "nerfstudio/cameras/rays.py",
"snippet": "class RaySamples(TensorDataclass):\n \"\"\"Samples along a ray\"\"\"\n\n frustums: Frustums\n \"\"\"Frustums along ray.\"\"\"\n camera_indices: Optional[TensorType[\"bs\":..., 1]] = None\n \"\"\"Camera index.\... | from typing import Dict, Optional, Tuple
from torch import nn
from torchtyping import TensorType
from nerfstudio.cameras.rays import RaySamples
from nerfstudio.field_components.encodings import Encoding, Identity
from nerfstudio.field_components.field_heads import (
DensityFieldHead,
FieldHeadNames,
RGBFieldHead,
SemanticFieldHead,
)
from nerfstudio.field_components.mlp import MLP
from nerfstudio.fields.base_field import Field
import torch | 3,786 | # Copyright 2022 The Nerfstudio Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Semantic NeRF field implementation.
"""
class SemanticNerfField(Field):
"""Semantic-NeRF field
Args:
num_semantic_classes: Number of distinct semantic classes.
position_encoding: Position encoder.
direction_encoding: Direction encoder.
base_mlp_num_layers: Number of layers for base MLP.
base_mlp_layer_width: Width of base MLP layers.
head_mlp_num_layers: Number of layer for output head MLP.
head_mlp_layer_width: Width of output head MLP layers.
skip_connections: Where to add skip connection in base MLP.
"""
def __init__(
self,
num_semantic_classes: int,
position_encoding: Encoding = Identity(in_dim=3),
direction_encoding: Encoding = Identity(in_dim=3),
base_mlp_num_layers: int = 8,
base_mlp_layer_width: int = 256,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
) -> None:
super().__init__()
self.num_semantic_classes = num_semantic_classes
self.position_encoding = position_encoding
self.direction_encoding = direction_encoding
self.mlp_base = MLP(
in_dim=self.position_encoding.get_out_dim(),
num_layers=base_mlp_num_layers,
layer_width=base_mlp_layer_width,
skip_connections=skip_connections,
out_activation=nn.ReLU(),
)
self.mlp_head = MLP(
in_dim=self.mlp_base.get_out_dim() + self.direction_encoding.get_out_dim(),
num_layers=head_mlp_num_layers,
layer_width=head_mlp_layer_width,
out_activation=nn.ReLU(),
)
self.mlp_semantic = MLP(
in_dim=self.mlp_head.get_out_dim(),
layer_width=self.mlp_head.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
out_activation=nn.ReLU(),
)
self.field_head_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
self.field_head_rgb = RGBFieldHead(in_dim=self.mlp_head.get_out_dim())
self.field_head_semantic = SemanticFieldHead(
in_dim=self.mlp_semantic.get_out_dim(), num_classes=self.num_semantic_classes
)
| # Copyright 2022 The Nerfstudio Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Semantic NeRF field implementation.
"""
class SemanticNerfField(Field):
"""Semantic-NeRF field
Args:
num_semantic_classes: Number of distinct semantic classes.
position_encoding: Position encoder.
direction_encoding: Direction encoder.
base_mlp_num_layers: Number of layers for base MLP.
base_mlp_layer_width: Width of base MLP layers.
head_mlp_num_layers: Number of layer for output head MLP.
head_mlp_layer_width: Width of output head MLP layers.
skip_connections: Where to add skip connection in base MLP.
"""
def __init__(
self,
num_semantic_classes: int,
position_encoding: Encoding = Identity(in_dim=3),
direction_encoding: Encoding = Identity(in_dim=3),
base_mlp_num_layers: int = 8,
base_mlp_layer_width: int = 256,
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
) -> None:
super().__init__()
self.num_semantic_classes = num_semantic_classes
self.position_encoding = position_encoding
self.direction_encoding = direction_encoding
self.mlp_base = MLP(
in_dim=self.position_encoding.get_out_dim(),
num_layers=base_mlp_num_layers,
layer_width=base_mlp_layer_width,
skip_connections=skip_connections,
out_activation=nn.ReLU(),
)
self.mlp_head = MLP(
in_dim=self.mlp_base.get_out_dim() + self.direction_encoding.get_out_dim(),
num_layers=head_mlp_num_layers,
layer_width=head_mlp_layer_width,
out_activation=nn.ReLU(),
)
self.mlp_semantic = MLP(
in_dim=self.mlp_head.get_out_dim(),
layer_width=self.mlp_head.layer_width // 2,
num_layers=1,
activation=nn.ReLU(),
out_activation=nn.ReLU(),
)
self.field_head_density = DensityFieldHead(in_dim=self.mlp_base.get_out_dim())
self.field_head_rgb = RGBFieldHead(in_dim=self.mlp_head.get_out_dim())
self.field_head_semantic = SemanticFieldHead(
in_dim=self.mlp_semantic.get_out_dim(), num_classes=self.num_semantic_classes
)
| def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]: | 0 | 2023-10-26 04:39:15+00:00 | 8k |
mikacuy/PL-NeRF | nerf_extract_mesh.py | [
{
"identifier": "load_llff_data",
"path": "load_llff.py",
"snippet": "def load_llff_data(basedir, factor=8, recenter=True, bd_factor=.75, spherify=False, path_zflat=False):\n \n\n poses, bds, imgs = _load_data(basedir, factor=factor) # factor=8 downsamples original imgs by 8x\n print('Loaded', ... | import os, sys
import numpy as np
import imageio
import json
import random
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import configargparse
import datetime
import math
import cv2
import shutil
import trimesh
import mcubes
import configargparse
from tqdm import tqdm, trange
from torch.utils.tensorboard import SummaryWriter
from skimage.metrics import structural_similarity
from lpips import LPIPS
from run_nerf_helpers import *
from load_llff import load_llff_data
from load_deepvoxels import load_dv_data
from load_blender import load_blender_data, load_scene_blender_fixed_dist_new, load_scene_blender2
from load_LINEMOD import load_LINEMOD_data
from natsort import natsorted
from argparse import Namespace
from tqdm import tqdm, trange | 6,404 |
parser.add_argument('--test_dist', default= 1.0, type=float)
parser.add_argument("--eval_scene_id", type=str, default="chair_rgba_fixdist_nv100_dist0.25-1.0-4_depth_sfn",
help='scene identifier for eval')
parser.add_argument("--eval_data_dir", type=str, default="../nerf_synthetic/fixed_dist_new-rgba/",
help='directory containing the scenes for eval')
### DTU flags
parser.add_argument("--dtu_scene_id", type=int, default=21,
help='scan id for DTU dataset to render')
parser.add_argument("--num_train", type=int, default=40,
help='number of training views to use (1 - 49)')
parser.add_argument("--dtu_split", type=str, default=None,
help='number of training views to use (1 - 49)')
##################
return parser
def train():
parser = config_parser()
args = parser.parse_args()
print(args.white_bkgd)
tmp_task = args.task
tmp_data_dir = args.data_dir
tmp_scene_id = args.scene_id
tmp_dataset = args.dataset
tmp_test_dist = args.test_dist
tmp_ckpt_dir = args.ckpt_dir
tmp_set_near_plane = args.set_near_plane
tmp_white_bkgd = args.white_bkgd
tmp_eval_scene_id = args.eval_scene_id
tmp_eval_data_dir = args.eval_data_dir
# tmp_white_bkgd = False
tmp_test_skip = args.testskip
# tmp_mode = args.mode
# tmp_N_samples = args.N_samples
# tmp_N_importance = args.N_importance
# load nerf parameters from training
args_file = os.path.join(args.ckpt_dir, args.expname, 'args.json')
with open(args_file, 'r') as af:
args_dict = json.load(af)
args = Namespace(**args_dict)
# task and paths are not overwritten
args.task = tmp_task
args.data_dir = tmp_data_dir
args.ckpt_dir = tmp_ckpt_dir
# args.mode = tmp_mode
args.train_jsonfile = 'transforms_train.json'
args.set_near_plane = tmp_set_near_plane
# args.N_samples = tmp_N_samples
# args.N_importance = tmp_N_importance
args.dataset = tmp_dataset
args.test_dist = tmp_test_dist
args.scene_id = tmp_scene_id
args.white_bkgd = tmp_white_bkgd
args.eval_scene_id = tmp_eval_scene_id
args.eval_data_dir = tmp_eval_data_dir
args.testskip = tmp_test_skip
print('\n'.join(f'{k}={v}' for k, v in vars(args).items()))
args.n_gpus = torch.cuda.device_count()
print(f"Using {args.n_gpus} GPU(s).")
# Load data
scene_data_dir = os.path.join(args.data_dir, args.scene_id)
K = None
if args.dataset == 'llff':
images, poses, bds, render_poses, i_test = load_llff_data(scene_data_dir, args.factor,
recenter=True, bd_factor=.75,
spherify=args.spherify)
hwf = poses[0,:3,-1]
poses = poses[:,:3,:4]
print('Loaded llff', images.shape, render_poses.shape, hwf, scene_data_dir)
if not isinstance(i_test, list):
i_test = [i_test]
if args.llffhold > 0:
print('Auto LLFF holdout,', args.llffhold)
i_test = np.arange(images.shape[0])[::args.llffhold]
i_val = i_test
i_train = np.array([i for i in np.arange(int(images.shape[0])) if
(i not in i_test and i not in i_val)])
print('DEFINING BOUNDS')
if args.no_ndc:
near = np.ndarray.min(bds) * .9
far = np.ndarray.max(bds) * 1.
else:
near = 0.
far = 1.
print('NEAR FAR', near, far)
elif args.dataset == 'blender':
images, poses, render_poses, hwf, i_split = load_blender_data(scene_data_dir, args.half_res, args.testskip)
print('Loaded blender', images.shape, render_poses.shape, hwf, scene_data_dir)
i_train, i_val, i_test = i_split
# near = 2.
near = args.set_near_plane
print("Set near plane to: " + str(near))
far = 6.
if args.white_bkgd:
images = images[...,:3]*images[...,-1:] + (1.-images[...,-1:])
else:
images = images[...,:3]
elif args.dataset == "blender2":
| '''
Use a different learning rate for the coarse network
Use constant aggregation for the first few iterations
'''
# from load_dtu import load_dtu, load_dtu2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
np.random.seed(0)
torch.manual_seed(0)
torch.cuda.manual_seed(0)
DEBUG = False
def build_json_for_dtu(splits, intrinsics, poses, near, far):
out_dict = {}
out_dict = {"near": near,
"far": far}
i_train, i_test = splits
train_dicts = []
test_dicts = []
for i in i_train:
train_dict = {}
train_dict["extrinsic"] = poses[i].tolist()
train_dict["intrinsic"] = intrinsics[i].tolist()
train_dict["pose_id"] = int(i)
train_dicts.append(train_dict)
for i in i_test:
test_dict = {}
test_dict["extrinsic"] = poses[i].tolist()
test_dict["intrinsic"] = intrinsics[i].tolist()
test_dict["pose_id"] = int(i)
test_dicts.append(test_dict)
out_dict["train_frames"] = train_dicts
out_dict["test_frames"] = test_dicts
return out_dict
def batchify(fn, chunk):
"""Constructs a version of 'fn' that applies to smaller batches.
"""
if chunk is None:
return fn
def ret(inputs):
return torch.cat([fn(inputs[i:i+chunk]) for i in range(0, inputs.shape[0], chunk)], 0)
return ret
def run_network(inputs, viewdirs, fn, embed_fn, embeddirs_fn, netchunk=1024*64):
"""Prepares inputs and applies network 'fn'.
"""
inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]])
embedded = embed_fn(inputs_flat)
if viewdirs is not None:
# input_dirs = viewdirs[:,None].expand(inputs.shape)
# input_dirs_flat = torch.reshape(input_dirs, [-1, input_dirs.shape[-1]])
input_dirs_flat = viewdirs
embedded_dirs = embeddirs_fn(input_dirs_flat)
embedded = torch.cat([embedded, embedded_dirs], -1)
outputs_flat = batchify(fn, netchunk)(embedded)
outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]])
return outputs
def batchify_rays(rays_flat, chunk=1024*32, **kwargs):
"""Render rays in smaller minibatches to avoid OOM.
"""
all_ret = {}
for i in range(0, rays_flat.shape[0], chunk):
ret = render_rays(rays_flat[i:i+chunk], **kwargs)
for k in ret:
if k not in all_ret:
all_ret[k] = []
all_ret[k].append(ret[k])
all_ret = {k : torch.cat(all_ret[k], 0) for k in all_ret}
return all_ret
def render(H, W, K, chunk=1024*32, rays=None, c2w=None, ndc=True,
near=0., far=1.,
use_viewdirs=False, c2w_staticcam=None,
**kwargs):
"""Render rays
Args:
H: int. Height of image in pixels.
W: int. Width of image in pixels.
focal: float. Focal length of pinhole camera.
chunk: int. Maximum number of rays to process simultaneously. Used to
control maximum memory usage. Does not affect final results.
rays: array of shape [2, batch_size, 3]. Ray origin and direction for
each example in batch.
c2w: array of shape [3, 4]. Camera-to-world transformation matrix.
ndc: bool. If True, represent ray origin, direction in NDC coordinates.
near: float or array of shape [batch_size]. Nearest distance for a ray.
far: float or array of shape [batch_size]. Farthest distance for a ray.
use_viewdirs: bool. If True, use viewing direction of a point in space in model.
c2w_staticcam: array of shape [3, 4]. If not None, use this transformation matrix for
camera while using other c2w argument for viewing directions.
Returns:
rgb_map: [batch_size, 3]. Predicted RGB values for rays.
disp_map: [batch_size]. Disparity map. Inverse of depth.
acc_map: [batch_size]. Accumulated opacity (alpha) along a ray.
extras: dict with everything returned by render_rays().
"""
if c2w is not None:
# special case to render full image
rays_o, rays_d = get_rays(H, W, K, c2w)
else:
# use provided ray batch
rays_o, rays_d = rays
if use_viewdirs:
# provide ray directions as input
viewdirs = rays_d
if c2w_staticcam is not None:
# special case to visualize effect of viewdirs
rays_o, rays_d = get_rays(H, W, K, c2w_staticcam)
viewdirs = viewdirs / torch.norm(viewdirs, dim=-1, keepdim=True)
viewdirs = torch.reshape(viewdirs, [-1,3]).float()
sh = rays_d.shape # [..., 3]
if ndc:
# for forward facing scenes
rays_o, rays_d = ndc_rays(H, W, K[0][0], 1., rays_o, rays_d)
# Create ray batch
rays_o = torch.reshape(rays_o, [-1,3]).float()
rays_d = torch.reshape(rays_d, [-1,3]).float()
near, far = near * torch.ones_like(rays_d[...,:1]), far * torch.ones_like(rays_d[...,:1])
rays = torch.cat([rays_o, rays_d, near, far], -1)
if use_viewdirs:
rays = torch.cat([rays, viewdirs], -1)
# Render and reshape
all_ret = batchify_rays(rays, chunk, **kwargs)
for k in all_ret:
k_sh = list(sh[:-1]) + list(all_ret[k].shape[1:])
all_ret[k] = torch.reshape(all_ret[k], k_sh)
k_extract = ['rgb_map', 'disp_map', 'acc_map']
ret_list = [all_ret[k] for k in k_extract]
ret_dict = {k : all_ret[k] for k in all_ret if k not in k_extract}
return ret_list + [ret_dict]
def create_nerf(args):
"""Instantiate NeRF's MLP model.
"""
embed_fn, input_ch = get_embedder(args.multires, args.i_embed)
input_ch_views = 0
embeddirs_fn = None
if args.use_viewdirs:
embeddirs_fn, input_ch_views = get_embedder(args.multires_views, args.i_embed)
output_ch = 5 if args.N_importance > 0 else 4
skips = [4]
model = NeRF(D=args.netdepth, W=args.netwidth,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_views=input_ch_views, use_viewdirs=args.use_viewdirs).to(device)
coarse_grad_vars = list(model.parameters())
model_fine = None
if args.N_importance > 0:
model_fine = NeRF(D=args.netdepth_fine, W=args.netwidth_fine,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_views=input_ch_views, use_viewdirs=args.use_viewdirs).to(device)
grad_vars = list(model_fine.parameters())
network_query_fn = lambda inputs, viewdirs, network_fn : run_network(inputs, viewdirs, network_fn,
embed_fn=embed_fn,
embeddirs_fn=embeddirs_fn,
netchunk=args.netchunk)
# Create optimizer
optimizer = torch.optim.Adam(params=grad_vars, lr=args.lrate, betas=(0.9, 0.999))
optimizer_coarse = torch.optim.Adam(params=coarse_grad_vars, lr=args.lrate, betas=(0.9, 0.999))
start = 0
##########################
# Load checkpoints
if args.ft_path is not None and args.ft_path!='None':
ckpts = [args.ft_path]
else:
ckpts = [os.path.join(args.ckpt_dir, args.expname, f) for f in sorted(os.listdir(os.path.join(args.ckpt_dir, args.expname))) if 'tar' in f]
print('Found ckpts', ckpts)
if len(ckpts) > 0 and not args.no_reload:
ckpt_path = ckpts[-1]
print('Reloading from', ckpt_path)
ckpt = torch.load(ckpt_path)
start = ckpt['global_step']
# optimizer.load_state_dict(ckpt['optimizer_state_dict'])
# Load model
model.load_state_dict(ckpt['network_fn_state_dict'])
if model_fine is not None:
model_fine.load_state_dict(ckpt['network_fine_state_dict'])
##########################
render_kwargs_train = {
'network_query_fn' : network_query_fn,
'perturb' : args.perturb,
'N_importance' : args.N_importance,
'network_fine' : model_fine,
'N_samples' : args.N_samples,
'network_fn' : model,
'use_viewdirs' : args.use_viewdirs,
'white_bkgd' : args.white_bkgd,
'raw_noise_std' : args.raw_noise_std,
'mode' : args.mode,
'color_mode': args.color_mode,
'farcolorfix': args.farcolorfix
}
# NDC only good for LLFF-style forward facing data
if args.dataset != 'llff' or args.no_ndc:
print('Not ndc!')
render_kwargs_train['ndc'] = False
render_kwargs_train['lindisp'] = args.lindisp
render_kwargs_test = {k : render_kwargs_train[k] for k in render_kwargs_train}
### set to True for linear
# render_kwargs_test['perturb'] = False
render_kwargs_test['perturb'] = True
render_kwargs_test['raw_noise_std'] = 0.
return render_kwargs_train, render_kwargs_test, start, grad_vars, optimizer, optimizer_coarse
def compute_weights(raw, z_vals, rays_d, noise=0.):
raw2alpha = lambda raw, dists, act_fn=F.relu: 1.-torch.exp(-act_fn(raw)*dists)
dists = z_vals[...,1:] - z_vals[...,:-1]
dists = torch.cat([dists, torch.full_like(dists[...,:1], 1e10, device=device)], -1) # [N_rays, N_samples]
dists = dists * torch.norm(rays_d[...,None,:], dim=-1)
alpha = raw2alpha(raw[...,3] + noise, dists) # [N_rays, N_samples]
weights = alpha * torch.cumprod(torch.cat([torch.ones((alpha.shape[0], 1), device=device), 1.-alpha + 1e-10], -1), -1)[:, :-1]
return weights
### Our reformulation to piecewise linear
def compute_weights_piecewise_linear(raw, z_vals, near, far, rays_d, noise=0., return_tau=False):
raw2expr = lambda raw, dists: torch.exp(-raw*dists)
### Concat
z_vals = torch.cat([near, z_vals, far], -1)
dists = z_vals[...,1:] - z_vals[...,:-1]
### Original code
dists = dists * torch.norm(rays_d[...,None,:], dim=-1)
tau = torch.cat([torch.ones((raw.shape[0], 1), device=device)*1e-10, raw[...,3] + noise, torch.ones((raw.shape[0], 1), device=device)*1e10], -1) ### tau(near) = 0, tau(far) = very big (will hit an opaque surface)
tau = F.relu(tau) ## Make positive from proof of DS-NeRF
interval_ave_tau = 0.5 * (tau[...,1:] + tau[...,:-1])
'''
Evaluating exp(-0.5 (tau_{i+1}+tau_i) (s_{i+1}-s_i) )
'''
expr = raw2expr(interval_ave_tau, dists) # [N_rays, N_samples+1]
### Transmittance until s_n
T = torch.cumprod(torch.cat([torch.ones((expr.shape[0], 1), device=device), expr], -1), -1) # [N_rays, N_samples+2], T(near)=1, starts off at 1
### Factor to multiply transmittance with
factor = (1 - expr)
weights = factor * T[:, :-1] # [N_rays, N_samples+1]
if return_tau:
return weights, tau, T
else:
return weights
def raw2outputs(raw, z_vals, near, far, rays_d, mode, color_mode, raw_noise_std=0, pytest=False, white_bkgd=False, farcolorfix=False):
"""Transforms model's predictions to semantically meaningful values.
Args:
raw: [num_rays, num_samples along ray, 4]. Prediction from model.
z_vals: [num_rays, num_samples along ray]. Integration time.
rays_d: [num_rays, 3]. Direction of each ray.
Returns:
rgb_map: [num_rays, 3]. Estimated RGB color of a ray.
disp_map: [num_rays]. Disparity map. Inverse of depth map.
acc_map: [num_rays]. Sum of weights along each ray.
weights: [num_rays, num_samples]. Weights assigned to each sampled color.
depth_map: [num_rays]. Estimated distance to object.
"""
rgb = torch.sigmoid(raw[...,:3]) # [N_rays, N_samples, 3]
noise = 0.
if raw_noise_std > 0.:
noise = torch.randn(raw[...,3].shape) * raw_noise_std
# Overwrite randomly sampled data if pytest
if pytest:
np.random.seed(0)
noise = np.random.rand(*list(raw[...,3].shape)) * raw_noise_std
noise = torch.Tensor(noise)
if mode == "linear":
weights, tau, T = compute_weights_piecewise_linear(raw, z_vals, near, far, rays_d, noise, return_tau=True)
if color_mode == "midpoint":
if farcolorfix:
rgb_concat = torch.cat([rgb[: ,0, :].unsqueeze(1), rgb, torch.zeros((rgb[:, -1].shape), device=device).unsqueeze(1)], 1)
else:
rgb_concat = torch.cat([rgb[: ,0, :].unsqueeze(1), rgb, rgb[: ,-1, :].unsqueeze(1)], 1)
rgb_mid = .5 * (rgb_concat[:, 1:, :] + rgb_concat[:, :-1, :])
rgb_map = torch.sum(weights[...,None] * rgb_mid, -2) # [N_rays, 3]
elif color_mode == "left":
rgb_concat = torch.cat([rgb[: ,0, :].unsqueeze(1), rgb], 1)
rgb_map = torch.sum(weights[...,None] * rgb_concat, -2)
else:
print("ERROR: Color mode unimplemented, please select left or midpoint.")
### Piecewise linear means take the midpoint
z_vals = torch.cat([near, z_vals, far], -1)
z_vals_mid = .5 * (z_vals[...,1:] + z_vals[...,:-1])
depth_map = torch.sum(weights * z_vals_mid, -1)
elif mode == "constant":
weights = compute_weights(raw, z_vals, rays_d, noise)
rgb_map = torch.sum(weights[...,None] * rgb, -2) # [N_rays, 3]
depth_map = torch.sum(weights * z_vals, -1)
tau = None
T = None
disp_map = 1./torch.max(1e-10 * torch.ones_like(depth_map), depth_map / torch.sum(weights, -1))
acc_map = torch.sum(weights, -1)
if white_bkgd:
rgb_map = rgb_map + (1.-acc_map[...,None])
return rgb_map, disp_map, acc_map, weights, depth_map, tau, T
def render_rays(ray_batch,
network_fn,
network_query_fn,
N_samples,
mode,
color_mode,
retraw=False,
lindisp=False,
perturb=0.,
N_importance=0,
network_fine=None,
white_bkgd=False,
raw_noise_std=0.,
verbose=False,
pytest=False,
quad_solution_v2=False,
zero_tol = 1e-4,
epsilon = 1e-3,
farcolorfix = False,
constant_init = False):
"""Volumetric rendering.
Args:
ray_batch: array of shape [batch_size, ...]. All information necessary
for sampling along a ray, including: ray origin, ray direction, min
dist, max dist, and unit-magnitude viewing direction.
network_fn: function. Model for predicting RGB and density at each point
in space.
network_query_fn: function used for passing queries to network_fn.
N_samples: int. Number of different times to sample along each ray.
retraw: bool. If True, include model's raw, unprocessed predictions.
lindisp: bool. If True, sample linearly in inverse depth rather than in depth.
perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified
random points in time.
N_importance: int. Number of additional times to sample along each ray.
These samples are only passed to network_fine.
network_fine: "fine" network with same spec as network_fn.
white_bkgd: bool. If True, assume a white background.
raw_noise_std: ...
verbose: bool. If True, print more debugging info.
Returns:
rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model.
disp_map: [num_rays]. Disparity map. 1 / depth.
acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model.
raw: [num_rays, num_samples, 4]. Raw predictions from model.
rgb0: See rgb_map. Output for coarse model.
disp0: See disp_map. Output for coarse model.
acc0: See acc_map. Output for coarse model.
z_std: [num_rays]. Standard deviation of distances along ray for each
sample.
"""
N_rays = ray_batch.shape[0]
rays_o, rays_d = ray_batch[:,0:3], ray_batch[:,3:6] # [N_rays, 3] each
viewdirs = ray_batch[:,-3:] if ray_batch.shape[-1] > 8 else None
bounds = torch.reshape(ray_batch[...,6:8], [-1,1,2])
near, far = bounds[...,0], bounds[...,1] # [-1,1]
t_vals = torch.linspace(0., 1., steps=N_samples)
if not lindisp:
z_vals = near * (1.-t_vals) + far * (t_vals)
else:
z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals))
z_vals = z_vals.expand([N_rays, N_samples])
if perturb > 0.:
# get intervals between samples
mids = .5 * (z_vals[...,1:] + z_vals[...,:-1])
upper = torch.cat([mids, z_vals[...,-1:]], -1)
lower = torch.cat([z_vals[...,:1], mids], -1)
# stratified samples in those intervals
t_rand = torch.rand(z_vals.shape)
# Pytest, overwrite u with numpy's fixed random numbers
if pytest:
np.random.seed(0)
t_rand = np.random.rand(*list(z_vals.shape))
t_rand = torch.Tensor(t_rand)
z_vals = lower + (upper - lower) * t_rand
pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples, 3]
### If constant init then overwrite mode for coarse model to constant first
if constant_init:
# coarse_mode = "constant"
mode = "constant"
# else:
# coarse_mode = mode
# print(mode)
# raw = run_network(pts)
raw = network_query_fn(pts, viewdirs, network_fn)
rgb_map, disp_map, acc_map, weights, depth_map, tau, T = raw2outputs(raw, z_vals, near, far, rays_d, mode, color_mode, raw_noise_std, pytest=pytest, white_bkgd=white_bkgd, farcolorfix=farcolorfix)
if N_importance > 0:
rgb_map_0, disp_map_0, acc_map_0, depth_map_0, z_vals_0, weights_0 = rgb_map, disp_map, acc_map, depth_map, z_vals, weights
z_vals_mid = .5 * (z_vals[...,1:] + z_vals[...,:-1])
if mode == "linear":
z_samples, _, _, _ = sample_pdf_reformulation(z_vals, weights, tau, T, near, far, N_importance, det=(perturb==0.), pytest=pytest, quad_solution_v2=quad_solution_v2, zero_threshold = zero_tol, epsilon_=epsilon)
elif mode == "constant":
z_samples = sample_pdf(z_vals_mid, weights[...,1:-1], N_importance, det=(perturb==0.), pytest=pytest)
z_samples = z_samples.detach()
######## Clamping in quad solution should have fixed this
z_samples = torch.clamp(z_samples, near, far)
########
z_vals, _ = torch.sort(torch.cat([z_vals, z_samples], -1), -1)
pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples + N_importance, 3]
run_fn = network_fn if network_fine is None else network_fine
# raw = run_network(pts, fn=run_fn)
raw = network_query_fn(pts, viewdirs, run_fn)
rgb_map, disp_map, acc_map, weights, depth_map, tau, T = raw2outputs(raw, z_vals, near, far, rays_d, mode, color_mode, raw_noise_std, pytest=pytest, white_bkgd=white_bkgd, farcolorfix=farcolorfix)
ret = {'rgb_map' : rgb_map, 'disp_map' : disp_map, 'acc_map' : acc_map, 'depth_map' : depth_map}
if retraw:
ret['raw'] = raw
if N_importance > 0:
ret['rgb0'] = rgb_map_0
ret['disp0'] = disp_map_0
ret['depth0'] = depth_map_0
ret['acc0'] = acc_map_0
ret['z_std'] = torch.std(z_samples, dim=-1, unbiased=False) # [N_rays]
for k in ret:
if (torch.isnan(ret[k]).any() or torch.isinf(ret[k]).any()) and DEBUG:
print(f"! [Numerical Error] {k} contains nan or inf.")
return ret
#### For mesh extraction ####
def extract_fields(bound_min, bound_max, resolution, query_func, model):
N = 64
X = torch.linspace(bound_min[0], bound_max[0], resolution).split(N)
Y = torch.linspace(bound_min[1], bound_max[1], resolution).split(N)
Z = torch.linspace(bound_min[2], bound_max[2], resolution).split(N)
u = np.zeros([resolution, resolution, resolution], dtype=np.float32)
with torch.no_grad():
for xi, xs in enumerate(tqdm(X)):
for yi, ys in enumerate(Y):
for zi, zs in enumerate(Z):
xx, yy, zz = torch.meshgrid(xs, ys, zs)
pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1)
viewdirs = torch.zeros_like(pts, device=pts.device)
# print(pts.shape)
# print(viewdirs.shape)
# print(query_func(pts, viewdirs, model).shape)
val = query_func(pts, viewdirs, model).reshape(len(xs), len(ys), len(zs), -1)
# print(val.shape)
taus = F.relu(val[...,3])
# print(taus.shape)
# print(torch.nonzero(taus))
# exit()
u[xi * N: xi * N + len(xs), yi * N: yi * N + len(ys), zi * N: zi * N + len(zs)] = taus.detach().cpu().numpy()
return u
def extract_iso_level(density, threshold=25):
# Density boundaries
min_a, max_a, std_a = density.min(), density.max(), density.std()
# Adaptive iso level
iso_value = min(max(threshold, min_a + std_a), max_a - std_a)
print(f"Min density {min_a}, Max density: {max_a}, Mean density {density.mean()}")
print(f"Querying based on iso level: {iso_value}")
return iso_value
def extract_geometry(bound_min, bound_max, resolution, threshold, query_func, model, adaptive=False):
print('threshold: {}'.format(threshold))
u = extract_fields(bound_min, bound_max, resolution, query_func, model)
if not adaptive:
vertices, triangles = mcubes.marching_cubes(u, threshold)
else:
vertices, triangles = mcubes.marching_cubes(u, extract_iso_level(u, threshold))
try:
b_max_np = bound_max.detach().cpu().numpy()
b_min_np = bound_min.detach().cpu().numpy()
except:
b_max_np = bound_max
b_min_np = bound_min
vertices = vertices / (resolution - 1.0) * (b_max_np - b_min_np)[None, :] + b_min_np[None, :]
return vertices, triangles
#############################
def config_parser():
parser = configargparse.ArgumentParser()
parser.add_argument('--task', default="train", type=str, help='one out of: "train", "test", "video"')
parser.add_argument('--config', is_config_file=True,
help='config file path')
parser.add_argument("--expname", type=str,
help='experiment name')
parser.add_argument("--ckpt_dir", type=str, default="",
help='checkpoint directory')
parser.add_argument("--scene_id", type=str, default="lego",
help='scene identifier')
parser.add_argument("--data_dir", type=str, default="../nerf_synthetic",
help='directory containing the scenes')
parser.add_argument("--dataset", type=str, default="blender",
help='dataset used -- selects which dataloader"')
# training options
parser.add_argument("--netdepth", type=int, default=8,
help='layers in network')
parser.add_argument("--netwidth", type=int, default=256,
help='channels per layer')
parser.add_argument("--netdepth_fine", type=int, default=8,
help='layers in fine network')
parser.add_argument("--netwidth_fine", type=int, default=256,
help='channels per layer in fine network')
parser.add_argument("--N_rand", type=int, default=32*32*4,
help='batch size (number of random rays per gradient step)')
parser.add_argument("--lrate", type=float, default=5e-4,
help='learning rate')
parser.add_argument("--coarse_lrate", type=float, default=1e-4,
help='learning rate')
parser.add_argument("--lrate_decay", type=int, default=250,
help='exponential learning rate decay (in 1000 steps)')
parser.add_argument("--chunk", type=int, default=1024*32,
help='number of rays processed in parallel, decrease if running out of memory')
parser.add_argument("--netchunk", type=int, default=1024*64,
help='number of pts sent through network in parallel, decrease if running out of memory')
parser.add_argument("--no_batching", action='store_true',
help='only take random rays from 1 image at a time')
parser.add_argument("--no_reload", action='store_true',
help='do not reload weights from saved ckpt')
parser.add_argument("--ft_path", type=str, default=None,
help='specific weights npy file to reload for coarse network')
# rendering options
parser.add_argument("--N_samples", type=int, default=64,
help='number of coarse samples per ray')
parser.add_argument("--N_importance", type=int, default=128,
help='number of additional fine samples per ray')
parser.add_argument("--perturb", type=float, default=1.,
help='set to 0. for no jitter, 1. for jitter')
parser.add_argument("--use_viewdirs", action='store_true',
help='use full 5D input instead of 3D')
parser.add_argument("--i_embed", type=int, default=0,
help='set 0 for default positional encoding, -1 for none')
parser.add_argument("--multires", type=int, default=10,
help='log2 of max freq for positional encoding (3D location)')
parser.add_argument("--multires_views", type=int, default=4,
help='log2 of max freq for positional encoding (2D direction)')
parser.add_argument("--raw_noise_std", type=float, default=0.,
help='std dev of noise added to regularize sigma_a output, 1e0 recommended')
parser.add_argument("--render_only", action='store_true',
help='do not optimize, reload weights and render out render_poses path')
parser.add_argument("--render_test", action='store_true',
help='render the test set instead of render_poses path')
parser.add_argument("--render_factor", type=int, default=0,
help='downsampling factor to speed up rendering, set 4 or 8 for fast preview')
# training options
parser.add_argument("--precrop_iters", type=int, default=0,
help='number of steps to train on central crops')
parser.add_argument("--precrop_frac", type=float,
default=.5, help='fraction of img taken for central crops')
# dataset options
parser.add_argument("--testskip", type=int, default=1,
help='will load 1/N images from test/val sets, useful for large datasets like deepvoxels')
## blender flags
parser.add_argument("--white_bkgd", action='store_true',
help='set to render synthetic data on a white bkgd (always use for dvoxels)')
# parser.add_argument('--white_bkgd', default= False, type=bool)
parser.add_argument("--half_res", action='store_true',
help='load blender synthetic data at 400x400 instead of 800x800')
## llff flags
parser.add_argument("--factor", type=int, default=8,
help='downsample factor for LLFF images')
parser.add_argument("--no_ndc", action='store_true',
help='do not use normalized device coordinates (set for non-forward facing scenes)')
parser.add_argument("--lindisp", action='store_true',
help='sampling linearly in disparity rather than depth')
parser.add_argument("--spherify", action='store_true',
help='set for spherical 360 scenes')
parser.add_argument("--llffhold", type=int, default=8,
help='will take every 1/N images as LLFF test set, paper uses 8')
# logging/saving options
parser.add_argument("--num_iterations", type=int, default=200000,
help='number of iterations for training')
parser.add_argument("--i_print", type=int, default=100,
help='frequency of console printout and metric loggin')
parser.add_argument("--i_img", type=int, default=600000,
help='frequency of tensorboard image logging')
parser.add_argument("--i_weights", type=int, default=100000,
help='frequency of weight ckpt saving')
parser.add_argument("--i_testset", type=int, default=500000,
help='frequency of testset saving')
parser.add_argument("--i_video", type=int, default=500000,
help='frequency of render_poses video saving')
### For PWL ###
parser.add_argument("--mode", type=str, default="constant",
help='rendering opacity aggregation mode -- whether to use piecewise constant (vanilla) or piecewise linear (reformulation)."')
parser.add_argument("--color_mode", type=str, default="midpoint",
help='rendering color aggregation mode -- whether to use left bin or midpoint."')
parser.add_argument('--quad_solution_v2', default= True, type=bool)
### Epsilon and zero tol in quadratic solution
parser.add_argument("--zero_tol", type=float, default=1e-4,
help='zero tol to revert to piecewise constant assumption')
parser.add_argument("--epsilon", type=float, default=1e-3,
help='epsilon value in the increasing and decreasing cases or max(x,epsilon)')
parser.add_argument('--set_near_plane', default= 2., type=float)
parser.add_argument('--farcolorfix', default= False, type=bool)
parser.add_argument("--constant_init", type=int, default=1000,
help='number of iterations to use constant aggregation')
parser.add_argument("--coarse_weight", type=float, default=1.0,
help='zero tol to revert to piecewise constant assumption')
parser.add_argument('--test_dist', default= 1.0, type=float)
parser.add_argument("--eval_scene_id", type=str, default="chair_rgba_fixdist_nv100_dist0.25-1.0-4_depth_sfn",
help='scene identifier for eval')
parser.add_argument("--eval_data_dir", type=str, default="../nerf_synthetic/fixed_dist_new-rgba/",
help='directory containing the scenes for eval')
### DTU flags
parser.add_argument("--dtu_scene_id", type=int, default=21,
help='scan id for DTU dataset to render')
parser.add_argument("--num_train", type=int, default=40,
help='number of training views to use (1 - 49)')
parser.add_argument("--dtu_split", type=str, default=None,
help='number of training views to use (1 - 49)')
##################
return parser
def train():
parser = config_parser()
args = parser.parse_args()
print(args.white_bkgd)
tmp_task = args.task
tmp_data_dir = args.data_dir
tmp_scene_id = args.scene_id
tmp_dataset = args.dataset
tmp_test_dist = args.test_dist
tmp_ckpt_dir = args.ckpt_dir
tmp_set_near_plane = args.set_near_plane
tmp_white_bkgd = args.white_bkgd
tmp_eval_scene_id = args.eval_scene_id
tmp_eval_data_dir = args.eval_data_dir
# tmp_white_bkgd = False
tmp_test_skip = args.testskip
# tmp_mode = args.mode
# tmp_N_samples = args.N_samples
# tmp_N_importance = args.N_importance
# load nerf parameters from training
args_file = os.path.join(args.ckpt_dir, args.expname, 'args.json')
with open(args_file, 'r') as af:
args_dict = json.load(af)
args = Namespace(**args_dict)
# task and paths are not overwritten
args.task = tmp_task
args.data_dir = tmp_data_dir
args.ckpt_dir = tmp_ckpt_dir
# args.mode = tmp_mode
args.train_jsonfile = 'transforms_train.json'
args.set_near_plane = tmp_set_near_plane
# args.N_samples = tmp_N_samples
# args.N_importance = tmp_N_importance
args.dataset = tmp_dataset
args.test_dist = tmp_test_dist
args.scene_id = tmp_scene_id
args.white_bkgd = tmp_white_bkgd
args.eval_scene_id = tmp_eval_scene_id
args.eval_data_dir = tmp_eval_data_dir
args.testskip = tmp_test_skip
print('\n'.join(f'{k}={v}' for k, v in vars(args).items()))
args.n_gpus = torch.cuda.device_count()
print(f"Using {args.n_gpus} GPU(s).")
# Load data
scene_data_dir = os.path.join(args.data_dir, args.scene_id)
K = None
if args.dataset == 'llff':
images, poses, bds, render_poses, i_test = load_llff_data(scene_data_dir, args.factor,
recenter=True, bd_factor=.75,
spherify=args.spherify)
hwf = poses[0,:3,-1]
poses = poses[:,:3,:4]
print('Loaded llff', images.shape, render_poses.shape, hwf, scene_data_dir)
if not isinstance(i_test, list):
i_test = [i_test]
if args.llffhold > 0:
print('Auto LLFF holdout,', args.llffhold)
i_test = np.arange(images.shape[0])[::args.llffhold]
i_val = i_test
i_train = np.array([i for i in np.arange(int(images.shape[0])) if
(i not in i_test and i not in i_val)])
print('DEFINING BOUNDS')
if args.no_ndc:
near = np.ndarray.min(bds) * .9
far = np.ndarray.max(bds) * 1.
else:
near = 0.
far = 1.
print('NEAR FAR', near, far)
elif args.dataset == 'blender':
images, poses, render_poses, hwf, i_split = load_blender_data(scene_data_dir, args.half_res, args.testskip)
print('Loaded blender', images.shape, render_poses.shape, hwf, scene_data_dir)
i_train, i_val, i_test = i_split
# near = 2.
near = args.set_near_plane
print("Set near plane to: " + str(near))
far = 6.
if args.white_bkgd:
images = images[...,:3]*images[...,-1:] + (1.-images[...,-1:])
else:
images = images[...,:3]
elif args.dataset == "blender2": | images, poses, render_poses, hwf, i_split = load_scene_blender2(scene_data_dir, half_res=args.half_res) | 3 | 2023-10-30 06:38:00+00:00 | 8k |
sehyunkwon/ICTC | step1/llava/model/language_model/mpt/modeling_mpt.py | [
{
"identifier": "attn_bias_shape",
"path": "step1/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 ... | 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,796 | """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-27 05:00:14+00:00 | 8k |
Trustworthy-AI-Group/TransferAttack | transferattack/model_related/dhf.py | [
{
"identifier": "dhf_inception_v3",
"path": "transferattack/model_related/dhf_networks/inception.py",
"snippet": "def dhf_inception_v3(mixup_weight_max: float, random_keep_prob: float, dhf_modules = None, weights: Optional[Inception_V3_Weights] = None, progress: bool = True, **kwargs: Any) -> Inception3... | from torch import Tensor
from ..utils import *
from .dhf_networks.inception import dhf_inception_v3
from .dhf_networks.inc_res_v2 import dhf_inc_res_v2
from .dhf_networks.resnet import dhf_resnet18, dhf_resnet50, dhf_resnet101, dhf_resnet152
from ..gradient.mifgsm import MIFGSM
from ..gradient.nifgsm import NIFGSM
from ..input_transformation.dim import DIM
from ..input_transformation.tim import TIM
from ..input_transformation.sim import SIM
from ..input_transformation.admix import Admix
from .dhf_networks import utils | 4,891 | # example bash: python main.py --attack=mifgsm_dhf
support_models = {
"inc_v3": dhf_inception_v3,
"inc_res": dhf_inc_res_v2,
'resnet18': dhf_resnet18,
"resnet50": dhf_resnet50,
"resnet101": dhf_resnet101,
| # example bash: python main.py --attack=mifgsm_dhf
support_models = {
"inc_v3": dhf_inception_v3,
"inc_res": dhf_inc_res_v2,
'resnet18': dhf_resnet18,
"resnet50": dhf_resnet50,
"resnet101": dhf_resnet101, | "resnet152": dhf_resnet152, | 5 | 2023-10-31 03:43:26+00:00 | 8k |
phineas-pta/comfy-trt-test | convert_unet.py | [
{
"identifier": "export_onnx",
"path": "comfy_trt/exporter.py",
"snippet": "def export_onnx(onnx_path: str, modelobj: UNetModel, profile: ProfileSettings, opset: int = 17, disable_optimizations: bool = False):\n\tlogging.info(\"Exporting to ONNX...\")\n\tinputs = modelobj.get_sample_input(profile.bs_opt... | import argparse
import sys
import os.path
import gc
import torch
from comfy_trt.exporter import export_onnx, export_trt
from comfy_trt.model_helper import UNetModel
from comfy_trt.model_manager import modelmanager, cc_major
from comfy_trt.datastructures import ProfileSettings
from comfy.utils import load_torch_file, calculate_parameters
from comfy.supported_models import models as LIST_MODELS
from comfy.model_detection import detect_unet_config
from comfy.model_management import unet_dtype as get_unet_dtype | 4,667 | # -*- coding: utf-8 -*-
# modified from https://github.com/NVIDIA/Stable-Diffusion-WebUI-TensorRT/blob/main/ui_trt.py
# CHANGE: remove lora, make script as CLI command
# STATUS: ok i guess
sys.path.append(os.path.join("..", ".."))
def parseArgs():
parser = argparse.ArgumentParser(description="test: convert Stable Diffusion checkpoint to TensorRT engine")
parser.add_argument("--ckpt_path", required=True)
parser.add_argument("--output_name", help=".onnx & .trt file name, default to ckpt file name")
parser.add_argument("--batch_min", type=int, default=1, help="default 1")
parser.add_argument("--batch_opt", type=int, default=1, help="default 1")
parser.add_argument("--batch_max", type=int, default=1, help="limit 16")
parser.add_argument("--height_min", type=int, help="default 768 if sdxl else 512, limit 256")
parser.add_argument("--height_opt", type=int, help="default 1024 if sdxl else 512")
parser.add_argument("--height_max", type=int, help="default 1024 if sdxl else 768, limit 4096")
parser.add_argument("--width_min", type=int, help="default 768 if sdxl else 512, limit 256")
parser.add_argument("--width_opt", type=int, help="default 768 if sdxl else 512")
parser.add_argument("--width_max", type=int, help="default 1024 if sdxl else 768, limit 4096")
parser.add_argument("--token_count_min", type=int, default=75, help="default 75, cannot go lower")
parser.add_argument("--token_count_opt", type=int, default=75, help="default 75")
parser.add_argument("--token_count_max", type=int, default=150, help="default 150, limit 750")
parser.add_argument("--force_export", action="store_true")
parser.add_argument("--static_shapes", action="store_true", help="may cause weird error (?) if enable")
parser.add_argument("--float32", action="store_true")
return parser.parse_args()
def get_config_from_checkpoint(ckpt_path: str) -> dict:
"""see comfy/sd.py >>> load_checkpoint_guess_config"""
tmp0 = "model.diffusion_model."
sd = load_torch_file(ckpt_path)
parameters = calculate_parameters(sd, tmp0)
unet_dtype = get_unet_dtype(model_params=parameters)
unet_config = detect_unet_config(sd, tmp0, unet_dtype)
for model_config in LIST_MODELS:
if model_config.matches(unet_config):
tmp1 = model_config(unet_config)
model = tmp1.get_model(sd, tmp0, device="cuda")
model.load_model_weights(sd, tmp0)
return {
"model": model.diffusion_model,
"baseline_model": model_config.__qualname__,
"prediction_type": str(model.model_type),
"unet_hidden_dim": unet_config["in_channels"],
"embedding_dim": unet_config["context_dim"],
}
if __name__ == "__main__":
args = parseArgs()
ckpt_config = get_config_from_checkpoint(args.ckpt_path)
if cc_major < 7:
args.float32 = True
print("FP16 has been disabled because your GPU does not support it.")
baseline_model = ckpt_config["baseline_model"]
print(f"\ndetected baseline model version: {baseline_model}")
is_sdxl = baseline_model in ["SDXL", "SDXLRefiner", "SSD1B", "Segmind_Vega"] # re-used later
if is_sdxl:
if args.height_min is None: args.height_min = 768
if args.height_opt is None: args.height_opt = 1024
if args.height_max is None: args.height_max = 1024
if args.width_min is None: args.width_min = 768
if args.width_opt is None: args.width_opt = 1024
if args.width_max is None: args.width_max = 1024
elif baseline_model in ["SD15", "SD20", "SD21UnclipL", "SD21UnclipH"]:
if args.height_min is None: args.height_min = 512
if args.height_opt is None: args.height_opt = 512
if args.height_max is None: args.height_max = 768
if args.width_min is None: args.width_min = 512
if args.width_opt is None: args.width_opt = 512
if args.width_max is None: args.width_max = 768
else: # ["SVD_img2vid", "Stable_Zero123", "SD_X4Upscaler"]
raise ValueError(f"{baseline_model} not yet supported")
if args.height_min % 64 != 0 or args.height_opt % 64 != 0 or args.height_max % 64 != 0 or args.width_min % 64 != 0 or args.width_opt % 64 != 0 or args.width_max % 64 != 0:
raise ValueError("height and width must be divisible by 64")
if not (args.height_min <= args.height_opt <= args.height_max and args.width_min <= args.width_opt <= args.width_max):
raise ValueError("need min ≤ opt ≤ max")
if args.height_min < 256 or args.height_max > 4096 or args.width_min < 256 or args.width_max > 4096:
raise ValueError("height and width out of limit")
ckpt_file = os.path.basename(args.ckpt_path)
if args.output_name is None: # default to ckpt file name
args.output_name = os.path.splitext(ckpt_file)[0]
onnx_filename, onnx_path = modelmanager.get_onnx_path(args.output_name)
print(f"Exporting {ckpt_file} to TensorRT")
timing_cache = modelmanager.get_timing_cache()
profile_settings = ProfileSettings(
args.batch_min, args.batch_opt, args.batch_max,
args.height_min, args.height_opt, args.height_max,
args.width_min, args.width_opt, args.width_max,
args.token_count_min, args.token_count_opt, args.token_count_max,
args.static_shapes
)
print(profile_settings, end="\n\n")
profile_settings.token_to_dim()
| # -*- coding: utf-8 -*-
# modified from https://github.com/NVIDIA/Stable-Diffusion-WebUI-TensorRT/blob/main/ui_trt.py
# CHANGE: remove lora, make script as CLI command
# STATUS: ok i guess
sys.path.append(os.path.join("..", ".."))
def parseArgs():
parser = argparse.ArgumentParser(description="test: convert Stable Diffusion checkpoint to TensorRT engine")
parser.add_argument("--ckpt_path", required=True)
parser.add_argument("--output_name", help=".onnx & .trt file name, default to ckpt file name")
parser.add_argument("--batch_min", type=int, default=1, help="default 1")
parser.add_argument("--batch_opt", type=int, default=1, help="default 1")
parser.add_argument("--batch_max", type=int, default=1, help="limit 16")
parser.add_argument("--height_min", type=int, help="default 768 if sdxl else 512, limit 256")
parser.add_argument("--height_opt", type=int, help="default 1024 if sdxl else 512")
parser.add_argument("--height_max", type=int, help="default 1024 if sdxl else 768, limit 4096")
parser.add_argument("--width_min", type=int, help="default 768 if sdxl else 512, limit 256")
parser.add_argument("--width_opt", type=int, help="default 768 if sdxl else 512")
parser.add_argument("--width_max", type=int, help="default 1024 if sdxl else 768, limit 4096")
parser.add_argument("--token_count_min", type=int, default=75, help="default 75, cannot go lower")
parser.add_argument("--token_count_opt", type=int, default=75, help="default 75")
parser.add_argument("--token_count_max", type=int, default=150, help="default 150, limit 750")
parser.add_argument("--force_export", action="store_true")
parser.add_argument("--static_shapes", action="store_true", help="may cause weird error (?) if enable")
parser.add_argument("--float32", action="store_true")
return parser.parse_args()
def get_config_from_checkpoint(ckpt_path: str) -> dict:
"""see comfy/sd.py >>> load_checkpoint_guess_config"""
tmp0 = "model.diffusion_model."
sd = load_torch_file(ckpt_path)
parameters = calculate_parameters(sd, tmp0)
unet_dtype = get_unet_dtype(model_params=parameters)
unet_config = detect_unet_config(sd, tmp0, unet_dtype)
for model_config in LIST_MODELS:
if model_config.matches(unet_config):
tmp1 = model_config(unet_config)
model = tmp1.get_model(sd, tmp0, device="cuda")
model.load_model_weights(sd, tmp0)
return {
"model": model.diffusion_model,
"baseline_model": model_config.__qualname__,
"prediction_type": str(model.model_type),
"unet_hidden_dim": unet_config["in_channels"],
"embedding_dim": unet_config["context_dim"],
}
if __name__ == "__main__":
args = parseArgs()
ckpt_config = get_config_from_checkpoint(args.ckpt_path)
if cc_major < 7:
args.float32 = True
print("FP16 has been disabled because your GPU does not support it.")
baseline_model = ckpt_config["baseline_model"]
print(f"\ndetected baseline model version: {baseline_model}")
is_sdxl = baseline_model in ["SDXL", "SDXLRefiner", "SSD1B", "Segmind_Vega"] # re-used later
if is_sdxl:
if args.height_min is None: args.height_min = 768
if args.height_opt is None: args.height_opt = 1024
if args.height_max is None: args.height_max = 1024
if args.width_min is None: args.width_min = 768
if args.width_opt is None: args.width_opt = 1024
if args.width_max is None: args.width_max = 1024
elif baseline_model in ["SD15", "SD20", "SD21UnclipL", "SD21UnclipH"]:
if args.height_min is None: args.height_min = 512
if args.height_opt is None: args.height_opt = 512
if args.height_max is None: args.height_max = 768
if args.width_min is None: args.width_min = 512
if args.width_opt is None: args.width_opt = 512
if args.width_max is None: args.width_max = 768
else: # ["SVD_img2vid", "Stable_Zero123", "SD_X4Upscaler"]
raise ValueError(f"{baseline_model} not yet supported")
if args.height_min % 64 != 0 or args.height_opt % 64 != 0 or args.height_max % 64 != 0 or args.width_min % 64 != 0 or args.width_opt % 64 != 0 or args.width_max % 64 != 0:
raise ValueError("height and width must be divisible by 64")
if not (args.height_min <= args.height_opt <= args.height_max and args.width_min <= args.width_opt <= args.width_max):
raise ValueError("need min ≤ opt ≤ max")
if args.height_min < 256 or args.height_max > 4096 or args.width_min < 256 or args.width_max > 4096:
raise ValueError("height and width out of limit")
ckpt_file = os.path.basename(args.ckpt_path)
if args.output_name is None: # default to ckpt file name
args.output_name = os.path.splitext(ckpt_file)[0]
onnx_filename, onnx_path = modelmanager.get_onnx_path(args.output_name)
print(f"Exporting {ckpt_file} to TensorRT")
timing_cache = modelmanager.get_timing_cache()
profile_settings = ProfileSettings(
args.batch_min, args.batch_opt, args.batch_max,
args.height_min, args.height_opt, args.height_max,
args.width_min, args.width_opt, args.width_max,
args.token_count_min, args.token_count_opt, args.token_count_max,
args.static_shapes
)
print(profile_settings, end="\n\n")
profile_settings.token_to_dim()
| modelobj = UNetModel( | 2 | 2023-10-25 23:58:12+00:00 | 8k |
hydrogram/hydrogram | hydrogram/dispatcher.py | [
{
"identifier": "utils",
"path": "hydrogram/utils.py",
"snippet": "async def ainput(prompt: str = \"\", *, hide: bool = False):\ndef get_input_media_from_file_id(\n file_id: str, expected_file_type: FileType = None, ttl_seconds: Optional[int] = None\n) -> Union[\"raw.types.InputMediaPhoto\", \"raw.ty... | import asyncio
import inspect
import logging
import hydrogram
from collections import OrderedDict
from hydrogram import utils
from hydrogram.handlers import (
CallbackQueryHandler,
ChatJoinRequestHandler,
ChatMemberUpdatedHandler,
ChosenInlineResultHandler,
DeletedMessagesHandler,
EditedMessageHandler,
InlineQueryHandler,
MessageHandler,
PollHandler,
RawUpdateHandler,
UserStatusHandler,
)
from hydrogram.raw.types import (
UpdateBotCallbackQuery,
UpdateBotChatInviteRequester,
UpdateBotInlineQuery,
UpdateBotInlineSend,
UpdateChannelParticipant,
UpdateChatParticipant,
UpdateDeleteChannelMessages,
UpdateDeleteMessages,
UpdateEditChannelMessage,
UpdateEditMessage,
UpdateInlineBotCallbackQuery,
UpdateMessagePoll,
UpdateNewChannelMessage,
UpdateNewMessage,
UpdateNewScheduledMessage,
UpdateUserStatus,
) | 6,938 | # Hydrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2023 Dan <https://github.com/delivrance>
# Copyright (C) 2023-present Hydrogram <https://hydrogram.org>
#
# This file is part of Hydrogram.
#
# Hydrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Hydrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class Dispatcher:
NEW_MESSAGE_UPDATES = (
UpdateNewMessage,
UpdateNewChannelMessage,
UpdateNewScheduledMessage,
)
EDIT_MESSAGE_UPDATES = (UpdateEditMessage, UpdateEditChannelMessage)
DELETE_MESSAGES_UPDATES = (UpdateDeleteMessages, UpdateDeleteChannelMessages)
CALLBACK_QUERY_UPDATES = (UpdateBotCallbackQuery, UpdateInlineBotCallbackQuery)
CHAT_MEMBER_UPDATES = (UpdateChatParticipant, UpdateChannelParticipant)
USER_STATUS_UPDATES = (UpdateUserStatus,)
BOT_INLINE_QUERY_UPDATES = (UpdateBotInlineQuery,)
POLL_UPDATES = (UpdateMessagePoll,)
CHOSEN_INLINE_RESULT_UPDATES = (UpdateBotInlineSend,)
CHAT_JOIN_REQUEST_UPDATES = (UpdateBotChatInviteRequester,)
def __init__(self, client: "hydrogram.Client"):
self.client = client
self.loop = asyncio.get_event_loop()
self.handler_worker_tasks = []
self.locks_list = []
self.updates_queue = asyncio.Queue()
self.groups = OrderedDict()
async def message_parser(update, users, chats):
return (
await hydrogram.types.Message._parse(
client=self.client,
message=update.message,
users=users,
chats=chats,
is_scheduled=isinstance(update, UpdateNewScheduledMessage),
),
MessageHandler,
)
async def edited_message_parser(update, users, chats):
# Edited messages are parsed the same way as new messages, but the handler is different
parsed, _ = await message_parser(update, users, chats)
return (parsed, EditedMessageHandler)
async def deleted_messages_parser(update, users, chats):
return (
| # Hydrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2023 Dan <https://github.com/delivrance>
# Copyright (C) 2023-present Hydrogram <https://hydrogram.org>
#
# This file is part of Hydrogram.
#
# Hydrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Hydrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class Dispatcher:
NEW_MESSAGE_UPDATES = (
UpdateNewMessage,
UpdateNewChannelMessage,
UpdateNewScheduledMessage,
)
EDIT_MESSAGE_UPDATES = (UpdateEditMessage, UpdateEditChannelMessage)
DELETE_MESSAGES_UPDATES = (UpdateDeleteMessages, UpdateDeleteChannelMessages)
CALLBACK_QUERY_UPDATES = (UpdateBotCallbackQuery, UpdateInlineBotCallbackQuery)
CHAT_MEMBER_UPDATES = (UpdateChatParticipant, UpdateChannelParticipant)
USER_STATUS_UPDATES = (UpdateUserStatus,)
BOT_INLINE_QUERY_UPDATES = (UpdateBotInlineQuery,)
POLL_UPDATES = (UpdateMessagePoll,)
CHOSEN_INLINE_RESULT_UPDATES = (UpdateBotInlineSend,)
CHAT_JOIN_REQUEST_UPDATES = (UpdateBotChatInviteRequester,)
def __init__(self, client: "hydrogram.Client"):
self.client = client
self.loop = asyncio.get_event_loop()
self.handler_worker_tasks = []
self.locks_list = []
self.updates_queue = asyncio.Queue()
self.groups = OrderedDict()
async def message_parser(update, users, chats):
return (
await hydrogram.types.Message._parse(
client=self.client,
message=update.message,
users=users,
chats=chats,
is_scheduled=isinstance(update, UpdateNewScheduledMessage),
),
MessageHandler,
)
async def edited_message_parser(update, users, chats):
# Edited messages are parsed the same way as new messages, but the handler is different
parsed, _ = await message_parser(update, users, chats)
return (parsed, EditedMessageHandler)
async def deleted_messages_parser(update, users, chats):
return ( | utils.parse_deleted_messages(self.client, update), | 0 | 2023-10-29 16:16:37+00:00 | 8k |
iwatake2222/rotop | src/rotop/gui_main.py | [
{
"identifier": "DataContainer",
"path": "src/rotop/data_container.py",
"snippet": "class DataContainer:\n MAX_ROW_CSV = 600\n MAX_NUM_HISTORY = 100\n\n def __init__(self, write_csv=False):\n now = datetime.datetime.now()\n if write_csv:\n self.csv_dir_name = now.strftime('./rotop_%Y%m%d_%... | import pandas as pd
import threading
import time
import dearpygui.dearpygui as dpg
from .data_container import DataContainer
from .top_runner import TopRunner
from .utility import create_logger | 4,806 |
def exit(self):
self.is_exit = True
def start_dpg(self):
dpg.create_context()
dpg.create_viewport(title='rotop', width=800, height=600)
dpg.setup_dearpygui()
with dpg.window(label='window', no_collapse=True, no_title_bar=True, no_move=True, no_resize=True) as self.dpg_window_id:
with dpg.group(horizontal=True):
self.dpg_button_cpumem = dpg.add_button(label='CPU/MEM', callback=self.cb_button_cpumem)
self.dpg_button_reset = dpg.add_button(label='RESET', callback=self.cb_button_reset)
self.dpg_button_pause = dpg.add_button(label='PAUSE', callback=self.cb_button_pause)
dpg.add_text('Help(?)')
with dpg.tooltip(dpg.last_item()):
dpg.add_text('- CLick "Reset" to clear graph and history.')
with dpg.plot(label=self.get_plot_title(), use_local_time=True, no_title=True) as self.dpg_plot_id:
self.dpg_plot_axis_x_id = dpg.add_plot_axis(dpg.mvXAxis, label='datetime', time=True)
self.dpg_text = dpg.add_text()
dpg.set_viewport_resize_callback(self.cb_resize)
self.cb_resize(None, [None, None, dpg.get_viewport_width(), dpg.get_viewport_height()])
dpg.show_viewport()
# Manually control FPS (10fps), otherwise FPS becomes very high, which causes high CPU load
# dpg.start_dearpygui()
while dpg.is_dearpygui_running() and not self.is_exit:
time.sleep(0.1)
dpg.render_dearpygui_frame()
dpg.destroy_context()
def get_plot_title(self):
return 'CPU [%]' if self.plot_is_cpu else 'MEM [%]'
def cb_button_cpumem(self, sender, app_data, user_data):
self.plot_is_cpu = not self.plot_is_cpu
dpg.set_item_label(self.dpg_plot_id, self.get_plot_title())
def cb_button_reset(self, sender, app_data, user_data):
global g_reset_history_df
g_reset_history_df = True
self.color_dict = {}
self.theme_dict = {}
def cb_button_pause(self, sender, app_data, user_data):
self.pause = not self.pause
def cb_resize(self, sender, app_data):
window_width = app_data[2]
window_height = app_data[3]
dpg.set_item_width(self.dpg_window_id, window_width)
dpg.set_item_height(self.dpg_window_id, window_height)
dpg.set_item_width(self.dpg_plot_id, window_width)
dpg.set_item_height(self.dpg_plot_id, window_height / 2)
def update_gui(self, result_lines:list[str], df_cpu_history:pd.DataFrame, df_mem_history:pd.DataFrame):
if self.pause:
return
if self.dpg_plot_axis_y_id:
dpg.delete_item(self.dpg_plot_axis_y_id)
self.dpg_plot_axis_y_id = dpg.add_plot_axis(dpg.mvYAxis, label=self.get_plot_title(), lock_min=True, parent=self.dpg_plot_id)
df = df_cpu_history if self.plot_is_cpu else df_mem_history
col_x = df.columns[0]
cols_y = df.columns[1:]
x = df[col_x].to_list()
for col_y in cols_y:
y = df[col_y].to_list()
line_series = dpg.add_line_series(x, y, label=col_y[:min(40, len(col_y))].ljust(40), parent=self.dpg_plot_axis_y_id)
theme = self.get_theme(col_y)
dpg.bind_item_theme(line_series, theme)
if self.plot_is_cpu:
dpg.add_line_series([x[0]], [110], label='', parent=self.dpg_plot_axis_y_id) # dummy for ymax>=100
dpg.add_plot_legend(parent=self.dpg_plot_id, outside=True, location=dpg.mvPlot_Location_NorthEast)
dpg.fit_axis_data(self.dpg_plot_axis_x_id)
dpg.fit_axis_data(self.dpg_plot_axis_y_id)
dpg.set_value(self.dpg_text, '\n'.join(result_lines))
def get_color(self, process_name)->tuple[int]:
# return (0, 0, 0)
if process_name in self.color_dict:
return self.color_dict[process_name]
else:
color = COLOR_MAP[len(self.color_dict)%len(COLOR_MAP)]
self.color_dict[process_name] = color
return color
def get_theme(self, process_name):
if process_name in self.theme_dict:
return self.theme_dict[process_name]
else:
with dpg.theme() as theme:
with dpg.theme_component(dpg.mvLineSeries):
dpg.add_theme_color(dpg.mvPlotCol_Line, self.get_color(process_name), category=dpg.mvThemeCat_Plots)
self.theme_dict[process_name] = theme
return theme
def gui_loop(view: GuiView):
view.start_dpg()
def gui_main(args):
global g_reset_history_df
top_runner = TopRunner(args.interval, args.filter)
| # Copyright 2023 iwatake2222
#
# 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.
from __future__ import annotations
logger = create_logger(__name__, log_filename='rotop.log')
g_reset_history_df = False # todo: add lock
COLOR_MAP = (
# matplotlib.cm.tab20
(31, 119, 180),
(174, 199, 232),
(256, 127, 14),
(256, 187, 120),
(44, 160, 44),
(152, 223, 138),
(214, 39, 40),
(256, 152, 150),
(148, 103, 189),
(197, 176, 213),
(140, 86, 75),
(196, 156, 148),
(227, 119, 194),
(247, 182, 210),
(127, 127, 127),
(199, 199, 199),
(188, 189, 34),
(219, 219, 141),
(23, 190, 207),
(158, 218, 229),
# matplotlib.cm.tab20b
(57, 59, 121),
(82, 84, 163),
(107, 110, 207),
(156, 158, 222),
(99, 121, 57),
(140, 162, 82),
(181, 207, 107),
(206, 219, 156),
(140, 109, 49),
(189, 158, 57),
(231, 186, 82),
(231, 203, 148),
(132, 60, 57),
(173, 73, 74),
(214, 97, 107),
(231, 150, 156),
(123, 65, 115),
(165, 81, 148),
(206, 109, 189),
(222, 158, 214),
)
class GuiView:
def __init__(self):
self.is_exit = False
self.pause = False # todo: add lock
self.plot_is_cpu = True
self.dpg_plot_axis_x_id = None
self.dpg_plot_axis_y_id = None
self.color_dict = {}
self.theme_dict = {}
def exit(self):
self.is_exit = True
def start_dpg(self):
dpg.create_context()
dpg.create_viewport(title='rotop', width=800, height=600)
dpg.setup_dearpygui()
with dpg.window(label='window', no_collapse=True, no_title_bar=True, no_move=True, no_resize=True) as self.dpg_window_id:
with dpg.group(horizontal=True):
self.dpg_button_cpumem = dpg.add_button(label='CPU/MEM', callback=self.cb_button_cpumem)
self.dpg_button_reset = dpg.add_button(label='RESET', callback=self.cb_button_reset)
self.dpg_button_pause = dpg.add_button(label='PAUSE', callback=self.cb_button_pause)
dpg.add_text('Help(?)')
with dpg.tooltip(dpg.last_item()):
dpg.add_text('- CLick "Reset" to clear graph and history.')
with dpg.plot(label=self.get_plot_title(), use_local_time=True, no_title=True) as self.dpg_plot_id:
self.dpg_plot_axis_x_id = dpg.add_plot_axis(dpg.mvXAxis, label='datetime', time=True)
self.dpg_text = dpg.add_text()
dpg.set_viewport_resize_callback(self.cb_resize)
self.cb_resize(None, [None, None, dpg.get_viewport_width(), dpg.get_viewport_height()])
dpg.show_viewport()
# Manually control FPS (10fps), otherwise FPS becomes very high, which causes high CPU load
# dpg.start_dearpygui()
while dpg.is_dearpygui_running() and not self.is_exit:
time.sleep(0.1)
dpg.render_dearpygui_frame()
dpg.destroy_context()
def get_plot_title(self):
return 'CPU [%]' if self.plot_is_cpu else 'MEM [%]'
def cb_button_cpumem(self, sender, app_data, user_data):
self.plot_is_cpu = not self.plot_is_cpu
dpg.set_item_label(self.dpg_plot_id, self.get_plot_title())
def cb_button_reset(self, sender, app_data, user_data):
global g_reset_history_df
g_reset_history_df = True
self.color_dict = {}
self.theme_dict = {}
def cb_button_pause(self, sender, app_data, user_data):
self.pause = not self.pause
def cb_resize(self, sender, app_data):
window_width = app_data[2]
window_height = app_data[3]
dpg.set_item_width(self.dpg_window_id, window_width)
dpg.set_item_height(self.dpg_window_id, window_height)
dpg.set_item_width(self.dpg_plot_id, window_width)
dpg.set_item_height(self.dpg_plot_id, window_height / 2)
def update_gui(self, result_lines:list[str], df_cpu_history:pd.DataFrame, df_mem_history:pd.DataFrame):
if self.pause:
return
if self.dpg_plot_axis_y_id:
dpg.delete_item(self.dpg_plot_axis_y_id)
self.dpg_plot_axis_y_id = dpg.add_plot_axis(dpg.mvYAxis, label=self.get_plot_title(), lock_min=True, parent=self.dpg_plot_id)
df = df_cpu_history if self.plot_is_cpu else df_mem_history
col_x = df.columns[0]
cols_y = df.columns[1:]
x = df[col_x].to_list()
for col_y in cols_y:
y = df[col_y].to_list()
line_series = dpg.add_line_series(x, y, label=col_y[:min(40, len(col_y))].ljust(40), parent=self.dpg_plot_axis_y_id)
theme = self.get_theme(col_y)
dpg.bind_item_theme(line_series, theme)
if self.plot_is_cpu:
dpg.add_line_series([x[0]], [110], label='', parent=self.dpg_plot_axis_y_id) # dummy for ymax>=100
dpg.add_plot_legend(parent=self.dpg_plot_id, outside=True, location=dpg.mvPlot_Location_NorthEast)
dpg.fit_axis_data(self.dpg_plot_axis_x_id)
dpg.fit_axis_data(self.dpg_plot_axis_y_id)
dpg.set_value(self.dpg_text, '\n'.join(result_lines))
def get_color(self, process_name)->tuple[int]:
# return (0, 0, 0)
if process_name in self.color_dict:
return self.color_dict[process_name]
else:
color = COLOR_MAP[len(self.color_dict)%len(COLOR_MAP)]
self.color_dict[process_name] = color
return color
def get_theme(self, process_name):
if process_name in self.theme_dict:
return self.theme_dict[process_name]
else:
with dpg.theme() as theme:
with dpg.theme_component(dpg.mvLineSeries):
dpg.add_theme_color(dpg.mvPlotCol_Line, self.get_color(process_name), category=dpg.mvThemeCat_Plots)
self.theme_dict[process_name] = theme
return theme
def gui_loop(view: GuiView):
view.start_dpg()
def gui_main(args):
global g_reset_history_df
top_runner = TopRunner(args.interval, args.filter) | data_container = DataContainer(args.csv) | 0 | 2023-10-30 22:21:05+00:00 | 8k |
chenruduan/OAReactDiff | oa_reactdiff/tests/model/test_equiv.py | [
{
"identifier": "EGNN",
"path": "oa_reactdiff/model/egnn.py",
"snippet": "class EGNN(nn.Module):\n def __init__(\n self,\n in_node_nf: int = 8,\n in_edge_nf: int = 2,\n hidden_nf: int = 256,\n edge_hidden_nf: int = 32,\n act_fn: str = \"swish\",\n n_la... | import unittest
import torch
import numpy as np
from pytorch_lightning import seed_everything
from oa_reactdiff.model import EGNN, LEFTNet
from .utils import tensor_relative_diff, egnn_config, init_weights, left_config | 5,581 | """Test model forward pass and equivariance."""
default_float = torch.float64
torch.set_default_dtype(default_float)
EPS = 1e-8
TIGHT_EPS = 1e-8
theta = 0.4
alpha = 0.9
seed_everything(42, workers=True)
def com(x):
return x - torch.mean(x, dim=0)
class TestModel(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.egnn = EGNN(**egnn_config)
cls.leftnet = LEFTNet(**left_config)
cls.edge_index = torch.tensor(
[[0, 1, 1, 2, 3, 0], [1, 0, 2, 1, 0, 3]], dtype=torch.long
)
cls.h = torch.rand(4, egnn_config["in_node_nf"])
cls.pos = torch.rand(4, 3)
cls.edge_attr = torch.rand(cls.edge_index.size(1), egnn_config["in_edge_nf"])
egnn_config.update({"reflect_equiv": False})
cls.egnn_no_reflect_equiv = EGNN(**egnn_config)
egnn_config.update({"reflect_equiv": True})
left_config.update({"reflect_equiv": False})
cls.leftnet_no_reflect_equiv = LEFTNet(**left_config)
left_config.update({"reflect_equiv": True})
egnn_config["in_edge_nf"] = 0
cls.egnn_no_edge_attr = EGNN(**egnn_config)
cls.edge_attr_zeros = torch.rand(
cls.edge_index.size(1), egnn_config["in_edge_nf"]
)
cls.edge_attr_null = None
rot_x = torch.tensor(
[
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)],
],
dtype=default_float,
)
rot_y = torch.tensor(
[
[np.cos(alpha), 0, np.sin(alpha)],
[0, 1, 0],
[-np.sin(alpha), 0, np.cos(alpha)],
],
dtype=default_float,
)
cls.rot = torch.matmul(rot_y, rot_x).double()
cls.trans = torch.rand(3) * 100
cls.egnn.apply(init_weights)
cls.egnn_no_edge_attr.apply(init_weights)
cls.leftnet.apply(init_weights)
cls.models = [cls.egnn, cls.leftnet]
cls.models_no_edge_attr = [cls.egnn_no_edge_attr, cls.leftnet]
cls.models_no_reflect_equiv = [
cls.egnn_no_reflect_equiv,
cls.leftnet_no_reflect_equiv,
]
def test_rotation(self):
for model in self.models:
_h, _pos, _edge_attr = model.forward(
self.h, self.pos, self.edge_index, self.edge_attr
)
_h_rot, _pos_rot, _edge_attr_rot = model.forward(
self.h,
torch.matmul(self.pos, self.rot).double(),
self.edge_index,
self.edge_attr,
)
| """Test model forward pass and equivariance."""
default_float = torch.float64
torch.set_default_dtype(default_float)
EPS = 1e-8
TIGHT_EPS = 1e-8
theta = 0.4
alpha = 0.9
seed_everything(42, workers=True)
def com(x):
return x - torch.mean(x, dim=0)
class TestModel(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.egnn = EGNN(**egnn_config)
cls.leftnet = LEFTNet(**left_config)
cls.edge_index = torch.tensor(
[[0, 1, 1, 2, 3, 0], [1, 0, 2, 1, 0, 3]], dtype=torch.long
)
cls.h = torch.rand(4, egnn_config["in_node_nf"])
cls.pos = torch.rand(4, 3)
cls.edge_attr = torch.rand(cls.edge_index.size(1), egnn_config["in_edge_nf"])
egnn_config.update({"reflect_equiv": False})
cls.egnn_no_reflect_equiv = EGNN(**egnn_config)
egnn_config.update({"reflect_equiv": True})
left_config.update({"reflect_equiv": False})
cls.leftnet_no_reflect_equiv = LEFTNet(**left_config)
left_config.update({"reflect_equiv": True})
egnn_config["in_edge_nf"] = 0
cls.egnn_no_edge_attr = EGNN(**egnn_config)
cls.edge_attr_zeros = torch.rand(
cls.edge_index.size(1), egnn_config["in_edge_nf"]
)
cls.edge_attr_null = None
rot_x = torch.tensor(
[
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)],
],
dtype=default_float,
)
rot_y = torch.tensor(
[
[np.cos(alpha), 0, np.sin(alpha)],
[0, 1, 0],
[-np.sin(alpha), 0, np.cos(alpha)],
],
dtype=default_float,
)
cls.rot = torch.matmul(rot_y, rot_x).double()
cls.trans = torch.rand(3) * 100
cls.egnn.apply(init_weights)
cls.egnn_no_edge_attr.apply(init_weights)
cls.leftnet.apply(init_weights)
cls.models = [cls.egnn, cls.leftnet]
cls.models_no_edge_attr = [cls.egnn_no_edge_attr, cls.leftnet]
cls.models_no_reflect_equiv = [
cls.egnn_no_reflect_equiv,
cls.leftnet_no_reflect_equiv,
]
def test_rotation(self):
for model in self.models:
_h, _pos, _edge_attr = model.forward(
self.h, self.pos, self.edge_index, self.edge_attr
)
_h_rot, _pos_rot, _edge_attr_rot = model.forward(
self.h,
torch.matmul(self.pos, self.rot).double(),
self.edge_index,
self.edge_attr,
)
| print(tensor_relative_diff(_h, _h_rot)) | 2 | 2023-10-30 02:53:38+00:00 | 8k |
Weitheskmt/WeiDMD | build/lib/weidmd/hodmd.py | [
{
"identifier": "HankelDMD",
"path": "build/lib/weidmd/hankeldmd.py",
"snippet": "class HankelDMD(DMDBase):\n \"\"\"\n Hankel Dynamic Mode Decomposition\n\n :param svd_rank: the rank for the truncation; If 0, the method computes the\n optimal rank and uses it for truncation; if positive ... | import warnings
import numpy as np
from .hankeldmd import HankelDMD
from .utils import compute_svd
from .snapshots import Snapshots | 6,230 | :param int tlsq_rank: rank truncation computing Total Least Square. Default
is 0, that means no truncation.
:param bool exact: flag to compute either exact DMD or projected DMD.
Default is False.
:param opt: argument to control the computation of DMD modes amplitudes.
See :class:`DMDBase`. Default is False.
:type opt: bool or int
:param rescale_mode: Scale Atilde as shown in
10.1016/j.jneumeth.2015.10.010 (section 2.4) before computing its
eigendecomposition. None means no rescaling, 'auto' means automatic
rescaling using singular values, otherwise the scaling factors.
:type rescale_mode: {'auto'} or None or numpy.ndarray
:param bool forward_backward: If True, the low-rank operator is computed
like in fbDMD (reference: https://arxiv.org/abs/1507.02264). Default is
False.
:param int d: the new order for spatial dimension of the input snapshots.
Default is 1.
:param sorted_eigs: Sort eigenvalues (and modes/dynamics accordingly) by
magnitude if `sorted_eigs='abs'`, by real part (and then by imaginary
part to break ties) if `sorted_eigs='real'`. Default: False.
:type sorted_eigs: {'real', 'abs'} or False
:param reconstruction_method: Method used to reconstruct the snapshots of
the dynamical system from the multiple versions available due to how
HODMD is conceived. If `'first'` (default) the first version
available is selected (i.e. the nearest to the 0-th row in the
augmented matrix). If `'mean'` we compute the element-wise mean. If
`reconstruction_method` is an array of float values we compute the
weighted average (for each snapshots) using the given values as weights
(the number of weights must be equal to `d`).
:param svd_rank_extra: the rank for the initial reduction of the input
data, performed before the rearrangement of the input data to the
(pseudo) Hankel matrix format; If 0, the method computes the optimal
rank and uses it for truncation; if positive interger, the method uses
the argument for the truncation; if float between 0 and 1, the rank is
the number of the biggest singular values that are needed to reach the
'energy' specified by `svd_rank`; if -1, the method does not compute
truncation.
:type svd_rank: int or float
"""
def __init__(
self,
svd_rank=0,
tlsq_rank=0,
exact=False,
opt=False,
rescale_mode=None,
forward_backward=False,
d=1,
sorted_eigs=False,
reconstruction_method="first",
svd_rank_extra=0,
):
super().__init__(
svd_rank=svd_rank,
tlsq_rank=tlsq_rank,
exact=exact,
opt=opt,
rescale_mode=rescale_mode,
forward_backward=forward_backward,
d=d,
sorted_eigs=sorted_eigs,
reconstruction_method=reconstruction_method,
)
self._svd_rank_extra = svd_rank_extra # TODO improve names
self.U_extra = None
def reconstructions_of_timeindex(self, timeindex=None):
"""
Build a collection of all the available versions of the given
`timeindex`. The indexing of time instants is the same used for
:func:`reconstructed_data`. For each time instant there are at least
one and at most `d` versions. If `timeindex` is `None` the function
returns the whole collection, for all the time instants.
:param int timeindex: The index of the time snapshot.
:return: A collection of all the available versions for the requested
time instants, represented by a matrix (or tensor).
Axes:
0. Number of time instants;
1. Copies of the snapshot;
2. Space dimension of the snapshot.
The first axis is omitted if only one single time instant is
selected, in this case the output becomes a 2D matrix.
:rtype: numpy.ndarray
"""
snapshots = super().reconstructions_of_timeindex(timeindex)
if snapshots.ndim == 2: # single time instant
snapshots = self.U_extra.dot(snapshots.T).T
elif snapshots.ndim == 3: # all time instants
snapshots = np.array(
[self.U_extra.dot(snapshot.T).T for snapshot in snapshots]
)
else:
raise RuntimeError
return snapshots
def fit(self, X):
"""
Compute the Dynamic Modes Decomposition to the input data.
:param X: the input snapshots.
:type X: numpy.ndarray or iterable
"""
snapshots_holder = Snapshots(X)
snapshots = snapshots_holder.snapshots
space_dim = snapshots.shape[0]
if space_dim == 1:
svd_rank_extra = -1
warnings.warn(
(
f"The parameter 'svd_rank_extra={self._svd_rank_extra}' has "
"been ignored because the given system is a scalar function"
)
)
else:
svd_rank_extra = self._svd_rank_extra
|
class HODMD(HankelDMD):
"""
Higher Order Dynamic Mode Decomposition
:param svd_rank: the rank for the truncation; If 0, the method computes the
optimal rank and uses it for truncation; if positive interger, the
method uses the argument for the truncation; if float between 0 and 1,
the rank is the number of the biggest singular values that are needed
to reach the 'energy' specified by `svd_rank`; if -1, the method does
not compute truncation.
:type svd_rank: int or float
:param int tlsq_rank: rank truncation computing Total Least Square. Default
is 0, that means no truncation.
:param bool exact: flag to compute either exact DMD or projected DMD.
Default is False.
:param opt: argument to control the computation of DMD modes amplitudes.
See :class:`DMDBase`. Default is False.
:type opt: bool or int
:param rescale_mode: Scale Atilde as shown in
10.1016/j.jneumeth.2015.10.010 (section 2.4) before computing its
eigendecomposition. None means no rescaling, 'auto' means automatic
rescaling using singular values, otherwise the scaling factors.
:type rescale_mode: {'auto'} or None or numpy.ndarray
:param bool forward_backward: If True, the low-rank operator is computed
like in fbDMD (reference: https://arxiv.org/abs/1507.02264). Default is
False.
:param int d: the new order for spatial dimension of the input snapshots.
Default is 1.
:param sorted_eigs: Sort eigenvalues (and modes/dynamics accordingly) by
magnitude if `sorted_eigs='abs'`, by real part (and then by imaginary
part to break ties) if `sorted_eigs='real'`. Default: False.
:type sorted_eigs: {'real', 'abs'} or False
:param reconstruction_method: Method used to reconstruct the snapshots of
the dynamical system from the multiple versions available due to how
HODMD is conceived. If `'first'` (default) the first version
available is selected (i.e. the nearest to the 0-th row in the
augmented matrix). If `'mean'` we compute the element-wise mean. If
`reconstruction_method` is an array of float values we compute the
weighted average (for each snapshots) using the given values as weights
(the number of weights must be equal to `d`).
:param svd_rank_extra: the rank for the initial reduction of the input
data, performed before the rearrangement of the input data to the
(pseudo) Hankel matrix format; If 0, the method computes the optimal
rank and uses it for truncation; if positive interger, the method uses
the argument for the truncation; if float between 0 and 1, the rank is
the number of the biggest singular values that are needed to reach the
'energy' specified by `svd_rank`; if -1, the method does not compute
truncation.
:type svd_rank: int or float
"""
def __init__(
self,
svd_rank=0,
tlsq_rank=0,
exact=False,
opt=False,
rescale_mode=None,
forward_backward=False,
d=1,
sorted_eigs=False,
reconstruction_method="first",
svd_rank_extra=0,
):
super().__init__(
svd_rank=svd_rank,
tlsq_rank=tlsq_rank,
exact=exact,
opt=opt,
rescale_mode=rescale_mode,
forward_backward=forward_backward,
d=d,
sorted_eigs=sorted_eigs,
reconstruction_method=reconstruction_method,
)
self._svd_rank_extra = svd_rank_extra # TODO improve names
self.U_extra = None
def reconstructions_of_timeindex(self, timeindex=None):
"""
Build a collection of all the available versions of the given
`timeindex`. The indexing of time instants is the same used for
:func:`reconstructed_data`. For each time instant there are at least
one and at most `d` versions. If `timeindex` is `None` the function
returns the whole collection, for all the time instants.
:param int timeindex: The index of the time snapshot.
:return: A collection of all the available versions for the requested
time instants, represented by a matrix (or tensor).
Axes:
0. Number of time instants;
1. Copies of the snapshot;
2. Space dimension of the snapshot.
The first axis is omitted if only one single time instant is
selected, in this case the output becomes a 2D matrix.
:rtype: numpy.ndarray
"""
snapshots = super().reconstructions_of_timeindex(timeindex)
if snapshots.ndim == 2: # single time instant
snapshots = self.U_extra.dot(snapshots.T).T
elif snapshots.ndim == 3: # all time instants
snapshots = np.array(
[self.U_extra.dot(snapshot.T).T for snapshot in snapshots]
)
else:
raise RuntimeError
return snapshots
def fit(self, X):
"""
Compute the Dynamic Modes Decomposition to the input data.
:param X: the input snapshots.
:type X: numpy.ndarray or iterable
"""
snapshots_holder = Snapshots(X)
snapshots = snapshots_holder.snapshots
space_dim = snapshots.shape[0]
if space_dim == 1:
svd_rank_extra = -1
warnings.warn(
(
f"The parameter 'svd_rank_extra={self._svd_rank_extra}' has "
"been ignored because the given system is a scalar function"
)
)
else:
svd_rank_extra = self._svd_rank_extra | self.U_extra, _, _ = compute_svd(snapshots, svd_rank_extra) | 1 | 2023-10-30 12:37:40+00:00 | 8k |
lewandofskee/DiAD | ldm/models/diffusion/ddim.py | [
{
"identifier": "make_ddim_sampling_parameters",
"path": "ldm/modules/diffusionmodules/util.py",
"snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n alphas_prev ... | import torch
import numpy as np
from tqdm import tqdm
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor | 4,046 | assert isinstance(unconditional_conditioning, dict)
c_in = dict()
for k in c:
if isinstance(c[k], list):
c_in[k] = [torch.cat([
unconditional_conditioning[k][i],
c[k][i]]) for i in range(len(c[k]))]
else:
c_in[k] = torch.cat([
unconditional_conditioning[k],
c[k]])
elif isinstance(c, list):
c_in = list()
assert isinstance(unconditional_conditioning, list)
for i in range(len(c)):
c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))
else:
c_in = torch.cat([unconditional_conditioning, c])
model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
if self.model.parameterization == "v":
e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
else:
e_t = model_output
if score_corrector is not None:
assert self.model.parameterization == "eps", 'not implemented'
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
# select parameters corresponding to the currently considered timestep
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
# current prediction for x_0
if self.model.parameterization != "v":
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
else:
pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
if quantize_denoised:
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
if dynamic_threshold is not None:
raise NotImplementedError()
# direction pointing to x_t
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
if noise_dropout > 0.:
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
return x_prev, pred_x0
@torch.no_grad()
def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]
assert t_enc <= num_reference_steps
num_steps = t_enc
if use_original_steps:
alphas_next = self.alphas_cumprod[:num_steps]
alphas = self.alphas_cumprod_prev[:num_steps]
else:
alphas_next = self.ddim_alphas[:num_steps]
alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
x_next = x0
intermediates = []
inter_steps = []
for i in tqdm(range(num_steps), desc='Encoding Image'):
t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)
if unconditional_guidance_scale == 1.:
noise_pred = self.model.apply_model(x_next, t, c)
else:
assert unconditional_conditioning is not None
e_t_uncond, noise_pred = torch.chunk(
self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
torch.cat((unconditional_conditioning, c))), 2)
noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
weighted_noise_pred = alphas_next[i].sqrt() * (
(1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
x_next = xt_weighted + weighted_noise_pred
if return_intermediates and i % (
num_steps // return_intermediates) == 0 and i < num_steps - 1:
intermediates.append(x_next)
inter_steps.append(i)
elif return_intermediates and i >= num_steps - 2:
intermediates.append(x_next)
inter_steps.append(i)
if callback: callback(i)
out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
if return_intermediates:
out.update({'intermediates': intermediates})
return x_next, out
@torch.no_grad()
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
# fast, but does not allow for exact reconstruction
# t serves as an index to gather the correct alphas
if use_original_steps:
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
else:
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
if noise is None:
noise = torch.randn_like(x0)
| """SAMPLING ONLY."""
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True,timesteps=1000):
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
alphas_cumprod = self.model.alphas_cumprod
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
self.register_buffer('betas', to_torch(self.model.betas))
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
# ddim sampling parameters
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
ddim_timesteps=self.ddim_timesteps,
eta=ddim_eta,verbose=verbose)
self.register_buffer('ddim_sigmas', ddim_sigmas)
self.register_buffer('ddim_alphas', ddim_alphas)
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
@torch.no_grad()
def sample(self,
S,
batch_size,
shape,
conditioning=None,
x_T=None,
timesteps=1000,
callback=None,
normals_sequence=None,
img_callback=None,
quantize_x0=False,
eta=0.,
mask=None,
x0=None,
temperature=1.,
noise_dropout=0.,
score_corrector=None,
corrector_kwargs=None,
verbose=True,
log_every_t=100,
unconditional_guidance_scale=1.,
unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
dynamic_threshold=None,
ucg_schedule=None,
**kwargs
):
if conditioning is not None:
if isinstance(conditioning, dict):
ctmp = conditioning[list(conditioning.keys())[0]]
while isinstance(ctmp, list): ctmp = ctmp[0]
cbs = ctmp.shape[0]
if cbs != batch_size:
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
elif isinstance(conditioning, list):
for ctmp in conditioning:
if ctmp.shape[0] != batch_size:
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
else:
if conditioning.shape[0] != batch_size:
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose,timesteps=timesteps)
# sampling
C, H, W = shape
size = (batch_size, C, H, W)
# print(f'Data shape for DDIM sampling is {size}, eta {eta}')
samples, intermediates = self.ddim_sampling(conditioning, size,
callback=callback,
img_callback=img_callback,
quantize_denoised=quantize_x0,
mask=mask, x0=x0,
ddim_use_original_steps=False,
noise_dropout=noise_dropout,
temperature=temperature,
score_corrector=score_corrector,
corrector_kwargs=corrector_kwargs,
x_T=x_T,
timesteps=timesteps,
log_every_t=log_every_t,
unconditional_guidance_scale=unconditional_guidance_scale,
unconditional_conditioning=unconditional_conditioning,
dynamic_threshold=dynamic_threshold,
ucg_schedule=ucg_schedule,
)
return samples, intermediates
@torch.no_grad()
def ddim_sampling(self, cond, shape,
x_T=None, ddim_use_original_steps=False,
callback=None, timesteps=None, quantize_denoised=False,
mask=None, x0=None, img_callback=None, log_every_t=100,
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
ucg_schedule=None):
device = self.model.betas.device
b = shape[0]
if x_T is None:
img = torch.randn(shape, device=device)
else:
img = x_T
if timesteps is None:
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
elif timesteps is not None and not ddim_use_original_steps:
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0])
# subset_end = int(timesteps+1 * self.ddim_timesteps.shape[0] / self.ddpm_num_timesteps)
timesteps = self.ddim_timesteps[:subset_end]
intermediates = {'x_inter': [img], 'pred_x0': [img]}
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
# print(f"Running DDIM Sampling with {total_steps} timesteps")
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
for i, step in enumerate(iterator):
index = total_steps - i - 1
ts = torch.full((b,), step, device=device, dtype=torch.long)
if mask is not None:
assert x0 is not None
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
img = img_orig * mask + (1. - mask) * img
if ucg_schedule is not None:
assert len(ucg_schedule) == len(time_range)
unconditional_guidance_scale = ucg_schedule[i]
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
quantize_denoised=quantize_denoised, temperature=temperature,
noise_dropout=noise_dropout, score_corrector=score_corrector,
corrector_kwargs=corrector_kwargs,
unconditional_guidance_scale=unconditional_guidance_scale,
unconditional_conditioning=unconditional_conditioning,
dynamic_threshold=dynamic_threshold)
img, pred_x0 = outs
if callback: callback(i)
if img_callback: img_callback(pred_x0, i)
if index % 500 == 0 or index == total_steps - 1:
intermediates['x_inter'].append(img)
intermediates['pred_x0'].append(pred_x0)
return img, intermediates
@torch.no_grad()
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
unconditional_guidance_scale=1., unconditional_conditioning=None,
dynamic_threshold=None):
b, *_, device = *x.shape, x.device
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
model_output = self.model.apply_model(x, t, c)
else:
x_in = torch.cat([x] * 2)
t_in = torch.cat([t] * 2)
if isinstance(c, dict):
assert isinstance(unconditional_conditioning, dict)
c_in = dict()
for k in c:
if isinstance(c[k], list):
c_in[k] = [torch.cat([
unconditional_conditioning[k][i],
c[k][i]]) for i in range(len(c[k]))]
else:
c_in[k] = torch.cat([
unconditional_conditioning[k],
c[k]])
elif isinstance(c, list):
c_in = list()
assert isinstance(unconditional_conditioning, list)
for i in range(len(c)):
c_in.append(torch.cat([unconditional_conditioning[i], c[i]]))
else:
c_in = torch.cat([unconditional_conditioning, c])
model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)
model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
if self.model.parameterization == "v":
e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
else:
e_t = model_output
if score_corrector is not None:
assert self.model.parameterization == "eps", 'not implemented'
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
# select parameters corresponding to the currently considered timestep
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
# current prediction for x_0
if self.model.parameterization != "v":
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
else:
pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
if quantize_denoised:
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
if dynamic_threshold is not None:
raise NotImplementedError()
# direction pointing to x_t
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
if noise_dropout > 0.:
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
return x_prev, pred_x0
@torch.no_grad()
def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0]
assert t_enc <= num_reference_steps
num_steps = t_enc
if use_original_steps:
alphas_next = self.alphas_cumprod[:num_steps]
alphas = self.alphas_cumprod_prev[:num_steps]
else:
alphas_next = self.ddim_alphas[:num_steps]
alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
x_next = x0
intermediates = []
inter_steps = []
for i in tqdm(range(num_steps), desc='Encoding Image'):
t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long)
if unconditional_guidance_scale == 1.:
noise_pred = self.model.apply_model(x_next, t, c)
else:
assert unconditional_conditioning is not None
e_t_uncond, noise_pred = torch.chunk(
self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
torch.cat((unconditional_conditioning, c))), 2)
noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
weighted_noise_pred = alphas_next[i].sqrt() * (
(1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
x_next = xt_weighted + weighted_noise_pred
if return_intermediates and i % (
num_steps // return_intermediates) == 0 and i < num_steps - 1:
intermediates.append(x_next)
inter_steps.append(i)
elif return_intermediates and i >= num_steps - 2:
intermediates.append(x_next)
inter_steps.append(i)
if callback: callback(i)
out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
if return_intermediates:
out.update({'intermediates': intermediates})
return x_next, out
@torch.no_grad()
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
# fast, but does not allow for exact reconstruction
# t serves as an index to gather the correct alphas
if use_original_steps:
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
else:
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
if noise is None:
noise = torch.randn_like(x0) | return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 + | 3 | 2023-10-30 14:21:09+00:00 | 8k |
nv-tlabs/trace | scripts/scene_editor.py | [
{
"identifier": "set_global_trajdata_batch_env",
"path": "tbsim/utils/trajdata_utils.py",
"snippet": "def set_global_trajdata_batch_env(batch_env):\n global BATCH_ENV\n BATCH_ENV = batch_env.split('-')[0] # if split is specified, remove it"
},
{
"identifier": "set_global_trajdata_batch_ras... | import argparse
import numpy as np
import json
import random
import importlib
import os
import torch
import h5py
from pprint import pprint
from tbsim.utils.trajdata_utils import set_global_trajdata_batch_env, set_global_trajdata_batch_raster_cfg
from tbsim.configs.scene_edit_config import SceneEditingConfig
from tbsim.utils.scene_edit_utils import guided_rollout, compute_heuristic_guidance, merge_guidance_configs
from tbsim.evaluation.env_builders import EnvUnifiedBuilder
from tbsim.policies.wrappers import RolloutWrapper
from tbsim.utils.tensor_utils import map_ndarray
from tbsim.policies.hardcoded import GTNaNPolicy
from tbsim.utils.viz_utils import get_trajdata_renderer
from tbsim.utils.viz_utils import visualize_guided_rollout | 4,780 | """A script for evaluating closed-loop simulation"""
def run_scene_editor(eval_cfg, save_cfg, data_to_disk, render_to_video, render_to_img, render_cfg,
use_gt=False):
# assumes all used trajdata datasets use share same map layers
set_global_trajdata_batch_env(eval_cfg.trajdata_source_test[0])
print(eval_cfg)
# for reproducibility
np.random.seed(eval_cfg.seed)
random.seed(eval_cfg.seed)
torch.manual_seed(eval_cfg.seed)
torch.cuda.manual_seed(eval_cfg.seed)
# basic setup
print('saving results to {}'.format(eval_cfg.results_dir))
os.makedirs(eval_cfg.results_dir, exist_ok=True)
if render_to_video:
os.makedirs(os.path.join(eval_cfg.results_dir, "videos/"), exist_ok=True)
if render_to_video or render_to_img:
os.makedirs(os.path.join(eval_cfg.results_dir, "viz/"), exist_ok=True)
if save_cfg:
json.dump(eval_cfg, open(os.path.join(eval_cfg.results_dir, "config.json"), "w+"))
if data_to_disk and os.path.exists(eval_cfg.experience_hdf5_path):
os.remove(eval_cfg.experience_hdf5_path)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# create policy and rollout wrapper
policy_composers = importlib.import_module("tbsim.evaluation.policy_composers")
composer_class = getattr(policy_composers, eval_cfg.eval_class)
composer = composer_class(eval_cfg, device)
policy, exp_config = composer.get_policy()
policy_model = policy.model
if use_gt:
# overwrite policy with dummy that always returns GT
policy = GTNaNPolicy(device=device)
policy_model = None
print('WARNING: Using GT data as the policy instead of the provided model!!')
# determines cfg for rasterizing agents
| """A script for evaluating closed-loop simulation"""
def run_scene_editor(eval_cfg, save_cfg, data_to_disk, render_to_video, render_to_img, render_cfg,
use_gt=False):
# assumes all used trajdata datasets use share same map layers
set_global_trajdata_batch_env(eval_cfg.trajdata_source_test[0])
print(eval_cfg)
# for reproducibility
np.random.seed(eval_cfg.seed)
random.seed(eval_cfg.seed)
torch.manual_seed(eval_cfg.seed)
torch.cuda.manual_seed(eval_cfg.seed)
# basic setup
print('saving results to {}'.format(eval_cfg.results_dir))
os.makedirs(eval_cfg.results_dir, exist_ok=True)
if render_to_video:
os.makedirs(os.path.join(eval_cfg.results_dir, "videos/"), exist_ok=True)
if render_to_video or render_to_img:
os.makedirs(os.path.join(eval_cfg.results_dir, "viz/"), exist_ok=True)
if save_cfg:
json.dump(eval_cfg, open(os.path.join(eval_cfg.results_dir, "config.json"), "w+"))
if data_to_disk and os.path.exists(eval_cfg.experience_hdf5_path):
os.remove(eval_cfg.experience_hdf5_path)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# create policy and rollout wrapper
policy_composers = importlib.import_module("tbsim.evaluation.policy_composers")
composer_class = getattr(policy_composers, eval_cfg.eval_class)
composer = composer_class(eval_cfg, device)
policy, exp_config = composer.get_policy()
policy_model = policy.model
if use_gt:
# overwrite policy with dummy that always returns GT
policy = GTNaNPolicy(device=device)
policy_model = None
print('WARNING: Using GT data as the policy instead of the provided model!!')
# determines cfg for rasterizing agents | set_global_trajdata_batch_raster_cfg(exp_config.env.rasterizer) | 1 | 2023-10-31 18:43:07+00:00 | 8k |
AetherBlack/abuseACL | abuseACL/network/LDAP.py | [
{
"identifier": "sAMAccountType",
"path": "abuseACL/structures/sAMAccountType.py",
"snippet": "class sAMAccountType:\n\n SAM_DOMAIN_OBJECT = 0x0\n SAM_GROUP_OBJECT = 0x10000000\n SAM_NON_SECURITY_GROUP_OBJECT = 0x10000001\n SAM_ALIAS_OBJECT = 0x20000000\n SAM_NON_SECURITY_ALIAS_OBJECT = 0... | from typing import List
from abuseACL.structures.sAMAccountType import sAMAccountType
from abuseACL.structures.Credentials import Credentials
from abuseACL.structures.Target import Target
from abuseACL.structures.ADObject.ADCertificateTemplate import ADCertificateTemplate
from abuseACL.structures.ADObject.ADAdminSDHolder import ADAdminSDHolder
from abuseACL.structures.ADObject.ADComputer import ADComputer
from abuseACL.structures.ADObject.ADSchema import ADSchema
from abuseACL.structures.ADObject.ADGroup import ADGroup
from abuseACL.structures.ADObject.ADUser import ADUser
from abuseACL.structures.ADObject.ADgMSA import ADgMSA
from abuseACL.structures.ADObject.ADGPO import ADGPO
from abuseACL.structures.ADObject.ADOU import ADOU
from abuseACL.network.Kerberos import Kerberos
from abuseACL.core.Logger import Logger
import ssl as tls
import ldap3 | 5,714 | ["namingContexts"]
)
self.namingContexts = response[0]["attributes"]["namingContexts"]
self.defaultNamingContext = self.namingContexts[0]
self.configurationNamingContext = self.namingContexts[1]
self.schemaNamingContext = self.namingContexts[2]
self.domainDnsZonesNamingContext = self.namingContexts[3]
self.forestDnsZonesNamingContext = self.namingContexts[4]
def getAllUsers(self) -> List[ADUser]:
if len(self.users):
return self.users
response = self.search(
self.defaultNamingContext,
"(sAMAccountType=%d)" % (sAMAccountType.SAM_NORMAL_USER_ACCOUNT),
ldap3.SUBTREE,
["DistinguishedName", "name", "userPrincipalName", "sAMAccountName", "objectSid", "ntSecurityDescriptor", "userAccountControl"]
)
self.users = self.__createArrayOfObject(response, ADUser)
return self.users
def getAllGroups(self) -> List[ADGroup]:
if len(self.groups):
return self.groups
response = self.search(
self.defaultNamingContext,
"(|(sAMAccountType=%d)(sAMAccountType=%d)(sAMAccountType=%d)(sAMAccountType=%d))" % (
sAMAccountType.SAM_GROUP_OBJECT,
sAMAccountType.SAM_NON_SECURITY_GROUP_OBJECT,
sAMAccountType.SAM_ALIAS_OBJECT,
sAMAccountType.SAM_NON_SECURITY_ALIAS_OBJECT
),
ldap3.SUBTREE,
["DistinguishedName", "name", "sAMAccountName", "objectSid", "ntSecurityDescriptor"]
)
self.groups = self.__createArrayOfObject(response, ADGroup)
return self.groups
def getAllComputers(self) -> List[ADComputer]:
if len(self.computers):
return self.computers
response = self.search(
self.defaultNamingContext,
"(sAMAccountType=%d)" % (sAMAccountType.SAM_MACHINE_ACCOUNT),
ldap3.SUBTREE,
["DistinguishedName", "name", "sAMAccountName", "objectSid", "ntSecurityDescriptor", "userAccountControl"]
)
self.computers = self.__createArrayOfObject(response, ADComputer)
return self.computers
def getAllCertificatesTemplates(self) -> List[ADCertificateTemplate]:
if len(self.certificatesTemplates):
return self.certificatesTemplates
response = self.search(
f"CN=Certificate Templates,CN=Public Key Services,CN=Services,{self.configurationNamingContext}",
"(objectClass=pkiCertificateTemplate)",
ldap3.SUBTREE,
["DistinguishedName", "name", "ntSecurityDescriptor"]
)
self.certificatesTemplates = self.__createArrayOfObject(response, ADCertificateTemplate)
return self.certificatesTemplates
def getAllGPOs(self) -> List[ADGPO]:
if len(self.gpos):
return self.gpos
response = self.search(
f"CN=Policies,CN=System,{self.defaultNamingContext}",
"(objectClass=groupPolicyContainer)",
ldap3.SUBTREE,
["DistinguishedName", "displayName", "gPCFileSysPath", "ntSecurityDescriptor"]
)
self.gpos = self.__createArrayOfObject(response, ADGPO)
return self.gpos
def getAllOUs(self) -> List[ADGPO]:
if len(self.ous):
return self.ous
response = self.search(
self.defaultNamingContext,
"(objectClass=organizationalUnit)",
ldap3.SUBTREE,
["DistinguishedName", "name", "ntSecurityDescriptor"]
)
self.ous = self.__createArrayOfObject(response, ADOU)
return self.ous
def getAdminSDHolder(self) -> List[ADAdminSDHolder]:
if len(self.adminSDHolder):
return self.adminSDHolder
response = self.search(
f"CN=AdminSDHolder,CN=System,{self.defaultNamingContext}",
"(cn=AdminSDHolder)",
ldap3.BASE,
["DistinguishedName", "name", "ntSecurityDescriptor"]
)
self.adminSDHolder = self.__createArrayOfObject(response, ADAdminSDHolder)
return self.adminSDHolder
|
class LDAP:
users = list()
groups = list()
computers = list()
certificatesTemplates = list()
gpos = list()
ous = list()
adminSDHolder = list()
schema = list()
gMSA = list()
def __init__(self, forest: str, target: Target, credentials: Credentials, logger: Logger) -> None:
self.target = target
self.credentials = credentials
self.logger = logger
self.__getPort()
self.__checkAuthentication()
def __getPort(self) -> None:
if self.target.port:
return
self.target.port, self.target.tlsv1_2 = self.__tryLDAPS(tls.PROTOCOL_TLSv1_2, self.target.port)
if self.target.tlsv1_2 is None:
self.target.port, self.target.tlsv1 = self.__tryLDAPS(tls.PROTOCOL_TLSv1, self.target.port)
if self.target.tlsv1 is None:
self.target.port = self.__tryLDAP(self.target.port)
if self.target.port is None:
self.logger.error(f"Impossible to communicate with the target {self.target.remote} !")
exit(1)
def __checkAuthentication(self) -> None:
self.logger.debug("Trying to connect to %s:%d" % (self.target.remote, self.target.port))
self.__Authentication()
try:
self.getNamingContexts()
except IndexError:
self.logger.error("Invalid credentials !")
exit(1)
self.logger.debug("Authentication success !")
def __Authentication(self) -> ldap3.Connection:
user = "%s\\%s" % (self.credentials.domain, self.credentials.username)
ldapTls = None
if self.target.tlsv1_2:
ldapTls = ldap3.Tls(validate=tls.CERT_NONE, version=tls.PROTOCOL_TLSv1_2, ciphers='ALL:@SECLEVEL=0')
elif self.target.tlsv1:
ldapTls = ldap3.Tls(validate=tls.CERT_NONE, version=tls.PROTOCOL_TLSv1, ciphers='ALL:@SECLEVEL=0')
ldapServer = ldap3.Server(self.target.remote, use_ssl=self.target.use_tls(), port=self.target.port, get_info=ldap3.ALL, tls=ldapTls)
if self.credentials.doKerberos:
ldapConn = ldap3.Connection(ldapServer)
ldapConn = self.kerberosAuthentication(ldapConn)
else:
ldapConn = ldap3.Connection(ldapServer, user=user, password=self.credentials.getAuthenticationSecret(), authentication=ldap3.NTLM)
ldapConn.bind()
if ldapConn.result["description"] == "invalidCredentials":
self.logger.error("Invalid credentials !")
exit(1)
return ldapConn
def __tryLDAPS(self, proto: tls._SSLMethod, port: int) -> int:
port = port or 636
ldapTls = ldap3.Tls(validate=tls.CERT_NONE, version=proto, ciphers="ALL:@SECLEVEL=0")
ldapServer = ldap3.Server(self.target.remote, use_ssl=True, port=port, get_info=ldap3.ALL, tls=ldapTls)
ldapConn = ldap3.Connection(ldapServer)
try:
ldapConn.bind()
except ldap3.core.exceptions.LDAPSocketOpenError:
return None, None
except ldap3.core.exceptions.LDAPSocketReceiveError:
pass
return port, True
def __tryLDAP(self, port: int) -> int:
self.logger.debug("LDAPS failed, trying with LDAP.")
port = port or 389
ldapServer = ldap3.Server(self.target.remote, use_ssl=False, port=port, get_info=ldap3.ALL)
ldapConn = ldap3.Connection(ldapServer)
try:
ldapConn.bind()
except ldap3.core.exceptions.LDAPSocketOpenError:
return None
except ldap3.core.exceptions.LDAPSocketReceiveError:
return port
return port
def kerberosAuthentication(self, ldapConn: ldap3.Connection) -> None:
blob = Kerberos.kerberosLogin(self.target.remote, self.credentials.username, self.credentials.password,
self.credentials.domain, self.credentials.ntlmhash, self.credentials.aesKey,
kdcHost=self.target.remote)
request = ldap3.operation.bind.bind_operation(ldapConn.version, ldap3.SASL, self.credentials.username, None, "GSS-SPNEGO", blob.getData())
# Done with the Kerberos saga, now let's get into LDAP
# try to open connection if closed
if ldapConn.closed:
ldapConn.open(read_server_info=False)
ldapConn.sasl_in_progress = True
response = ldapConn.post_send_single_response(ldapConn.send('bindRequest', request, None))
ldapConn.sasl_in_progress = False
if response[0]['result'] != 0:
raise Exception(response)
ldapConn.bound = True
return ldapConn
def search(self, dn: str, filter: str, scope: str, attributes: list = ["*"]) -> list:
ldapConn = self.__Authentication()
ldapConn.search(
search_base=dn,
search_filter=filter,
search_scope=scope,
attributes=attributes,
# Controls to get nTSecurityDescriptor from standard user
# OWNER_SECURITY_INFORMATION + GROUP_SECURITY_INFORMATION + DACL_SECURITY_INFORMATION
controls=[("1.2.840.113556.1.4.801", True, "%c%c%c%c%c" % (48, 3, 2, 1, 7), )]
)
return ldapConn.response
def __createArrayOfObject(self, response: list, obj: object) -> list:
array = list()
for entry in response:
# Not a response object
if entry["type"] != "searchResEntry":
continue
array.append(
obj(**entry["raw_attributes"])
)
return array
def getNamingContexts(self) -> list:
response = self.search(
"",
"(objectClass=*)",
ldap3.BASE,
["namingContexts"]
)
self.namingContexts = response[0]["attributes"]["namingContexts"]
self.defaultNamingContext = self.namingContexts[0]
self.configurationNamingContext = self.namingContexts[1]
self.schemaNamingContext = self.namingContexts[2]
self.domainDnsZonesNamingContext = self.namingContexts[3]
self.forestDnsZonesNamingContext = self.namingContexts[4]
def getAllUsers(self) -> List[ADUser]:
if len(self.users):
return self.users
response = self.search(
self.defaultNamingContext,
"(sAMAccountType=%d)" % (sAMAccountType.SAM_NORMAL_USER_ACCOUNT),
ldap3.SUBTREE,
["DistinguishedName", "name", "userPrincipalName", "sAMAccountName", "objectSid", "ntSecurityDescriptor", "userAccountControl"]
)
self.users = self.__createArrayOfObject(response, ADUser)
return self.users
def getAllGroups(self) -> List[ADGroup]:
if len(self.groups):
return self.groups
response = self.search(
self.defaultNamingContext,
"(|(sAMAccountType=%d)(sAMAccountType=%d)(sAMAccountType=%d)(sAMAccountType=%d))" % (
sAMAccountType.SAM_GROUP_OBJECT,
sAMAccountType.SAM_NON_SECURITY_GROUP_OBJECT,
sAMAccountType.SAM_ALIAS_OBJECT,
sAMAccountType.SAM_NON_SECURITY_ALIAS_OBJECT
),
ldap3.SUBTREE,
["DistinguishedName", "name", "sAMAccountName", "objectSid", "ntSecurityDescriptor"]
)
self.groups = self.__createArrayOfObject(response, ADGroup)
return self.groups
def getAllComputers(self) -> List[ADComputer]:
if len(self.computers):
return self.computers
response = self.search(
self.defaultNamingContext,
"(sAMAccountType=%d)" % (sAMAccountType.SAM_MACHINE_ACCOUNT),
ldap3.SUBTREE,
["DistinguishedName", "name", "sAMAccountName", "objectSid", "ntSecurityDescriptor", "userAccountControl"]
)
self.computers = self.__createArrayOfObject(response, ADComputer)
return self.computers
def getAllCertificatesTemplates(self) -> List[ADCertificateTemplate]:
if len(self.certificatesTemplates):
return self.certificatesTemplates
response = self.search(
f"CN=Certificate Templates,CN=Public Key Services,CN=Services,{self.configurationNamingContext}",
"(objectClass=pkiCertificateTemplate)",
ldap3.SUBTREE,
["DistinguishedName", "name", "ntSecurityDescriptor"]
)
self.certificatesTemplates = self.__createArrayOfObject(response, ADCertificateTemplate)
return self.certificatesTemplates
def getAllGPOs(self) -> List[ADGPO]:
if len(self.gpos):
return self.gpos
response = self.search(
f"CN=Policies,CN=System,{self.defaultNamingContext}",
"(objectClass=groupPolicyContainer)",
ldap3.SUBTREE,
["DistinguishedName", "displayName", "gPCFileSysPath", "ntSecurityDescriptor"]
)
self.gpos = self.__createArrayOfObject(response, ADGPO)
return self.gpos
def getAllOUs(self) -> List[ADGPO]:
if len(self.ous):
return self.ous
response = self.search(
self.defaultNamingContext,
"(objectClass=organizationalUnit)",
ldap3.SUBTREE,
["DistinguishedName", "name", "ntSecurityDescriptor"]
)
self.ous = self.__createArrayOfObject(response, ADOU)
return self.ous
def getAdminSDHolder(self) -> List[ADAdminSDHolder]:
if len(self.adminSDHolder):
return self.adminSDHolder
response = self.search(
f"CN=AdminSDHolder,CN=System,{self.defaultNamingContext}",
"(cn=AdminSDHolder)",
ldap3.BASE,
["DistinguishedName", "name", "ntSecurityDescriptor"]
)
self.adminSDHolder = self.__createArrayOfObject(response, ADAdminSDHolder)
return self.adminSDHolder
| def getSchema(self) -> List[ADSchema]: | 6 | 2023-10-30 21:19:24+00:00 | 8k |
gydpku/PPTC | main.py | [
{
"identifier": "ppt_executor",
"path": "src/ppt_executor.py",
"snippet": "SLIDE_HEIGHT = 6858000\nSLIDE_WIDTH = 9144000\nCENTER_TOP = 3429000\nCENTER_LEFT = 4572000\nSHAPE_HEIGHT = 900000\nSHAPE_WIDTH = 900000\nTABLE_HEIGHT = 370000 # per line\nCONTENT_HEIGHT = 4351338\nCONTENT_WIDTH = 7886700\nCONTENT... | from src import ppt_executor, ppt_reader, openai_api, prompt_factor, dataset, api_selection, utils, modeling, evaluate, content_selection
from tqdm import tqdm
import argparse
import os
import jsonlines | 4,373 | utils.write_lines([prompt],args.user_path+f'PPT_Prompt_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.txt')
with jsonlines.open(args.user_path+f"PPT_test_output/{set_name}/{args.exp_name}_session_{sess_id}.json", mode='a') as writer:
data={'Turn':turn_id,'User instruction':instruction,'Feasible API sequence':label_api,'Reply':reply,'Pred API sequence':apis,'Pred File':f'PPT_Pred_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.pptx','Label File':label_file,'Prompt File':f'PPT_Prompt_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.txt'}
writer.write(data)
def test_planning(ppt_assistant):
instructions, labels = dataset.load_data(args.data_path, args.dataset)
f = open(f'test_system/planning_{args.dataset}.txt','a+')
for idx, dialogue in tqdm(enumerate(instructions)):
for step, instruction in enumerate(dialogue):
instruction = instruction.split("##")[0]
try:
planned = ppt_assistant.planner(instruction)
f.write(f'{idx}/{step}\n')
f.write(instruction+'\n')
f.write(str(planned)+'\n\n')
f.flush()
except:
pass
def test_api_selection(ppt_assistant):
instructions, labels = dataset.load_data(args.data_path, args.dataset)
f = open(f'test_system/api_selection_{args.api_topk}_{args.dataset}.txt','a+')
cnt = 0
for idx, dialogue in tqdm(enumerate(instructions)):
for step, instruction in enumerate(dialogue):
label_apis = labels[idx][step]
instruction = instruction.split("##")[0]
# instructions = ppt_assistant.planner(instruction)
# selected_apis = []
# for ins in instructions:
# selected_apis.extend(ppt_assistant.api_selector(ins))
selected_apis = ppt_assistant.api_selector(instruction)
selected_apis = [x.name for x in selected_apis]
for xx in label_apis:
if ('align_slide' in xx.split('(')[0]) or (xx.split('(')[0] in ['set_left','set_right','set_top','set_bottom']) or ('corner' in xx.split('(')[0]):
continue
if not xx.split('(')[0] in selected_apis:
f.write(f'{idx}/{step}\n')
f.write(instruction+'\n')
f.write(xx.split('(')[0]+'\n')
f.write(str(selected_apis)+'\n\n')
f.flush()
cnt += 1
print(cnt)
def test_content_selection(ppt_assistant):
instructions, labels = dataset.load_data(args.data_path, args.dataset)
f = open(f'test_system/content_selection_{args.dataset}.txt','a+')
for idx, dialogue in tqdm(enumerate(instructions)):
for step, instruction in enumerate(dialogue):
instruction = instruction.split("##")[0]
prompt = prompt_factor.PPT_content_selection_prompt.format(instruction)
reply = openai_api.query_azure_openai(prompt, model='turbo')
f.write(f'{idx}/{step}\n')
f.write(instruction+'\n')
f.write(reply+'\n\n')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# PPT assistant
parser.add_argument("--data_path", default="test", type=str,
help="The data path to load the instructions")
parser.add_argument("--dataset", default="short", type=str,
help="short/long")
parser.add_argument("--model_id", default="None", type=str,
help="short/long")
parser.add_argument("--user_path", default='./PPTC/', type=str,
help="the user storage file path ")
parser.add_argument("--save_path", default="test_pptx_data", type=str,
help="the path to save the intermediate ppts.")
# mode
parser.add_argument("--prepare", default=False, action='store_true',
help='whether to prepare the data for the model')
parser.add_argument("--eval", default=False, action='store_true',
help='whether to evaluate the pptx file generated by the model')
parser.add_argument("--test", default=False, action='store_true',
help='whether to test on the instruction data loaded from data_path')
parser.add_argument("--tf", default=False, action='store_true',
help='whether to use teacher forcing mode')
parser.add_argument("--sess", default=False, action='store_true',
help='whether to test from session level')
parser.add_argument("--resume", default=False, action='store_true',
help='whether to continue generation from the last unfinished instruction')
# modeling
parser.add_argument("--model", default="turbo",type=str,
help="turbo/gpt4/text3")
parser.add_argument("--planning", default=False, action='store_true',
help="whether to apply the planning module")
parser.add_argument("--api_selection", default=False, action='store_true',
help="whether to apply the api selection module")
parser.add_argument("--api_topk", default=10, type=int,
help="How many apis to retrieve from the api pool")
parser.add_argument("--content_selection", default=False, action='store_true',
help="whether to apply the shape selection module")
# api update/lack
parser.add_argument("--api_lack", default=False, action='store_true',
help='whether to test in the api lack setting')
parser.add_argument("--api_update", default=False, action='store_true',
help='whether to test in the api update setting')
parser.add_argument("--second", default=False, action='store_true',
help='second test')
parser.add_argument("--robust", default=False, action='store_true',
help='whether to test in robust data')
parser.add_argument("--robust_num", default=0, type=int,
help="which robusted data")
parser.add_argument("--noisy", default=False, action='store_true',
help='whether to test in noisy data')
args = parser.parse_args()
args.exp_name = utils.prepare_exp_name(args)
args.save_path = os.path.join(args.save_path,args.dataset)
api_selection.prepare_embedding(args)
|
def prepare_data(ppt_assistant, args):
instructions, labels = dataset.load_data(args.user_path+args.data_path, args.dataset, args)
print(f"#Dialogues: {len(instructions)}")
for idx, dialogue in enumerate(instructions):
if args.dataset == 'long':
ppt_assistant.load_ppt(os.path.join(args.user_path+'long_slides',f'{idx}.pptx'))
else:
ppt_assistant.load_ppt(None)
set_name = 'Edit_PPT_template' if args.dataset == 'long' else 'Create_new_slides'
if args.api_lack:
utils.makedir(args.user_path+f"PPT_Base_File/{set_name}_API_lack/")
utils.makedir(args.user_path+f"PPT_Label_File/{set_name}_API_lack/")
else:
utils.makedir(args.user_path+f"PPT_Base_File/{set_name}/")
utils.makedir(args.user_path+f"PPT_Label_File/{set_name}/")
for step, instruction in enumerate(dialogue):
instruction = instruction.split("##")[0]
label_apis = utils.merge_list(labels[idx][:step])
if args.dataset == 'long':
ppt_assistant.load_ppt(os.path.join(args.user_path+'long_slides',f'{idx}.pptx'))
else:
ppt_assistant.load_ppt(None)
ppt_assistant.api_executor(label_apis,test=False)
if args.api_lack:
ppt_executor.save_ppt(args.user_path+f"PPT_Base_File/{set_name}_API_lack/{idx}_{step}.pptx")
else:
ppt_executor.save_ppt(args.user_path+f"PPT_Base_File/{set_name}/{idx}_{step}.pptx")
ppt_assistant.api_executor(labels[idx][step],test=False)
if args.api_lack:
ppt_executor.save_ppt(args.user_path+f"PPT_Label_File/{set_name}_API_lack/{idx}_{step}.pptx")
else:
ppt_executor.save_ppt(args.user_path+f"PPT_Label_File/{set_name}/{idx}_{step}.pptx")
print(f"{idx}/{step} done!")
def test(ppt_assistant, args):
set_name = 'Create_new_slides' if args.dataset == 'short' else 'Edit_PPT_template'
utils.makedir(args.user_path+f'PPT_Pred_File/{set_name}')
utils.makedir(args.user_path+f'PPT_Prompt_File/{set_name}')
for sess_id, session_path in enumerate(utils.sorted_list(args.user_path+f'PPT_test_input/{set_name}')):
session = utils.parse_train_json(args.user_path+f'PPT_test_input/{set_name}/{session_path}')
chat_history = []
for turn_id, turn in tqdm(enumerate(session)):
print(f"{sess_id}/{turn_id}")
if args.resume:
if args.tf and os.path.exists(args.user_path+f'PPT_Pred_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.pptx'):
print('Exists!')
continue
if args.sess and os.path.exists(args.user_path+f'PPT_Pred_File/{set_name}/{args.exp_name}_{sess_id}_{len(session)-1}.pptx'):
print('Exists!')
continue
turn_id, instruction, label_api, base_ppt_path, label_ppt_path, api_lack_base_ppt_path, api_lack_label_ppt_path = turn
if turn_id == 0 and args.sess:
if args.api_lack:
ppt_assistant.load_ppt(args.user_path+api_lack_base_ppt_path)
label_file = api_lack_label_ppt_path
else:
ppt_assistant.load_ppt(args.user_path+base_ppt_path)
label_file = label_ppt_path
splitted_instruction = instruction.split("##")[0]
if args.tf:
if args.api_lack:
ppt_assistant.load_ppt(args.user_path+api_lack_base_ppt_path)
label_file = api_lack_label_ppt_path
else:
ppt_assistant.load_ppt(args.user_path+base_ppt_path)
label_file = label_ppt_path
ppt_assistant.load_chat_history([x[0] for x in chat_history],[x[1].strip(';').split(';') for x in chat_history])
prompt, reply = ppt_assistant.chat(splitted_instruction, ppt_path=args.user_path+base_ppt_path, verbose=False)
apis = utils.parse_api(reply)
ppt_assistant.api_executor(apis,test=True)
ppt_executor.save_ppt(args.user_path+f'PPT_Pred_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.pptx')
utils.write_lines([prompt],args.user_path+f'PPT_Prompt_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.txt')
#import pdb
#pdb.set_trace()
with jsonlines.open(args.user_path+f"PPT_test_output/{set_name}/{args.exp_name}_session_{sess_id}.json", mode='a') as writer:
data={'Turn':turn_id,'User instruction':instruction,'Feasible API sequence':label_api,'Reply':reply,'Pred API sequence':apis,'Pred File':f'PPT_Pred_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.pptx','Label File':label_file,'Prompt File':f'PPT_Prompt_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.txt'}
writer.write(data)
chat_history.append([splitted_instruction, label_api])
elif args.sess:
prompt, reply = ppt_assistant.chat(instruction, ppt_path=None, verbose=False)
apis = utils.parse_api(reply)
ppt_assistant.api_executor(apis,test=True)
ppt_executor.save_ppt(args.user_path+f'PPT_Pred_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.pptx')
utils.write_lines([prompt],args.user_path+f'PPT_Prompt_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.txt')
with jsonlines.open(args.user_path+f"PPT_test_output/{set_name}/{args.exp_name}_session_{sess_id}.json", mode='a') as writer:
data={'Turn':turn_id,'User instruction':instruction,'Feasible API sequence':label_api,'Reply':reply,'Pred API sequence':apis,'Pred File':f'PPT_Pred_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.pptx','Label File':label_file,'Prompt File':f'PPT_Prompt_File/{set_name}/{args.exp_name}_{sess_id}_{turn_id}.txt'}
writer.write(data)
def test_planning(ppt_assistant):
instructions, labels = dataset.load_data(args.data_path, args.dataset)
f = open(f'test_system/planning_{args.dataset}.txt','a+')
for idx, dialogue in tqdm(enumerate(instructions)):
for step, instruction in enumerate(dialogue):
instruction = instruction.split("##")[0]
try:
planned = ppt_assistant.planner(instruction)
f.write(f'{idx}/{step}\n')
f.write(instruction+'\n')
f.write(str(planned)+'\n\n')
f.flush()
except:
pass
def test_api_selection(ppt_assistant):
instructions, labels = dataset.load_data(args.data_path, args.dataset)
f = open(f'test_system/api_selection_{args.api_topk}_{args.dataset}.txt','a+')
cnt = 0
for idx, dialogue in tqdm(enumerate(instructions)):
for step, instruction in enumerate(dialogue):
label_apis = labels[idx][step]
instruction = instruction.split("##")[0]
# instructions = ppt_assistant.planner(instruction)
# selected_apis = []
# for ins in instructions:
# selected_apis.extend(ppt_assistant.api_selector(ins))
selected_apis = ppt_assistant.api_selector(instruction)
selected_apis = [x.name for x in selected_apis]
for xx in label_apis:
if ('align_slide' in xx.split('(')[0]) or (xx.split('(')[0] in ['set_left','set_right','set_top','set_bottom']) or ('corner' in xx.split('(')[0]):
continue
if not xx.split('(')[0] in selected_apis:
f.write(f'{idx}/{step}\n')
f.write(instruction+'\n')
f.write(xx.split('(')[0]+'\n')
f.write(str(selected_apis)+'\n\n')
f.flush()
cnt += 1
print(cnt)
def test_content_selection(ppt_assistant):
instructions, labels = dataset.load_data(args.data_path, args.dataset)
f = open(f'test_system/content_selection_{args.dataset}.txt','a+')
for idx, dialogue in tqdm(enumerate(instructions)):
for step, instruction in enumerate(dialogue):
instruction = instruction.split("##")[0]
prompt = prompt_factor.PPT_content_selection_prompt.format(instruction)
reply = openai_api.query_azure_openai(prompt, model='turbo')
f.write(f'{idx}/{step}\n')
f.write(instruction+'\n')
f.write(reply+'\n\n')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# PPT assistant
parser.add_argument("--data_path", default="test", type=str,
help="The data path to load the instructions")
parser.add_argument("--dataset", default="short", type=str,
help="short/long")
parser.add_argument("--model_id", default="None", type=str,
help="short/long")
parser.add_argument("--user_path", default='./PPTC/', type=str,
help="the user storage file path ")
parser.add_argument("--save_path", default="test_pptx_data", type=str,
help="the path to save the intermediate ppts.")
# mode
parser.add_argument("--prepare", default=False, action='store_true',
help='whether to prepare the data for the model')
parser.add_argument("--eval", default=False, action='store_true',
help='whether to evaluate the pptx file generated by the model')
parser.add_argument("--test", default=False, action='store_true',
help='whether to test on the instruction data loaded from data_path')
parser.add_argument("--tf", default=False, action='store_true',
help='whether to use teacher forcing mode')
parser.add_argument("--sess", default=False, action='store_true',
help='whether to test from session level')
parser.add_argument("--resume", default=False, action='store_true',
help='whether to continue generation from the last unfinished instruction')
# modeling
parser.add_argument("--model", default="turbo",type=str,
help="turbo/gpt4/text3")
parser.add_argument("--planning", default=False, action='store_true',
help="whether to apply the planning module")
parser.add_argument("--api_selection", default=False, action='store_true',
help="whether to apply the api selection module")
parser.add_argument("--api_topk", default=10, type=int,
help="How many apis to retrieve from the api pool")
parser.add_argument("--content_selection", default=False, action='store_true',
help="whether to apply the shape selection module")
# api update/lack
parser.add_argument("--api_lack", default=False, action='store_true',
help='whether to test in the api lack setting')
parser.add_argument("--api_update", default=False, action='store_true',
help='whether to test in the api update setting')
parser.add_argument("--second", default=False, action='store_true',
help='second test')
parser.add_argument("--robust", default=False, action='store_true',
help='whether to test in robust data')
parser.add_argument("--robust_num", default=0, type=int,
help="which robusted data")
parser.add_argument("--noisy", default=False, action='store_true',
help='whether to test in noisy data')
args = parser.parse_args()
args.exp_name = utils.prepare_exp_name(args)
args.save_path = os.path.join(args.save_path,args.dataset)
api_selection.prepare_embedding(args) | ppt_assistant = modeling.PPT_assistant(args) | 7 | 2023-10-25 13:14:46+00:00 | 8k |
nv-tlabs/pacer | pacer/env/tasks/humanoid_pedestrain_terrain.py | [
{
"identifier": "flags",
"path": "pacer/utils/flags.py",
"snippet": "class Flags(object):\n def __init__(self, items):"
},
{
"identifier": "quat_inverse",
"path": "poselib/poselib/core/rotation3d.py",
"snippet": "@torch.jit.script\ndef quat_inverse(x):\n \"\"\"\n The inverse of ... | from shutil import ExecError
from isaacgym import gymapi
from isaacgym.torch_utils import *
from env.tasks.humanoid import dof_to_obs
from env.tasks.humanoid_amp import HumanoidAMP, remove_base_rot
from pacer.utils.flags import flags
from utils import torch_utils
from isaacgym import gymtorch
from poselib.poselib.core.rotation3d import quat_inverse, quat_mul
from tqdm import tqdm
from scipy.spatial.transform import Rotation as sRot
from typing import OrderedDict
from pacer.utils.draw_utils import agt_color
from pacer.env.tasks.humanoid import compute_humanoid_observations_smpl_max, compute_humanoid_observations_smpl,\
compute_humanoid_observations_max, compute_humanoid_observations,\
ENABLE_MAX_COORD_OBS
from isaacgym.terrain_utils import *
from pacer.utils.draw_utils import *
import torch
import numpy as np
import env.tasks.humanoid_traj as humanoid_traj
import joblib
import matplotlib.pyplot as plt | 4,958 | self.sensor_extent = cfg["env"].get("sensor_extent", 2)
self.sensor_res = cfg["env"].get("sensor_res", 32)
self.power_reward = cfg["env"].get("power_reward", False)
self.power_coefficient = cfg["env"].get("power_coefficient", 0.0005)
self.fuzzy_target = cfg["env"].get("fuzzy_target", False)
self.square_height_points = self.init_square_height_points()
self.terrain_obs_type = self.cfg['env'].get("terrain_obs_type",
"square")
self.terrain_obs = self.cfg['env'].get("terrain_obs", False)
self.terrain_obs_root = self.cfg['env'].get("terrain_obs_root",
"pelvis")
if self.terrain_obs_type == "fov":
self.height_points = self.init_fov_height_points()
elif self.terrain_obs_type == "square_fov":
self.height_points = self.init_square_fov_height_points()
elif self.terrain_obs_type == "square":
self.height_points = self.square_height_points
self.root_points = self.init_root_points()
self.center_height_points = self.init_center_height_points()
self.height_meas_scale = 5
self.show_sensors = self.cfg['args'].show_sensors
if (not self.headless) and self.show_sensors:
self._sensor_handles = [[] for _ in range(self.num_envs)]
super().__init__(cfg=cfg,
sim_params=sim_params,
physics_engine=physics_engine,
device_type=device_type,
device_id=device_id,
headless=headless)
self.reward_raw = torch.zeros((self.num_envs, 2)).to(self.device)
if (not self.headless) and self.show_sensors:
self._build_sensor_state_tensors()
return
def _build_env(self, env_id, env_ptr, humanoid_asset):
super()._build_env(env_id, env_ptr, humanoid_asset)
if (not self.headless) and self.show_sensors:
self._load_sensor_asset()
self._build_sensor(env_id, env_ptr)
return
def _build_sensor(self, env_id, env_ptr):
default_pose = gymapi.Transform()
for i in range(self.num_height_points):
marker_handle = self.gym.create_actor(env_ptr, self._sensor_asset,
default_pose, "marker",
self.num_envs + 1, 0, 0)
self.gym.set_rigid_body_color(env_ptr, marker_handle, 0,
gymapi.MESH_VISUAL,
gymapi.Vec3(*agt_color(env_id)))
self._sensor_handles[env_id].append(marker_handle)
return
def _build_sensor_state_tensors(self):
num_actors = self._root_states.shape[0] // self.num_envs
self._sensor_states = self._root_states.view(self.num_envs, num_actors, self._root_states.shape[-1])[..., 11:(11 + self.num_height_points), :]
self._sensor_pos = self._sensor_states[..., :3]
self._sensor_actor_ids = self._humanoid_actor_ids.unsqueeze(-1) + to_torch(self._sensor_handles, dtype=torch.int32, device=self.device)
self._sensor_actor_ids = self._sensor_actor_ids.flatten()
return
def _load_sensor_asset(self):
asset_root = "pacer/data/assets/mjcf/"
asset_file = "sensor_marker.urdf"
asset_options = gymapi.AssetOptions()
asset_options.angular_damping = 0.01
asset_options.linear_damping = 0.01
asset_options.max_angular_velocity = 100.0
asset_options.density = 1.0
asset_options.fix_base_link = True
asset_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE
self._sensor_asset = self.gym.load_asset(self.sim, asset_root,
asset_file, asset_options)
return
def _draw_task(self):
# cols = np.array([[1.0, 0.0, 0.0]], dtype=np.float32)
norm_states = self.get_head_pose()
base_quat = norm_states[:, 3:7]
if not self._has_upright_start:
base_quat = remove_base_rot(base_quat)
heading_rot = torch_utils.calc_heading_quat(base_quat)
points = quat_apply(
heading_rot.repeat(1, self.num_height_points).reshape(-1, 4),
self.height_points) + (norm_states[:, :3]).unsqueeze(1)
if (not self.headless) and self.show_sensors:
self._sensor_pos[:] = points
# self._sensor_pos[..., 2] += 0.3
# self._sensor_pos[..., 2] -= 5
traj_samples = self._fetch_traj_samples()
self._marker_pos[:] = traj_samples
self._marker_pos[..., 2] = self._humanoid_root_states[..., 2:3] # jp hack # ZL hack
# self._marker_pos[..., 2] = 0.89
# self._marker_pos[..., 2] = 0
if (not self.headless) and self.show_sensors:
comb_idx = torch.cat([self._sensor_actor_ids, self._marker_actor_ids])
else:
comb_idx = torch.cat([self._marker_actor_ids])
| # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
HACK_MOTION_SYNC = False
class HumanoidPedestrianTerrain(humanoid_traj.HumanoidTraj):
def __init__(self, cfg, sim_params, physics_engine, device_type, device_id,
headless):
## ZL Hack to get the height map to load.
self.real_mesh = cfg['args'].real_mesh
self.device = "cpu"
self.device_type = device_type
if device_type == "cuda" or device_type == "GPU":
self.device = "cuda" + ":" + str(device_id)
self.load_smpl_configs(cfg)
self.cfg = cfg
self.num_envs = cfg["env"]["numEnvs"]
self.device_type = cfg.get("device_type", "cuda")
self.device_id = cfg.get("device_id", 0)
self.headless = cfg["headless"]
self.sensor_extent = cfg["env"].get("sensor_extent", 2)
self.sensor_res = cfg["env"].get("sensor_res", 32)
self.power_reward = cfg["env"].get("power_reward", False)
self.power_coefficient = cfg["env"].get("power_coefficient", 0.0005)
self.fuzzy_target = cfg["env"].get("fuzzy_target", False)
self.square_height_points = self.init_square_height_points()
self.terrain_obs_type = self.cfg['env'].get("terrain_obs_type",
"square")
self.terrain_obs = self.cfg['env'].get("terrain_obs", False)
self.terrain_obs_root = self.cfg['env'].get("terrain_obs_root",
"pelvis")
if self.terrain_obs_type == "fov":
self.height_points = self.init_fov_height_points()
elif self.terrain_obs_type == "square_fov":
self.height_points = self.init_square_fov_height_points()
elif self.terrain_obs_type == "square":
self.height_points = self.square_height_points
self.root_points = self.init_root_points()
self.center_height_points = self.init_center_height_points()
self.height_meas_scale = 5
self.show_sensors = self.cfg['args'].show_sensors
if (not self.headless) and self.show_sensors:
self._sensor_handles = [[] for _ in range(self.num_envs)]
super().__init__(cfg=cfg,
sim_params=sim_params,
physics_engine=physics_engine,
device_type=device_type,
device_id=device_id,
headless=headless)
self.reward_raw = torch.zeros((self.num_envs, 2)).to(self.device)
if (not self.headless) and self.show_sensors:
self._build_sensor_state_tensors()
return
def _build_env(self, env_id, env_ptr, humanoid_asset):
super()._build_env(env_id, env_ptr, humanoid_asset)
if (not self.headless) and self.show_sensors:
self._load_sensor_asset()
self._build_sensor(env_id, env_ptr)
return
def _build_sensor(self, env_id, env_ptr):
default_pose = gymapi.Transform()
for i in range(self.num_height_points):
marker_handle = self.gym.create_actor(env_ptr, self._sensor_asset,
default_pose, "marker",
self.num_envs + 1, 0, 0)
self.gym.set_rigid_body_color(env_ptr, marker_handle, 0,
gymapi.MESH_VISUAL,
gymapi.Vec3(*agt_color(env_id)))
self._sensor_handles[env_id].append(marker_handle)
return
def _build_sensor_state_tensors(self):
num_actors = self._root_states.shape[0] // self.num_envs
self._sensor_states = self._root_states.view(self.num_envs, num_actors, self._root_states.shape[-1])[..., 11:(11 + self.num_height_points), :]
self._sensor_pos = self._sensor_states[..., :3]
self._sensor_actor_ids = self._humanoid_actor_ids.unsqueeze(-1) + to_torch(self._sensor_handles, dtype=torch.int32, device=self.device)
self._sensor_actor_ids = self._sensor_actor_ids.flatten()
return
def _load_sensor_asset(self):
asset_root = "pacer/data/assets/mjcf/"
asset_file = "sensor_marker.urdf"
asset_options = gymapi.AssetOptions()
asset_options.angular_damping = 0.01
asset_options.linear_damping = 0.01
asset_options.max_angular_velocity = 100.0
asset_options.density = 1.0
asset_options.fix_base_link = True
asset_options.default_dof_drive_mode = gymapi.DOF_MODE_NONE
self._sensor_asset = self.gym.load_asset(self.sim, asset_root,
asset_file, asset_options)
return
def _draw_task(self):
# cols = np.array([[1.0, 0.0, 0.0]], dtype=np.float32)
norm_states = self.get_head_pose()
base_quat = norm_states[:, 3:7]
if not self._has_upright_start:
base_quat = remove_base_rot(base_quat)
heading_rot = torch_utils.calc_heading_quat(base_quat)
points = quat_apply(
heading_rot.repeat(1, self.num_height_points).reshape(-1, 4),
self.height_points) + (norm_states[:, :3]).unsqueeze(1)
if (not self.headless) and self.show_sensors:
self._sensor_pos[:] = points
# self._sensor_pos[..., 2] += 0.3
# self._sensor_pos[..., 2] -= 5
traj_samples = self._fetch_traj_samples()
self._marker_pos[:] = traj_samples
self._marker_pos[..., 2] = self._humanoid_root_states[..., 2:3] # jp hack # ZL hack
# self._marker_pos[..., 2] = 0.89
# self._marker_pos[..., 2] = 0
if (not self.headless) and self.show_sensors:
comb_idx = torch.cat([self._sensor_actor_ids, self._marker_actor_ids])
else:
comb_idx = torch.cat([self._marker_actor_ids])
| if flags.show_traj: | 0 | 2023-10-31 20:47:12+00:00 | 8k |
Improbable-AI/dexenv | dexenv/envs/dclaw_rptd.py | [
{
"identifier": "DclawMultiObjs",
"path": "dexenv/envs/dclaw_multiobjs.py",
"snippet": "class DclawMultiObjs(DClawBase):\n def __init__(self, cfg, sim_device, rl_device, graphics_device_id):\n self.set_random_gen()\n self.object_urdfs, self.dataset_path, self.obj_name_to_cat_id = self.p... | import numpy as np
import pytorch3d.transforms as p3dtf
import torch
import dexenv
from gym import spaces
from isaacgym import gymapi
from scipy.spatial.transform import Rotation as R
from dexenv.envs.dclaw_multiobjs import DclawMultiObjs
from dexenv.utils.common import load_from_pickle
from dexenv.utils.isaac_utils import get_camera_params
from dexenv.utils.point_cloud_utils import CameraPointCloud
from dexenv.utils.torch_utils import quat_xyzw_to_wxyz
from dexenv.utils.torch_utils import torch_float
from dexenv.utils.torch_utils import torch_long | 6,479 | 1,
1)
def _create_envs(self, num_envs, spacing, num_per_row):
lower = gymapi.Vec3(-spacing, -spacing, 0.0)
upper = gymapi.Vec3(spacing, spacing, spacing)
dclaw_asset, dclaw_dof_props = self.get_dclaw_asset(asset_root=None)
object_assets, goal_assets, object_ids, object_textures, object_ptds, object_cat_ids = self.load_object_asset()
table_asset = self.get_table_asset()
table_pose = self.get_table_pose()
if self.obs_type == "full_state":
sensor_pose = gymapi.Transform()
for ft_handle in self.fingertip_handles:
self.gym.create_asset_force_sensor(dclaw_asset, ft_handle, sensor_pose)
dclaw_start_pose = self.get_dclaw_start_pose()
object_start_pose = self.get_object_start_pose(dclaw_start_pose)
goal_start_pose = self.get_goal_object_start_pose(object_start_pose=object_start_pose)
self.dclaws = []
self.envs = []
self.object_init_state = []
self.hand_start_states = []
self.hand_indices = []
self.fingertip_indices = []
self.object_indices = []
self.object_cat_indices = []
self.goal_object_indices = []
self.cam_handles = []
self.fingertip_handles = [self.gym.find_asset_rigid_body_index(dclaw_asset, name) for name in
self.fingertips]
camera_poses, camera_params = self.get_camera_setup()
dclaw_rb_count = self.gym.get_asset_rigid_body_count(dclaw_asset)
object_rb_count = self.gym.get_asset_rigid_body_count(object_assets[0])
self.object_rb_handles = list(range(dclaw_rb_count, dclaw_rb_count + object_rb_count))
num_object_assets = len(object_assets)
env_obj_ids = []
self.object_ptds = []
self.object_handles = []
for i in range(self.num_envs):
obj_asset_id = i % num_object_assets
env_obj_ids.append(object_ids[obj_asset_id])
env_ptr = self.gym.create_env(
self.sim, lower, upper, num_per_row
)
self.object_ptds.append(object_ptds[obj_asset_id])
if self.aggregate_mode >= 1:
# compute aggregate size
obj_num_bodies = self.gym.get_asset_rigid_body_count(object_assets[obj_asset_id])
obj_num_shapes = self.gym.get_asset_rigid_shape_count(object_assets[obj_asset_id])
max_agg_bodies = self.num_dclaw_bodies + obj_num_bodies * 2 + 1
max_agg_shapes = self.num_dclaw_shapes + obj_num_shapes * 2 + 1
self.gym.begin_aggregate(env_ptr, max_agg_bodies, max_agg_shapes, True)
self.create_hand_actor(env_ptr=env_ptr,
dclaw_asset=dclaw_asset,
dclaw_start_pose=dclaw_start_pose,
dclaw_dof_props=dclaw_dof_props,
env_id=i)
# add object
object_handle = self.gym.create_actor(env_ptr, object_assets[obj_asset_id],
object_start_pose, "object", i, 0, 1)
self.object_handles.append(object_handle)
self.object_init_state.append([object_start_pose.p.x, object_start_pose.p.y, object_start_pose.p.z,
object_start_pose.r.x, object_start_pose.r.y, object_start_pose.r.z,
object_start_pose.r.w,
0, 0, 0, 0, 0, 0])
object_idx = self.gym.get_actor_index(env_ptr, object_handle, gymapi.DOMAIN_SIM)
self.object_indices.append(object_idx)
self.object_cat_indices.append(object_cat_ids[obj_asset_id])
# add goal object
goal_handle = self.gym.create_actor(env_ptr, goal_assets[obj_asset_id],
goal_start_pose, "goal_object",
i + self.num_envs,
0, 2)
goal_object_idx = self.gym.get_actor_index(env_ptr, goal_handle, gymapi.DOMAIN_SIM)
self.goal_object_indices.append(goal_object_idx)
if self.cfg.obj.load_texture:
self.gym.set_rigid_body_texture(env_ptr,
object_handle,
0,
gymapi.MESH_VISUAL_AND_COLLISION,
object_textures[obj_asset_id]
)
self.gym.set_rigid_body_texture(env_ptr,
goal_handle,
0,
gymapi.MESH_VISUAL_AND_COLLISION,
object_textures[obj_asset_id]
)
else:
self.gym.set_rigid_body_color(
env_ptr, object_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98))
self.gym.set_rigid_body_color(
env_ptr, goal_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98))
cam_handles = self.create_camera(camera_poses, env_ptr, camera_params)
self.cam_handles.append(cam_handles)
table_handle = self.gym.create_actor(env_ptr, table_asset, table_pose, "table", i, 0)
self.gym.set_rigid_body_color(env_ptr, table_handle, 0, gymapi.MESH_VISUAL,
gymapi.Vec3(180 / 255., 180 / 255., 180 / 255.))
if self.aggregate_mode > 0:
self.gym.end_aggregate(env_ptr)
self.envs.append(env_ptr)
self.setup_ptd_cam(camera_params)
self.setup_torch_states()
self.env_obj_ids = torch.LongTensor(env_obj_ids).to(self.device).view(-1, 1)
self.object_cat_indices = torch.LongTensor(self.object_cat_indices).to(self.device).view(-1, 1)
self.object_ptds = np.stack(self.object_ptds, axis=0)
|
class DclawRealPTD(DclawMultiObjs):
def __init__(self, cfg, sim_device, rl_device,
graphics_device_id, quantization_size=None):
cfg.env.enableCameraSensors = True
super().__init__(cfg=cfg,
sim_device=sim_device,
rl_device=rl_device,
graphics_device_id=graphics_device_id)
self.quantization_size = quantization_size
self.read_finger_ptd()
ob_buf_shape = (self.cfg.env.robotCadNumPts * len(self.ptd_body_links) + self.cfg.env.objCadNumPts + self.cfg.cam.sample_num, 3)
self.obs_space = spaces.Dict({'ob': spaces.Box(np.ones(ob_buf_shape) * -np.Inf, np.ones(ob_buf_shape) * np.Inf),
'state': spaces.Box(np.ones(self.num_obs) * -np.Inf, np.ones(self.num_obs) * np.Inf)})
def read_finger_ptd(self):
ptd_path = dexenv.LIB_PATH.joinpath('assets', f'{self.cfg.env.robot}', 'meshes',
'visual', f'point_cloud_{self.cfg.env.robotCadNumPts}_pts.pkl')
self.hand_ptd_dict = load_from_pickle(ptd_path)
body_links = list(self.hand_ptd_dict.keys())
body_links.remove('base_link')
self.ptd_body_links = body_links
self.hand_body_links_to_handles = self.gym.get_actor_rigid_body_dict(self.envs[0], self.dclaws[0])
self.hand_ptds = torch.from_numpy(np.stack([self.hand_ptd_dict[x] for x in self.ptd_body_links]))
self.hand_ptds = self.hand_ptds.to(self.device)
self.base_link_handle = torch_long([self.hand_body_links_to_handles['base_link']])
self.hand_body_handles = [self.hand_body_links_to_handles[x] for x in self.ptd_body_links]
self.hand_body_handles = torch_long(self.hand_body_handles, device=self.device)
hand_ptds = self.hand_ptds.repeat(self.num_envs, 1, 1, 1)
self.scene_cad_ptd = torch.cat((hand_ptds, self.object_ptds.unsqueeze(1)), dim=1)
self.scene_cad_ptd = self.scene_cad_ptd.view(-1, self.scene_cad_ptd.shape[-2],
self.scene_cad_ptd.shape[-1]).float()
self.scene_ptd_buf = torch.zeros(
(self.num_envs, self.cfg.env.robotCadNumPts * len(self.ptd_body_links) + self.cfg.env.objCadNumPts + self.cfg.cam.sample_num, 3),
device=self.device, dtype=torch.float)
self.se3_T_buf = torch.eye(4, device=self.device).repeat(self.num_envs * (len(self.ptd_body_links) + 1),
1,
1)
def _create_envs(self, num_envs, spacing, num_per_row):
lower = gymapi.Vec3(-spacing, -spacing, 0.0)
upper = gymapi.Vec3(spacing, spacing, spacing)
dclaw_asset, dclaw_dof_props = self.get_dclaw_asset(asset_root=None)
object_assets, goal_assets, object_ids, object_textures, object_ptds, object_cat_ids = self.load_object_asset()
table_asset = self.get_table_asset()
table_pose = self.get_table_pose()
if self.obs_type == "full_state":
sensor_pose = gymapi.Transform()
for ft_handle in self.fingertip_handles:
self.gym.create_asset_force_sensor(dclaw_asset, ft_handle, sensor_pose)
dclaw_start_pose = self.get_dclaw_start_pose()
object_start_pose = self.get_object_start_pose(dclaw_start_pose)
goal_start_pose = self.get_goal_object_start_pose(object_start_pose=object_start_pose)
self.dclaws = []
self.envs = []
self.object_init_state = []
self.hand_start_states = []
self.hand_indices = []
self.fingertip_indices = []
self.object_indices = []
self.object_cat_indices = []
self.goal_object_indices = []
self.cam_handles = []
self.fingertip_handles = [self.gym.find_asset_rigid_body_index(dclaw_asset, name) for name in
self.fingertips]
camera_poses, camera_params = self.get_camera_setup()
dclaw_rb_count = self.gym.get_asset_rigid_body_count(dclaw_asset)
object_rb_count = self.gym.get_asset_rigid_body_count(object_assets[0])
self.object_rb_handles = list(range(dclaw_rb_count, dclaw_rb_count + object_rb_count))
num_object_assets = len(object_assets)
env_obj_ids = []
self.object_ptds = []
self.object_handles = []
for i in range(self.num_envs):
obj_asset_id = i % num_object_assets
env_obj_ids.append(object_ids[obj_asset_id])
env_ptr = self.gym.create_env(
self.sim, lower, upper, num_per_row
)
self.object_ptds.append(object_ptds[obj_asset_id])
if self.aggregate_mode >= 1:
# compute aggregate size
obj_num_bodies = self.gym.get_asset_rigid_body_count(object_assets[obj_asset_id])
obj_num_shapes = self.gym.get_asset_rigid_shape_count(object_assets[obj_asset_id])
max_agg_bodies = self.num_dclaw_bodies + obj_num_bodies * 2 + 1
max_agg_shapes = self.num_dclaw_shapes + obj_num_shapes * 2 + 1
self.gym.begin_aggregate(env_ptr, max_agg_bodies, max_agg_shapes, True)
self.create_hand_actor(env_ptr=env_ptr,
dclaw_asset=dclaw_asset,
dclaw_start_pose=dclaw_start_pose,
dclaw_dof_props=dclaw_dof_props,
env_id=i)
# add object
object_handle = self.gym.create_actor(env_ptr, object_assets[obj_asset_id],
object_start_pose, "object", i, 0, 1)
self.object_handles.append(object_handle)
self.object_init_state.append([object_start_pose.p.x, object_start_pose.p.y, object_start_pose.p.z,
object_start_pose.r.x, object_start_pose.r.y, object_start_pose.r.z,
object_start_pose.r.w,
0, 0, 0, 0, 0, 0])
object_idx = self.gym.get_actor_index(env_ptr, object_handle, gymapi.DOMAIN_SIM)
self.object_indices.append(object_idx)
self.object_cat_indices.append(object_cat_ids[obj_asset_id])
# add goal object
goal_handle = self.gym.create_actor(env_ptr, goal_assets[obj_asset_id],
goal_start_pose, "goal_object",
i + self.num_envs,
0, 2)
goal_object_idx = self.gym.get_actor_index(env_ptr, goal_handle, gymapi.DOMAIN_SIM)
self.goal_object_indices.append(goal_object_idx)
if self.cfg.obj.load_texture:
self.gym.set_rigid_body_texture(env_ptr,
object_handle,
0,
gymapi.MESH_VISUAL_AND_COLLISION,
object_textures[obj_asset_id]
)
self.gym.set_rigid_body_texture(env_ptr,
goal_handle,
0,
gymapi.MESH_VISUAL_AND_COLLISION,
object_textures[obj_asset_id]
)
else:
self.gym.set_rigid_body_color(
env_ptr, object_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98))
self.gym.set_rigid_body_color(
env_ptr, goal_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98))
cam_handles = self.create_camera(camera_poses, env_ptr, camera_params)
self.cam_handles.append(cam_handles)
table_handle = self.gym.create_actor(env_ptr, table_asset, table_pose, "table", i, 0)
self.gym.set_rigid_body_color(env_ptr, table_handle, 0, gymapi.MESH_VISUAL,
gymapi.Vec3(180 / 255., 180 / 255., 180 / 255.))
if self.aggregate_mode > 0:
self.gym.end_aggregate(env_ptr)
self.envs.append(env_ptr)
self.setup_ptd_cam(camera_params)
self.setup_torch_states()
self.env_obj_ids = torch.LongTensor(env_obj_ids).to(self.device).view(-1, 1)
self.object_cat_indices = torch.LongTensor(self.object_cat_indices).to(self.device).view(-1, 1)
self.object_ptds = np.stack(self.object_ptds, axis=0) | self.object_ptds = torch_float(self.object_ptds, device=self.device) | 5 | 2023-10-25 17:22:41+00:00 | 8k |
ai-safety-foundation/sparse_autoencoder | sparse_autoencoder/metrics/train/neuron_activity_metric.py | [
{
"identifier": "MetricLocation",
"path": "sparse_autoencoder/metrics/abstract_metric.py",
"snippet": "class MetricLocation(SnakeCaseStrEnum):\n \"\"\"Metric location.\n\n Metrics can be logged at different stages of the training pipeline. This enum is used to define\n when the metric was logge... | from jaxtyping import Float, Int, Int64
from torch import Tensor
from sparse_autoencoder.metrics.abstract_metric import (
MetricLocation,
MetricResult,
)
from sparse_autoencoder.metrics.train.abstract_train_metric import (
AbstractTrainMetric,
TrainMetricData,
)
from sparse_autoencoder.tensor_types import Axis
import numpy as np
import torch
import wandb | 4,602 | """Neuron activity metric.
Logs the number of dead and alive neurons at various horizons. Also logs histograms of neuron
activity, and the number of neurons that are almost dead.
"""
DEFAULT_HORIZONS = [10_000, 100_000, 1_000_000, 10_000_000]
"""Default horizons (in number of logged activations)."""
DEFAULT_THRESHOLDS = [1e-5, 1e-6]
"""Default thresholds for determining if a neuron is almost dead."""
class NeuronActivityHorizonData:
"""Neuron activity data for a specific horizon (number of activations seen).
For each time horizon we store some data (e.g. the number of times each neuron fired inside this
time horizon). This class also contains some helper methods for then calculating metrics from
this data.
"""
_horizon_n_activations: int
"""Horizon in number of activations."""
_horizon_steps: int
"""Horizon in number of steps."""
_steps_since_last_calculated: int
"""Steps since last calculated."""
_neuron_activity: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)]
"""Neuron activity since inception."""
_thresholds: list[float]
"""Thresholds for almost dead neurons."""
_n_components: int
"""Number of components."""
_n_learned_features: int
"""Number of learned features."""
@property
def _dead_count(self) -> Int[Tensor, Axis.COMPONENT]:
"""Dead count."""
dead_bool_mask: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)] = (
self._neuron_activity == 0
)
return dead_bool_mask.sum(-1)
@property
def _dead_fraction(self) -> Float[Tensor, Axis.COMPONENT]:
"""Dead fraction."""
return self._dead_count / self._n_learned_features
@property
def _alive_count(self) -> Int[Tensor, Axis.COMPONENT]:
"""Alive count."""
alive_bool_mask: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)] = (
self._neuron_activity > 0
)
return alive_bool_mask.sum(-1)
def _almost_dead(self, threshold: float) -> Int[Tensor, Axis.COMPONENT]:
"""Almost dead count."""
threshold_in_activations: float = threshold * self._horizon_n_activations
almost_dead_bool_mask: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)] = (
self._neuron_activity < threshold_in_activations
)
return almost_dead_bool_mask.sum(-1)
@property
def _activity_histogram(self) -> list[wandb.Histogram]:
"""Activity histogram."""
numpy_neuron_activity: Float[
np.ndarray, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)
] = self._neuron_activity.cpu().numpy()
np_histograms = [np.histogram(activity) for activity in numpy_neuron_activity]
return [wandb.Histogram(np_histogram=histogram) for histogram in np_histograms]
@property
def _log_activity_histogram(self) -> list[wandb.Histogram]:
"""Log activity histogram."""
log_epsilon = 0.1 # To avoid log(0)
log_neuron_activity: Float[
Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)
] = torch.log(self._neuron_activity + log_epsilon)
numpy_log_neuron_activity: Float[
np.ndarray, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)
] = log_neuron_activity.cpu().numpy()
np_histograms = [np.histogram(activity) for activity in numpy_log_neuron_activity]
return [wandb.Histogram(np_histogram=histogram) for histogram in np_histograms]
@property
def metric_results(self) -> list[MetricResult]:
"""Metric results."""
| """Neuron activity metric.
Logs the number of dead and alive neurons at various horizons. Also logs histograms of neuron
activity, and the number of neurons that are almost dead.
"""
DEFAULT_HORIZONS = [10_000, 100_000, 1_000_000, 10_000_000]
"""Default horizons (in number of logged activations)."""
DEFAULT_THRESHOLDS = [1e-5, 1e-6]
"""Default thresholds for determining if a neuron is almost dead."""
class NeuronActivityHorizonData:
"""Neuron activity data for a specific horizon (number of activations seen).
For each time horizon we store some data (e.g. the number of times each neuron fired inside this
time horizon). This class also contains some helper methods for then calculating metrics from
this data.
"""
_horizon_n_activations: int
"""Horizon in number of activations."""
_horizon_steps: int
"""Horizon in number of steps."""
_steps_since_last_calculated: int
"""Steps since last calculated."""
_neuron_activity: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)]
"""Neuron activity since inception."""
_thresholds: list[float]
"""Thresholds for almost dead neurons."""
_n_components: int
"""Number of components."""
_n_learned_features: int
"""Number of learned features."""
@property
def _dead_count(self) -> Int[Tensor, Axis.COMPONENT]:
"""Dead count."""
dead_bool_mask: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)] = (
self._neuron_activity == 0
)
return dead_bool_mask.sum(-1)
@property
def _dead_fraction(self) -> Float[Tensor, Axis.COMPONENT]:
"""Dead fraction."""
return self._dead_count / self._n_learned_features
@property
def _alive_count(self) -> Int[Tensor, Axis.COMPONENT]:
"""Alive count."""
alive_bool_mask: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)] = (
self._neuron_activity > 0
)
return alive_bool_mask.sum(-1)
def _almost_dead(self, threshold: float) -> Int[Tensor, Axis.COMPONENT]:
"""Almost dead count."""
threshold_in_activations: float = threshold * self._horizon_n_activations
almost_dead_bool_mask: Int64[Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)] = (
self._neuron_activity < threshold_in_activations
)
return almost_dead_bool_mask.sum(-1)
@property
def _activity_histogram(self) -> list[wandb.Histogram]:
"""Activity histogram."""
numpy_neuron_activity: Float[
np.ndarray, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)
] = self._neuron_activity.cpu().numpy()
np_histograms = [np.histogram(activity) for activity in numpy_neuron_activity]
return [wandb.Histogram(np_histogram=histogram) for histogram in np_histograms]
@property
def _log_activity_histogram(self) -> list[wandb.Histogram]:
"""Log activity histogram."""
log_epsilon = 0.1 # To avoid log(0)
log_neuron_activity: Float[
Tensor, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)
] = torch.log(self._neuron_activity + log_epsilon)
numpy_log_neuron_activity: Float[
np.ndarray, Axis.names(Axis.COMPONENT, Axis.LEARNT_FEATURE)
] = log_neuron_activity.cpu().numpy()
np_histograms = [np.histogram(activity) for activity in numpy_log_neuron_activity]
return [wandb.Histogram(np_histogram=histogram) for histogram in np_histograms]
@property
def metric_results(self) -> list[MetricResult]:
"""Metric results.""" | metric_location = MetricLocation.TRAIN | 0 | 2023-10-27 07:37:15+00:00 | 8k |
NVlabs/handover-sim2real | examples/train.py | [
{
"identifier": "get_cfg",
"path": "handover_sim2real/config.py",
"snippet": "def get_cfg(handover_config_only=False):\n if not handover_config_only:\n cfg = _C\n else:\n cfg = _C_handover_config\n return cfg.clone()"
},
{
"identifier": "HandoverSim2RealPolicy",
"path"... | import argparse
import gym
import itertools
import numpy as np
import os
import ray
from datetime import datetime
from handover.benchmark_wrapper import EpisodeStatus, HandoverBenchmarkWrapper
from handover_sim2real.config import get_cfg
from handover_sim2real.policy import HandoverSim2RealPolicy
from handover_sim2real.utils import add_sys_path_from_env
from experiments.config import cfg_from_file, save_cfg_to_file
from core.trainer import (
AgentWrapper,
AgentWrapperGPU05,
ReplayMemoryWrapper,
ReplayMemoryWrapperBase,
RolloutAgentWrapperGPU1,
Trainer,
TrainerRemote,
)
from core.utils import get_noise_delta, get_valid_index, rand_sample_joint | 4,272 | action, obs
)
else:
# Online.
action = self._policy.select_action(state)
noise = get_noise_delta(
action, self._cfg.RL_TRAIN.action_noise, self._cfg.RL_TRAIN.noise_type
)
action = action + noise * noise_scale
target_joint_position = self._policy.convert_action_to_target_joint_position(
action, obs
)
if self._stage == "finetune" and expert_flag:
expert_action = action
obs, reward, done, info = self._step_env_repeat(
target_joint_position, break_if_done=True
)
run_grasp_and_back = False
if not done:
if (
step + 1 == self._max_explore_steps
or self._stage == "pretrain"
and not explore
and step == len(expert_plan) - 5
):
run_grasp_and_back = True
elif self._use_grasp_predictor and (
self._stage == "pretrain" and explore or self._stage == "finetune"
):
state_grasp, _ = self._policy.get_state(obs)
grasp_pred = self._policy.select_action_grasp(state_grasp).item()
if grasp_pred:
run_grasp_and_back = True
if run_grasp_and_back:
back_done = False
if self._stage == "pretrain" and not explore:
obs, _, done, _ = self._step_env_repeat(
target_joint_position, break_if_done=True
)
if done:
back_done = True
while not back_done:
target_joint_position, back_done = self._policy.grasp_and_back(obs)
obs, reward, done, info = self._step_env_repeat(
target_joint_position, break_if_done=True
)
if done:
back_done = True
if not done:
done = True
failure_1 = (
info["status"] & EpisodeStatus.FAILURE_HUMAN_CONTACT
== EpisodeStatus.FAILURE_HUMAN_CONTACT
)
failure_2 = (
info["status"] & EpisodeStatus.FAILURE_OBJECT_DROP
== EpisodeStatus.FAILURE_OBJECT_DROP
)
failure_3 = (
info["status"] & EpisodeStatus.FAILURE_TIMEOUT == EpisodeStatus.FAILURE_TIMEOUT
)
step_dict = {
"timestep": step,
"point_state": state[0][0],
"expert_flags": expert_flag,
"perturb_flags": perturb_flag,
"action": action,
"reward": reward,
"returns": reward,
"terminal": done,
"target_name": "",
"failure_case_1": failure_1,
"failure_case_2": failure_2,
"failure_case_3": failure_3,
}
if self._stage == "pretrain":
step_dict["goal"] = ee_to_goal_pose
if expert_flag:
step_dict["expert_action"] = expert_action
cur_episode.append(step_dict)
step += 1
if not explore:
if self._use_ray:
self._expert_buffer.add_episode.remote(cur_episode, explore, test)
else:
self._expert_buffer.add_episode(cur_episode, explore, test)
else:
if self._use_ray:
self._online_buffer.add_episode.remote(cur_episode, explore, test)
else:
self._online_buffer.add_episode(cur_episode, explore, test)
def _step_env_repeat(self, target_joint_position, break_if_done=False):
for _ in range(self._policy.steps_action_repeat):
obs, reward, done, info = self._env.step(target_joint_position)
if break_if_done and done:
break
return obs, reward, done, info
@ray.remote(num_gpus=0.13)
class ActorWrapperRemote(ActorWrapper):
pass
def main():
args = parse_args()
args.log = True
args.policy = "DDPG"
args.save_model = True
| # Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Licensed under the NVIDIA License [see LICENSE for details].
add_sys_path_from_env("GADDPG_DIR")
def parse_args():
parser = argparse.ArgumentParser(description="Train.")
parser.add_argument("--cfg-file", help="path to config file")
parser.add_argument("--seed", default=0, type=int, help="random seed")
parser.add_argument("--use-grasp-predictor", action="store_true", help="use grasp predictor")
parser.add_argument("--use-ray", action="store_true", help="use Ray")
parser.add_argument("--pretrained-dir", help="pretrained model directory")
parser.add_argument(
"opts",
nargs=argparse.REMAINDER,
help=(
"""modify config options at the end of the command; use space-separated """
""""PATH.KEY VALUE" pairs; see handover_sim2real/config.py, """
"""handover-sim/handover/config.py, and easysim/src/easysim/config.py for all options"""
),
)
args = parser.parse_args()
return args
class ActorWrapper:
def __init__(
self,
stage,
cfg,
use_ray,
rollout_agent,
expert_buffer,
online_buffer,
actor_seed,
grasp_agent,
grasp_pred_threshold,
):
self._stage = stage
self._cfg = cfg
self._use_ray = use_ray
self._expert_buffer = expert_buffer
self._online_buffer = online_buffer
self._use_grasp_predictor = grasp_agent is not None
self._env = HandoverBenchmarkWrapper(gym.make(self._cfg.ENV.ID, cfg=self._cfg))
self._policy = HandoverSim2RealPolicy(
cfg, rollout_agent, grasp_agent, grasp_pred_threshold, use_ray=self._use_ray
)
self._max_explore_steps = self._cfg.RL_MAX_STEP + 7
if actor_seed is not None:
np.random.seed(seed=actor_seed)
def rollout(self, num_episodes, explore, test, noise_scale):
for _ in range(num_episodes):
self._rollout_one(explore, test, noise_scale)
def _rollout_one(self, explore, test, noise_scale):
scene_idx = np.random.randint(self._env.num_scenes)
if self._stage == "pretrain":
sample_initial_joint_position = (
np.random.uniform()
< self._cfg.RL_TRAIN.HANDOVER_SIM2REAL.sample_initial_joint_position_ratio
)
if self._stage == "finetune":
sample_initial_joint_position = False
reset_to_sample = False
if sample_initial_joint_position:
self._env.reset(idx=scene_idx)
for _ in range(self._cfg.RL_TRAIN.ENV_RESET_TRIALS):
initial_joint_position = rand_sample_joint(self._env, init_joints=None)
if initial_joint_position is not None:
self._env.set_initial_joint_position(initial_joint_position)
obs = self._env.reset(idx=scene_idx)
if self._env.get_ee_to_ycb_distance() > self._cfg.RL_TRAIN.init_distance_low:
reset_to_sample = True
break
if not reset_to_sample:
self._env.set_initial_joint_position(self._cfg.ENV.PANDA_INITIAL_POSITION)
obs = self._env.reset(idx=scene_idx)
self._policy.reset()
expert_plan, _ = self._env.run_omg_planner(self._cfg.RL_MAX_STEP, scene_idx)
if expert_plan is None:
return
if self._stage == "pretrain" and explore:
expert_initial = self._cfg.RL_TRAIN.expert_initial_state and not test
if expert_initial:
expert_initial_steps = np.random.randint(
self._cfg.RL_TRAIN.EXPERT_INIT_MIN_STEP,
high=self._cfg.RL_TRAIN.EXPERT_INIT_MAX_STEP,
)
step = 0
done = False
cur_episode = []
while not done:
state, _ = self._policy.get_state(obs)
if self._stage == "pretrain":
apply_dart = (
self._cfg.RL_TRAIN.dart
and not explore
and reset_to_sample
and step > self._cfg.RL_TRAIN.DART_MIN_STEP
and step < self._cfg.RL_TRAIN.DART_MAX_STEP
and np.random.uniform() < self._cfg.RL_TRAIN.DART_RATIO
)
apply_dagger = (
self._cfg.RL_TRAIN.dagger
and explore
and reset_to_sample
and step > self._cfg.RL_TRAIN.DAGGER_MIN_STEP
and step < self._cfg.RL_TRAIN.DAGGER_MAX_STEP
and np.random.uniform() < self._cfg.RL_TRAIN.DAGGER_RATIO
)
if apply_dart:
t = np.random.uniform(low=-0.04, high=+0.04, size=(3,))
r = np.random.uniform(low=-0.20, high=+0.20, size=(3,))
action = np.hstack([t, r])
target_joint_position = self._policy.convert_action_to_target_joint_position(
action, obs
)
obs, _, _, _ = self._step_env_repeat(target_joint_position)
if apply_dart or apply_dagger:
num_steps = self._cfg.RL_MAX_STEP - step
expert_plan_dart, _ = self._env.run_omg_planner(
num_steps, scene_idx, reset_scene=False
)
expert_plan = np.concatenate((expert_plan[:step], expert_plan_dart))
if self._stage == "pretrain":
nearest = explore and not apply_dagger
ee_to_goal_pose = self._env.get_ee_to_goal_pose(nearest=nearest)
if self._stage == "pretrain":
expert_flag = (
not explore or expert_initial and step < expert_initial_steps or apply_dagger
)
perturb_flag = apply_dart
if self._stage == "finetune":
expert_flag = not explore
perturb_flag = False
if self._stage == "pretrain" and expert_flag:
expert_action = self._env.convert_target_joint_position_to_action(expert_plan[step])
if (
not explore
or self._stage == "pretrain"
and expert_initial
and step < expert_initial_steps
):
# Expert.
if self._stage == "pretrain":
action = expert_action
target_joint_position = expert_plan[step]
if self._stage == "finetune":
action = self._policy.select_action(state, expert_policy=True)
target_joint_position = self._policy.convert_action_to_target_joint_position(
action, obs
)
else:
# Online.
action = self._policy.select_action(state)
noise = get_noise_delta(
action, self._cfg.RL_TRAIN.action_noise, self._cfg.RL_TRAIN.noise_type
)
action = action + noise * noise_scale
target_joint_position = self._policy.convert_action_to_target_joint_position(
action, obs
)
if self._stage == "finetune" and expert_flag:
expert_action = action
obs, reward, done, info = self._step_env_repeat(
target_joint_position, break_if_done=True
)
run_grasp_and_back = False
if not done:
if (
step + 1 == self._max_explore_steps
or self._stage == "pretrain"
and not explore
and step == len(expert_plan) - 5
):
run_grasp_and_back = True
elif self._use_grasp_predictor and (
self._stage == "pretrain" and explore or self._stage == "finetune"
):
state_grasp, _ = self._policy.get_state(obs)
grasp_pred = self._policy.select_action_grasp(state_grasp).item()
if grasp_pred:
run_grasp_and_back = True
if run_grasp_and_back:
back_done = False
if self._stage == "pretrain" and not explore:
obs, _, done, _ = self._step_env_repeat(
target_joint_position, break_if_done=True
)
if done:
back_done = True
while not back_done:
target_joint_position, back_done = self._policy.grasp_and_back(obs)
obs, reward, done, info = self._step_env_repeat(
target_joint_position, break_if_done=True
)
if done:
back_done = True
if not done:
done = True
failure_1 = (
info["status"] & EpisodeStatus.FAILURE_HUMAN_CONTACT
== EpisodeStatus.FAILURE_HUMAN_CONTACT
)
failure_2 = (
info["status"] & EpisodeStatus.FAILURE_OBJECT_DROP
== EpisodeStatus.FAILURE_OBJECT_DROP
)
failure_3 = (
info["status"] & EpisodeStatus.FAILURE_TIMEOUT == EpisodeStatus.FAILURE_TIMEOUT
)
step_dict = {
"timestep": step,
"point_state": state[0][0],
"expert_flags": expert_flag,
"perturb_flags": perturb_flag,
"action": action,
"reward": reward,
"returns": reward,
"terminal": done,
"target_name": "",
"failure_case_1": failure_1,
"failure_case_2": failure_2,
"failure_case_3": failure_3,
}
if self._stage == "pretrain":
step_dict["goal"] = ee_to_goal_pose
if expert_flag:
step_dict["expert_action"] = expert_action
cur_episode.append(step_dict)
step += 1
if not explore:
if self._use_ray:
self._expert_buffer.add_episode.remote(cur_episode, explore, test)
else:
self._expert_buffer.add_episode(cur_episode, explore, test)
else:
if self._use_ray:
self._online_buffer.add_episode.remote(cur_episode, explore, test)
else:
self._online_buffer.add_episode(cur_episode, explore, test)
def _step_env_repeat(self, target_joint_position, break_if_done=False):
for _ in range(self._policy.steps_action_repeat):
obs, reward, done, info = self._env.step(target_joint_position)
if break_if_done and done:
break
return obs, reward, done, info
@ray.remote(num_gpus=0.13)
class ActorWrapperRemote(ActorWrapper):
pass
def main():
args = parse_args()
args.log = True
args.policy = "DDPG"
args.save_model = True
| cfg = get_cfg() | 0 | 2023-10-26 23:25:13+00:00 | 8k |
openai/bugbounty-gpt | bugbounty_gpt/__main__.py | [
{
"identifier": "db_handler",
"path": "bugbounty_gpt/db/db_handler.py",
"snippet": "async def _find_submission_by_id(session, submission_id):\nasync def insert_submission(session, submission_data):\nasync def update_submission_state(session, submission_id, new_state):\nasync def fetch_submission_by_stat... | import logging
import asyncio
from bugbounty_gpt.db import db_handler
from bugbounty_gpt.db.models import SubmissionState
from bugbounty_gpt.handlers.openai_handler import OpenAIHandler
from bugbounty_gpt.handlers.submission_handler import BugCrowdSubmission
from bugbounty_gpt.handlers.bugcrowd_api import BugCrowdAPI
from bugbounty_gpt.env import USER_ID, FILTER_PROGRAM, RESPONSE_CATEGORIES, SQLALCHEMY_URL
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker | 3,627 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info("Configuration is valid.")
logger.info("Initializing database connection.")
engine = create_async_engine(SQLALCHEMY_URL, echo=False)
SessionLocal = sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
)
SEEN_SUBMISSIONS = []
async def process_new_submissions():
"""
Fetch and process new submissions that are not duplicates and store them in the database.
"""
params = {
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info("Configuration is valid.")
logger.info("Initializing database connection.")
engine = create_async_engine(SQLALCHEMY_URL, echo=False)
SessionLocal = sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
)
SEEN_SUBMISSIONS = []
async def process_new_submissions():
"""
Fetch and process new submissions that are not duplicates and store them in the database.
"""
params = { | 'filter[program]': FILTER_PROGRAM, | 6 | 2023-10-27 22:41:24+00:00 | 8k |
LeapLabTHU/FamO2O | jax_cql/JaxCQL/sac_main.py | [
{
"identifier": "SAC",
"path": "jax_cql/JaxCQL/sac.py",
"snippet": "class SAC(object):\n\n @staticmethod\n def get_default_config(updates=None):\n config = ConfigDict()\n config.discount = 0.99\n config.alpha_multiplier = 1.0\n config.use_automatic_entropy_tuning = True... | import os
import time
import uuid
import numpy as np
import pprint
import gym
import jax
import jax.numpy as jnp
import flax
import absl.app
import absl.flags
from copy import deepcopy
from .sac import SAC
from .replay_buffer import ReplayBuffer
from .jax_utils import batch_to_jax
from .model import TanhGaussianPolicy, FullyConnectedQFunction, SamplerPolicy
from .sampler import StepSampler, TrajSampler
from .utils import (
Timer, define_flags_with_default, set_random_seed, print_flags,
get_user_flags, prefix_metrics, WandBLogger
)
from viskit.logging import logger, setup_logger | 6,539 |
FLAGS_DEF = define_flags_with_default(
env='HalfCheetah-v2',
max_traj_length=1000,
replay_buffer_size=1000000,
seed=42,
save_model=False,
policy_arch='256-256',
qf_arch='256-256',
orthogonal_init=False,
policy_log_std_multiplier=1.0,
policy_log_std_offset=-1.0,
n_epochs=2000,
n_env_steps_per_epoch=1000,
n_train_step_per_epoch=1000,
eval_period=10,
eval_n_trajs=5,
batch_size=256,
sac=SAC.get_default_config(),
logging=WandBLogger.get_default_config(),
)
def main(argv):
FLAGS = absl.flags.FLAGS
variant = get_user_flags(FLAGS, FLAGS_DEF)
wandb_logger = WandBLogger(config=FLAGS.logging, variant=variant)
setup_logger(
variant=variant,
exp_id=wandb_logger.experiment_id,
seed=FLAGS.seed,
base_log_dir=FLAGS.logging.output_dir,
include_exp_prefix_sub_dir=False
)
set_random_seed(FLAGS.seed)
train_sampler = StepSampler(gym.make(FLAGS.env).unwrapped, FLAGS.max_traj_length)
eval_sampler = TrajSampler(gym.make(FLAGS.env).unwrapped, FLAGS.max_traj_length)
replay_buffer = ReplayBuffer(FLAGS.replay_buffer_size)
observation_dim = eval_sampler.env.observation_space.shape[0]
action_dim = eval_sampler.env.action_space.shape[0]
policy = TanhGaussianPolicy(
observation_dim, action_dim, FLAGS.policy_arch, FLAGS.orthogonal_init,
FLAGS.policy_log_std_multiplier, FLAGS.policy_log_std_offset
)
qf = FullyConnectedQFunction(observation_dim, action_dim, FLAGS.qf_arch, FLAGS.orthogonal_init)
if FLAGS.sac.target_entropy >= 0.0:
FLAGS.sac.target_entropy = -np.prod(eval_sampler.env.action_space.shape).item()
sac = SAC(FLAGS.sac, policy, qf)
sampler_policy = SamplerPolicy(sac.policy, sac.train_params['policy'])
viskit_metrics = {}
for epoch in range(FLAGS.n_epochs):
metrics = {}
with Timer() as rollout_timer:
train_sampler.sample(
sampler_policy.update_params(sac.train_params['policy']),
FLAGS.n_env_steps_per_epoch, deterministic=False, replay_buffer=replay_buffer
)
metrics['env_steps'] = replay_buffer.total_steps
metrics['epoch'] = epoch
with Timer() as train_timer:
for batch_idx in range(FLAGS.n_train_step_per_epoch):
|
FLAGS_DEF = define_flags_with_default(
env='HalfCheetah-v2',
max_traj_length=1000,
replay_buffer_size=1000000,
seed=42,
save_model=False,
policy_arch='256-256',
qf_arch='256-256',
orthogonal_init=False,
policy_log_std_multiplier=1.0,
policy_log_std_offset=-1.0,
n_epochs=2000,
n_env_steps_per_epoch=1000,
n_train_step_per_epoch=1000,
eval_period=10,
eval_n_trajs=5,
batch_size=256,
sac=SAC.get_default_config(),
logging=WandBLogger.get_default_config(),
)
def main(argv):
FLAGS = absl.flags.FLAGS
variant = get_user_flags(FLAGS, FLAGS_DEF)
wandb_logger = WandBLogger(config=FLAGS.logging, variant=variant)
setup_logger(
variant=variant,
exp_id=wandb_logger.experiment_id,
seed=FLAGS.seed,
base_log_dir=FLAGS.logging.output_dir,
include_exp_prefix_sub_dir=False
)
set_random_seed(FLAGS.seed)
train_sampler = StepSampler(gym.make(FLAGS.env).unwrapped, FLAGS.max_traj_length)
eval_sampler = TrajSampler(gym.make(FLAGS.env).unwrapped, FLAGS.max_traj_length)
replay_buffer = ReplayBuffer(FLAGS.replay_buffer_size)
observation_dim = eval_sampler.env.observation_space.shape[0]
action_dim = eval_sampler.env.action_space.shape[0]
policy = TanhGaussianPolicy(
observation_dim, action_dim, FLAGS.policy_arch, FLAGS.orthogonal_init,
FLAGS.policy_log_std_multiplier, FLAGS.policy_log_std_offset
)
qf = FullyConnectedQFunction(observation_dim, action_dim, FLAGS.qf_arch, FLAGS.orthogonal_init)
if FLAGS.sac.target_entropy >= 0.0:
FLAGS.sac.target_entropy = -np.prod(eval_sampler.env.action_space.shape).item()
sac = SAC(FLAGS.sac, policy, qf)
sampler_policy = SamplerPolicy(sac.policy, sac.train_params['policy'])
viskit_metrics = {}
for epoch in range(FLAGS.n_epochs):
metrics = {}
with Timer() as rollout_timer:
train_sampler.sample(
sampler_policy.update_params(sac.train_params['policy']),
FLAGS.n_env_steps_per_epoch, deterministic=False, replay_buffer=replay_buffer
)
metrics['env_steps'] = replay_buffer.total_steps
metrics['epoch'] = epoch
with Timer() as train_timer:
for batch_idx in range(FLAGS.n_train_step_per_epoch): | batch = batch_to_jax(replay_buffer.sample(FLAGS.batch_size)) | 2 | 2023-10-25 11:53:25+00:00 | 8k |
DAMO-NLP-SG/CLEX | serve/cli.py | [
{
"identifier": "ChatIO",
"path": "serve/inference.py",
"snippet": "class ChatIO(abc.ABC):\n @abc.abstractmethod\n def prompt_for_input(self, role: str) -> str:\n \"\"\"Prompt for input from a role.\"\"\"\n\n @abc.abstractmethod\n def prompt_for_output(self, role: str):\n \"\"\... | import argparse
import os
import re
import sys
import torch
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.key_binding import KeyBindings
from rich.console import Console
from rich.live import Live
from rich.markdown import Markdown
from fastchat.model.model_adapter import add_model_args
from fastchat.modules.awq import AWQConfig
from fastchat.modules.exllama import ExllamaConfig
from fastchat.modules.gptq import GptqConfig
from serve.inference import ChatIO, chat_loop
from fastchat.utils import str_to_torch_dtype | 3,622 | # TODO(suquark): multiline input has some issues. fix it later.
prompt_input = self._prompt_session.prompt(
completer=self._completer,
multiline=False,
mouse_support=self._mouse,
auto_suggest=AutoSuggestFromHistory(),
key_bindings=self.bindings if self._multiline else None,
)
self._console.print()
return prompt_input
def prompt_for_output(self, role: str):
self._console.print(f"[bold]{role.replace('/', '|')}:")
def stream_output(self, output_stream):
"""Stream output from a role."""
# TODO(suquark): the console flickers when there is a code block
# above it. We need to cut off "live" when a code block is done.
# Create a Live context for updating the console output
with Live(console=self._console, refresh_per_second=4) as live:
# Read lines from the stream
for outputs in output_stream:
if not outputs:
continue
text = outputs["text"]
# Render the accumulated text as Markdown
# NOTE: this is a workaround for the rendering "unstandard markdown"
# in rich. The chatbots output treat "\n" as a new line for
# better compatibility with real-world text. However, rendering
# in markdown would break the format. It is because standard markdown
# treat a single "\n" in normal text as a space.
# Our workaround is adding two spaces at the end of each line.
# This is not a perfect solution, as it would
# introduce trailing spaces (only) in code block, but it works well
# especially for console output, because in general the console does not
# care about trailing spaces.
lines = []
for line in text.splitlines():
lines.append(line)
if line.startswith("```"):
# Code block marker - do not add trailing spaces, as it would
# break the syntax highlighting
lines.append("\n")
else:
lines.append(" \n")
markdown = Markdown("".join(lines))
# Update the Live console output
live.update(markdown)
self._console.print()
return text
def print_output(self, text: str):
self.stream_output([{"text": text}])
class ProgrammaticChatIO(ChatIO):
def prompt_for_input(self, role) -> str:
contents = ""
# `end_sequence` signals the end of a message. It is unlikely to occur in
# message content.
end_sequence = " __END_OF_A_MESSAGE_47582648__\n"
len_end = len(end_sequence)
while True:
if len(contents) >= len_end:
last_chars = contents[-len_end:]
if last_chars == end_sequence:
break
try:
char = sys.stdin.read(1)
contents = contents + char
except EOFError:
continue
contents = contents[:-len_end]
print(f"[!OP:{role}]: {contents}", flush=True)
return contents
def prompt_for_output(self, role: str):
print(f"[!OP:{role}]: ", end="", flush=True)
def stream_output(self, output_stream):
pre = 0
for outputs in output_stream:
output_text = outputs["text"]
output_text = output_text.strip().split(" ")
now = len(output_text) - 1
if now > pre:
print(" ".join(output_text[pre:now]), end=" ", flush=True)
pre = now
print(" ".join(output_text[pre:]), flush=True)
return " ".join(output_text)
def print_output(self, text: str):
print(text)
def main(args):
if args.gpus:
if len(args.gpus.split(",")) < args.num_gpus:
raise ValueError(
f"Larger --num-gpus ({args.num_gpus}) than --gpus {args.gpus}!"
)
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
os.environ["XPU_VISIBLE_DEVICES"] = args.gpus
if args.enable_exllama:
exllama_config = ExllamaConfig(
max_seq_len=args.exllama_max_seq_len,
gpu_split=args.exllama_gpu_split,
)
else:
exllama_config = None
if args.style == "simple":
chatio = SimpleChatIO(args.multiline)
elif args.style == "rich":
chatio = RichChatIO(args.multiline, args.mouse)
elif args.style == "programmatic":
chatio = ProgrammaticChatIO()
else:
raise ValueError(f"Invalid style for console: {args.style}")
try:
| """
Chat with a model with command line interface.
Usage:
python3 -m fastchat.serve.cli --model lmsys/vicuna-7b-v1.3
python3 -m fastchat.serve.cli --model lmsys/fastchat-t5-3b-v1.0
Other commands:
- Type "!!exit" or an empty line to exit.
- Type "!!reset" to start a new conversation.
- Type "!!remove" to remove the last prompt.
- Type "!!regen" to regenerate the last message.
- Type "!!save <filename>" to save the conversation history to a json file.
- Type "!!load <filename>" to load a conversation history from a json file.
"""
class SimpleChatIO(ChatIO):
def __init__(self, multiline: bool = False):
self._multiline = multiline
def prompt_for_input(self, role) -> str:
if not self._multiline:
return input(f"{role}: ")
prompt_data = []
line = input(f"{role} [ctrl-d/z on empty line to end]: ")
while True:
prompt_data.append(line.strip())
try:
line = input()
except EOFError as e:
break
return "\n".join(prompt_data)
def prompt_for_output(self, role: str):
print(f"{role}: ", end="", flush=True)
def stream_output(self, output_stream):
pre = 0
for outputs in output_stream:
output_text = outputs["text"]
output_text = output_text.strip().split(" ")
now = len(output_text) - 1
if now > pre:
print(" ".join(output_text[pre:now]), end=" ", flush=True)
pre = now
print(" ".join(output_text[pre:]), flush=True)
return " ".join(output_text)
def print_output(self, text: str):
print(text)
class RichChatIO(ChatIO):
bindings = KeyBindings()
@bindings.add("escape", "enter")
def _(event):
event.app.current_buffer.newline()
def __init__(self, multiline: bool = False, mouse: bool = False):
self._prompt_session = PromptSession(history=InMemoryHistory())
self._completer = WordCompleter(
words=["!!exit", "!!reset", "!!remove", "!!regen", "!!save", "!!load"],
pattern=re.compile("$"),
)
self._console = Console()
self._multiline = multiline
self._mouse = mouse
def prompt_for_input(self, role) -> str:
self._console.print(f"[bold]{role}:")
# TODO(suquark): multiline input has some issues. fix it later.
prompt_input = self._prompt_session.prompt(
completer=self._completer,
multiline=False,
mouse_support=self._mouse,
auto_suggest=AutoSuggestFromHistory(),
key_bindings=self.bindings if self._multiline else None,
)
self._console.print()
return prompt_input
def prompt_for_output(self, role: str):
self._console.print(f"[bold]{role.replace('/', '|')}:")
def stream_output(self, output_stream):
"""Stream output from a role."""
# TODO(suquark): the console flickers when there is a code block
# above it. We need to cut off "live" when a code block is done.
# Create a Live context for updating the console output
with Live(console=self._console, refresh_per_second=4) as live:
# Read lines from the stream
for outputs in output_stream:
if not outputs:
continue
text = outputs["text"]
# Render the accumulated text as Markdown
# NOTE: this is a workaround for the rendering "unstandard markdown"
# in rich. The chatbots output treat "\n" as a new line for
# better compatibility with real-world text. However, rendering
# in markdown would break the format. It is because standard markdown
# treat a single "\n" in normal text as a space.
# Our workaround is adding two spaces at the end of each line.
# This is not a perfect solution, as it would
# introduce trailing spaces (only) in code block, but it works well
# especially for console output, because in general the console does not
# care about trailing spaces.
lines = []
for line in text.splitlines():
lines.append(line)
if line.startswith("```"):
# Code block marker - do not add trailing spaces, as it would
# break the syntax highlighting
lines.append("\n")
else:
lines.append(" \n")
markdown = Markdown("".join(lines))
# Update the Live console output
live.update(markdown)
self._console.print()
return text
def print_output(self, text: str):
self.stream_output([{"text": text}])
class ProgrammaticChatIO(ChatIO):
def prompt_for_input(self, role) -> str:
contents = ""
# `end_sequence` signals the end of a message. It is unlikely to occur in
# message content.
end_sequence = " __END_OF_A_MESSAGE_47582648__\n"
len_end = len(end_sequence)
while True:
if len(contents) >= len_end:
last_chars = contents[-len_end:]
if last_chars == end_sequence:
break
try:
char = sys.stdin.read(1)
contents = contents + char
except EOFError:
continue
contents = contents[:-len_end]
print(f"[!OP:{role}]: {contents}", flush=True)
return contents
def prompt_for_output(self, role: str):
print(f"[!OP:{role}]: ", end="", flush=True)
def stream_output(self, output_stream):
pre = 0
for outputs in output_stream:
output_text = outputs["text"]
output_text = output_text.strip().split(" ")
now = len(output_text) - 1
if now > pre:
print(" ".join(output_text[pre:now]), end=" ", flush=True)
pre = now
print(" ".join(output_text[pre:]), flush=True)
return " ".join(output_text)
def print_output(self, text: str):
print(text)
def main(args):
if args.gpus:
if len(args.gpus.split(",")) < args.num_gpus:
raise ValueError(
f"Larger --num-gpus ({args.num_gpus}) than --gpus {args.gpus}!"
)
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
os.environ["XPU_VISIBLE_DEVICES"] = args.gpus
if args.enable_exllama:
exllama_config = ExllamaConfig(
max_seq_len=args.exllama_max_seq_len,
gpu_split=args.exllama_gpu_split,
)
else:
exllama_config = None
if args.style == "simple":
chatio = SimpleChatIO(args.multiline)
elif args.style == "rich":
chatio = RichChatIO(args.multiline, args.mouse)
elif args.style == "programmatic":
chatio = ProgrammaticChatIO()
else:
raise ValueError(f"Invalid style for console: {args.style}")
try: | chat_loop( | 1 | 2023-10-25 05:30:25+00:00 | 8k |
RenShuhuai-Andy/TESTA | models/blip.py | [
{
"identifier": "VisionTransformer",
"path": "models/vit.py",
"snippet": "class VisionTransformer(nn.Module):\n \"\"\" Vision Transformer\n A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -\n https://arxiv.org/abs/2010.11929\n \"\"\"\n ... | import warnings
import torch
import torch.nn.functional as F
import os
from models.vit import VisionTransformer, interpolate_pos_embed
from models.med import BertConfig, BertModel, BertLMHeadModel
from transformers import BertTokenizer
from torch import nn
from urllib.parse import urlparse
from timm.models.hub import download_cached_file
from models.timesformer.models.vit import TimeSformer
from configs.config import basic_check_arguments, shared_configs, restore_training_settings
from utils import str_to_bool
from einops import rearrange
from timm.models.helpers import load_custom_pretrained
from timm.models.vision_transformer import default_cfgs | 3,933 | '''
Adapted from https://github.com/salesforce/BLIP
'''
warnings.filterwarnings("ignore")
def get_custom_args(base_config):
parser = base_config.parser
'''
parser.add_argument('--max_num_frames', type=int, default=32)
parser.add_argument('--img_res', type=int, default=224)
parser.add_argument('--patch_size', type=int, default=32)
parser.add_argument("--grid_feat", type=str_to_bool, nargs='?', const=True, default=True)
parser.add_argument("--kinetics", type=str, default='600', help="400 or 600")
parser.add_argument("--pretrained_2d", type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument("--vidswin_size", type=str, default='base') # change base to tiny
parser.add_argument('--freeze_backbone', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--use_checkpoint', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--backbone_coef_lr', type=float, default=0.001)
parser.add_argument("--reload_pretrained_swin", type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--learn_mask_enabled', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--loss_sparse_w', type=float, default=0)
parser.add_argument('--sparse_mask_soft2hard', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--transfer_method', type=int, default=-1,
help="0: load all SwinBERT pre-trained weights, 1: load only pre-trained sparse mask")
parser.add_argument('--att_mask_expansion', type=int, default=-1,
help="-1: random init, 0: random init and then diag-based copy, 1: interpolation")
parser.add_argument('--resume_checkpoint', type=str, default='None')
parser.add_argument('--test_video_fname', type=str, default='None')
'''
args = base_config.parse_args() # change parse_args() to parse_known_args()
return args
class BLIP_Base(nn.Module):
def __init__(self,
med_config='configs/med_config.json',
image_size=224,
vit='base',
vit_grad_ckpt=False,
vit_ckpt_layer=0,
):
"""
Args:
med_config (str): path for the mixture of encoder-decoder model's configuration file
image_size (int): input image size
vit (str): model size of vision transformer
"""
super().__init__()
self.visual_encoder, vision_width = create_vit(vit, image_size, vit_grad_ckpt, vit_ckpt_layer)
self.tokenizer = init_tokenizer()
| '''
Adapted from https://github.com/salesforce/BLIP
'''
warnings.filterwarnings("ignore")
def get_custom_args(base_config):
parser = base_config.parser
'''
parser.add_argument('--max_num_frames', type=int, default=32)
parser.add_argument('--img_res', type=int, default=224)
parser.add_argument('--patch_size', type=int, default=32)
parser.add_argument("--grid_feat", type=str_to_bool, nargs='?', const=True, default=True)
parser.add_argument("--kinetics", type=str, default='600', help="400 or 600")
parser.add_argument("--pretrained_2d", type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument("--vidswin_size", type=str, default='base') # change base to tiny
parser.add_argument('--freeze_backbone', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--use_checkpoint', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--backbone_coef_lr', type=float, default=0.001)
parser.add_argument("--reload_pretrained_swin", type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--learn_mask_enabled', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--loss_sparse_w', type=float, default=0)
parser.add_argument('--sparse_mask_soft2hard', type=str_to_bool, nargs='?', const=True, default=False)
parser.add_argument('--transfer_method', type=int, default=-1,
help="0: load all SwinBERT pre-trained weights, 1: load only pre-trained sparse mask")
parser.add_argument('--att_mask_expansion', type=int, default=-1,
help="-1: random init, 0: random init and then diag-based copy, 1: interpolation")
parser.add_argument('--resume_checkpoint', type=str, default='None')
parser.add_argument('--test_video_fname', type=str, default='None')
'''
args = base_config.parse_args() # change parse_args() to parse_known_args()
return args
class BLIP_Base(nn.Module):
def __init__(self,
med_config='configs/med_config.json',
image_size=224,
vit='base',
vit_grad_ckpt=False,
vit_ckpt_layer=0,
):
"""
Args:
med_config (str): path for the mixture of encoder-decoder model's configuration file
image_size (int): input image size
vit (str): model size of vision transformer
"""
super().__init__()
self.visual_encoder, vision_width = create_vit(vit, image_size, vit_grad_ckpt, vit_ckpt_layer)
self.tokenizer = init_tokenizer() | med_config = BertConfig.from_json_file(med_config) | 2 | 2023-10-29 12:09:38+00:00 | 8k |
microsoft/MathOctopus | step1_supervised_finetuning/main.py | [
{
"identifier": "create_prompt_dataset",
"path": "utils/data/data_utils.py",
"snippet": "def create_prompt_dataset(local_rank,\n data_path,\n data_split,\n output_path,\n train_phase,\n ... | import argparse
import os
import math
import sys
import torch
import transformers
import deepspeed
from torch.utils import tensorboard
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from typing import Optional, Dict, Sequence
from transformers import (
AutoModelForCausalLM,
SchedulerType,
default_data_collator,
get_scheduler,
LlamaTokenizer
)
from deepspeed.accelerator import get_accelerator
from deepspeed.ops.adam import DeepSpeedCPUAdam, FusedAdam
from utils.data.data_utils import create_prompt_dataset
from utils.utils import print_rank_0, to_device, save_hf_format, set_random_seed, get_all_reduce_mean, get_optimizer_grouped_parameters, save_zero_three_model, load_hf_tokenizer
from utils.ds_utils import get_train_ds_config
from utils.module.lora import convert_linear_layer_to_lora, convert_lora_to_linear_layer, only_optimize_lora_parameters
from utils.model.model_utils import create_hf_model | 5,807 |
# tokenizer.pad_token_id = 0
# make sure tokenizer is right pad in our logic
tokenizer.padding_side = 'right'
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# special_tokens_dict = dict()
# if tokenizer.pad_token is None:
# tokenizer.pad_token = tokenizer.unk_token
# special_tokens_dict["pad_token"] = "[PAD]"
# tokenizer.add_special_tokens(special_tokens_dict)
# print_rank_0(special_tokens_dict, args.global_rank)
# tokenizer.pad_token_id = 0
# tokenizer.bos_token_id = 1
# tokenizer.eos_token_id = 2
model = create_hf_model(AutoModelForCausalLM,
args.model_name_or_path,
tokenizer,
ds_config,
disable_dropout=args.disable_dropout)
# smart_tokenizer_and_embedding_resize(
# special_tokens_dict=special_tokens_dict,
# tokenizer=tokenizer,
# model=model,
# )
# model.resize_token_embeddings(len(tokenizer))
if args.lora_dim > 0:
model = convert_linear_layer_to_lora(model, args.lora_module_name,
args.lora_dim)
if args.only_optimize_lora:
model = only_optimize_lora_parameters(model)
# Prepare the data
train_phase = 1
train_dataset, eval_dataset = create_prompt_dataset(
args.local_rank,
args.data_path,
args.data_split,
args.data_output_path,
train_phase,
args.seed,
tokenizer,
args.max_seq_len,
end_of_conversation_token = tokenizer.eos_token,
sft_only_data_path=args.sft_only_data_path)
# DataLoaders creation:
if args.local_rank == -1:
train_sampler = RandomSampler(train_dataset)
eval_sampler = SequentialSampler(eval_dataset)
else:
train_sampler = DistributedSampler(train_dataset)
eval_sampler = DistributedSampler(eval_dataset)
train_dataloader = DataLoader(train_dataset,
collate_fn=default_data_collator,
sampler=train_sampler,
batch_size=args.per_device_train_batch_size)
eval_dataloader = DataLoader(eval_dataset,
collate_fn=default_data_collator,
sampler=eval_sampler,
batch_size=args.per_device_eval_batch_size)
def evaluation(model, eval_dataloader):
model.eval()
losses = 0
for step, batch in enumerate(eval_dataloader):
batch = to_device(batch, device)
with torch.no_grad():
outputs = model(**batch)
loss = outputs.loss
losses += loss.float()
losses = losses / (step + 1)
try:
perplexity = torch.exp(losses)
except OverflowError:
perplexity = float("inf")
try:
perplexity = get_all_reduce_mean(perplexity).item()
except:
pass
try:
loss = get_all_reduce_mean(losses).item()
except:
loss = float("inf")
return loss, perplexity
# Split weights in two groups, one with weight decay and the other not.
optimizer_grouped_parameters = get_optimizer_grouped_parameters(
model, args.weight_decay)
AdamOptimizer = DeepSpeedCPUAdam if args.offload else FusedAdam
optimizer = AdamOptimizer(optimizer_grouped_parameters,
lr=args.learning_rate,
betas=(0.9, 0.95))
num_update_steps_per_epoch = math.ceil(
len(train_dataloader) / args.gradient_accumulation_steps)
lr_scheduler = get_scheduler(
name=args.lr_scheduler_type,
optimizer=optimizer,
num_warmup_steps=args.num_warmup_steps,
num_training_steps=args.num_train_epochs * num_update_steps_per_epoch,
)
model, optimizer, _, lr_scheduler = deepspeed.initialize(
model=model,
optimizer=optimizer,
args=args,
config=ds_config,
lr_scheduler=lr_scheduler,
dist_init_required=True)
if args.gradient_checkpointing:
model.gradient_checkpointing_enable()
# Train!
| #!/usr/bin/env python
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# import matplotlib.pyplot as plt
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
def parse_args():
parser = argparse.ArgumentParser(
description=
"Finetune a transformers model on a causal language modeling task")
parser.add_argument('--data_path',
nargs='*',
default=['Dahoas/rm-static'],
help='Path to the training dataset. Accepted format:'
'1) a single data path, 2) multiple datasets in the'
'form: dataset1-path dataset2-path ...')
parser.add_argument('--data_split',
type=str,
default='2,4,4',
help='Comma-separated list of proportions for training'
'phase 1, 2, and 3 data. For example the split `6,2,2`'
'will use 60% of data for phase 1, 20% for phase 2'
'and 20% for phase 3.')
parser.add_argument(
'--sft_only_data_path',
nargs='*',
default=[],
help='Path to the dataset for only using in SFT phase.')
parser.add_argument(
'--data_output_path',
type=str,
default='/tmp/data_files/',
help=
'Where to store the data-related files such as shuffle index. This needs to be on a local storage of a node (not on a shared storage)'
)
parser.add_argument(
"--model_name_or_path",
type=str,
help=
"Path to pretrained model or model identifier from huggingface.co/models.",
required=True,
)
parser.add_argument(
"--per_device_train_batch_size",
type=int,
default=16,
help="Batch size (per device) for the training dataloader.",
)
parser.add_argument(
"--per_device_eval_batch_size",
type=int,
default=16,
help="Batch size (per device) for the evaluation dataloader.",
)
parser.add_argument(
"--max_seq_len",
type=int,
default=512,
help="The maximum sequence length.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=1e-3,
help=
"Initial learning rate (after the potential warmup period) to use.",
)
parser.add_argument("--weight_decay",
type=float,
default=0.,
help="Weight decay to use.")
parser.add_argument("--num_train_epochs",
type=int,
default=1,
help="Total number of training epochs to perform.")
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help=
"Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument(
"--lr_scheduler_type",
type=SchedulerType,
default="cosine",
help="The scheduler type to use.",
choices=[
"linear", "cosine", "cosine_with_restarts", "polynomial",
"constant", "constant_with_warmup"
],
)
parser.add_argument(
"--num_warmup_steps",
type=int,
default=0,
help="Number of steps for the warmup in the lr scheduler.")
parser.add_argument("--output_dir",
type=str,
default=None,
help="Where to store the model.")
parser.add_argument("--seed",
type=int,
default=1234,
help="A seed for reproducible training.")
parser.add_argument("--local_rank",
type=int,
default=-1,
help="local_rank for distributed training on gpus")
parser.add_argument('--gradient_checkpointing',
action='store_true',
help='Enable HF gradient checkpointing for model.')
parser.add_argument('--disable_dropout',
action='store_true',
help='Disable the dropout of the model.')
# deepspeed features
parser.add_argument('--offload',
action='store_true',
help='Enable ZeRO Offload techniques.')
parser.add_argument(
'--zero_stage',
type=int,
default=0,
help='ZeRO optimization stage for Actor model (and clones).')
## LoRA for efficient training setting
parser.add_argument("--lora_dim",
type=int,
default=0,
help="If > 0, use LoRA for efficient training.")
parser.add_argument("--lora_module_name",
type=str,
default="decoder.layers.",
help="The scope of LoRA.")
parser.add_argument('--only_optimize_lora',
action='store_true',
help='Only optimize the LoRA parameters.')
parser = deepspeed.add_config_arguments(parser)
args = parser.parse_args()
# Validate settings
if args.gradient_checkpointing and args.lora_dim > 0:
assert (
not args.only_optimize_lora
), "--gradient_checkpointing and --only_optimize_lora cannot be enabled at the same time."
return args
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 main():
# if args.tensorboard_path != "":
args = parse_args()
writer = tensorboard.SummaryWriter(f'{args.output_dir}/runs')
if args.local_rank == -1:
device = torch.device("cuda")
else:
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
# Initializes the distributed backend which will take care of sychronizing nodes/GPUs
# torch.distributed.init_process_group(backend='nccl')
deepspeed.init_distributed()
args.global_rank = torch.distributed.get_rank()
ds_config = get_train_ds_config(offload=args.offload,
stage=args.zero_stage)
ds_config[
'train_micro_batch_size_per_gpu'] = args.per_device_train_batch_size
ds_config[
'train_batch_size'] = args.per_device_train_batch_size * torch.distributed.get_world_size(
) * args.gradient_accumulation_steps
# If passed along, set the training seed now.
set_random_seed(args.seed)
torch.distributed.barrier()
print('loading from ...', args.model_name_or_path)
tokenizer = LlamaTokenizer.from_pretrained(args.model_name_or_path,
fast_tokenizer=True)
# tokenizer = load_hf_tokenizer(args.model_name_or_path, fast_tokenizer=True)
# tokenizer.pad_token_id = 0
# make sure tokenizer is right pad in our logic
tokenizer.padding_side = 'right'
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# special_tokens_dict = dict()
# if tokenizer.pad_token is None:
# tokenizer.pad_token = tokenizer.unk_token
# special_tokens_dict["pad_token"] = "[PAD]"
# tokenizer.add_special_tokens(special_tokens_dict)
# print_rank_0(special_tokens_dict, args.global_rank)
# tokenizer.pad_token_id = 0
# tokenizer.bos_token_id = 1
# tokenizer.eos_token_id = 2
model = create_hf_model(AutoModelForCausalLM,
args.model_name_or_path,
tokenizer,
ds_config,
disable_dropout=args.disable_dropout)
# smart_tokenizer_and_embedding_resize(
# special_tokens_dict=special_tokens_dict,
# tokenizer=tokenizer,
# model=model,
# )
# model.resize_token_embeddings(len(tokenizer))
if args.lora_dim > 0:
model = convert_linear_layer_to_lora(model, args.lora_module_name,
args.lora_dim)
if args.only_optimize_lora:
model = only_optimize_lora_parameters(model)
# Prepare the data
train_phase = 1
train_dataset, eval_dataset = create_prompt_dataset(
args.local_rank,
args.data_path,
args.data_split,
args.data_output_path,
train_phase,
args.seed,
tokenizer,
args.max_seq_len,
end_of_conversation_token = tokenizer.eos_token,
sft_only_data_path=args.sft_only_data_path)
# DataLoaders creation:
if args.local_rank == -1:
train_sampler = RandomSampler(train_dataset)
eval_sampler = SequentialSampler(eval_dataset)
else:
train_sampler = DistributedSampler(train_dataset)
eval_sampler = DistributedSampler(eval_dataset)
train_dataloader = DataLoader(train_dataset,
collate_fn=default_data_collator,
sampler=train_sampler,
batch_size=args.per_device_train_batch_size)
eval_dataloader = DataLoader(eval_dataset,
collate_fn=default_data_collator,
sampler=eval_sampler,
batch_size=args.per_device_eval_batch_size)
def evaluation(model, eval_dataloader):
model.eval()
losses = 0
for step, batch in enumerate(eval_dataloader):
batch = to_device(batch, device)
with torch.no_grad():
outputs = model(**batch)
loss = outputs.loss
losses += loss.float()
losses = losses / (step + 1)
try:
perplexity = torch.exp(losses)
except OverflowError:
perplexity = float("inf")
try:
perplexity = get_all_reduce_mean(perplexity).item()
except:
pass
try:
loss = get_all_reduce_mean(losses).item()
except:
loss = float("inf")
return loss, perplexity
# Split weights in two groups, one with weight decay and the other not.
optimizer_grouped_parameters = get_optimizer_grouped_parameters(
model, args.weight_decay)
AdamOptimizer = DeepSpeedCPUAdam if args.offload else FusedAdam
optimizer = AdamOptimizer(optimizer_grouped_parameters,
lr=args.learning_rate,
betas=(0.9, 0.95))
num_update_steps_per_epoch = math.ceil(
len(train_dataloader) / args.gradient_accumulation_steps)
lr_scheduler = get_scheduler(
name=args.lr_scheduler_type,
optimizer=optimizer,
num_warmup_steps=args.num_warmup_steps,
num_training_steps=args.num_train_epochs * num_update_steps_per_epoch,
)
model, optimizer, _, lr_scheduler = deepspeed.initialize(
model=model,
optimizer=optimizer,
args=args,
config=ds_config,
lr_scheduler=lr_scheduler,
dist_init_required=True)
if args.gradient_checkpointing:
model.gradient_checkpointing_enable()
# Train! | print_rank_0("***** Running training *****", args.global_rank) | 1 | 2023-10-25 05:36:54+00:00 | 8k |
ATR-DBI/CityRefer | lib/solver.py | [
{
"identifier": "get_loss",
"path": "lib/loss_helper.py",
"snippet": "def get_loss(args, data_dict, config, reference=True, use_lang_classifier=False):\n if args.model == 'cityrefer':\n data_dict = get_ref_loss(args, data_dict, config, reference, use_lang_classifier)\n elif args.model == 'r... | import os
import sys
import time
import torch
import numpy as np
import importlib
import lib
from tqdm import tqdm
from tensorboardX import SummaryWriter
from torch.optim.lr_scheduler import StepLR, MultiStepLR
from lib.loss_helper import get_loss
from lib.eval_helper import get_eval
from lib.scheduler_helper import BNMomentumScheduler
from utils.eta import decode_eta
from models.util import mask_tokens
from models.util import get_mask | 4,364 | self.bn_scheduler = None
def __call__(self, epoch, verbose):
# setting
self.epoch = epoch
self.verbose = verbose
self._total_iter["train"] = len(self.dataloader["train"]) * epoch
self._total_iter["val"] = len(self.dataloader["val"]) * self.val_step
for epoch_id in range(epoch):
try:
self._log("epoch {} starting...".format(epoch_id + 1))
# feed
self._feed(self.dataloader["train"], "train", epoch_id)
# save model
self._log("saving last models...\n")
model_root = os.path.join(self.CONF.PATH.OUTPUT, self.stamp)
torch.save(self.model.state_dict(), os.path.join(model_root, "model_last.pth"))
print("evaluating...")
self.init_log()
# val
self._feed(self.dataloader["val"], "val", epoch_id)
# update lr scheduler
if self.lr_scheduler:
self.lr_scheduler.step()
self._log("update learning rate --> {}\n".format(self.lr_scheduler.get_last_lr()))
# update bn scheduler
if self.bn_scheduler:
self.bn_scheduler.step()
self._log("update batch normalization momentum --> {}\n".format(
self.bn_scheduler.lmbd(self.bn_scheduler.last_epoch)))
except KeyboardInterrupt:
# finish training
self._finish(epoch_id)
exit()
# finish training
self._finish(epoch_id)
def _log(self, info_str):
self.log_fout.write(info_str + "\n")
self.log_fout.flush()
print(info_str)
def _set_phase(self, phase):
if phase == "train":
self.model.train()
elif phase == "val":
self.model.eval()
else:
raise ValueError("invalid phase")
def _forward(self, data_dict):
data_dict = self.model(data_dict)
return data_dict
def _backward(self):
# optimize
self.optimizer.zero_grad()
self.scaler.scale(self._running_log["loss"]).backward()
self.scaler.step(self.optimizer)
self.scaler.update()
def _compute_loss(self, data_dict):
data_dict = get_loss(
args=self.args,
data_dict=data_dict,
config=self.DC,
)
# dump
self._running_log["ref_loss"] = data_dict["ref_loss"]
self._running_log["lang_loss"] = data_dict["lang_loss"]
self._running_log["mlm_loss"] = data_dict["mlm_loss"]
self._running_log["loss"] = data_dict["loss"]
def _eval(self, data_dict):
data_dict = get_eval(
args=self.args,
data_dict=data_dict,
config=self.DC,
)
# dump
self._running_log["lang_acc"] = data_dict["lang_acc"].item()
self._running_log["ref_acc"] = np.mean(data_dict["ref_acc"])
self._running_log['ref_iou'] = data_dict['ref_iou']
def _feed(self, dataloader, phase, epoch_id):
# switch mode
self._set_phase(phase)
# change dataloader
dataloader = dataloader if phase == "train" else tqdm(dataloader)
fetch_time_start = time.time()
for data_dict in dataloader:
# move to cuda
for key in data_dict:
if key in ['object_cat', 'lidar', 'point_min', 'point_max', 'mlm_label',
'ref_center_label', 'ref_size_residual_label']:
data_dict[key] = data_dict[key].cuda()
# text encoding
query = data_dict["query"]
encoded_query = self.tokenizer(
query,
add_special_tokens=True,
max_length=self.max_desc_len,
padding="longest",
truncation=True,
return_tensors="pt",
)
# mlm for description
|
sys.path.append(os.path.join(os.getcwd(), "lib")) # HACK add the lib folder
sys.path.append(os.path.join(os.getcwd(), "utils")) # HACK add the lib folder
importlib.reload(lib)
ITER_REPORT_TEMPLATE = """
-------------------------------iter: [{epoch_id}: {iter_id}/{total_iter}]-------------------------------
[loss] train_loss: {train_loss}
[loss] train_ref_loss: {train_ref_loss}
[loss] train_lang_loss: {train_lang_loss}
[loss] train_mlm_loss: {train_mlm_loss}
[loss] train_lang_acc: {train_lang_acc}
[sco.] train_ref_acc: {train_ref_acc}
[sco.] train_iou_rate_0.25: {train_iou_rate_25}, train_iou_rate_0.5: {train_iou_rate_5}
[info] mean_fetch_time: {mean_fetch_time}s
[info] mean_forward_time: {mean_forward_time}s
[info] mean_backward_time: {mean_backward_time}s
[info] mean_eval_time: {mean_eval_time}s
[info] mean_iter_time: {mean_iter_time}s
[info] ETA: {eta_h}h {eta_m}m {eta_s}s
"""
EPOCH_REPORT_TEMPLATE = """
---------------------------------summary---------------------------------
[val] val_loss: {val_loss}
[val] val_lang_loss: {val_lang_loss}
[val] val_lang_acc: {val_lang_acc}
[val] val_ref_acc: {val_ref_acc}
[val] val_iou_rate_0.25: {val_iou_rate_25}, val_iou_rate_0.5: {val_iou_rate_5}
"""
BEST_REPORT_TEMPLATE = """
--------------------------------------best--------------------------------------
[best] epoch: {epoch}
[loss] loss: {loss}
[loss] ref_loss: {ref_loss}
[loss] lang_loss: {lang_loss}
[loss] mlm_loss: {mlm_loss}
[sco.] ref_acc: {ref_acc}
[sco.] lang_acc: {lang_acc}
[sco.] iou_rate_0.25: {iou_rate_25}, iou_rate_0.5: {iou_rate_5}
"""
class Solver():
def __init__(self, args, model, DC, CONF, dataloader, optimizer, scaler, stamp, tokenizer=None, val_step=10,
reference=True, use_lang_classifier=True,
lr_decay_step=None, lr_decay_rate=None, bn_decay_step=None, bn_decay_rate=None, use_amp=False):
self.epoch = 0 # set in __call__
self.verbose = 0 # set in __call__
self.model = model
self.tokenizer = tokenizer
self.args = args
self.CONF = CONF
self.DC = DC
self.dataloader = dataloader
self.optimizer = optimizer
self.scaler = scaler
self.stamp = stamp
self.val_step = val_step
self.use_amp = use_amp
self.reference = reference
self.use_lang_classifier = use_lang_classifier
self.max_desc_len = args.max_desc_len
self.max_land_len = args.max_land_len
self.max_num_object = args.max_num_object if args.num_cands < 0 else args.num_cands
self.max_num_landmark = args.max_num_landmark
self.mlm_prob = args.mlm_prob
self.lr_decay_step = lr_decay_step
self.lr_decay_rate = lr_decay_rate
self.bn_decay_step = bn_decay_step
self.bn_decay_rate = bn_decay_rate
self.best = {
"epoch": 0,
"loss": float("inf"),
"ref_loss": float("inf"),
"lang_loss": float("inf"),
"lang_acc": -float("inf"),
"ref_acc": -float("inf"),
"iou_rate_0.25": -float("inf"),
"iou_rate_0.5": -float("inf")
}
# log
self.init_log()
# tensorboard
os.makedirs(os.path.join(self.CONF.PATH.OUTPUT, stamp, "tensorboard/train"), exist_ok=True)
os.makedirs(os.path.join(self.CONF.PATH.OUTPUT, stamp, "tensorboard/val"), exist_ok=True)
self._log_writer = {
"train": SummaryWriter(os.path.join(self.CONF.PATH.OUTPUT, stamp, "tensorboard/train")),
"val": SummaryWriter(os.path.join(self.CONF.PATH.OUTPUT, stamp, "tensorboard/val"))
}
# training log
log_path = os.path.join(self.CONF.PATH.OUTPUT, stamp, "log.txt")
self.log_fout = open(log_path, "a")
# private
# only for internal access and temporary results
self._running_log = {}
self._global_iter_id = 0
self._total_iter = {} # set in __call__
# templates
self.__iter_report_template = ITER_REPORT_TEMPLATE
self.__epoch_report_template = EPOCH_REPORT_TEMPLATE
self.__best_report_template = BEST_REPORT_TEMPLATE
# lr scheduler
if lr_decay_step and lr_decay_rate:
if isinstance(lr_decay_step, list):
self.lr_scheduler = MultiStepLR(optimizer, lr_decay_step, lr_decay_rate)
else:
self.lr_scheduler = StepLR(optimizer, lr_decay_step, lr_decay_rate)
else:
self.lr_scheduler = None
# bn scheduler
if bn_decay_step and bn_decay_rate:
it = -1
start_epoch = 0
BN_MOMENTUM_INIT = 0.5
BN_MOMENTUM_MAX = 0.001
bn_lbmd = lambda it: max(BN_MOMENTUM_INIT * bn_decay_rate ** (int(it / bn_decay_step)), BN_MOMENTUM_MAX)
self.bn_scheduler = BNMomentumScheduler(model, bn_lambda=bn_lbmd, last_epoch=start_epoch - 1)
else:
self.bn_scheduler = None
def __call__(self, epoch, verbose):
# setting
self.epoch = epoch
self.verbose = verbose
self._total_iter["train"] = len(self.dataloader["train"]) * epoch
self._total_iter["val"] = len(self.dataloader["val"]) * self.val_step
for epoch_id in range(epoch):
try:
self._log("epoch {} starting...".format(epoch_id + 1))
# feed
self._feed(self.dataloader["train"], "train", epoch_id)
# save model
self._log("saving last models...\n")
model_root = os.path.join(self.CONF.PATH.OUTPUT, self.stamp)
torch.save(self.model.state_dict(), os.path.join(model_root, "model_last.pth"))
print("evaluating...")
self.init_log()
# val
self._feed(self.dataloader["val"], "val", epoch_id)
# update lr scheduler
if self.lr_scheduler:
self.lr_scheduler.step()
self._log("update learning rate --> {}\n".format(self.lr_scheduler.get_last_lr()))
# update bn scheduler
if self.bn_scheduler:
self.bn_scheduler.step()
self._log("update batch normalization momentum --> {}\n".format(
self.bn_scheduler.lmbd(self.bn_scheduler.last_epoch)))
except KeyboardInterrupt:
# finish training
self._finish(epoch_id)
exit()
# finish training
self._finish(epoch_id)
def _log(self, info_str):
self.log_fout.write(info_str + "\n")
self.log_fout.flush()
print(info_str)
def _set_phase(self, phase):
if phase == "train":
self.model.train()
elif phase == "val":
self.model.eval()
else:
raise ValueError("invalid phase")
def _forward(self, data_dict):
data_dict = self.model(data_dict)
return data_dict
def _backward(self):
# optimize
self.optimizer.zero_grad()
self.scaler.scale(self._running_log["loss"]).backward()
self.scaler.step(self.optimizer)
self.scaler.update()
def _compute_loss(self, data_dict):
data_dict = get_loss(
args=self.args,
data_dict=data_dict,
config=self.DC,
)
# dump
self._running_log["ref_loss"] = data_dict["ref_loss"]
self._running_log["lang_loss"] = data_dict["lang_loss"]
self._running_log["mlm_loss"] = data_dict["mlm_loss"]
self._running_log["loss"] = data_dict["loss"]
def _eval(self, data_dict):
data_dict = get_eval(
args=self.args,
data_dict=data_dict,
config=self.DC,
)
# dump
self._running_log["lang_acc"] = data_dict["lang_acc"].item()
self._running_log["ref_acc"] = np.mean(data_dict["ref_acc"])
self._running_log['ref_iou'] = data_dict['ref_iou']
def _feed(self, dataloader, phase, epoch_id):
# switch mode
self._set_phase(phase)
# change dataloader
dataloader = dataloader if phase == "train" else tqdm(dataloader)
fetch_time_start = time.time()
for data_dict in dataloader:
# move to cuda
for key in data_dict:
if key in ['object_cat', 'lidar', 'point_min', 'point_max', 'mlm_label',
'ref_center_label', 'ref_size_residual_label']:
data_dict[key] = data_dict[key].cuda()
# text encoding
query = data_dict["query"]
encoded_query = self.tokenizer(
query,
add_special_tokens=True,
max_length=self.max_desc_len,
padding="longest",
truncation=True,
return_tensors="pt",
)
# mlm for description | inputs, labels = mask_tokens(encoded_query["input_ids"], self.tokenizer, mlm_probability=self.mlm_prob) | 4 | 2023-10-25 10:02:28+00:00 | 8k |
OATML-Markslab/ProteinNPT | utils/tranception/model_pytorch.py | [
{
"identifier": "tranception_ACT2FN",
"path": "utils/tranception/activations.py",
"snippet": "def _gelu_python(x):\ndef gelu_new(x):\ndef gelu_fast(x):\ndef quick_gelu(x):\ndef _silu_python(x):\ndef _mish_python(x):\ndef linear_act(x):\ndef squared_relu(x):\ndef squared_relu_xla(x):\ndef get_activation(... | from dataclasses import dataclass
from typing import Optional, Tuple
from torch import nn
from torch.nn import CrossEntropyLoss, NLLLoss
from transformers import GPT2PreTrainedModel
from transformers import PreTrainedTokenizerFast
from transformers.modeling_utils import (
Conv1D,
PreTrainedModel,
SequenceSummary,
find_pruneable_heads_and_indices,
prune_conv1d_layer,
)
from transformers.file_utils import (
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings
)
from transformers.modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
SequenceClassifierOutputWithPast,
TokenClassifierOutput
)
from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
from .activations import tranception_ACT2FN
from .config import TranceptionConfig
from .outputs import (
TranceptionCausalLMOutputWithCrossAttentions,
)
from .utils import msa_utils
from .utils import scoring_utils
import math
import os
import pandas as pd
import torch
import torch.nn.functional as F
import utils | 4,851 | past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
flip=None,
start_slice=None,
end_slice=None,
mutated_sequence=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size]`` All labels set to
``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size]``
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict
)
hidden_states = transformer_outputs[0]
# Set device for model parallelism
if self.model_parallel:
torch.cuda.set_device(self.transformer.first_device)
hidden_states = hidden_states.to(self.lm_head.weight.device)
self.MSA_log_prior = self.MSA_log_prior.to(self.lm_head.weight.device)
lm_logits = self.lm_head(hidden_states)
loss = None
fused_shift_log_probas = None
if labels is not None:
# Shift so that tokens < n predict n
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
if self.retrieval_aggregation_mode is not None:
batch_size = input_ids.size(0)
if self.retrieval_aggregation_mode=="aggregate_indel":
assert batch_size==1, "Aggregate indel is only supported for batch size of 1"
truncated_sequence_text = mutated_sequence[0][start_slice[0]:end_slice[0]]
if len(truncated_sequence_text)!=shift_logits.shape[1]-1: # shift_logits only has one extra token compared to truncated_sequence_text (the BOS token)
print("Tokenization error -- seq length: {} and shift_logits length - 1 : {}".format(len(mutated_sequence),shift_logits.shape[1]-1))
MSA_log_prior, MSA_start, MSA_end = msa_utils.update_retrieved_MSA_log_prior_indel(self, self.MSA_log_prior, self.MSA_start, self.MSA_end, mutated_sequence[0])
elif self.retrieval_aggregation_mode=="aggregate_substitution":
MSA_log_prior=self.MSA_log_prior
MSA_start=self.MSA_start
MSA_end=self.MSA_end
shift_log_probas = torch.log_softmax(shift_logits,dim=-1)
fused_shift_log_probas = shift_log_probas.clone()
if flip is None:
flip = torch.zeros(batch_size).to(fused_shift_log_probas.device)
flip = flip > 0
for seq_index in range(batch_size):
min_prior_slice = max(start_slice[seq_index], MSA_start)
max_prior_slice = min(end_slice[seq_index], MSA_end)
if max_prior_slice <= min_prior_slice:
print("Non overlapping region detected: min_prior_slice {} and max_prior_slice {}".format(min_prior_slice,max_prior_slice))
continue
slice_prior = MSA_log_prior[min_prior_slice:max_prior_slice,:].to(fused_shift_log_probas.device)
if flip[seq_index]:
slice_prior = torch.flip(slice_prior,dims=(0,))
min_logits_slice = max(0,end_slice[seq_index]-MSA_end)
max_logits_slice = min_logits_slice + (max_prior_slice-min_prior_slice)
fused_shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] = (1-self.retrieval_inference_weight_RL)*shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] + self.retrieval_inference_weight_RL*slice_prior
else:
min_logits_slice = max(0, MSA_start-start_slice[seq_index])
max_logits_slice = min_logits_slice + (max_prior_slice-min_prior_slice)
fused_shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] = (1-self.retrieval_inference_weight_LR)*shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] + self.retrieval_inference_weight_LR*slice_prior
if self.retrieval_aggregation_mode=="aggregate_indel":
try:
# If a given residue colume is an added zero-column, then we overwrite prior fusion and only predict based on the autoregressive transformer inference mode.
inserted_retrieval_positions = [True if slice_prior[i].sum()==0 else False for i in range(len(slice_prior))]+[True] #Last True is for the end of sentence token
fused_shift_log_probas[:,inserted_retrieval_positions,:]=shift_log_probas[:,inserted_retrieval_positions,:]
except:
print("Error when adding zero column(s) to account for insertion mutations.")
loss_fct = NLLLoss(reduction='none')
loss = loss_fct(input=fused_shift_log_probas.view(-1, fused_shift_log_probas.size(-1)), target=shift_labels.view(-1)).view(fused_shift_log_probas.shape[0],fused_shift_log_probas.shape[1])
mask = attention_mask[..., 1:].float()
mask[mask==0]=float('nan')
loss *= mask
loss = nanmean(loss, dim=1).mean()
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
|
def nanmean(v, *args, inplace=False, **kwargs):
if not inplace:
v = v.clone()
is_nan = torch.isnan(v)
v[is_nan] = 0
return v.sum(*args, **kwargs) / (~is_nan).float().sum(*args, **kwargs)
def get_slopes(n, mode="standard_alibi", verbose=False):
"""
Function to compute the m constant for each attention head. Code has been adapted from the official ALiBi codebase at:
https://github.com/ofirpress/attention_with_linear_biases/blob/master/fairseq/models/transformer.py
"""
def get_slopes_power_of_2(n):
start = (2**(-2**-(math.log2(n)-3)))
ratio = start
return [start*ratio**i for i in range(n)]
if mode=="grouped_alibi":
n = n // 4
if math.log2(n).is_integer():
result = get_slopes_power_of_2(n)
else:
#Workaround when the number of heads is not a power of 2
closest_power_of_2 = 2**math.floor(math.log2(n))
result = get_slopes_power_of_2(closest_power_of_2) + get_slopes(2*closest_power_of_2)[0::2][:n-closest_power_of_2]
if mode=="grouped_alibi":
result = result * 4
if verbose:
print("ALiBi slopes: {}".format(result))
return result
class SpatialDepthWiseConvolution(nn.Module):
def __init__(self, head_dim: int, kernel_size: int = 3):
super().__init__()
self.kernel_size = kernel_size
self.conv = nn.Conv1d(in_channels=head_dim, out_channels=head_dim, kernel_size=(kernel_size,), padding=(kernel_size - 1,), groups=head_dim)
def forward(self, x: torch.Tensor):
batch_size, heads, seq_len, head_dim = x.shape
x = x.permute(0, 1, 3, 2).contiguous()
x = x.view(batch_size * heads, head_dim, seq_len)
x = self.conv(x)
if self.kernel_size>1:
x = x[:, :, :-(self.kernel_size - 1)]
x = x.view(batch_size, heads, head_dim, seq_len)
x = x.permute(0, 1, 3, 2)
return x
class TranceptionBlockAttention(nn.Module):
def __init__(self, config, is_cross_attention=False, SDWC_kernel_size=None):
super().__init__()
max_positions = config.max_position_embeddings
self.register_buffer(
"bias",
torch.tril(torch.ones((max_positions, max_positions), dtype=torch.uint8)).view(
1, 1, max_positions, max_positions
),
)
self.register_buffer("masked_bias", torch.tensor(-1e4))
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
self.split_size = self.embed_dim
if self.head_dim * self.num_heads != self.embed_dim:
raise ValueError(
f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
)
self.scale_attn_weights = config.scale_attn_weights
self.is_cross_attention = is_cross_attention
if self.is_cross_attention:
self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
else:
self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
self.attn_dropout = nn.Dropout(config.attn_pdrop)
self.resid_dropout = nn.Dropout(config.resid_pdrop)
self.pruned_heads = set()
self.attention_mode=config.attention_mode
if self.attention_mode=="tranception":
assert self.num_heads%4==0, "Invalid number of heads. Tranception requires the number of heads to be a multiple of 4."
self.num_heads_per_kernel_size = self.num_heads // 4
self.query_depthwiseconv = nn.ModuleDict()
self.key_depthwiseconv = nn.ModuleDict()
self.value_depthwiseconv = nn.ModuleDict()
for kernel_idx, kernel in enumerate([3,5,7]):
self.query_depthwiseconv[str(kernel_idx)] = SpatialDepthWiseConvolution(self.head_dim,kernel)
self.key_depthwiseconv[str(kernel_idx)] = SpatialDepthWiseConvolution(self.head_dim,kernel)
self.value_depthwiseconv[str(kernel_idx)] = SpatialDepthWiseConvolution(self.head_dim,kernel)
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
# Prune conv1d layers
self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
# Update hyper params
self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
self.num_heads = self.num_heads - len(heads)
self.pruned_heads = self.pruned_heads.union(heads)
def _attn(self, query, key, value, attention_mask=None, head_mask=None, alibi_bias=None):
attn_weights = torch.matmul(query, key.transpose(-1, -2))
if self.scale_attn_weights:
attn_weights = attn_weights / (float(value.size(-1)) ** 0.5)
if not self.is_cross_attention:
# if only "normal" attention layer implements causal mask
query_length, key_length = query.size(-2), key.size(-2)
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool()
attn_weights = torch.where(causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype))
if alibi_bias is not None:
attn_weights = attn_weights + alibi_bias[:,:,:attn_weights.size(-1)]
if attention_mask is not None:
# Apply the attention mask
attn_weights = attn_weights + attention_mask
attn_weights = nn.Softmax(dim=-1)(attn_weights)
attn_weights = self.attn_dropout(attn_weights)
# Mask heads if we want to
if head_mask is not None:
attn_weights = attn_weights * head_mask
attn_output = torch.matmul(attn_weights, value)
return attn_output, attn_weights
def _split_heads(self, tensor, num_heads, attn_head_size):
"""
Splits hidden_size dim into attn_head_size and num_heads
"""
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
tensor = tensor.view(*new_shape)
return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
def _merge_heads(self, tensor, num_heads, attn_head_size):
"""
Merges attn_head_size dim and num_attn_heads dim into hidden_size
"""
tensor = tensor.permute(0, 2, 1, 3).contiguous()
new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
return tensor.view(new_shape)
def forward(
self,
hidden_states,
layer_past=None,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
use_cache=False,
output_attentions=False,
alibi_bias=None,
):
if encoder_hidden_states is not None:
if not hasattr(self, "q_attn"):
raise ValueError(
"If class is used as cross attention, the weights `q_attn` have to be defined. "
"Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
)
query = self.q_attn(hidden_states)
key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
attention_mask = encoder_attention_mask
else:
query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
query = self._split_heads(query, self.num_heads, self.head_dim)
key = self._split_heads(key, self.num_heads, self.head_dim)
value = self._split_heads(value, self.num_heads, self.head_dim)
if layer_past is not None:
past_key, past_value = layer_past
key = torch.cat((past_key, key), dim=-2)
value = torch.cat((past_value, value), dim=-2)
if use_cache is True:
present = (key, value)
else:
present = None
if self.attention_mode=="tranception":
# We do not do anything on the first self.num_heads_per_kernel_size heads (kernel =1)
query_list=[query[:,:self.num_heads_per_kernel_size,:,:]]
key_list=[key[:,:self.num_heads_per_kernel_size,:,:]]
value_list=[value[:,:self.num_heads_per_kernel_size,:,:]]
for kernel_idx in range(3):
query_list.append(self.query_depthwiseconv[str(kernel_idx)](query[:,(kernel_idx+1)*self.num_heads_per_kernel_size:(kernel_idx+2)*self.num_heads_per_kernel_size,:,:]))
key_list.append(self.key_depthwiseconv[str(kernel_idx)](key[:,(kernel_idx+1)*self.num_heads_per_kernel_size:(kernel_idx+2)*self.num_heads_per_kernel_size,:,:]))
value_list.append(self.value_depthwiseconv[str(kernel_idx)](value[:,(kernel_idx+1)*self.num_heads_per_kernel_size:(kernel_idx+2)*self.num_heads_per_kernel_size,:,:]))
query=torch.cat(query_list, dim=1)
key=torch.cat(key_list, dim=1)
value=torch.cat(value_list, dim=1)
attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask, alibi_bias=alibi_bias)
attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
attn_output = self.c_proj(attn_output)
attn_output = self.resid_dropout(attn_output)
outputs = (attn_output, present)
if output_attentions:
outputs += (attn_weights,)
return outputs # a, present, (attentions)
class TranceptionBlockMLP(nn.Module):
def __init__(self, intermediate_size, config):
super().__init__()
embed_dim = config.hidden_size
self.c_fc = Conv1D(intermediate_size, embed_dim)
self.c_proj = Conv1D(embed_dim, intermediate_size)
self.act = tranception_ACT2FN[config.activation_function]
self.dropout = nn.Dropout(config.resid_pdrop)
def forward(self, hidden_states):
hidden_states = self.c_fc(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.c_proj(hidden_states)
hidden_states = self.dropout(hidden_states)
return hidden_states
class TranceptionBlock(nn.Module):
def __init__(self, config, SDWC_kernel_size=None):
super().__init__()
hidden_size = config.hidden_size
inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
self.attn = TranceptionBlockAttention(config, SDWC_kernel_size=SDWC_kernel_size)
self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
if config.add_cross_attention:
self.crossattention = TranceptionBlockAttention(config, is_cross_attention=True, SDWC_kernel_size=SDWC_kernel_size)
self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
self.mlp = TranceptionBlockMLP(inner_dim, config)
def forward(
self,
hidden_states,
layer_past=None,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
use_cache=False,
output_attentions=False,
alibi_bias=None,
):
residual = hidden_states
hidden_states = self.ln_1(hidden_states)
attn_outputs = self.attn(
hidden_states,
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask,
use_cache=use_cache,
output_attentions=output_attentions,
alibi_bias=alibi_bias,
)
attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
outputs = attn_outputs[1:]
# residual connection
hidden_states = attn_output + residual
if encoder_hidden_states is not None:
# add one self-attention block for cross-attention
if not hasattr(self, "crossattention"):
raise ValueError(
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
"cross-attention layers by setting `config.add_cross_attention=True`"
)
residual = hidden_states
hidden_states = self.ln_cross_attn(hidden_states)
cross_attn_outputs = self.crossattention(
hidden_states,
attention_mask=attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
)
attn_output = cross_attn_outputs[0]
# residual connection
hidden_states = residual + attn_output
outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
residual = hidden_states
hidden_states = self.ln_2(hidden_states)
feed_forward_hidden_states = self.mlp(hidden_states)
# residual connection
hidden_states = residual + feed_forward_hidden_states
if use_cache:
outputs = (hidden_states,) + outputs
else:
outputs = (hidden_states,) + outputs[1:]
return outputs # hidden_states, present, (attentions, cross_attentions)
class TranceptionModel(GPT2PreTrainedModel):
_keys_to_ignore_on_load_missing = ["attn.masked_bias"]
def __init__(self, config):
super().__init__(config)
self.embed_dim = config.hidden_size
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
self.position_embedding = config.position_embedding if hasattr(config, "position_embedding") else "learned"
if self.position_embedding=="learned":
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
self.alibi = None
elif self.position_embedding=="grouped_alibi":
maxpos = config.n_positions
attn_heads = config.n_head
self.slopes = torch.Tensor(get_slopes(attn_heads, mode=self.position_embedding))
#The softmax operation is invariant to translation, and bias functions used are always linear.
alibi = self.slopes.unsqueeze(1).unsqueeze(1) * torch.arange(maxpos).unsqueeze(0).unsqueeze(0).expand(attn_heads, -1, -1)
alibi = alibi.view(attn_heads, 1, maxpos)
self.register_buffer('alibi',alibi)
self.drop = nn.Dropout(config.embd_pdrop)
self.h = nn.ModuleList([TranceptionBlock(config) for _ in range(config.num_hidden_layers)])
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
self.init_weights()
# Model parallel
self.model_parallel = False
self.device_map = None
self.gradient_checkpointing = False
def parallelize(self, device_map=None, num_cores=None):
self.device_map = (
get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
)
device_prefix="cuda:"
assert_device_map(self.device_map, len(self.h))
self.model_parallel = True
self.first_device = "cpu" if "cpu" in self.device_map.keys() else device_prefix + str(min(self.device_map.keys()))
self.last_device = device_prefix + str(max(self.device_map.keys()))
self.wte = self.wte.to(self.first_device)
if self.position_embedding=="learned":
self.wpe = self.wpe.to(self.first_device)
for k, v in self.device_map.items():
print("k,v :"+str(k)+","+str(v))
for block in v:
cuda_device = device_prefix + str(k)
self.h[block] = self.h[block].to(cuda_device)
self.ln_f = self.ln_f.to(self.last_device)
def deparallelize(self):
self.model_parallel = False
self.device_map = None
self.first_device = "cpu"
self.last_device = "cpu"
self.wte = self.wte.to("cpu")
if self.position_embedding=="learned":
self.wpe = self.wpe.to("cpu")
for index in range(len(self.h)):
self.h[index] = self.h[index].to("cpu")
self.ln_f = self.ln_f.to("cpu")
torch.cuda.empty_cache()
def get_input_embeddings(self):
return self.wte
def set_input_embeddings(self, new_embeddings):
self.wte = new_embeddings
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}
"""
for layer, heads in heads_to_prune.items():
self.h[layer].attn.prune_heads(heads)
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
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
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
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:
raise ValueError("You cannot specify both input_ids and 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])
batch_size = input_ids.shape[0]
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
batch_size = inputs_embeds.shape[0]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if token_type_ids is not None:
token_type_ids = token_type_ids.view(-1, input_shape[-1])
if position_ids is not None:
position_ids = position_ids.view(-1, input_shape[-1])
if past_key_values is None:
past_length = 0
past_key_values = tuple([None] * len(self.h))
else:
past_length = past_key_values[0][0].size(-2)
if position_ids is None:
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
# GPT2Attention mask.
if attention_mask is not None:
if batch_size <= 0:
raise ValueError("batch_size has to be defined and > 0")
attention_mask = attention_mask.view(batch_size, -1)
# We create a 3D attention mask from a 2D tensor mask.
# Sizes are [batch_size, 1, 1, to_seq_length]
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
# this attention mask is more simple than the triangular masking of causal attention
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
attention_mask = attention_mask[:, None, None, :]
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
attention_mask = (1.0 - attention_mask) * -10000.0
# If a 2D ou 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if self.config.add_cross_attention and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# head_mask has shape n_layer x batch x n_heads x N x N
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
if inputs_embeds is None:
inputs_embeds = self.wte(input_ids)
if self.position_embedding=="learned":
position_embeds = self.wpe(position_ids)
hidden_states = inputs_embeds + position_embeds
else:
hidden_states = inputs_embeds
if token_type_ids is not None:
token_type_embeds = self.wte(token_type_ids)
hidden_states = hidden_states + token_type_embeds
hidden_states = self.drop(hidden_states)
output_shape = input_shape + (hidden_states.size(-1),)
presents = () if use_cache else None
all_self_attentions = () if output_attentions else None
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
all_hidden_states = () if output_hidden_states else None
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
# Model parallel
if self.model_parallel:
torch.cuda.set_device(hidden_states.device)
# Ensure layer_past is on same device as hidden_states (might not be correct)
if layer_past is not None:
layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
# Ensure that attention_mask is always on the same device as hidden_states
if attention_mask is not None:
attention_mask = attention_mask.to(hidden_states.device)
if isinstance(head_mask, torch.Tensor):
head_mask = head_mask.to(hidden_states.device)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if self.gradient_checkpointing and self.training:
if use_cache:
print("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
# None for past_key_value
return module(*inputs, use_cache, output_attentions)
return custom_forward
outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(block),
hidden_states,
None,
attention_mask,
head_mask[i],
encoder_hidden_states,
encoder_attention_mask,
)
else:
outputs = block(
hidden_states,
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask[i],
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
alibi_bias=self.alibi if hasattr(self, "alibi") else None
)
hidden_states = outputs[0]
if use_cache is True:
presents = presents + (outputs[1],)
if output_attentions:
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
if self.config.add_cross_attention:
all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
if self.model_parallel:
device_prefix="cuda:"
for k, v in self.device_map.items():
if i == v[-1] and device_prefix + str(k) != self.last_device:
hidden_states = hidden_states.to(device_prefix + str(k + 1))
hidden_states = self.ln_f(hidden_states)
hidden_states = hidden_states.view(*output_shape)
# Add last hidden state
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=presents,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
cross_attentions=all_cross_attentions,
)
class TranceptionLMHeadModel(GPT2PreTrainedModel):
_keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
def __init__(self, config):
super().__init__(config)
self.transformer = TranceptionModel(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.config = config
self.init_weights()
self.default_model_device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Model parallel
self.model_parallel = False
self.device_map = None
self.retrieval_aggregation_mode = config.retrieval_aggregation_mode if hasattr(config, "retrieval_aggregation_mode") else None
if self.retrieval_aggregation_mode is not None:
print("Model leverages both autoregressive and retrieval inference")
self.MSA_filename = config.MSA_filename if hasattr(config, "MSA_filename") else False
self.MSA_folder = '/'.join(self.MSA_filename.split(os.sep)[:-1])
self.MSA_name = self.MSA_filename.split(os.sep)[-1]
self.retrieval_inference_weight_LR = config.retrieval_inference_weight if hasattr(config, "retrieval_inference_weight") else 0.6
self.retrieval_inference_weight_RL = config.retrieval_inference_weight if hasattr(config, "retrieval_inference_weight") else 0.6
self.MSA_start=config.MSA_start
self.MSA_end=config.MSA_end
self.full_protein_length = config.full_protein_length if hasattr(config, "full_protein_length") else -1
self.MSA_log_prior = torch.log(torch.tensor(
msa_utils.get_msa_prior(
MSA_data_file=self.MSA_filename,
MSA_weight_file_name=config.MSA_weight_file_name,
retrieval_aggregation_mode=self.retrieval_aggregation_mode,
MSA_start=self.MSA_start,
MSA_end=self.MSA_end,
len_target_seq=self.full_protein_length,
vocab=config.tokenizer.get_vocab(),
verbose=False
)
).float().to(self.default_model_device))
else:
print("Model only uses autoregressive inference")
def parallelize(self, device_map=None, num_cores=None, num_pipelines=1):
self.num_pipelines=num_pipelines
self.device_map = (
get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
if device_map is None
else device_map
)
assert_device_map(self.device_map, len(self.transformer.h))
self.transformer.parallelize(self.device_map, num_cores=num_cores)
self.lm_head = self.lm_head.to(self.transformer.first_device)
self.model_parallel = True
def deparallelize(self):
self.transformer.deparallelize()
self.transformer = self.transformer.to("cpu")
self.lm_head = self.lm_head.to("cpu")
self.model_parallel = False
torch.cuda.empty_cache()
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
token_type_ids = kwargs.get("token_type_ids", None)
# only last token for inputs_ids if past is defined in kwargs
if past:
input_ids = input_ids[:, -1].unsqueeze(-1)
if token_type_ids is not None:
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
attention_mask = kwargs.get("attention_mask", None)
position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past:
position_ids = position_ids[:, -1].unsqueeze(-1)
else:
position_ids = None
return {
"input_ids": input_ids,
"past_key_values": past,
"use_cache": kwargs.get("use_cache"),
"position_ids": position_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
"flip": kwargs.get("flip", None),
}
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
flip=None,
start_slice=None,
end_slice=None,
mutated_sequence=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size]`` All labels set to
``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size]``
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict
)
hidden_states = transformer_outputs[0]
# Set device for model parallelism
if self.model_parallel:
torch.cuda.set_device(self.transformer.first_device)
hidden_states = hidden_states.to(self.lm_head.weight.device)
self.MSA_log_prior = self.MSA_log_prior.to(self.lm_head.weight.device)
lm_logits = self.lm_head(hidden_states)
loss = None
fused_shift_log_probas = None
if labels is not None:
# Shift so that tokens < n predict n
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
if self.retrieval_aggregation_mode is not None:
batch_size = input_ids.size(0)
if self.retrieval_aggregation_mode=="aggregate_indel":
assert batch_size==1, "Aggregate indel is only supported for batch size of 1"
truncated_sequence_text = mutated_sequence[0][start_slice[0]:end_slice[0]]
if len(truncated_sequence_text)!=shift_logits.shape[1]-1: # shift_logits only has one extra token compared to truncated_sequence_text (the BOS token)
print("Tokenization error -- seq length: {} and shift_logits length - 1 : {}".format(len(mutated_sequence),shift_logits.shape[1]-1))
MSA_log_prior, MSA_start, MSA_end = msa_utils.update_retrieved_MSA_log_prior_indel(self, self.MSA_log_prior, self.MSA_start, self.MSA_end, mutated_sequence[0])
elif self.retrieval_aggregation_mode=="aggregate_substitution":
MSA_log_prior=self.MSA_log_prior
MSA_start=self.MSA_start
MSA_end=self.MSA_end
shift_log_probas = torch.log_softmax(shift_logits,dim=-1)
fused_shift_log_probas = shift_log_probas.clone()
if flip is None:
flip = torch.zeros(batch_size).to(fused_shift_log_probas.device)
flip = flip > 0
for seq_index in range(batch_size):
min_prior_slice = max(start_slice[seq_index], MSA_start)
max_prior_slice = min(end_slice[seq_index], MSA_end)
if max_prior_slice <= min_prior_slice:
print("Non overlapping region detected: min_prior_slice {} and max_prior_slice {}".format(min_prior_slice,max_prior_slice))
continue
slice_prior = MSA_log_prior[min_prior_slice:max_prior_slice,:].to(fused_shift_log_probas.device)
if flip[seq_index]:
slice_prior = torch.flip(slice_prior,dims=(0,))
min_logits_slice = max(0,end_slice[seq_index]-MSA_end)
max_logits_slice = min_logits_slice + (max_prior_slice-min_prior_slice)
fused_shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] = (1-self.retrieval_inference_weight_RL)*shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] + self.retrieval_inference_weight_RL*slice_prior
else:
min_logits_slice = max(0, MSA_start-start_slice[seq_index])
max_logits_slice = min_logits_slice + (max_prior_slice-min_prior_slice)
fused_shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] = (1-self.retrieval_inference_weight_LR)*shift_log_probas[seq_index,min_logits_slice:max_logits_slice,:] + self.retrieval_inference_weight_LR*slice_prior
if self.retrieval_aggregation_mode=="aggregate_indel":
try:
# If a given residue colume is an added zero-column, then we overwrite prior fusion and only predict based on the autoregressive transformer inference mode.
inserted_retrieval_positions = [True if slice_prior[i].sum()==0 else False for i in range(len(slice_prior))]+[True] #Last True is for the end of sentence token
fused_shift_log_probas[:,inserted_retrieval_positions,:]=shift_log_probas[:,inserted_retrieval_positions,:]
except:
print("Error when adding zero column(s) to account for insertion mutations.")
loss_fct = NLLLoss(reduction='none')
loss = loss_fct(input=fused_shift_log_probas.view(-1, fused_shift_log_probas.size(-1)), target=shift_labels.view(-1)).view(fused_shift_log_probas.shape[0],fused_shift_log_probas.shape[1])
mask = attention_mask[..., 1:].float()
mask[mask==0]=float('nan')
loss *= mask
loss = nanmean(loss, dim=1).mean()
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
| return TranceptionCausalLMOutputWithCrossAttentions( | 2 | 2023-10-28 11:41:05+00:00 | 8k |
CVHub520/yolov5_obb | models/yolo.py | [
{
"identifier": "check_anchor_order",
"path": "utils/autoanchor.py",
"snippet": "def check_anchor_order(m):\n # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary\n a = m.anchors.prod(-1).view(-1) # anchor area\n da = a[-1] - a[0] # delta a\n ds ... | import argparse
import sys
import thop # for FLOPs computation
import yaml # for torch hub
from copy import deepcopy
from pathlib import Path
from models.common import *
from models.experimental import *
from utils.autoanchor import check_anchor_order
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
from utils.plots import feature_visualization
from utils.torch_utils import fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device, time_sync | 5,876 | initialize_weights(self)
self.info()
LOGGER.info('')
def forward(self, x, augment=False, profile=False, visualize=False):
"""
Args:
x (tensor): (b, 3, height, width), RGB
Return:
if not augment:
x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales
else:
"""
if augment:
return self._forward_augment(x) # augmented inference, None
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_augment(self, x):
img_size = x.shape[-2:] # height, width
s = [1, 0.83, 0.67] # scales
f = [None, 3, None] # flips (2-ud, 3-lr)
y = [] # outputs
for si, fi in zip(s, f):
xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
yi = self._forward_once(xi)[0] # forward
# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
yi = self._descale_pred(yi, fi, si, img_size)
y.append(yi)
y = self._clip_augmented(y) # clip augmented tails
return torch.cat(y, 1), None # augmented inference, train
def _forward_once(self, x, profile=False, visualize=False):
"""
Args:
x (tensor): (b, 3, height, width), RGB
Return:
x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales
"""
y, dt = [], [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
if profile:
self._profile_one_layer(m, x, dt)
x = m(x) # run
y.append(x if m.i in self.save else None) # save output
if visualize:
feature_visualization(x, m.type, m.i, save_dir=visualize)
return x
def _descale_pred(self, p, flips, scale, img_size):
# de-scale predictions following augmented inference (inverse operation)
if self.inplace:
p[..., :4] /= scale # de-scale
if flips == 2:
p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
elif flips == 3:
p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
else:
x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
if flips == 2:
y = img_size[0] - y # de-flip ud
elif flips == 3:
x = img_size[1] - x # de-flip lr
p = torch.cat((x, y, wh, p[..., 4:]), -1)
return p
def _clip_augmented(self, y):
# Clip YOLOv5 augmented inference tails
nl = self.model[-1].nl # number of detection layers (P3-P5)
g = sum(4 ** x for x in range(nl)) # grid points
e = 1 # exclude layer count
i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
y[0] = y[0][:, :-i] # large
i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
y[-1] = y[-1][:, i:] # small
return y
def _profile_one_layer(self, m, x, dt):
c = isinstance(m, Detect) # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
t = time_sync()
for _ in range(10):
m(x.copy() if c else x)
dt.append((time_sync() - t) * 100)
if m == self.model[0]:
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
if c:
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
# https://arxiv.org/abs/1708.02002 section 3.3
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
m = self.model[-1] # Detect() module
for mi, s in zip(m.m, m.stride): # from
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
def _print_biases(self):
m = self.model[-1] # Detect() module
for mi in m.m: # from
b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
LOGGER.info(
('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
# def _print_weights(self):
# for m in self.model.modules():
# if type(m) is Bottleneck:
# LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
LOGGER.info('Fusing layers... ')
for m in self.model.modules():
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
| # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
YOLO-specific modules
Usage:
$ python path/to/models/yolo.py --cfg yolov5s.yaml
"""
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
# ROOT = ROOT.relative_to(Path.cwd()) # relative
try:
except ImportError:
thop = None
class Detect(nn.Module):
stride = None # strides computed during build
onnx_dynamic = False # ONNX export parameter
export = False # export mode
def __init__(self, nc=80, anchors=(), ch=(), inplace=False): # detection layer
super().__init__()
self.nc = nc # number of classes
self.no = nc + 5 + 180 # number of outputs per anchor
self.nl = len(anchors) # number of detection layers
self.na = len(anchors[0]) // 2 # number of anchors
self.grid = [torch.zeros(1)] * self.nl # init grid
self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid
self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
self.inplace = inplace # use in-place ops (e.g. slice assignment)
def forward(self, x):
"""
Args:
x (list[P3_in,...]): torch.Size(b, c_i, h_i, w_i)
Return:
if train:
x (list[P3_out,...]): torch.Size(b, self.na, h_i, w_i, self.no), self.na means the number of anchors scales
else:
inference (tensor): (b, n_all_anchors, self.no)
x (list[P3_in,...]): torch.Size(b, c_i, h_i, w_i)
"""
z = [] # inference output
for i in range(self.nl):
x[i] = self.m[i](x[i]) # conv
bs, _, ny, nx = x[i].shape # x[i](bs,self.no * self.na,20,20) to x[i](bs,self.na,20,20,self.no)
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
if not self.training: # inference
if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
y = x[i].sigmoid() # (tensor): (b, self.na, h, w, self.no)
if self.inplace:
y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
xy = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy
wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, y[..., 4:]), -1)
z.append(y.view(bs, -1, self.no)) # z (list[P3_pred]): Torch.Size(b, n_anchors, self.no)
return x if self.training else (torch.cat(z, 1), ) if self.export else (torch.cat(z, 1), x)
def _make_grid(self, nx=20, ny=20, i=0):
d = self.anchors[i].device
if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)], indexing='ij')
else:
yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)])
grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float()
anchor_grid = (self.anchors[i].clone() * self.stride[i]) \
.view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float()
return grid, anchor_grid
class Model(nn.Module):
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
super().__init__()
if isinstance(cfg, dict):
self.yaml = cfg # model dict
else: # is *.yaml
self.yaml_file = Path(cfg).name
with open(cfg, encoding='ascii', errors='ignore') as f:
self.yaml = yaml.safe_load(f) # model dict
# Define model
ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
if nc and nc != self.yaml['nc']:
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
self.yaml['nc'] = nc # override yaml value
if anchors:
LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
self.yaml['anchors'] = round(anchors) # override yaml value
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
self.names = [str(i) for i in range(self.yaml['nc'])] # default names
self.inplace = self.yaml.get('inplace', True)
# Build strides, anchors
m = self.model[-1] # Detect()
if isinstance(m, Detect):
s = 256 # 2x min stride
m.inplace = self.inplace
m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
m.anchors /= m.stride.view(-1, 1, 1) # featuremap pixel
check_anchor_order(m)
self.stride = m.stride
self._initialize_biases() # only run once
# Init weights, biases
initialize_weights(self)
self.info()
LOGGER.info('')
def forward(self, x, augment=False, profile=False, visualize=False):
"""
Args:
x (tensor): (b, 3, height, width), RGB
Return:
if not augment:
x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales
else:
"""
if augment:
return self._forward_augment(x) # augmented inference, None
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_augment(self, x):
img_size = x.shape[-2:] # height, width
s = [1, 0.83, 0.67] # scales
f = [None, 3, None] # flips (2-ud, 3-lr)
y = [] # outputs
for si, fi in zip(s, f):
xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
yi = self._forward_once(xi)[0] # forward
# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
yi = self._descale_pred(yi, fi, si, img_size)
y.append(yi)
y = self._clip_augmented(y) # clip augmented tails
return torch.cat(y, 1), None # augmented inference, train
def _forward_once(self, x, profile=False, visualize=False):
"""
Args:
x (tensor): (b, 3, height, width), RGB
Return:
x (list[P3_out, ...]): tensor.Size(b, self.na, h_i, w_i, c), self.na means the number of anchors scales
"""
y, dt = [], [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
if profile:
self._profile_one_layer(m, x, dt)
x = m(x) # run
y.append(x if m.i in self.save else None) # save output
if visualize:
feature_visualization(x, m.type, m.i, save_dir=visualize)
return x
def _descale_pred(self, p, flips, scale, img_size):
# de-scale predictions following augmented inference (inverse operation)
if self.inplace:
p[..., :4] /= scale # de-scale
if flips == 2:
p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
elif flips == 3:
p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
else:
x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
if flips == 2:
y = img_size[0] - y # de-flip ud
elif flips == 3:
x = img_size[1] - x # de-flip lr
p = torch.cat((x, y, wh, p[..., 4:]), -1)
return p
def _clip_augmented(self, y):
# Clip YOLOv5 augmented inference tails
nl = self.model[-1].nl # number of detection layers (P3-P5)
g = sum(4 ** x for x in range(nl)) # grid points
e = 1 # exclude layer count
i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices
y[0] = y[0][:, :-i] # large
i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
y[-1] = y[-1][:, i:] # small
return y
def _profile_one_layer(self, m, x, dt):
c = isinstance(m, Detect) # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
t = time_sync()
for _ in range(10):
m(x.copy() if c else x)
dt.append((time_sync() - t) * 100)
if m == self.model[0]:
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
if c:
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
# https://arxiv.org/abs/1708.02002 section 3.3
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
m = self.model[-1] # Detect() module
for mi, s in zip(m.m, m.stride): # from
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
def _print_biases(self):
m = self.model[-1] # Detect() module
for mi in m.m: # from
b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
LOGGER.info(
('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
# def _print_weights(self):
# for m in self.model.modules():
# if type(m) is Bottleneck:
# LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
LOGGER.info('Fusing layers... ')
for m in self.model.modules():
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): | m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv | 7 | 2023-10-31 06:06:41+00:00 | 8k |
hyw-dev/AFI-ForwardDeduplicate | models/model_pg104/RIFE.py | [
{
"identifier": "GMFlow",
"path": "models/gmflow/gmflow.py",
"snippet": "class GMFlow(nn.Module):\r\n def __init__(self,\r\n num_scales=2,\r\n upsample_factor=4,\r\n feature_channels=128,\r\n attention_type='swin',\r\n nu... | import torch
import torch.nn.functional as F
from models.gmflow.gmflow import GMFlow
from models.model_pg104.IFNet_HDv3 import IFNet
from models.model_pg104.MetricNet import MetricNet
from models.model_pg104.FeatureNet import FeatureNet
from models.model_pg104.FusionNet import GridNet
from models.model_pg104.softsplat import softsplat as warp | 5,500 |
device = torch.device("cuda")
class Model:
def __init__(self):
self.flownet = GMFlow().half()
self.ifnet = IFNet().half()
self.metricnet = MetricNet().half()
self.feat_ext = FeatureNet().half()
|
device = torch.device("cuda")
class Model:
def __init__(self):
self.flownet = GMFlow().half()
self.ifnet = IFNet().half()
self.metricnet = MetricNet().half()
self.feat_ext = FeatureNet().half() | self.fusionnet = GridNet(9, 64 * 2, 128 * 2, 192 * 2, 3).half() | 4 | 2023-10-29 18:25:36+00:00 | 8k |
tencent-ailab/PCDMs | caculate_metrics_256.py | [
{
"identifier": "FID",
"path": "metrics.py",
"snippet": "class FID():\n \"\"\"docstring for FID\n Calculates the Frechet Inception Distance (FID) to evalulate GANs\n The FID metric calculates the distance between two distributions of images.\n Typically, we have summary statistics (mean & co... | from metrics import FID, LPIPS, Reconstruction_Metrics, preprocess_path_for_deform_task
import torch | 5,253 |
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
fid = FID()
lpips_obj = LPIPS()
rec = Reconstruction_Metrics()
real_path = './datasets/deepfashing/train_lst_256_png'
gt_path = '/datasets/deepfashing/test_lst_256_png'
distorated_path = './PCDMs_Results/stage3_256_results'
results_save_path = distorated_path + '_results.txt' # save path
|
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
fid = FID()
lpips_obj = LPIPS()
rec = Reconstruction_Metrics()
real_path = './datasets/deepfashing/train_lst_256_png'
gt_path = '/datasets/deepfashing/test_lst_256_png'
distorated_path = './PCDMs_Results/stage3_256_results'
results_save_path = distorated_path + '_results.txt' # save path
| gt_list, distorated_list = preprocess_path_for_deform_task(gt_path, distorated_path) | 3 | 2023-10-26 13:30:44+00:00 | 8k |
Kiteretsu77/VCISR-official | train_code/train_master.py | [
{
"identifier": "GANLoss",
"path": "loss/gan_loss.py",
"snippet": "class GANLoss(nn.Module):\n \"\"\"Define GAN loss.\n From Real-ESRGAN code\n Args:\n gan_type (str): Support 'vanilla', 'lsgan', 'wgan', 'hinge'.\n real_label_val (float): The value for real label. Default: 1.0.\n ... | import os, sys
import torch
import glob
import time, shutil
import math
import gc
from tqdm import tqdm
from collections import defaultdict
from torch.multiprocessing import Pool, Process, set_start_method
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from loss.gan_loss import GANLoss
from loss.pixel_loss import PixelLoss, L1_Charbonnier_loss, MS_SSIM_L1_LOSS
from loss.perceptual_loss import PerceptualLoss
from architecture.dataset import ImageDataset
from scripts.generate_lr_esr import generate_low_res_esr | 5,504 | # -*- coding: utf-8 -*-
# torch module import
try:
set_start_method('spawn')
except RuntimeError:
pass
# import files from local folder
root_path = os.path.abspath('.')
sys.path.append(root_path)
# Mixed precision training
scaler = torch.cuda.amp.GradScaler()
class train_master(object):
def __init__(self, options, args, model_name, has_discriminator=False) -> None:
# General specs setup
self.args = args
self.model_name = model_name
self.options = options
self.has_discriminator = has_discriminator
self.loss_init()
# Generator
self.call_model() # generator + discriminator...
# Optimizer
self.learning_rate = options['start_learning_rate']
self.optimizer_g = torch.optim.Adam(self.generator.parameters(), lr=self.learning_rate, betas=(options["adam_beta1"], options["adam_beta2"]))
if self.has_discriminator:
self.optimizer_d = torch.optim.Adam(self.discriminator.parameters(), lr=self.learning_rate, betas=(self.options["adam_beta1"], self.options["adam_beta2"]))
# Train specs
self.start_iteration = 0
self.lowest_generator_loss = float("inf")
# Other auxiliary function
self.writer = SummaryWriter()
self.weight_store = defaultdict(int)
# Options setting
self.n_iterations = options['train_iterations']
self.batch_size = options['train_batch_size']
self.n_cpu = options['train_dataloader_workers']
self.dataset_path = options['dataset_path']
def adjust_learning_rate(self, iteration_idx):
self.learning_rate = self.options['start_learning_rate']
end_iteration = self.options['train_iterations'] - 2*self.options['decay_iteration']
# Caclulate a learning rate we need in real-time based on the iteration_idx
for idx in range(min(end_iteration, iteration_idx)//self.options['decay_iteration']):
idx = idx+1
if idx * self.options['decay_iteration'] in self.options['double_milestones']:
# double the learning rate in milestones
self.learning_rate = self.learning_rate * 2
else:
# else, try to multiply decay_gamma (when we decay, we won't upscale)
self.learning_rate = self.learning_rate * self.options['decay_gamma'] # should be divisible in all cases
for param_group in self.optimizer_g.param_groups:
param_group['lr'] = self.learning_rate
if self.has_discriminator:
print("For the Learning Rate Decay, we didn't yet handle discriminator, but we think that it should be necessary")
assert(self.learning_rate == self.optimizer_g.param_groups[0]['lr'])
def pixel_loss_load(self):
if self.options['pixel_loss'] == "L1":
self.cri_pix = PixelLoss().cuda()
elif self.options['pixel_loss'] == "L1_Charbonnier":
self.cri_pix = L1_Charbonnier_loss().cuda()
elif self.options['pixel_loss'] == "L1_MS-SSIM_loss":
self.cri_pix = MS_SSIM_L1_LOSS(alpha=self.options['MS-SSIM_alpha']).cuda()
print("We are using {} loss".format(self.options['pixel_loss']))
def GAN_loss_load(self):
# parameter init
gan_loss_weight = self.options["gan_loss_weight"]
vgg_type = self.options['train_perceptual_vgg_type']
layer_weights = self.options['train_perceptual_layer_weights']
# Preceptual Loss and GAN Loss
self.cri_pix = torch.nn.L1Loss().cuda()
| # -*- coding: utf-8 -*-
# torch module import
try:
set_start_method('spawn')
except RuntimeError:
pass
# import files from local folder
root_path = os.path.abspath('.')
sys.path.append(root_path)
# Mixed precision training
scaler = torch.cuda.amp.GradScaler()
class train_master(object):
def __init__(self, options, args, model_name, has_discriminator=False) -> None:
# General specs setup
self.args = args
self.model_name = model_name
self.options = options
self.has_discriminator = has_discriminator
self.loss_init()
# Generator
self.call_model() # generator + discriminator...
# Optimizer
self.learning_rate = options['start_learning_rate']
self.optimizer_g = torch.optim.Adam(self.generator.parameters(), lr=self.learning_rate, betas=(options["adam_beta1"], options["adam_beta2"]))
if self.has_discriminator:
self.optimizer_d = torch.optim.Adam(self.discriminator.parameters(), lr=self.learning_rate, betas=(self.options["adam_beta1"], self.options["adam_beta2"]))
# Train specs
self.start_iteration = 0
self.lowest_generator_loss = float("inf")
# Other auxiliary function
self.writer = SummaryWriter()
self.weight_store = defaultdict(int)
# Options setting
self.n_iterations = options['train_iterations']
self.batch_size = options['train_batch_size']
self.n_cpu = options['train_dataloader_workers']
self.dataset_path = options['dataset_path']
def adjust_learning_rate(self, iteration_idx):
self.learning_rate = self.options['start_learning_rate']
end_iteration = self.options['train_iterations'] - 2*self.options['decay_iteration']
# Caclulate a learning rate we need in real-time based on the iteration_idx
for idx in range(min(end_iteration, iteration_idx)//self.options['decay_iteration']):
idx = idx+1
if idx * self.options['decay_iteration'] in self.options['double_milestones']:
# double the learning rate in milestones
self.learning_rate = self.learning_rate * 2
else:
# else, try to multiply decay_gamma (when we decay, we won't upscale)
self.learning_rate = self.learning_rate * self.options['decay_gamma'] # should be divisible in all cases
for param_group in self.optimizer_g.param_groups:
param_group['lr'] = self.learning_rate
if self.has_discriminator:
print("For the Learning Rate Decay, we didn't yet handle discriminator, but we think that it should be necessary")
assert(self.learning_rate == self.optimizer_g.param_groups[0]['lr'])
def pixel_loss_load(self):
if self.options['pixel_loss'] == "L1":
self.cri_pix = PixelLoss().cuda()
elif self.options['pixel_loss'] == "L1_Charbonnier":
self.cri_pix = L1_Charbonnier_loss().cuda()
elif self.options['pixel_loss'] == "L1_MS-SSIM_loss":
self.cri_pix = MS_SSIM_L1_LOSS(alpha=self.options['MS-SSIM_alpha']).cuda()
print("We are using {} loss".format(self.options['pixel_loss']))
def GAN_loss_load(self):
# parameter init
gan_loss_weight = self.options["gan_loss_weight"]
vgg_type = self.options['train_perceptual_vgg_type']
layer_weights = self.options['train_perceptual_layer_weights']
# Preceptual Loss and GAN Loss
self.cri_pix = torch.nn.L1Loss().cuda() | self.cri_perceptual = PerceptualLoss(layer_weights, vgg_type, perceptual_weight=self.options["perceptual_loss_weight"]).cuda() | 4 | 2023-10-29 04:33:38+00:00 | 8k |
DataCanvasIO/LMS | lms/runtime/prune/llm_pruner/LLMPruner/peft/tuners/adalora.py | [
{
"identifier": "PeftType",
"path": "lms/runtime/prune/llm_pruner/LLMPruner/peft/utils/config.py",
"snippet": "class PeftType(str, enum.Enum):\n PROMPT_TUNING = \"PROMPT_TUNING\"\n P_TUNING = \"P_TUNING\"\n PREFIX_TUNING = \"PREFIX_TUNING\"\n LORA = \"LORA\"\n ADALORA = \"ADALORA\""
},
... | import importlib
import re
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
import bitsandbytes as bnb
from dataclasses import dataclass, field
from typing import Optional
from transformers.pytorch_utils import Conv1D
from ..utils import (
TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING,
PeftType,
_freeze_adapter,
_get_submodules,
transpose,
)
from .lora import (
LoraConfig,
LoraLayer,
LoraModel,
mark_only_lora_as_trainable,
) | 6,011 |
def is_bnb_available():
return importlib.util.find_spec("bitsandbytes") is not None
if is_bnb_available():
@dataclass
class AdaLoraConfig(LoraConfig):
"""
This is the configuration class to store the configuration of a [`~peft.AdaLora`].
Args:
target_r (`int`): The target average rank of incremental matrix.
init_r (`int`): The initial rank for each incremental matrix.
tinit (`int`): The steps of initial fine-tuning warmup.
tfinal (`int`): The step of final fine-tuning.
deltaT (`int`): The time internval between two budget allocations.
beta1 (`float`): The hyperparameter of EMA for sensitivity smoothing.
beta2 (`float`): The hyperparameter of EMA for undertainty quantification.
orth_reg_weight (`float`): The coefficient of orthogonal regularization.
total_step (`int`): The total training steps that should be specified before training.
rank_pattern (`list`): The allocated rank for each weight matrix by RankAllocator.
"""
target_r: int = field(default=8, metadata={"help": "Target Lora matrix dimension."})
init_r: int = field(default=12, metadata={"help": "Intial Lora matrix dimension."})
tinit: int = field(default=0, metadata={"help": "The steps of initial warmup."})
tfinal: int = field(default=0, metadata={"help": "The steps of final warmup."})
deltaT: int = field(default=1, metadata={"help": "Step interval of rank allocation."})
beta1: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."})
beta2: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."})
orth_reg_weight: float = field(default=0.5, metadata={"help": "The orthogonal regularization coefficient."})
total_step: Optional[int] = field(default=None, metadata={"help": "The total training steps."})
rank_pattern: Optional[dict] = field(default=None, metadata={"help": "The saved rank pattern."})
def __post_init__(self):
self.peft_type = PeftType.ADALORA
class AdaLoraModel(LoraModel):
"""
Creates AdaLoRA (Adaptive LoRA) model from a pretrained transformers model. Paper:
https://openreview.net/pdf?id=lq62uWRJjiY
Args:
model ([`transformers.PreTrainedModel`]): The model to be adapted.
config ([`AdaLoraConfig`]): The configuration of the AdaLora model.
Returns:
`torch.nn.Module`: The AdaLora model.
Example::
>>> from transformers import AutoModelForSeq2SeqLM, LoraConfig >>> from peft import AdaLoraModel, AdaLoraConfig
>>> config = AdaLoraConfig(
peft_type="ADALORA", task_type="SEQ_2_SEQ_LM", r=8, lora_alpha=32, target_modules=["q", "v"],
lora_dropout=0.01,
)
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") >>> model = AdaLoraModel(config, model)
**Attributes**:
- **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted.
- **peft_config** ([`AdaLoraConfig`]): The configuration of the AdaLora model.
"""
def __init__(self, model, config, adapter_name):
nn.Module.__init__(self)
self.model = model
self.peft_config = config
self.add_adapter(adapter_name, self.peft_config[adapter_name])
def add_adapter(self, adapter_name, config=None):
if config is not None:
model_config = self.model.config.to_dict() if hasattr(self.model.config, "to_dict") else self.model.config
config = self._prepare_adalora_config(config, model_config)
self.peft_config[adapter_name] = config
self._find_and_replace(adapter_name)
if len(self.peft_config) > 1 and self.peft_config[adapter_name].bias != "none":
raise ValueError(
"AdaLoraModel supports only 1 adapter with bias. When using multiple adapters, set bias to 'none' for all adapters."
)
traininable_mode_counter = 0
for config in self.peft_config.values():
if not config.inference_mode:
traininable_mode_counter += 1
if traininable_mode_counter > 1:
raise ValueError(
"AdaLoraModel supports only 1 trainable adapter. "
"When using multiple adapters, set inference_mode to True for all adapters except the one you want to train."
)
mark_only_lora_as_trainable(self.model, self.peft_config[adapter_name].bias)
if self.peft_config[adapter_name].inference_mode:
|
def is_bnb_available():
return importlib.util.find_spec("bitsandbytes") is not None
if is_bnb_available():
@dataclass
class AdaLoraConfig(LoraConfig):
"""
This is the configuration class to store the configuration of a [`~peft.AdaLora`].
Args:
target_r (`int`): The target average rank of incremental matrix.
init_r (`int`): The initial rank for each incremental matrix.
tinit (`int`): The steps of initial fine-tuning warmup.
tfinal (`int`): The step of final fine-tuning.
deltaT (`int`): The time internval between two budget allocations.
beta1 (`float`): The hyperparameter of EMA for sensitivity smoothing.
beta2 (`float`): The hyperparameter of EMA for undertainty quantification.
orth_reg_weight (`float`): The coefficient of orthogonal regularization.
total_step (`int`): The total training steps that should be specified before training.
rank_pattern (`list`): The allocated rank for each weight matrix by RankAllocator.
"""
target_r: int = field(default=8, metadata={"help": "Target Lora matrix dimension."})
init_r: int = field(default=12, metadata={"help": "Intial Lora matrix dimension."})
tinit: int = field(default=0, metadata={"help": "The steps of initial warmup."})
tfinal: int = field(default=0, metadata={"help": "The steps of final warmup."})
deltaT: int = field(default=1, metadata={"help": "Step interval of rank allocation."})
beta1: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."})
beta2: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."})
orth_reg_weight: float = field(default=0.5, metadata={"help": "The orthogonal regularization coefficient."})
total_step: Optional[int] = field(default=None, metadata={"help": "The total training steps."})
rank_pattern: Optional[dict] = field(default=None, metadata={"help": "The saved rank pattern."})
def __post_init__(self):
self.peft_type = PeftType.ADALORA
class AdaLoraModel(LoraModel):
"""
Creates AdaLoRA (Adaptive LoRA) model from a pretrained transformers model. Paper:
https://openreview.net/pdf?id=lq62uWRJjiY
Args:
model ([`transformers.PreTrainedModel`]): The model to be adapted.
config ([`AdaLoraConfig`]): The configuration of the AdaLora model.
Returns:
`torch.nn.Module`: The AdaLora model.
Example::
>>> from transformers import AutoModelForSeq2SeqLM, LoraConfig >>> from peft import AdaLoraModel, AdaLoraConfig
>>> config = AdaLoraConfig(
peft_type="ADALORA", task_type="SEQ_2_SEQ_LM", r=8, lora_alpha=32, target_modules=["q", "v"],
lora_dropout=0.01,
)
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") >>> model = AdaLoraModel(config, model)
**Attributes**:
- **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted.
- **peft_config** ([`AdaLoraConfig`]): The configuration of the AdaLora model.
"""
def __init__(self, model, config, adapter_name):
nn.Module.__init__(self)
self.model = model
self.peft_config = config
self.add_adapter(adapter_name, self.peft_config[adapter_name])
def add_adapter(self, adapter_name, config=None):
if config is not None:
model_config = self.model.config.to_dict() if hasattr(self.model.config, "to_dict") else self.model.config
config = self._prepare_adalora_config(config, model_config)
self.peft_config[adapter_name] = config
self._find_and_replace(adapter_name)
if len(self.peft_config) > 1 and self.peft_config[adapter_name].bias != "none":
raise ValueError(
"AdaLoraModel supports only 1 adapter with bias. When using multiple adapters, set bias to 'none' for all adapters."
)
traininable_mode_counter = 0
for config in self.peft_config.values():
if not config.inference_mode:
traininable_mode_counter += 1
if traininable_mode_counter > 1:
raise ValueError(
"AdaLoraModel supports only 1 trainable adapter. "
"When using multiple adapters, set inference_mode to True for all adapters except the one you want to train."
)
mark_only_lora_as_trainable(self.model, self.peft_config[adapter_name].bias)
if self.peft_config[adapter_name].inference_mode: | _freeze_adapter(self.model, adapter_name) | 4 | 2023-10-30 10:50:32+00:00 | 8k |
imhotep/hass-unifi-access | custom_components/unifi_access/lock.py | [
{
"identifier": "DOMAIN",
"path": "custom_components/unifi_access/const.py",
"snippet": "DOMAIN = \"unifi_access\""
},
{
"identifier": "UnifiAccessDoor",
"path": "custom_components/unifi_access/door.py",
"snippet": "class UnifiAccessDoor:\n \"\"\"Unifi Access Door Class.\"\"\"\n\n ... | import logging
from typing import Any
from homeassistant.components.lock import LockEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .door import UnifiAccessDoor
from .hub import UnifiAccessCoordinator, UnifiAccessHub | 3,614 | """Platform for sensor integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Add Binary Sensor for passed config entry."""
hub: UnifiAccessHub = hass.data[DOMAIN][config_entry.entry_id]
coordinator = UnifiAccessCoordinator(hass, hub)
await coordinator.async_config_entry_first_refresh()
async_add_entities(
UnifiDoorLockEntity(coordinator, key) for key, value in coordinator.data.items()
)
class UnifiDoorLockEntity(CoordinatorEntity, LockEntity):
"""Unifi Access Door Lock."""
should_poll = False
def __init__(self, coordinator, door_id) -> None:
"""Initialize Unifi Access Door Lock."""
super().__init__(coordinator, context=id)
self.id = door_id
| """Platform for sensor integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Add Binary Sensor for passed config entry."""
hub: UnifiAccessHub = hass.data[DOMAIN][config_entry.entry_id]
coordinator = UnifiAccessCoordinator(hass, hub)
await coordinator.async_config_entry_first_refresh()
async_add_entities(
UnifiDoorLockEntity(coordinator, key) for key, value in coordinator.data.items()
)
class UnifiDoorLockEntity(CoordinatorEntity, LockEntity):
"""Unifi Access Door Lock."""
should_poll = False
def __init__(self, coordinator, door_id) -> None:
"""Initialize Unifi Access Door Lock."""
super().__init__(coordinator, context=id)
self.id = door_id | self.door: UnifiAccessDoor = self.coordinator.data[door_id] | 1 | 2023-10-27 20:34:27+00:00 | 8k |
pengsongyou/lseg_feature_extraction | fusion_scannet.py | [
{
"identifier": "LSeg_MultiEvalModule",
"path": "additional_utils/models.py",
"snippet": "class LSeg_MultiEvalModule(DataParallel):\n \"\"\"Multi-size Segmentation Eavluator\"\"\"\n def __init__(self, module, device_ids=None, flip=True,\n scales=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75]):\... | import os
import torch
import imageio
import argparse
import numpy as np
import torchvision.transforms as transforms
from os.path import join, exists
from glob import glob
from tqdm import tqdm, trange
from additional_utils.models import LSeg_MultiEvalModule
from modules.lseg_module import LSegModule
from encoding.models.sseg import BaseNet
from fusion_util import extract_lseg_img_feature, PointCloudToImageMapper, save_fused_feature, adjust_intrinsic, make_intrinsic | 5,292 | num_rand_file_per_scene = args.num_rand_file_per_scene
feat_dim = args.feat_dim
point2img_mapper = args.point2img_mapper
depth_scale = args.depth_scale
keep_features_in_memory = args.keep_features_in_memory
evaluator = args.evaluator
transform = args.transform
# load 3D data (point cloud)
locs_in = torch.load(data_path)[0]
n_points = locs_in.shape[0]
n_interval = num_rand_file_per_scene
n_finished = 0
for n in range(n_interval):
if exists(join(out_dir, scene_id +'_%d.pt'%(n))):
n_finished += 1
print(scene_id +'_%d.pt'%(n) + ' already done!')
continue
if n_finished == n_interval:
return 1
# short hand for processing 2D features
scene = join(args.data_root_2d, scene_id)
img_dirs = sorted(glob(join(scene, 'color/*')), key=lambda x: int(os.path.basename(x)[:-4]))
num_img = len(img_dirs)
device = torch.device('cpu')
# extract image features and keep them in the memory
# default: False (extract image on the fly)
if keep_features_in_memory and evaluator is not None:
img_features = []
for img_dir in tqdm(img_dirs):
img_features.append(extract_lseg_img_feature(img_dir, transform, evaluator))
n_points_cur = n_points
counter = torch.zeros((n_points_cur, 1), device=device)
sum_features = torch.zeros((n_points_cur, feat_dim), device=device)
################ Feature Fusion ###################
vis_id = torch.zeros((n_points_cur, num_img), dtype=int, device=device)
for img_id, img_dir in enumerate(tqdm(img_dirs)):
# load pose
posepath = img_dir.replace('color', 'pose').replace('.jpg', '.txt')
pose = np.loadtxt(posepath)
# load depth and convert to meter
depth = imageio.v2.imread(img_dir.replace('color', 'depth').replace('jpg', 'png')) / depth_scale
# calculate the 3d-2d mapping based on the depth
mapping = np.ones([n_points, 4], dtype=int)
mapping[:, 1:4] = point2img_mapper.compute_mapping(pose, locs_in, depth)
if mapping[:, 3].sum() == 0: # no points corresponds to this image, skip
continue
mapping = torch.from_numpy(mapping).to(device)
mask = mapping[:, 3]
vis_id[:, img_id] = mask
if keep_features_in_memory:
feat_2d = img_features[img_id].to(device)
else:
feat_2d = extract_lseg_img_feature(img_dir, transform, evaluator).to(device)
feat_2d_3d = feat_2d[:, mapping[:, 1], mapping[:, 2]].permute(1, 0)
counter[mask!=0]+= 1
sum_features[mask!=0] += feat_2d_3d[mask!=0]
counter[counter==0] = 1e-5
feat_bank = sum_features/counter
point_ids = torch.unique(vis_id.nonzero(as_tuple=False)[:, 0])
save_fused_feature(feat_bank, point_ids, n_points, out_dir, scene_id, args)
def main(args):
seed = 1457
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
#!### Dataset specific parameters #####
img_dim = (320, 240)
depth_scale = 1000.0
fx = 577.870605
fy = 577.870605
mx=319.5
my=239.5
#######################################
visibility_threshold = 0.25 # threshold for the visibility check
args.depth_scale = depth_scale
args.cut_num_pixel_boundary = 10 # do not use the features on the image boundary
args.keep_features_in_memory = False # keep image features in the memory, very expensive
split = args.split
data_dir = args.data_dir
data_root = join(data_dir, 'scannet_3d')
data_root_2d = join(data_dir,'scannet_2d')
args.data_root_2d = data_root_2d
out_dir = args.output_dir
args.feat_dim = 512 # CLIP feature dimension
os.makedirs(out_dir, exist_ok=True)
process_id_range = args.process_id_range
if split== 'train': # for training set, export a chunk of point cloud
args.n_split_points = 20000
args.num_rand_file_per_scene = 5
else: # for the validation set, export the entire point cloud instead of chunks
args.n_split_points = 2000000
args.num_rand_file_per_scene = 1
##############################
##### load the LSeg model ####
| #!!!!!!! this file needs to be placed in the root directory of LSeg
def get_args():
# command line args
parser = argparse.ArgumentParser(
description='Multi-view feature fusion of LSeg on ScanNet.')
parser.add_argument('--data_dir', type=str, help='Where is the base logging directory')
parser.add_argument('--output_dir', type=str, help='Where is the base logging directory')
parser.add_argument('--split', type=str, default='val', help='split: "train"| "val"')
parser.add_argument('--lseg_model', type=str, default='checkpoints/demo_e200.ckpt', help='Where is the LSeg checkpoint')
parser.add_argument('--process_id_range', nargs='+', default=None, help='the id range to process')
parser.add_argument('--img_feat_dir', type=str, default='', help='the id range to process')
# Hyper parameters
parser.add_argument('--hparams', default=[], nargs="+")
args = parser.parse_args()
return args
def process_one_scene(data_path, out_dir, args):
# short hand
scene_id = data_path.split('/')[-1].split('_vh')[0]
num_rand_file_per_scene = args.num_rand_file_per_scene
feat_dim = args.feat_dim
point2img_mapper = args.point2img_mapper
depth_scale = args.depth_scale
keep_features_in_memory = args.keep_features_in_memory
evaluator = args.evaluator
transform = args.transform
# load 3D data (point cloud)
locs_in = torch.load(data_path)[0]
n_points = locs_in.shape[0]
n_interval = num_rand_file_per_scene
n_finished = 0
for n in range(n_interval):
if exists(join(out_dir, scene_id +'_%d.pt'%(n))):
n_finished += 1
print(scene_id +'_%d.pt'%(n) + ' already done!')
continue
if n_finished == n_interval:
return 1
# short hand for processing 2D features
scene = join(args.data_root_2d, scene_id)
img_dirs = sorted(glob(join(scene, 'color/*')), key=lambda x: int(os.path.basename(x)[:-4]))
num_img = len(img_dirs)
device = torch.device('cpu')
# extract image features and keep them in the memory
# default: False (extract image on the fly)
if keep_features_in_memory and evaluator is not None:
img_features = []
for img_dir in tqdm(img_dirs):
img_features.append(extract_lseg_img_feature(img_dir, transform, evaluator))
n_points_cur = n_points
counter = torch.zeros((n_points_cur, 1), device=device)
sum_features = torch.zeros((n_points_cur, feat_dim), device=device)
################ Feature Fusion ###################
vis_id = torch.zeros((n_points_cur, num_img), dtype=int, device=device)
for img_id, img_dir in enumerate(tqdm(img_dirs)):
# load pose
posepath = img_dir.replace('color', 'pose').replace('.jpg', '.txt')
pose = np.loadtxt(posepath)
# load depth and convert to meter
depth = imageio.v2.imread(img_dir.replace('color', 'depth').replace('jpg', 'png')) / depth_scale
# calculate the 3d-2d mapping based on the depth
mapping = np.ones([n_points, 4], dtype=int)
mapping[:, 1:4] = point2img_mapper.compute_mapping(pose, locs_in, depth)
if mapping[:, 3].sum() == 0: # no points corresponds to this image, skip
continue
mapping = torch.from_numpy(mapping).to(device)
mask = mapping[:, 3]
vis_id[:, img_id] = mask
if keep_features_in_memory:
feat_2d = img_features[img_id].to(device)
else:
feat_2d = extract_lseg_img_feature(img_dir, transform, evaluator).to(device)
feat_2d_3d = feat_2d[:, mapping[:, 1], mapping[:, 2]].permute(1, 0)
counter[mask!=0]+= 1
sum_features[mask!=0] += feat_2d_3d[mask!=0]
counter[counter==0] = 1e-5
feat_bank = sum_features/counter
point_ids = torch.unique(vis_id.nonzero(as_tuple=False)[:, 0])
save_fused_feature(feat_bank, point_ids, n_points, out_dir, scene_id, args)
def main(args):
seed = 1457
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
#!### Dataset specific parameters #####
img_dim = (320, 240)
depth_scale = 1000.0
fx = 577.870605
fy = 577.870605
mx=319.5
my=239.5
#######################################
visibility_threshold = 0.25 # threshold for the visibility check
args.depth_scale = depth_scale
args.cut_num_pixel_boundary = 10 # do not use the features on the image boundary
args.keep_features_in_memory = False # keep image features in the memory, very expensive
split = args.split
data_dir = args.data_dir
data_root = join(data_dir, 'scannet_3d')
data_root_2d = join(data_dir,'scannet_2d')
args.data_root_2d = data_root_2d
out_dir = args.output_dir
args.feat_dim = 512 # CLIP feature dimension
os.makedirs(out_dir, exist_ok=True)
process_id_range = args.process_id_range
if split== 'train': # for training set, export a chunk of point cloud
args.n_split_points = 20000
args.num_rand_file_per_scene = 5
else: # for the validation set, export the entire point cloud instead of chunks
args.n_split_points = 2000000
args.num_rand_file_per_scene = 1
##############################
##### load the LSeg model ####
| module = LSegModule.load_from_checkpoint( | 1 | 2023-10-27 15:40:36+00:00 | 8k |
chenran-li/RQL-release | imitation/scripts/eval_policy.py | [
{
"identifier": "VecEnvWrapper",
"path": "stable_baselines3/common/vec_env/base_vec_env.py",
"snippet": "class VecEnvWrapper(VecEnv):\n \"\"\"\n Vectorized environment base class\n\n :param venv: the vectorized environment to wrap\n :param observation_space: the observation space (can be Non... | import logging
import pathlib
import time
import gym
import numpy as np
from typing import Any, Mapping, Optional
from sacred.observers import FileStorageObserver
from stable_baselines3.common.vec_env import VecEnvWrapper
from imitation.data import rollout, types
from imitation.policies.exploration_wrapper import ExplorationWrapper
from imitation.rewards import reward_wrapper
from imitation.rewards.serialize import load_reward
from imitation.scripts.config.eval_policy import eval_policy_ex
from imitation.scripts.ingredients import environment, expert
from imitation.scripts.ingredients import logging as logging_ingredient
from imitation.util import video_wrapper | 4,009 | """Evaluate policies: render policy interactively, save videos, log episode return."""
class InteractiveRender(VecEnvWrapper):
"""Render the wrapped environment(s) on screen."""
def __init__(self, venv, fps):
"""Builds renderer for `venv` running at `fps` frames per second."""
super().__init__(venv)
self.render_fps = fps
def reset(self):
ob = self.venv.reset()
self.venv.render()
return ob
def step_wait(self):
ob = self.venv.step_wait()
if self.render_fps > 0:
time.sleep(1 / self.render_fps)
self.venv.render()
return ob
def video_wrapper_factory(log_dir: pathlib.Path, **kwargs):
"""Returns a function that wraps the environment in a video recorder."""
| """Evaluate policies: render policy interactively, save videos, log episode return."""
class InteractiveRender(VecEnvWrapper):
"""Render the wrapped environment(s) on screen."""
def __init__(self, venv, fps):
"""Builds renderer for `venv` running at `fps` frames per second."""
super().__init__(venv)
self.render_fps = fps
def reset(self):
ob = self.venv.reset()
self.venv.render()
return ob
def step_wait(self):
ob = self.venv.step_wait()
if self.render_fps > 0:
time.sleep(1 / self.render_fps)
self.venv.render()
return ob
def video_wrapper_factory(log_dir: pathlib.Path, **kwargs):
"""Returns a function that wraps the environment in a video recorder."""
| def f(env: gym.Env, i: int) -> video_wrapper.VideoWrapper: | 10 | 2023-10-28 01:09:21+00:00 | 8k |
AmgdGocha/DriveFS-Sleuth | drivefs_sleuth/setup.py | [
{
"identifier": "get_last_pid",
"path": "drivefs_sleuth/utils.py",
"snippet": "def get_last_pid(drivefs_path):\n try:\n with open(os.path.join(drivefs_path, 'pid.txt')) as pid_file:\n return pid_file.read()\n except OSError:\n return -1"
},
{
"identifier": "get_ite... | import os.path
import datetime
from enum import Enum
from collections import OrderedDict
from drivefs_sleuth.utils import get_last_pid
from drivefs_sleuth.utils import get_item_info
from drivefs_sleuth.utils import get_last_sync
from drivefs_sleuth.utils import parse_protobuf
from drivefs_sleuth.utils import get_max_root_ids
from drivefs_sleuth.utils import get_deleted_items
from drivefs_sleuth.utils import get_mirrored_items
from drivefs_sleuth.utils import get_item_properties
from drivefs_sleuth.utils import get_target_stable_id
from drivefs_sleuth.utils import get_connected_devices
from drivefs_sleuth.utils import get_parent_relationships
from drivefs_sleuth.utils import get_content_caches_paths
from drivefs_sleuth.utils import get_file_content_cache_path
from drivefs_sleuth.utils import get_shared_with_me_without_link
from drivefs_sleuth.utils import get_mirroring_roots_for_account
from drivefs_sleuth.synced_files_tree import File
from drivefs_sleuth.synced_files_tree import Link
from drivefs_sleuth.synced_files_tree import Directory
from drivefs_sleuth.synced_files_tree import DummyItem
from drivefs_sleuth.synced_files_tree import MirrorItem
from drivefs_sleuth.synced_files_tree import SyncedFilesTree
from drivefs_sleuth.tasks import get_accounts | 6,840 | parent_info[9], get_item_properties(self.__profile_path,
parent_id), parent_info[3],
parent_info[10])
orphan_dirs[parent_id] = current_parent_dir
for child_id in childs_ids:
child_info = get_item_info(self.__profile_path, child_id)
child_properties = get_item_properties(self.__profile_path, child_id)
if not child_info:
self.__synced_files_tree.add_deleted_item(DummyItem(child_id))
continue
if child_info[0] == 0:
content_cache_path = get_file_content_cache_path(
child_properties.get('content-entry', None), content_caches_paths)
child_file = File(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9], child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', content_cache_path,
child_info[10])
current_parent_dir.add_item(child_file)
if content_cache_path:
self.__synced_files_tree.add_recoverable_item_from_cache(child_file)
else:
if child_info[4] == 'application/vnd.google-apps.shortcut':
target_stable_id = get_target_stable_id(self.__profile_path, child_info[1])
if target_stable_id:
target = orphan_dirs.get(target_stable_id, None)
if target:
added_dirs[target_stable_id] = target
del orphan_dirs[target_stable_id]
else:
target_info = get_item_info(self.__profile_path, target_stable_id)
if target_info:
if target_info[0] == 0:
content_cache_path = get_file_content_cache_path(
child_properties.get('content-entry', None), content_caches_paths)
target = File(target_info[1], target_info[2], target_info[3], target_info[4],
target_info[5], target_info[6], target_info[7], target_info[8],
target_info[9],
get_item_properties(self.__profile_path, target_info[1]),
f'{current_parent_dir.tree_path}\\{target_info[3]}',
content_cache_path, target_info[10])
else:
target = Directory(target_info[1], target_info[2], target_info[3],
target_info[4], target_info[5], target_info[6],
target_info[7], target_info[8], target_info[9],
get_item_properties(self.__profile_path, target_info[1]),
f'{current_parent_dir.tree_path}\\{target_info[3]}',
target_info[10])
added_dirs[target_stable_id] = target
else:
target = DummyItem(target_stable_id)
self.__synced_files_tree.add_deleted_item(target)
child = Link(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9], child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', target, child_info[10])
else:
target = DummyItem('-1')
child = Link(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9], child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', target, child_info[10])
else:
child = orphan_dirs.get(child_id, None)
if child:
child.tree_path = f'{current_parent_dir.tree_path}\\{child.local_title}'
del orphan_dirs[child_id]
else:
child = Directory(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9],
child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', child_info[10])
added_dirs[child_id] = child
current_parent_dir.add_item(child)
# TODO: check if I can add a link in the shared with me
for shared_with_me_item_info in get_shared_with_me_without_link(self.__profile_path):
shared_with_me_item_properties = get_item_properties(self.__profile_path, shared_with_me_item_info[1])
if shared_with_me_item_info[0] == 0:
content_cache_path = get_file_content_cache_path(
shared_with_me_item_properties.get('content-entry', None), content_caches_paths)
shared_with_me_file = File(shared_with_me_item_info[1], shared_with_me_item_info[2],
shared_with_me_item_info[3], shared_with_me_item_info[4],
shared_with_me_item_info[5], shared_with_me_item_info[6],
shared_with_me_item_info[7], shared_with_me_item_info[8],
shared_with_me_item_info[9], shared_with_me_item_properties,
f'Shared with me\\{shared_with_me_item_info[3]}', content_cache_path,
shared_with_me_item_info[10])
self.__synced_files_tree.add_shared_with_me_item(shared_with_me_file)
if shared_with_me_file:
self.__synced_files_tree.add_recoverable_item_from_cache(shared_with_me_file)
else:
shared_with_me_item = orphan_dirs.get(shared_with_me_item_info[1], None)
if shared_with_me_item:
del orphan_dirs[shared_with_me_item_info[1]]
else:
shared_with_me_item = Directory(shared_with_me_item_info[1], shared_with_me_item_info[2],
shared_with_me_item_info[3], shared_with_me_item_info[4],
shared_with_me_item_info[5], shared_with_me_item_info[6],
shared_with_me_item_info[7], shared_with_me_item_info[8],
shared_with_me_item_info[9], shared_with_me_item_properties,
f'{current_parent_dir.tree_path}\\{shared_with_me_item_info[3]}',
shared_with_me_item_info[10])
self.__synced_files_tree.add_shared_with_me_item(shared_with_me_item)
for orphan_id, orphan_dir in orphan_dirs.items():
self.__synced_files_tree.add_orphan_item(orphan_dir)
mirrored_items = get_mirrored_items(self.__profile_path)
for item in mirrored_items:
self.__synced_files_tree.add_mirrored_item(
MirrorItem(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8], item[9],
item[10], item[11], item[12], item[13], item[14], item[15], item[16]
)
)
|
class StorageDestinations(Enum):
DRIVE = "DRIVE"
PHOTOS = "PHOTOS"
class Account:
def __init__(self, drivefs_path, account_id, email, is_logged_in, mirroring_roots, properties):
self.__profile_path = os.path.join(drivefs_path, account_id)
self.__account_id = account_id
self.__account_email = email
self.__is_logged_in = is_logged_in
self.__synced_files_tree = None
if is_logged_in:
self._construct_synced_files_trees()
self.__mirroring_roots = []
for mirroring_root in mirroring_roots:
mirroring_root_info = {
'root_id': mirroring_root[1],
'media_id': mirroring_root[2],
'title': mirroring_root[3],
'root_path': mirroring_root[4],
'sync_type': mirroring_root[5],
'last_seen_absolute_path': mirroring_root[7],
}
if mirroring_root[6] == 1:
mirroring_root_info['destination'] = StorageDestinations.DRIVE.value
else:
mirroring_root_info['destination'] = StorageDestinations.PHOTOS.value
self.__mirroring_roots.append(mirroring_root_info)
self.__name = properties['name']
self.__photo_url = properties['photo_url']
def get_profile_path(self):
return self.__profile_path
def get_account_id(self):
return self.__account_id
def get_account_email(self):
return self.__account_email
def is_logged_in(self):
return self.__is_logged_in
def get_synced_files_tree(self):
return self.__synced_files_tree
def get_mirroring_roots(self):
return self.__mirroring_roots
def get_name(self):
return self.__name
def get_photo_url(self):
return self.__photo_url
def _construct_synced_files_trees(self):
parent_relationships = get_parent_relationships(self.__profile_path)
root_info = get_item_info(self.__profile_path, parent_relationships[0][0])
root = Directory(root_info[1], root_info[2], root_info[3], root_info[4], root_info[5], root_info[6],
root_info[7], root_info[8], root_info[9],
get_item_properties(self.__profile_path, root_info[1]), root_info[3], root_info[10])
self.__synced_files_tree = SyncedFilesTree(root)
content_caches_paths = get_content_caches_paths(os.path.join(self.__profile_path, 'content_cache'))
parent_relationships_dict = OrderedDict()
for parent, child in parent_relationships:
if parent not in parent_relationships_dict.keys():
parent_relationships_dict[parent] = []
parent_relationships_dict[parent].append(child)
added_dirs = {self.__synced_files_tree.get_root().get_stable_id(): self.__synced_files_tree.get_root()}
orphan_dirs = {}
current_parent_dir = self.__synced_files_tree.get_root()
for parent_id, childs_ids in parent_relationships_dict.items():
if parent_id != current_parent_dir.get_stable_id():
if parent_id in added_dirs:
current_parent_dir = added_dirs[parent_id]
elif parent_id in orphan_dirs:
current_parent_dir = orphan_dirs[parent_id]
else:
parent_info = get_item_info(self.__profile_path, parent_id)
if not parent_info:
self.__synced_files_tree.add_deleted_item(DummyItem(parent_id))
else:
current_parent_dir = Directory(parent_info[1], parent_info[2], parent_info[3], parent_info[4],
parent_info[5], parent_info[6], parent_info[7], parent_info[8],
parent_info[9], get_item_properties(self.__profile_path,
parent_id), parent_info[3],
parent_info[10])
orphan_dirs[parent_id] = current_parent_dir
for child_id in childs_ids:
child_info = get_item_info(self.__profile_path, child_id)
child_properties = get_item_properties(self.__profile_path, child_id)
if not child_info:
self.__synced_files_tree.add_deleted_item(DummyItem(child_id))
continue
if child_info[0] == 0:
content_cache_path = get_file_content_cache_path(
child_properties.get('content-entry', None), content_caches_paths)
child_file = File(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9], child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', content_cache_path,
child_info[10])
current_parent_dir.add_item(child_file)
if content_cache_path:
self.__synced_files_tree.add_recoverable_item_from_cache(child_file)
else:
if child_info[4] == 'application/vnd.google-apps.shortcut':
target_stable_id = get_target_stable_id(self.__profile_path, child_info[1])
if target_stable_id:
target = orphan_dirs.get(target_stable_id, None)
if target:
added_dirs[target_stable_id] = target
del orphan_dirs[target_stable_id]
else:
target_info = get_item_info(self.__profile_path, target_stable_id)
if target_info:
if target_info[0] == 0:
content_cache_path = get_file_content_cache_path(
child_properties.get('content-entry', None), content_caches_paths)
target = File(target_info[1], target_info[2], target_info[3], target_info[4],
target_info[5], target_info[6], target_info[7], target_info[8],
target_info[9],
get_item_properties(self.__profile_path, target_info[1]),
f'{current_parent_dir.tree_path}\\{target_info[3]}',
content_cache_path, target_info[10])
else:
target = Directory(target_info[1], target_info[2], target_info[3],
target_info[4], target_info[5], target_info[6],
target_info[7], target_info[8], target_info[9],
get_item_properties(self.__profile_path, target_info[1]),
f'{current_parent_dir.tree_path}\\{target_info[3]}',
target_info[10])
added_dirs[target_stable_id] = target
else:
target = DummyItem(target_stable_id)
self.__synced_files_tree.add_deleted_item(target)
child = Link(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9], child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', target, child_info[10])
else:
target = DummyItem('-1')
child = Link(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9], child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', target, child_info[10])
else:
child = orphan_dirs.get(child_id, None)
if child:
child.tree_path = f'{current_parent_dir.tree_path}\\{child.local_title}'
del orphan_dirs[child_id]
else:
child = Directory(child_info[1], child_info[2], child_info[3], child_info[4], child_info[5],
child_info[6], child_info[7], child_info[8], child_info[9],
child_properties,
f'{current_parent_dir.tree_path}\\{child_info[3]}', child_info[10])
added_dirs[child_id] = child
current_parent_dir.add_item(child)
# TODO: check if I can add a link in the shared with me
for shared_with_me_item_info in get_shared_with_me_without_link(self.__profile_path):
shared_with_me_item_properties = get_item_properties(self.__profile_path, shared_with_me_item_info[1])
if shared_with_me_item_info[0] == 0:
content_cache_path = get_file_content_cache_path(
shared_with_me_item_properties.get('content-entry', None), content_caches_paths)
shared_with_me_file = File(shared_with_me_item_info[1], shared_with_me_item_info[2],
shared_with_me_item_info[3], shared_with_me_item_info[4],
shared_with_me_item_info[5], shared_with_me_item_info[6],
shared_with_me_item_info[7], shared_with_me_item_info[8],
shared_with_me_item_info[9], shared_with_me_item_properties,
f'Shared with me\\{shared_with_me_item_info[3]}', content_cache_path,
shared_with_me_item_info[10])
self.__synced_files_tree.add_shared_with_me_item(shared_with_me_file)
if shared_with_me_file:
self.__synced_files_tree.add_recoverable_item_from_cache(shared_with_me_file)
else:
shared_with_me_item = orphan_dirs.get(shared_with_me_item_info[1], None)
if shared_with_me_item:
del orphan_dirs[shared_with_me_item_info[1]]
else:
shared_with_me_item = Directory(shared_with_me_item_info[1], shared_with_me_item_info[2],
shared_with_me_item_info[3], shared_with_me_item_info[4],
shared_with_me_item_info[5], shared_with_me_item_info[6],
shared_with_me_item_info[7], shared_with_me_item_info[8],
shared_with_me_item_info[9], shared_with_me_item_properties,
f'{current_parent_dir.tree_path}\\{shared_with_me_item_info[3]}',
shared_with_me_item_info[10])
self.__synced_files_tree.add_shared_with_me_item(shared_with_me_item)
for orphan_id, orphan_dir in orphan_dirs.items():
self.__synced_files_tree.add_orphan_item(orphan_dir)
mirrored_items = get_mirrored_items(self.__profile_path)
for item in mirrored_items:
self.__synced_files_tree.add_mirrored_item(
MirrorItem(item[0], item[1], item[2], item[3], item[4], item[5], item[6], item[7], item[8], item[9],
item[10], item[11], item[12], item[13], item[14], item[15], item[16]
)
)
| for deleted_item in get_deleted_items(self.__profile_path): | 5 | 2023-10-29 11:05:04+00:00 | 8k |
zyang1580/CoLLM | train_collm_sasrec.py | [
{
"identifier": "Config",
"path": "minigpt4/common/config.py",
"snippet": "class Config:\n def __init__(self, args):\n self.config = {}\n\n self.args = args\n\n # Register the config and configuration for setup\n registry.register(\"configuration\", self)\n\n user_c... | import argparse
import os
import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import minigpt4.tasks as tasks
import pandas as pd
from minigpt4.common.config import Config
from minigpt4.common.dist_utils import get_rank, init_distributed_mode
from minigpt4.datasets.datasets.rec_gnndataset import GnnDataset
from minigpt4.common.logger import setup_logger
from minigpt4.common.optims import (
LinearWarmupCosineLRScheduler,
LinearWarmupStepLRScheduler,
)
from minigpt4.common.registry import registry
from minigpt4.common.utils import now
from minigpt4.datasets.builders import *
from minigpt4.models import *
from minigpt4.processors import *
from minigpt4.runners import *
from minigpt4.tasks import *
from torch.distributed.elastic.multiprocessing.errors import * | 5,111 | """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
# import os
# os.environ['CURL_CA_BUNDLE'] = ''
# os.environ["CUDA_VISIBLE_DEVICES"]="4"
# imports modules for registration
def parse_args():
parser = argparse.ArgumentParser(description="Training")
# parser.add_argument("--cfg-path", required=True, help="path to configuration file.")
parser.add_argument("--cfg-path", default='train_configs/minigpt4rec_pretrain_sasrec_ood_cc.yaml', help="path to configuration file.")
parser.add_argument(
"--options",
nargs="+",
help="override some settings in the used config, the key-value pair "
"in xxx=yyy format will be merged into config file (deprecate), "
"change to --cfg-options instead.",
)
args = parser.parse_args()
# if 'LOCAL_RANK' not in os.environ:
# os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def setup_seeds(config):
seed = config.run_cfg.seed + get_rank()
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
cudnn.benchmark = False
cudnn.deterministic = True
def get_runner_class(cfg):
"""
Get runner class from config. Default to epoch-based runner.
"""
runner_cls = registry.get_runner_class(cfg.run_cfg.get("runner", "rec_runner_base"))
return runner_cls
@record
def main():
# allow auto-dl completes on main process without timeout when using NCCL backend.
# os.environ["NCCL_BLOCKING_WAIT"] = "1"
# set before init_distributed_mode() to ensure the same job_id shared across all ranks.
job_id = now()
| """
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
# import os
# os.environ['CURL_CA_BUNDLE'] = ''
# os.environ["CUDA_VISIBLE_DEVICES"]="4"
# imports modules for registration
def parse_args():
parser = argparse.ArgumentParser(description="Training")
# parser.add_argument("--cfg-path", required=True, help="path to configuration file.")
parser.add_argument("--cfg-path", default='train_configs/minigpt4rec_pretrain_sasrec_ood_cc.yaml', help="path to configuration file.")
parser.add_argument(
"--options",
nargs="+",
help="override some settings in the used config, the key-value pair "
"in xxx=yyy format will be merged into config file (deprecate), "
"change to --cfg-options instead.",
)
args = parser.parse_args()
# if 'LOCAL_RANK' not in os.environ:
# os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def setup_seeds(config):
seed = config.run_cfg.seed + get_rank()
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
cudnn.benchmark = False
cudnn.deterministic = True
def get_runner_class(cfg):
"""
Get runner class from config. Default to epoch-based runner.
"""
runner_cls = registry.get_runner_class(cfg.run_cfg.get("runner", "rec_runner_base"))
return runner_cls
@record
def main():
# allow auto-dl completes on main process without timeout when using NCCL backend.
# os.environ["NCCL_BLOCKING_WAIT"] = "1"
# set before init_distributed_mode() to ensure the same job_id shared across all ranks.
job_id = now()
| cfg = Config(parse_args()) | 0 | 2023-10-29 12:47:25+00:00 | 8k |
tobagin/whakarere | whakarere/managers/whatsapp.py | [
{
"identifier": "UnknownContact",
"path": "whakarere/images/unknown_contact.py",
"snippet": "class UnknownContact:\n base64image = \"PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPCEtLSBVcGxvYWRlZCB0bzogU1ZHIFJlcG8s... | import gi, sqlite3, os, threading, requests, base64
from gi.repository import Gdk, GdkPixbuf, Gio, GLib
from whakarere.images.unknown_contact import UnknownContact
from whakarere.pages.whatsapp import WhatsappMessengerPage | 5,003 | gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("GdkPixbuf", "2.0")
gi.require_version("Gdk", "4.0")
class WhatsAppSessionManager:
def __init__(self, window):
self.window = window
api_key = "your_global_api_key_here"
self.api_url = "http://localhost:3000"
self.headers = { 'x-api-key': api_key }
self.whatsapp_messenger_pages = {}
self.chats = {} # Changed to a dictionary to map session IDs to chats
self.chats_avatar = {} # Presumably for future functionality
self.databases = {} # Changed to a dictionary to map session IDs to databases
self.chat_messages = {} # Presumably for future functionality
self.number = 0
def load_or_create_databases(self):
db_directory = os.path.expanduser("~/.config/whakarere/dbs")
# Ensure the database directory exists
if not os.path.exists(db_directory):
os.makedirs(db_directory)
for session_id in self.window.session_manager.session_ids:
db_file = f"{session_id}.db"
db_path = os.path.join(db_directory, db_file)
# Connect to the SQLite database
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Store the connection in the dictionary
self.databases[session_id] = conn
# Close the cursor
cursor.close()
def initialize(self):
sessions_thread = threading.Thread(target=self.initialize_sessions)
sessions_thread.start()
def initialize_sessions(self):
for session in self.window.session_manager.session_ids:
if self.window.session_manager.check_session_status(session):
result = self.get_chats(session) # Fixed assignment
self.chats[session] = result # Store chats indexed by session ID
for chat in result:
chat_id = chat["id"]["_serialized"]
if chat["isGroup"]:
print(chat_id)
try:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session)
except:
trimmed_chat_id = chat_id[-15:]
print(trimmed_chat_id)
self.chats[trimmed_chat_id] = self.chat_fetch_messages(trimmed_chat_id, session)
else:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session)
self.chats_avatar[chat_id] = self.get_user_profile_picture(chat_id, session)
self.window.whatsapp_manager.add_whatsapp_messenger_page(session)
def initialize_session_by_id(self, session_id):
if self.window.session_manager.check_session_status(session_id):
result = self.get_chats(session_id) # Fixed assignment
self.chats[session_id] = result # Store chats indexed by session ID
for chat in result:
chat_id = chat["id"]["_serialized"]
if chat["isGroup"]:
print(chat_id)
try:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session_id)
except:
trimmed_chat_id = chat_id[-15:]
print(trimmed_chat_id)
self.chats[trimmed_chat_id] = self.chat_fetch_messages(trimmed_chat_id, session_id)
else:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session_id)
self.chats_avatar[chat_id] = self.get_user_profile_picture(chat_id, session_id)
if session_id not in self.whatsapp_sessions_pages:
| gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("GdkPixbuf", "2.0")
gi.require_version("Gdk", "4.0")
class WhatsAppSessionManager:
def __init__(self, window):
self.window = window
api_key = "your_global_api_key_here"
self.api_url = "http://localhost:3000"
self.headers = { 'x-api-key': api_key }
self.whatsapp_messenger_pages = {}
self.chats = {} # Changed to a dictionary to map session IDs to chats
self.chats_avatar = {} # Presumably for future functionality
self.databases = {} # Changed to a dictionary to map session IDs to databases
self.chat_messages = {} # Presumably for future functionality
self.number = 0
def load_or_create_databases(self):
db_directory = os.path.expanduser("~/.config/whakarere/dbs")
# Ensure the database directory exists
if not os.path.exists(db_directory):
os.makedirs(db_directory)
for session_id in self.window.session_manager.session_ids:
db_file = f"{session_id}.db"
db_path = os.path.join(db_directory, db_file)
# Connect to the SQLite database
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Store the connection in the dictionary
self.databases[session_id] = conn
# Close the cursor
cursor.close()
def initialize(self):
sessions_thread = threading.Thread(target=self.initialize_sessions)
sessions_thread.start()
def initialize_sessions(self):
for session in self.window.session_manager.session_ids:
if self.window.session_manager.check_session_status(session):
result = self.get_chats(session) # Fixed assignment
self.chats[session] = result # Store chats indexed by session ID
for chat in result:
chat_id = chat["id"]["_serialized"]
if chat["isGroup"]:
print(chat_id)
try:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session)
except:
trimmed_chat_id = chat_id[-15:]
print(trimmed_chat_id)
self.chats[trimmed_chat_id] = self.chat_fetch_messages(trimmed_chat_id, session)
else:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session)
self.chats_avatar[chat_id] = self.get_user_profile_picture(chat_id, session)
self.window.whatsapp_manager.add_whatsapp_messenger_page(session)
def initialize_session_by_id(self, session_id):
if self.window.session_manager.check_session_status(session_id):
result = self.get_chats(session_id) # Fixed assignment
self.chats[session_id] = result # Store chats indexed by session ID
for chat in result:
chat_id = chat["id"]["_serialized"]
if chat["isGroup"]:
print(chat_id)
try:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session_id)
except:
trimmed_chat_id = chat_id[-15:]
print(trimmed_chat_id)
self.chats[trimmed_chat_id] = self.chat_fetch_messages(trimmed_chat_id, session_id)
else:
self.chat_messages[chat_id] = self.chat_fetch_messages(chat_id, session_id)
self.chats_avatar[chat_id] = self.get_user_profile_picture(chat_id, session_id)
if session_id not in self.whatsapp_sessions_pages: | self.whatsapp_sessions_pages[session_id] = WhatsappMessengerPage(self, session_id) | 1 | 2023-10-29 15:46:50+00:00 | 8k |
KHU-VLL/CAST | util_tools/video_transforms.py | [
{
"identifier": "rand_augment_transform",
"path": "util_tools/rand_augment.py",
"snippet": "def rand_augment_transform(config_str, hparams):\n \"\"\"\n RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719\n\n Create a RandAugment transform\n :param config_... | import math
import numpy as np
import random
import torch
import torchvision.transforms.functional as F
import numbers
import PIL
import torchvision
import skimage
from PIL import Image
from torchvision import transforms
from .rand_augment import rand_augment_transform
from .random_erasing import RandomErasing
from . import functional as FF | 4,727 | else: # whole image
w = img.size[0]
h = img.size[1]
i = (img.size[1] - h) // 2
j = (img.size[0] - w) // 2
return i, j, h, w
def __call__(self, img):
"""
Args:
img (PIL Image): Image to be cropped and resized.
Returns:
PIL Image: Randomly cropped and resized image.
"""
i, j, h, w = self.get_params(img, self.scale, self.ratio)
if isinstance(self.interpolation, (tuple, list)):
interpolation = random.choice(self.interpolation)
else:
interpolation = self.interpolation
return F.resized_crop(img, i, j, h, w, self.size, interpolation)
def __repr__(self):
if isinstance(self.interpolation, (tuple, list)):
interpolate_str = " ".join(
[_pil_interpolation_to_str[x] for x in self.interpolation]
)
else:
interpolate_str = _pil_interpolation_to_str[self.interpolation]
format_string = self.__class__.__name__ + "(size={0}".format(self.size)
format_string += ", scale={0}".format(
tuple(round(s, 4) for s in self.scale)
)
format_string += ", ratio={0}".format(
tuple(round(r, 4) for r in self.ratio)
)
format_string += ", interpolation={0})".format(interpolate_str)
return format_string
def transforms_imagenet_train(
img_size=224,
scale=None,
ratio=None,
hflip=0.5,
vflip=0.0,
color_jitter=0.4,
auto_augment=None,
interpolation="random",
use_prefetcher=False,
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225),
re_prob=0.0,
re_mode="const",
re_count=1,
re_num_splits=0,
separate=False,
):
"""
If separate==True, the transforms are returned as a tuple of 3 separate transforms
for use in a mixing dataset that passes
* all data through the first (primary) transform, called the 'clean' data
* a portion of the data through the secondary transform
* normalizes and converts the branches above with the third, final transform
"""
if isinstance(img_size, tuple):
img_size = img_size[-2:]
else:
img_size = img_size
scale = tuple(scale or (0.08, 1.0)) # default imagenet scale range
ratio = tuple(
ratio or (3.0 / 4.0, 4.0 / 3.0)
) # default imagenet ratio range
primary_tfl = [
RandomResizedCropAndInterpolation(
img_size, scale=scale, ratio=ratio, interpolation=interpolation
)
]
if hflip > 0.0:
primary_tfl += [transforms.RandomHorizontalFlip(p=hflip)]
if vflip > 0.0:
primary_tfl += [transforms.RandomVerticalFlip(p=vflip)]
secondary_tfl = []
if auto_augment:
assert isinstance(auto_augment, str)
if isinstance(img_size, tuple):
img_size_min = min(img_size)
else:
img_size_min = img_size
aa_params = dict(
translate_const=int(img_size_min * 0.45),
img_mean=tuple([min(255, round(255 * x)) for x in mean]),
)
if interpolation and interpolation != "random":
aa_params["interpolation"] = _pil_interp(interpolation)
if auto_augment.startswith("rand"):
secondary_tfl += [rand_augment_transform(auto_augment, aa_params)]
elif auto_augment.startswith("augmix"):
raise NotImplementedError("Augmix not implemented")
else:
raise NotImplementedError("Auto aug not implemented")
elif color_jitter is not None:
# color jitter is enabled when not using AA
if isinstance(color_jitter, (list, tuple)):
# color jitter should be a 3-tuple/list if spec brightness/contrast/saturation
# or 4 if also augmenting hue
assert len(color_jitter) in (3, 4)
else:
# if it's a scalar, duplicate for brightness, contrast, and saturation, no hue
color_jitter = (float(color_jitter),) * 3
secondary_tfl += [transforms.ColorJitter(*color_jitter)]
final_tfl = []
final_tfl += [
transforms.ToTensor(),
transforms.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)),
]
if re_prob > 0.0:
final_tfl.append(
| #!/usr/bin/env python3
_pil_interpolation_to_str = {
Image.NEAREST: "PIL.Image.NEAREST",
Image.BILINEAR: "PIL.Image.BILINEAR",
Image.BICUBIC: "PIL.Image.BICUBIC",
Image.LANCZOS: "PIL.Image.LANCZOS",
Image.HAMMING: "PIL.Image.HAMMING",
Image.BOX: "PIL.Image.BOX",
}
_RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC)
def _pil_interp(method):
if method == "bicubic":
return Image.BICUBIC
elif method == "lanczos":
return Image.LANCZOS
elif method == "hamming":
return Image.HAMMING
else:
return Image.BILINEAR
def random_short_side_scale_jitter(
images, min_size, max_size, boxes=None, inverse_uniform_sampling=False
):
"""
Perform a spatial short scale jittering on the given images and
corresponding boxes.
Args:
images (tensor): images to perform scale jitter. Dimension is
`num frames` x `channel` x `height` x `width`.
min_size (int): the minimal size to scale the frames.
max_size (int): the maximal size to scale the frames.
boxes (ndarray): optional. Corresponding boxes to images.
Dimension is `num boxes` x 4.
inverse_uniform_sampling (bool): if True, sample uniformly in
[1 / max_scale, 1 / min_scale] and take a reciprocal to get the
scale. If False, take a uniform sample from [min_scale, max_scale].
Returns:
(tensor): the scaled images with dimension of
`num frames` x `channel` x `new height` x `new width`.
(ndarray or None): the scaled boxes with dimension of
`num boxes` x 4.
"""
if inverse_uniform_sampling:
size = int(
round(1.0 / np.random.uniform(1.0 / max_size, 1.0 / min_size))
)
else:
size = int(round(np.random.uniform(min_size, max_size)))
height = images.shape[2]
width = images.shape[3]
if (width <= height and width == size) or (
height <= width and height == size
):
return images, boxes
new_width = size
new_height = size
if width < height:
new_height = int(math.floor((float(height) / width) * size))
if boxes is not None:
boxes = boxes * float(new_height) / height
else:
new_width = int(math.floor((float(width) / height) * size))
if boxes is not None:
boxes = boxes * float(new_width) / width
return (
torch.nn.functional.interpolate(
images,
size=(new_height, new_width),
mode="bilinear",
align_corners=False,
),
boxes,
)
def crop_boxes(boxes, x_offset, y_offset):
"""
Peform crop on the bounding boxes given the offsets.
Args:
boxes (ndarray or None): bounding boxes to peform crop. The dimension
is `num boxes` x 4.
x_offset (int): cropping offset in the x axis.
y_offset (int): cropping offset in the y axis.
Returns:
cropped_boxes (ndarray or None): the cropped boxes with dimension of
`num boxes` x 4.
"""
cropped_boxes = boxes.copy()
cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset
cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset
return cropped_boxes
def random_crop(images, size, boxes=None):
"""
Perform random spatial crop on the given images and corresponding boxes.
Args:
images (tensor): images to perform random crop. The dimension is
`num frames` x `channel` x `height` x `width`.
size (int): the size of height and width to crop on the image.
boxes (ndarray or None): optional. Corresponding boxes to images.
Dimension is `num boxes` x 4.
Returns:
cropped (tensor): cropped images with dimension of
`num frames` x `channel` x `size` x `size`.
cropped_boxes (ndarray or None): the cropped boxes with dimension of
`num boxes` x 4.
"""
if images.shape[2] == size and images.shape[3] == size:
return images
height = images.shape[2]
width = images.shape[3]
y_offset = 0
if height > size:
y_offset = int(np.random.randint(0, height - size))
x_offset = 0
if width > size:
x_offset = int(np.random.randint(0, width - size))
cropped = images[
:, :, y_offset : y_offset + size, x_offset : x_offset + size
]
cropped_boxes = (
crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
)
return cropped, cropped_boxes
def horizontal_flip(prob, images, boxes=None):
"""
Perform horizontal flip on the given images and corresponding boxes.
Args:
prob (float): probility to flip the images.
images (tensor): images to perform horizontal flip, the dimension is
`num frames` x `channel` x `height` x `width`.
boxes (ndarray or None): optional. Corresponding boxes to images.
Dimension is `num boxes` x 4.
Returns:
images (tensor): images with dimension of
`num frames` x `channel` x `height` x `width`.
flipped_boxes (ndarray or None): the flipped boxes with dimension of
`num boxes` x 4.
"""
if boxes is None:
flipped_boxes = None
else:
flipped_boxes = boxes.copy()
if np.random.uniform() < prob:
images = images.flip((-1))
if len(images.shape) == 3:
width = images.shape[2]
elif len(images.shape) == 4:
width = images.shape[3]
else:
raise NotImplementedError("Dimension does not supported")
if boxes is not None:
flipped_boxes[:, [0, 2]] = width - boxes[:, [2, 0]] - 1
return images, flipped_boxes
def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None):
"""
Perform uniform spatial sampling on the images and corresponding boxes.
Args:
images (tensor): images to perform uniform crop. The dimension is
`num frames` x `channel` x `height` x `width`.
size (int): size of height and weight to crop the images.
spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width
is larger than height. Or 0, 1, or 2 for top, center, and bottom
crop if height is larger than width.
boxes (ndarray or None): optional. Corresponding boxes to images.
Dimension is `num boxes` x 4.
scale_size (int): optinal. If not None, resize the images to scale_size before
performing any crop.
Returns:
cropped (tensor): images with dimension of
`num frames` x `channel` x `size` x `size`.
cropped_boxes (ndarray or None): the cropped boxes with dimension of
`num boxes` x 4.
"""
assert spatial_idx in [0, 1, 2]
ndim = len(images.shape)
if ndim == 3:
images = images.unsqueeze(0)
height = images.shape[2]
width = images.shape[3]
if scale_size is not None:
if width <= height:
width, height = scale_size, int(height / width * scale_size)
else:
width, height = int(width / height * scale_size), scale_size
images = torch.nn.functional.interpolate(
images,
size=(height, width),
mode="bilinear",
align_corners=False,
)
y_offset = int(math.ceil((height - size) / 2))
x_offset = int(math.ceil((width - size) / 2))
if height > width:
if spatial_idx == 0:
y_offset = 0
elif spatial_idx == 2:
y_offset = height - size
else:
if spatial_idx == 0:
x_offset = 0
elif spatial_idx == 2:
x_offset = width - size
cropped = images[
:, :, y_offset : y_offset + size, x_offset : x_offset + size
]
cropped_boxes = (
crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None
)
if ndim == 3:
cropped = cropped.squeeze(0)
return cropped, cropped_boxes
def clip_boxes_to_image(boxes, height, width):
"""
Clip an array of boxes to an image with the given height and width.
Args:
boxes (ndarray): bounding boxes to perform clipping.
Dimension is `num boxes` x 4.
height (int): given image height.
width (int): given image width.
Returns:
clipped_boxes (ndarray): the clipped boxes with dimension of
`num boxes` x 4.
"""
clipped_boxes = boxes.copy()
clipped_boxes[:, [0, 2]] = np.minimum(
width - 1.0, np.maximum(0.0, boxes[:, [0, 2]])
)
clipped_boxes[:, [1, 3]] = np.minimum(
height - 1.0, np.maximum(0.0, boxes[:, [1, 3]])
)
return clipped_boxes
def blend(images1, images2, alpha):
"""
Blend two images with a given weight alpha.
Args:
images1 (tensor): the first images to be blended, the dimension is
`num frames` x `channel` x `height` x `width`.
images2 (tensor): the second images to be blended, the dimension is
`num frames` x `channel` x `height` x `width`.
alpha (float): the blending weight.
Returns:
(tensor): blended images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
return images1 * alpha + images2 * (1 - alpha)
def grayscale(images):
"""
Get the grayscale for the input images. The channels of images should be
in order BGR.
Args:
images (tensor): the input images for getting grayscale. Dimension is
`num frames` x `channel` x `height` x `width`.
Returns:
img_gray (tensor): blended images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
# R -> 0.299, G -> 0.587, B -> 0.114.
img_gray = torch.tensor(images)
gray_channel = (
0.299 * images[:, 2] + 0.587 * images[:, 1] + 0.114 * images[:, 0]
)
img_gray[:, 0] = gray_channel
img_gray[:, 1] = gray_channel
img_gray[:, 2] = gray_channel
return img_gray
def color_jitter(images, img_brightness=0, img_contrast=0, img_saturation=0):
"""
Perfrom a color jittering on the input images. The channels of images
should be in order BGR.
Args:
images (tensor): images to perform color jitter. Dimension is
`num frames` x `channel` x `height` x `width`.
img_brightness (float): jitter ratio for brightness.
img_contrast (float): jitter ratio for contrast.
img_saturation (float): jitter ratio for saturation.
Returns:
images (tensor): the jittered images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
jitter = []
if img_brightness != 0:
jitter.append("brightness")
if img_contrast != 0:
jitter.append("contrast")
if img_saturation != 0:
jitter.append("saturation")
if len(jitter) > 0:
order = np.random.permutation(np.arange(len(jitter)))
for idx in range(0, len(jitter)):
if jitter[order[idx]] == "brightness":
images = brightness_jitter(img_brightness, images)
elif jitter[order[idx]] == "contrast":
images = contrast_jitter(img_contrast, images)
elif jitter[order[idx]] == "saturation":
images = saturation_jitter(img_saturation, images)
return images
def brightness_jitter(var, images):
"""
Perfrom brightness jittering on the input images. The channels of images
should be in order BGR.
Args:
var (float): jitter ratio for brightness.
images (tensor): images to perform color jitter. Dimension is
`num frames` x `channel` x `height` x `width`.
Returns:
images (tensor): the jittered images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
alpha = 1.0 + np.random.uniform(-var, var)
img_bright = torch.zeros(images.shape)
images = blend(images, img_bright, alpha)
return images
def contrast_jitter(var, images):
"""
Perfrom contrast jittering on the input images. The channels of images
should be in order BGR.
Args:
var (float): jitter ratio for contrast.
images (tensor): images to perform color jitter. Dimension is
`num frames` x `channel` x `height` x `width`.
Returns:
images (tensor): the jittered images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
alpha = 1.0 + np.random.uniform(-var, var)
img_gray = grayscale(images)
img_gray[:] = torch.mean(img_gray, dim=(1, 2, 3), keepdim=True)
images = blend(images, img_gray, alpha)
return images
def saturation_jitter(var, images):
"""
Perfrom saturation jittering on the input images. The channels of images
should be in order BGR.
Args:
var (float): jitter ratio for saturation.
images (tensor): images to perform color jitter. Dimension is
`num frames` x `channel` x `height` x `width`.
Returns:
images (tensor): the jittered images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
alpha = 1.0 + np.random.uniform(-var, var)
img_gray = grayscale(images)
images = blend(images, img_gray, alpha)
return images
def lighting_jitter(images, alphastd, eigval, eigvec):
"""
Perform AlexNet-style PCA jitter on the given images.
Args:
images (tensor): images to perform lighting jitter. Dimension is
`num frames` x `channel` x `height` x `width`.
alphastd (float): jitter ratio for PCA jitter.
eigval (list): eigenvalues for PCA jitter.
eigvec (list[list]): eigenvectors for PCA jitter.
Returns:
out_images (tensor): the jittered images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
if alphastd == 0:
return images
# generate alpha1, alpha2, alpha3.
alpha = np.random.normal(0, alphastd, size=(1, 3))
eig_vec = np.array(eigvec)
eig_val = np.reshape(eigval, (1, 3))
rgb = np.sum(
eig_vec * np.repeat(alpha, 3, axis=0) * np.repeat(eig_val, 3, axis=0),
axis=1,
)
out_images = torch.zeros_like(images)
if len(images.shape) == 3:
# C H W
channel_dim = 0
elif len(images.shape) == 4:
# T C H W
channel_dim = 1
else:
raise NotImplementedError(f"Unsupported dimension {len(images.shape)}")
for idx in range(images.shape[channel_dim]):
# C H W
if len(images.shape) == 3:
out_images[idx] = images[idx] + rgb[2 - idx]
# T C H W
elif len(images.shape) == 4:
out_images[:, idx] = images[:, idx] + rgb[2 - idx]
else:
raise NotImplementedError(
f"Unsupported dimension {len(images.shape)}"
)
return out_images
def color_normalization(images, mean, stddev):
"""
Perform color nomration on the given images.
Args:
images (tensor): images to perform color normalization. Dimension is
`num frames` x `channel` x `height` x `width`.
mean (list): mean values for normalization.
stddev (list): standard deviations for normalization.
Returns:
out_images (tensor): the noramlized images, the dimension is
`num frames` x `channel` x `height` x `width`.
"""
if len(images.shape) == 3:
assert (
len(mean) == images.shape[0]
), "channel mean not computed properly"
assert (
len(stddev) == images.shape[0]
), "channel stddev not computed properly"
elif len(images.shape) == 4:
assert (
len(mean) == images.shape[1]
), "channel mean not computed properly"
assert (
len(stddev) == images.shape[1]
), "channel stddev not computed properly"
else:
raise NotImplementedError(f"Unsupported dimension {len(images.shape)}")
out_images = torch.zeros_like(images)
for idx in range(len(mean)):
# C H W
if len(images.shape) == 3:
out_images[idx] = (images[idx] - mean[idx]) / stddev[idx]
elif len(images.shape) == 4:
out_images[:, idx] = (images[:, idx] - mean[idx]) / stddev[idx]
else:
raise NotImplementedError(
f"Unsupported dimension {len(images.shape)}"
)
return out_images
def _get_param_spatial_crop(
scale, ratio, height, width, num_repeat=10, log_scale=True, switch_hw=False
):
"""
Given scale, ratio, height and width, return sampled coordinates of the videos.
"""
for _ in range(num_repeat):
area = height * width
target_area = random.uniform(*scale) * area
if log_scale:
log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
aspect_ratio = math.exp(random.uniform(*log_ratio))
else:
aspect_ratio = random.uniform(*ratio)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if np.random.uniform() < 0.5 and switch_hw:
w, h = h, w
if 0 < w <= width and 0 < h <= height:
i = random.randint(0, height - h)
j = random.randint(0, width - w)
return i, j, h, w
# Fallback to central crop
in_ratio = float(width) / float(height)
if in_ratio < min(ratio):
w = width
h = int(round(w / min(ratio)))
elif in_ratio > max(ratio):
h = height
w = int(round(h * max(ratio)))
else: # whole image
w = width
h = height
i = (height - h) // 2
j = (width - w) // 2
return i, j, h, w
def random_resized_crop(
images,
target_height,
target_width,
scale=(0.8, 1.0),
ratio=(3.0 / 4.0, 4.0 / 3.0),
):
"""
Crop the given images to random size and aspect ratio. A crop of random
size (default: of 0.08 to 1.0) of the original size and a random aspect
ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This
crop is finally resized to given size. This is popularly used to train the
Inception networks.
Args:
images: Images to perform resizing and cropping.
target_height: Desired height after cropping.
target_width: Desired width after cropping.
scale: Scale range of Inception-style area based random resizing.
ratio: Aspect ratio range of Inception-style area based random resizing.
"""
height = images.shape[2]
width = images.shape[3]
i, j, h, w = _get_param_spatial_crop(scale, ratio, height, width)
cropped = images[:, :, i : i + h, j : j + w]
return torch.nn.functional.interpolate(
cropped,
size=(target_height, target_width),
mode="bilinear",
align_corners=False,
)
def random_resized_crop_with_shift(
images,
target_height,
target_width,
scale=(0.8, 1.0),
ratio=(3.0 / 4.0, 4.0 / 3.0),
):
"""
This is similar to random_resized_crop. However, it samples two different
boxes (for cropping) for the first and last frame. It then linearly
interpolates the two boxes for other frames.
Args:
images: Images to perform resizing and cropping.
target_height: Desired height after cropping.
target_width: Desired width after cropping.
scale: Scale range of Inception-style area based random resizing.
ratio: Aspect ratio range of Inception-style area based random resizing.
"""
t = images.shape[1]
height = images.shape[2]
width = images.shape[3]
i, j, h, w = _get_param_spatial_crop(scale, ratio, height, width)
i_, j_, h_, w_ = _get_param_spatial_crop(scale, ratio, height, width)
i_s = [int(i) for i in torch.linspace(i, i_, steps=t).tolist()]
j_s = [int(i) for i in torch.linspace(j, j_, steps=t).tolist()]
h_s = [int(i) for i in torch.linspace(h, h_, steps=t).tolist()]
w_s = [int(i) for i in torch.linspace(w, w_, steps=t).tolist()]
out = torch.zeros((3, t, target_height, target_width))
for ind in range(t):
out[:, ind : ind + 1, :, :] = torch.nn.functional.interpolate(
images[
:,
ind : ind + 1,
i_s[ind] : i_s[ind] + h_s[ind],
j_s[ind] : j_s[ind] + w_s[ind],
],
size=(target_height, target_width),
mode="bilinear",
align_corners=False,
)
return out
def create_random_augment(
input_size,
auto_augment=None,
interpolation="bilinear",
):
"""
Get video randaug transform.
Args:
input_size: The size of the input video in tuple.
auto_augment: Parameters for randaug. An example:
"rand-m7-n4-mstd0.5-inc1" (m is the magnitude and n is the number
of operations to apply).
interpolation: Interpolation method.
"""
if isinstance(input_size, tuple):
img_size = input_size[-2:]
else:
img_size = input_size
if auto_augment:
assert isinstance(auto_augment, str)
if isinstance(img_size, tuple):
img_size_min = min(img_size)
else:
img_size_min = img_size
aa_params = {"translate_const": int(img_size_min * 0.45)}
if interpolation and interpolation != "random":
aa_params["interpolation"] = _pil_interp(interpolation)
if auto_augment.startswith("rand"):
return transforms.Compose(
[rand_augment_transform(auto_augment, aa_params)]
)
raise NotImplementedError
def random_sized_crop_img(
im,
size,
jitter_scale=(0.08, 1.0),
jitter_aspect=(3.0 / 4.0, 4.0 / 3.0),
max_iter=10,
):
"""
Performs Inception-style cropping (used for training).
"""
assert (
len(im.shape) == 3
), "Currently only support image for random_sized_crop"
h, w = im.shape[1:3]
i, j, h, w = _get_param_spatial_crop(
scale=jitter_scale,
ratio=jitter_aspect,
height=h,
width=w,
num_repeat=max_iter,
log_scale=False,
switch_hw=True,
)
cropped = im[:, i : i + h, j : j + w]
return torch.nn.functional.interpolate(
cropped.unsqueeze(0),
size=(size, size),
mode="bilinear",
align_corners=False,
).squeeze(0)
# The following code are modified based on timm lib, we will replace the following
# contents with dependency from PyTorchVideo.
# https://github.com/facebookresearch/pytorchvideo
class RandomResizedCropAndInterpolation:
"""Crop the given PIL Image to random size and aspect ratio with random interpolation.
A crop of random size (default: of 0.08 to 1.0) of the original size and a random
aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
is finally resized to given size.
This is popularly used to train the Inception networks.
Args:
size: expected output size of each edge
scale: range of size of the origin size cropped
ratio: range of aspect ratio of the origin aspect ratio cropped
interpolation: Default: PIL.Image.BILINEAR
"""
def __init__(
self,
size,
scale=(0.08, 1.0),
ratio=(3.0 / 4.0, 4.0 / 3.0),
interpolation="bilinear",
):
if isinstance(size, tuple):
self.size = size
else:
self.size = (size, size)
if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
print("range should be of kind (min, max)")
if interpolation == "random":
self.interpolation = _RANDOM_INTERPOLATION
else:
self.interpolation = _pil_interp(interpolation)
self.scale = scale
self.ratio = ratio
@staticmethod
def get_params(img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (PIL Image): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for a random
sized crop.
"""
area = img.size[0] * img.size[1]
for _ in range(10):
target_area = random.uniform(*scale) * area
log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
aspect_ratio = math.exp(random.uniform(*log_ratio))
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if w <= img.size[0] and h <= img.size[1]:
i = random.randint(0, img.size[1] - h)
j = random.randint(0, img.size[0] - w)
return i, j, h, w
# Fallback to central crop
in_ratio = img.size[0] / img.size[1]
if in_ratio < min(ratio):
w = img.size[0]
h = int(round(w / min(ratio)))
elif in_ratio > max(ratio):
h = img.size[1]
w = int(round(h * max(ratio)))
else: # whole image
w = img.size[0]
h = img.size[1]
i = (img.size[1] - h) // 2
j = (img.size[0] - w) // 2
return i, j, h, w
def __call__(self, img):
"""
Args:
img (PIL Image): Image to be cropped and resized.
Returns:
PIL Image: Randomly cropped and resized image.
"""
i, j, h, w = self.get_params(img, self.scale, self.ratio)
if isinstance(self.interpolation, (tuple, list)):
interpolation = random.choice(self.interpolation)
else:
interpolation = self.interpolation
return F.resized_crop(img, i, j, h, w, self.size, interpolation)
def __repr__(self):
if isinstance(self.interpolation, (tuple, list)):
interpolate_str = " ".join(
[_pil_interpolation_to_str[x] for x in self.interpolation]
)
else:
interpolate_str = _pil_interpolation_to_str[self.interpolation]
format_string = self.__class__.__name__ + "(size={0}".format(self.size)
format_string += ", scale={0}".format(
tuple(round(s, 4) for s in self.scale)
)
format_string += ", ratio={0}".format(
tuple(round(r, 4) for r in self.ratio)
)
format_string += ", interpolation={0})".format(interpolate_str)
return format_string
def transforms_imagenet_train(
img_size=224,
scale=None,
ratio=None,
hflip=0.5,
vflip=0.0,
color_jitter=0.4,
auto_augment=None,
interpolation="random",
use_prefetcher=False,
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225),
re_prob=0.0,
re_mode="const",
re_count=1,
re_num_splits=0,
separate=False,
):
"""
If separate==True, the transforms are returned as a tuple of 3 separate transforms
for use in a mixing dataset that passes
* all data through the first (primary) transform, called the 'clean' data
* a portion of the data through the secondary transform
* normalizes and converts the branches above with the third, final transform
"""
if isinstance(img_size, tuple):
img_size = img_size[-2:]
else:
img_size = img_size
scale = tuple(scale or (0.08, 1.0)) # default imagenet scale range
ratio = tuple(
ratio or (3.0 / 4.0, 4.0 / 3.0)
) # default imagenet ratio range
primary_tfl = [
RandomResizedCropAndInterpolation(
img_size, scale=scale, ratio=ratio, interpolation=interpolation
)
]
if hflip > 0.0:
primary_tfl += [transforms.RandomHorizontalFlip(p=hflip)]
if vflip > 0.0:
primary_tfl += [transforms.RandomVerticalFlip(p=vflip)]
secondary_tfl = []
if auto_augment:
assert isinstance(auto_augment, str)
if isinstance(img_size, tuple):
img_size_min = min(img_size)
else:
img_size_min = img_size
aa_params = dict(
translate_const=int(img_size_min * 0.45),
img_mean=tuple([min(255, round(255 * x)) for x in mean]),
)
if interpolation and interpolation != "random":
aa_params["interpolation"] = _pil_interp(interpolation)
if auto_augment.startswith("rand"):
secondary_tfl += [rand_augment_transform(auto_augment, aa_params)]
elif auto_augment.startswith("augmix"):
raise NotImplementedError("Augmix not implemented")
else:
raise NotImplementedError("Auto aug not implemented")
elif color_jitter is not None:
# color jitter is enabled when not using AA
if isinstance(color_jitter, (list, tuple)):
# color jitter should be a 3-tuple/list if spec brightness/contrast/saturation
# or 4 if also augmenting hue
assert len(color_jitter) in (3, 4)
else:
# if it's a scalar, duplicate for brightness, contrast, and saturation, no hue
color_jitter = (float(color_jitter),) * 3
secondary_tfl += [transforms.ColorJitter(*color_jitter)]
final_tfl = []
final_tfl += [
transforms.ToTensor(),
transforms.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)),
]
if re_prob > 0.0:
final_tfl.append( | RandomErasing( | 1 | 2023-10-25 07:07:05+00:00 | 8k |
Agricultural-Robotics-Bonn/pagnerf | config_parser.py | [
{
"identifier": "MultiviewDataset",
"path": "datasets/multiview_dataset.py",
"snippet": "class MultiviewDataset(Dataset):\n \"\"\"This is a static multiview image dataset class.\n\n This class should be used for training tasks where the task is to fit a static 3D volume from\n multiview images.... | import os
import sys
import argparse
import pprint
import yaml
import torch
import logging as log
from datasets import MultiviewDataset
from datasets.transforms import *
from wisp.datasets import SDFDataset
from wisp.models import Pipeline
from wisp.models.nefs import *
from wisp.models.grids import *
from wisp.tracers import *
from grids.permuto_grid import PermutoGrid
from pc_nerf.ba_pipeline import BAPipeline | 6,631 | parser.set_defaults(**defaults_dict)
def parse_config_dict(config_dict, parser):
"""Parses and sets the parser defaults with a yaml config file.
Args:
config_path : path to the yaml config file.
parser : The parser for which the defaults will be set.
parent : True if parsing the parent yaml. Should never be set to True by the user.
"""
list_of_valid_fields = []
for group in parser._action_groups:
group_dict = {list_of_valid_fields.append(a.dest) for a in group._group_actions}
list_of_valid_fields = set(list_of_valid_fields)
defaults_dict = {}
# Loads child parent and overwrite the parent configs
# The yaml files assumes the argument groups, which aren't actually nested.
for key in config_dict:
for field in config_dict[key]:
if field not in list_of_valid_fields:
raise ValueError(
f"ERROR: {field} is not a valid option. Check for typos in the config."
)
defaults_dict[field] = config_dict[key][field]
parser.set_defaults(**defaults_dict)
def argparse_to_str(parser, args=None, config_dict=None):
"""Convert parser to string representation for Tensorboard logging.
Args:
parser (argparse.parser): Parser object. Needed for the argument groups.
args : The parsed arguments. Will compute from the parser if None.
Returns:
args : The parsed arguments.
arg_str : The string to be printed.
"""
if args is None:
args = parser.parse_args()
if config_dict is not None:
parse_config_dict(config_dict, parser)
elif args.config is not None:
parse_yaml_config(args.config, parser)
args = parser.parse_args()
args_dict = {}
for group in parser._action_groups:
group_dict = {a.dest: getattr(args, a.dest, None) for a in group._group_actions}
args_dict[group.title] = vars(argparse.Namespace(**group_dict))
pp = pprint.PrettyPrinter(indent=2)
args_str = pp.pformat(args_dict)
args_str = f'```{args_str}```'
return args, args_str
def get_trainer(args):
return globals()[args.trainer_type]
def get_optimizer_from_config(args):
"""Utility function to get the optimizer from the parsed config.
"""
optim_cls = str2optim[args.optimizer_type]
if args.optimizer_type == 'adam':
optim_params = {'eps': 1e-15}
elif args.optimizer_type == 'sgd':
optim_params = {'momentum': 0.8}
else:
optim_params = {}
return optim_cls, optim_params
def get_modules_from_config(args):
"""Utility function to get the modules for training from the parsed config.
"""
val_dataset = None
if args.dataset_type == "multiview":
log.info('Loading training dataset...')
transform = SampleRays(args.num_rays_sampled_per_img)
train_dataset = MultiviewDataset(**vars(args), transform=transform)
train_dataset.init()
args.ray_max_travel = args.ray_max_travel * train_dataset.scale
if args.optimize_val_extrinsics:
log.info('Loading validation split for pose optimization only...')
val_dataset = MultiviewDataset(**vars(args), split='val', transform=transform)
val_dataset.init()
if 'semantic_info' in vars(train_dataset) and train_dataset.semantic_info is not None:
args.num_classes = train_dataset.semantic_info['num_classes']
args.num_instances = train_dataset.semantic_info['num_instances']
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
nef = globals()[args.nef_type](**vars(args))
tracer = globals()[args.tracer_type](**vars(args))
# Use a Bundle Adjustment pipeline if extriniscs need to be optimized
if args.optimize_extrinsics:
cameras = train_dataset.data['cameras']
# add validation cameras if val extrinsics need to be optimized
if args.optimize_val_extrinsics:
cameras.update(val_dataset.data['cameras'])
pipeline = BAPipeline(nef, cameras, tracer)
else:
pipeline = Pipeline(nef, tracer)
if args.dataset_type == "multiview":
if pipeline.nef.grid is not None:
if isinstance(pipeline.nef.grid, OctreeGrid):
if not args.valid_only and not pipeline.nef.grid.blas_initialized():
if args.multiview_dataset_format in ['rtmv']:
pipeline.nef.grid.init_from_pointcloud(train_dataset.coords)
else:
pipeline.nef.grid.init_dense()
| # Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited.
str2optim = {m.lower(): getattr(torch.optim, m) for m in dir(torch.optim) if m[0].isupper()}
def register_class(cls, name):
globals()[name] = cls
def parse_options(return_parser=False):
"""Function used to parse options.
Apps should use these CLI options, and then extend using parser.add_argument_group('app')
Args:
return_parser : If true, will return the parser object instead of the parsed arguments.
This is useful if you want to keep the parser around to add special argument
groups through app.
"""
# New CLI parser
parser = argparse.ArgumentParser(description='ArgumentParser for kaolin-wisp.')
###################
# Global arguments
###################
global_group = parser.add_argument_group('global')
global_group.add_argument('--trainer-type', type=str,
help='Trainer class to use')
global_group.add_argument('--exp-name', type=str,
help='Experiment name.')
global_group.add_argument('--perf', action='store', const=True, default=False, nargs='?',
help='Use high-level profiling for the trainer.')
global_group.add_argument('--detect-anomaly', action='store', const=True, default=False, nargs='?',
help='Turn on anomaly detection.')
global_group.add_argument('--config', type=str,
help='Path to config file to replace defaults.')
global_group.add_argument('--default-channel', type=str,
help='Default channel to show in the viewer')
global_group.add_argument('--save-map-only', action='store', const=True, default=False, nargs='?',
help='Load model and save the 3D map only')
###################
# Grid arguments
###################
grid_group = parser.add_argument_group('grid')
grid_group.add_argument('--grid-type', type=str, default='OctreeGrid',
choices=['None', 'OctreeGrid', 'CodebookOctreeGrid', 'TriplanarGrid', 'HashGrid'],
help='Type of grid to use.')
grid_group.add_argument('--interpolation-type', type=str, default='linear',
choices=['linear', 'closest'],
help='SPC interpolation mode.')
grid_group.add_argument('--as-type', type=str, default='none',
choices=['none', 'octree'],
help='Type of accelstruct to use.')
grid_group.add_argument('--raymarch-type', type=str, default='voxel',
choices=['voxel', 'ray'],
help='Method of raymarching. `voxel` samples within each primitive, \
`ray` samples within rays and then filters them with the primitives. \
See the accelstruct for details.')
grid_group.add_argument('--multiscale-type', type=str, default='sum',
choices=['cat', 'sum'],
help='Type of multiscale aggregation function to use.')
grid_group.add_argument('--feature-dim', type=int, default=32,
help='Feature map dimension')
grid_group.add_argument('--feature-std', type=float, default=0.0,
help='Feature map std')
grid_group.add_argument('--feature-bias', type=float, default=0.0,
help='Feature map bias')
grid_group.add_argument('--noise-std', type=float, default=0.0,
help='Added noise to features in training.')
grid_group.add_argument('--num-lods', type=int, default=1,
help='Number of LODs')
grid_group.add_argument('--base-lod', type=int, default=2,
help='Base level LOD')
grid_group.add_argument('--max-grid-res', type=int, default=2048,
help='The maximum grid resolution. Used only in geometric initialization.')
grid_group.add_argument('--tree-type', type=str, default='quad',
choices=['quad', 'geometric'],
help='What type of tree to use. `quad` is a quadtree or octree-like growing \
scheme, whereas geometric is the Instant-NGP growing scheme.')
grid_group.add_argument('--codebook-bitwidth', type=int, default=8,
help='Bitwidth to use for the codebook. The number of vectors will be 2^bitwidth.')
# for Permutohedral grids
grid_group.add_argument('--coarsest-scale', type=float, default=1.0,
help='Coarsest grid scale')
grid_group.add_argument('--finest-scale', type=float, default=0.0001,
help='Finest grid scale')
grid_group.add_argument('--capacity-log-2', type=int, default=18,
help='Log2 capacity of grid')
grid_group.add_argument('--delta-capacity-log-2', type=int, default=18,
help='Log2 capacity of delta grid')
###################
# Embedder arguments
###################
embedder_group = parser.add_argument_group('embedder')
embedder_group.add_argument('--embedder-type', type=str, default='none',
choices=['none', 'positional', 'fourier'])
embedder_group.add_argument('--pos-multires', type=int, default=10,
help='log2 of max freq')
embedder_group.add_argument('--view-multires', type=int, default=4,
help='log2 of max freq')
###################
# Decoder arguments (and general global network things)
###################
net_group = parser.add_argument_group('net')
net_group.add_argument('--nef-type', type=str,
help='The neural field class to be used.')
net_group.add_argument('--layer-type', type=str, default='none',
choices=['none', 'spectral_norm', 'frobenius_norm', 'l_1_norm', 'l_inf_norm'])
net_group.add_argument('--activation-type', type=str, default='relu',
choices=['relu', 'sin'])
net_group.add_argument('--decoder-type', type=str, default='basic',
choices=['none', 'basic'])
net_group.add_argument('--num-layers', type=int, default=1,
help='Number of layers for the decoder')
net_group.add_argument('--hidden-dim', type=int, default=128,
help='Network width')
net_group.add_argument('--out-dim', type=int, default=1,
help='output dimension')
net_group.add_argument('--skip', type=int, default=None,
help='Layer to have skip connection.')
net_group.add_argument('--pretrained', type=str,
help='Path to pretrained model weights.')
net_group.add_argument('--position-input', action='store', const=True, default=False, nargs='?',
help='Use position as input.')
# Semantic NeRF parameters
net_group.add_argument('--num-classes', type=int, default=-1,
help='num of semantic classes')
net_group.add_argument('--num-instances', type=int, default=-1,
help='num of object instnces')
# if not specifiend, the following copy base net parameters
net_group.add_argument('--sem-activation-type', type=str, default=None,
choices=['relu', 'sin'])
net_group.add_argument('--sem-num-layers', type=int, default=None,
help='num of semantic layers')
net_group.add_argument('--sem-hidden-dim', type=int, default=None,
help='semantic hidden layer dimension')
net_group.add_argument('--sem-detach', action='store', const=True, default=True, nargs='?',
help='Detach encoder features before the semantic decoder.')
net_group.add_argument('--sem-sigmoid', action='store', const=True, default=False, nargs='?',
help='apply sigomid activation to semantic head.')
net_group.add_argument('--sem-softmax', action='store', const=True, default=False, nargs='?',
help='apply softmax to activation to semantic head.')
net_group.add_argument('--sem-normalize', action='store', const=True, default=False, nargs='?',
help='normalize output of semantic head.')
net_group.add_argument('--contrast-sem-weight', type=float, default=0.,
help='semanticn semi sup loss weight.')
net_group.add_argument('--sem-conf-enable', action='store', const=True, default=False, nargs='?',
help='Reweight semantic predictions with confidence.')
net_group.add_argument('--sem-temperature', type=float, default=1.,
help='semantic softmax temperature. 1 by default and has no effect.')
net_group.add_argument('--sem-epoch-start', type=int, default=0,
help='Epoch to start training semantic head')
net_group.add_argument('--sem-cascade', action='store', const=True, default=False, nargs='?',
help='Cascade panoptic decoders, first density then semantics')
net_group.add_argument('--panoptic-features-type', type=str, default=None,
choices=['position', 'pos_encoding', 'appearance', 'delta', 'separate'])
# Semi supervised parameters
net_group.add_argument('--inst-num-layers', type=int, default=None,
help='num of instance layers')
net_group.add_argument('--inst-hidden-dim', type=int, default=None,
help='instance hidden layer dimension')
net_group.add_argument('--inst-detach', action='store', const=True, default=True, nargs='?',
help='Detach encoder features before the instance decoder.')
net_group.add_argument('--inst-sigmoid', action='store', const=True, default=False, nargs='?',
help='apply sigomid activation to instance head.')
net_group.add_argument('--inst-softmax', action='store', const=True, default=False, nargs='?',
help='apply softmax activation to instance head.')
net_group.add_argument('--inst-direct-pos', action='store', const=True, default=False, nargs='?',
help='use coordinates directly as instance decoder input')
# for delta grid only
net_group.add_argument('--separate-sem-grid', action='store', const=True, default=False, nargs='?',
help='Do not fuse apperence and semantic grids in delta models')
net_group.add_argument('--no-delta-grid', action='store', const=True, default=False, nargs='?',
help='use only a color grid')
net_group.add_argument('--inst-conf-bootstrap-epoch-start', type=int, default=-1,
help='Epoch to start using the instance ID confidence to bootstrap training')
###################
# Arguments for dataset
###################
data_group = parser.add_argument_group('dataset')
data_group.add_argument('--dataset-type', type=str, default=None,
choices=['sdf', 'multiview'],
help='Dataset class to use')
data_group.add_argument('--dataset-path', type=str,
help='Path to the dataset')
data_group.add_argument('--dataset-num-workers', type=int, default=-1,
help='Number of workers for dataset preprocessing, if it supports multiprocessing. \
-1 indicates no multiprocessing.')
data_group.add_argument('--load-modes', nargs='+', default=[],
help='modes to be loaded from the dataset.[] or None implies load all modes.')
data_group.add_argument('--scale', type=list, default=None,
help='scale factor to fit the data to the unit cube')
data_group.add_argument('--offset', type=list, default=None,
help='Position offset in in the unit cube')
data_group.add_argument('--pose-src', type=str, default='odom',
choices=['odom', 'metashape'],
help='Dataset poses source')
data_group.add_argument('--dataset-mode', type=str, default='label_window',
choices=['label_window', 'all_frames_window'],
help='Dataset mode configuration. Load sequences around each labeled frame or create sequences to cover the whole dataset')
net_group.add_argument('--max-depth', type=float, default=-1.,
help='max depth for labels.')
data_group.add_argument('--class-labels', nargs='+', default=[],
help='classes to be loaded from the dataset. The order is used to enumerate the class IDs in the output predictions')
# SDF Dataset
data_group.add_argument('--sample-mode', type=str, nargs='*',
default=['rand', 'near', 'near', 'trace', 'trace'],
help='The sampling scheme to be used.')
data_group.add_argument('--get-normals', action='store', const=True, default=False, nargs='?',
help='Sample the normals.')
data_group.add_argument('--num-samples', type=int, default=100000,
help='Number of samples per mode (or per epoch for SPC)')
data_group.add_argument('--num-samples-on-mesh', type=int, default=100000000,
help='Number of samples generated on mesh surface to initialize occupancy structures')
data_group.add_argument('--sample-tex', action='store', const=True, default=False, nargs='?',
help='Sample textures')
data_group.add_argument('--mode-mesh-norm', type=str, default='sphere',
choices=['sphere', 'aabb', 'planar', 'none'],
help='Normalize the mesh')
data_group.add_argument('--samples-per-voxel', type=int, default=256,
help='Number of samples per voxel (for SDF initialization from grid)')
data_group.add_argument('--voxel-raymarch-epoch-start', type=int, default=-1,
help='change raymarching to voxel tracing after this epoch')
# Multiview Dataset
data_group.add_argument('--multiview-dataset-format', default='standard',
choices=['standard', 'rtmv'],
help='Data format for the transforms')
data_group.add_argument('--num-rays-sampled-per-img', type=int, default='4096',
help='Number of rays to sample per image')
data_group.add_argument('--bg-color', default='white',
choices=['white', 'black'],
help='Background color')
data_group.add_argument('--mip', type=int, default=None,
help='MIP level of ground truth image')
data_group.add_argument('--val-mip', type=int, default=None,
help='MIP level of ground truth image for validation')
data_group.add_argument('--model-rescaling', default='snap_to_bottom',
choices=['snap_to_bottom', 'scale_to_fit'],
help='Rescaling of model options to fit in the unit cube')
data_group.add_argument('--add-noise-to-train-poses', action='store', const=True, default=False, nargs='?',
help='add noise to train poses to test pose optimization')
data_group.add_argument('--pose-noise-strength', type=float, default=0.01,
help='spose noise multipier.')
# For sequence of real images with semantic labels on a specific frame
# This index corresponds to the labeled frame to run NeRF around
data_group.add_argument('--dataset-center-idx', type=int, default=0,
help='Semantinc labeled center image')
###################
# Arguments for optimizer
###################
optim_group = parser.add_argument_group('optimizer')
optim_group.add_argument('--optimizer-type', type=str, default='adam', choices=list(str2optim.keys()),
help='Optimizer to be used.')
optim_group.add_argument('--lr', type=float, default=0.001,
help='Learning rate.')
optim_group.add_argument('--extrinsics-lr', type=float, default=-1,
help='extrinsics Learning rate.')
optim_group.add_argument('--use-lr-scheduler', action='store', const=True, default=False, nargs='?',
help='Flag to enable lr scheduler.')
optim_group.add_argument('--lr-scheduler-type', type=str, default='step',
choices=['panoptic_step', 'step', 'one_cycle'],
help='Type of lr scheduler to use.')
optim_group.add_argument('--lr-step-size', type=int, default=0,
help='Step size for lr scheduler.')
optim_group.add_argument('--lr-step-gamma', type=float, default=0.1,
help='Gamma for lr scheduler.')
optim_group.add_argument('--weight-decay', type=float, default=0,
help='Weight decay.')
optim_group.add_argument('--grid-lr-weight', type=float, default=100.0,
help='Relative LR weighting for the grid')
optim_group.add_argument('--delta-grid-lr-weight', type=float, default=100.0,
help='Relative LR weighting for the delta grid')
optim_group.add_argument('--rgb-weight', type=float, default=1.0,
help='Weight of rgb loss')
optim_group.add_argument('--lr-warmup-epochs', type=int, default=1,
help='Number of learning rate warm up epochs.')
optim_group.add_argument('--lr-div-factor', type=float, default=1.0,
help='Learning rate final division factor')
optim_group.add_argument('--sem-weight', type=float, default=1.0,
help='Weight of semantic loss')
optim_group.add_argument('--inst-weight', type=float, default=0.01,
help='Semi-supervised loss weight.')
optim_group.add_argument('--inst-outlier-rejection', action='store', const=True, default=False, nargs='?',
help='Reject repeated ID outliers in instance segmentation.')
optim_group.add_argument('--grid-tvl1-reg', type=float, default=0.0,
help='Grid total vatiation L1 regulatization weight.')
optim_group.add_argument('--grid-tvl2-reg', type=float, default=0.0,
help='Grid total vatiation L2 regulatization weight.')
optim_group.add_argument('--delta-grid-tvl1-reg', type=float, default=0.0,
help='Delta grid total vatiation L1 regulatization weight.')
optim_group.add_argument('--delta-grid-tvl2-reg', type=float, default=0.0,
help='Delta grid total vatiation L2 regulatization weight.')
optim_group.add_argument('--tv-window-size', type=float, default=0.0,
help='Persentage of the hypervolume to aplly total vatiation to.')
optim_group.add_argument('--tv-edge-num-samples', type=float, default=0.0,
help='Number edge samples for total vatiation.')
optim_group.add_argument('--ray-sparcity-reg', type=float, default=0.0,
help='Ray density sparcity regularizarion weight.')
###################
# Arguments for training
###################
train_group = parser.add_argument_group('trainer')
train_group.add_argument('--epochs', type=int, default=250,
help='Number of epochs to run the training.')
train_group.add_argument('--batch-size', type=int, default=512,
help='Batch size for the training.')
train_group.add_argument('--resample', action='store', const=True, default=False, nargs='?',
help='Resample the dataset after every epoch.')
train_group.add_argument('--only-last', action='store', const=True, default=False, nargs='?',
help='Train only last LOD.')
train_group.add_argument('--resample-every', type=int, default=1,
help='Resample every N epochs')
train_group.add_argument('--model-format', type=str, default='full',
choices=['full', 'params_only', 'state_dict', 'params_only_ignore_missmatch'],
help='Format in which to save models.')
train_group.add_argument('--save-as-new', action='store', const=True, default=False, nargs='?',
help='Save the model at every epoch (no overwrite).')
train_group.add_argument('--save-every', type=int, default=5,
help='Save the model at every N epoch.')
train_group.add_argument('--render-every', type=int, default=5,
help='Render every N epochs')
train_group.add_argument('--render-val-labels', action='store', const=True, default=False, nargs='?',
help='Render semantic labels in validations stage')
train_group.add_argument('--save-grid', action='store', const=True, default=False, nargs='?',
help='Save 3D grids to visualize with kaolin dash3d or omniverse')
train_group.add_argument('--save-preds', action='store', const=True, default=False, nargs='?',
help='save all preds and confidence')
# TODO (ttakikawa): Only used for SDFs, but also should support RGB etc
train_group.add_argument('--log-2d', action='store', const=True, default=False, nargs='?',
help='Log cutting plane renders to TensorBoard.')
train_group.add_argument('--log-dir', type=str, default='_results/logs/runs/',
help='Log file directory for checkpoints.')
# TODO (ttakikawa): This is only really used in the SDF training but it should be useful for multiview too
train_group.add_argument('--grow-every', type=int, default=-1,
help='Grow network every X epochs')
train_group.add_argument('--prune-every', type=int, default=-1,
help='Prune every N epochs')
train_group.add_argument('--prune-at-epoch', type=int, default=-1,
help='Prune one time at a the specified epoch')
train_group.add_argument('--prune-at-start', action='store', const=True, default=False, nargs='?',
help='Prune once at the begining of training, useful for pretrained models.')
train_group.add_argument('--inst-num-dilations', type=int, default=-1,
help='num of post-processing erosion/dilation steps for instance segmentation')
train_group.add_argument('--low-res-val', action='store', const=True, default=False, nargs='?',
help='use val-mip even at the last validation stage')
# TODO (ttakikawa): Only used in multiview training, combine with the SDF growing schemes.
train_group.add_argument('--random-lod', action='store', const=True, default=False, nargs='?',
help='Use random lods to train.')
# One by one trains one level at a time.
# Increase starts from [0] and ends up at [0,...,N]
# Shrink strats from [0,...,N] and ends up at [N]
# Fine to coarse starts from [N] and ends up at [0,...,N]
# Only last starts and ends at [N]
train_group.add_argument('--growth-strategy', type=str, default='increase',
choices=['onebyone','increase','shrink', 'finetocoarse', 'onlylast'],
help='Strategy for coarse-to-fine training')
train_group.add_argument('--log-sub-losses', action='store', const=True, default=False, nargs='?',
help='If loss is composed, log all sub-losses as well.')
# Camera params
train_group.add_argument('--optimize-extrinsics', action='store', const=True, default=False, nargs='?',
help='Weather to optimize camera extrinsics from the dataset.')
train_group.add_argument('--extrinsics-epoch-start', type=int, default=0,
help='Epoch to start training clustering post-processing')
train_group.add_argument('--extrinsics-epoch-end', type=int, default=-1,
help='Epoch to end training clustering post-processing')
# Semi-Supervised params
train_group.add_argument('--clustering-epoch-start', type=int, default=0,
help='Epoch to start training clustering post-processing')
train_group.add_argument('--num-clustering-samples', type=int, default=0,
help='Number of render samples to use for clustering')
train_group.add_argument('--num-clustering-workers', type=int, default=1,
help='Number of jobs to run clustering')
train_group.add_argument('--lod-anneling', action='store', const=True, default=False, nargs='?',
help='Enable lod grid feature anneling.')
train_group.add_argument('--lod-annel-epochs', type=int, default=0,
help='Epoch to run anneling on lod grid features')
train_group.add_argument('--lod-annel-epoch-start', type=int, default=0,
help='Epoch to start anneling lod grid features')
train_group.add_argument('--inst-epoch-start', type=int, default=0,
help='Epoch to start training instance head')
train_group.add_argument('--inst-loss', type=str, default='sup_contrastive',
choices=['sup_contrastive'],
help='Semi-supervised loss type. this loss is disabled if not specified')
train_group.add_argument('--inst-dist-func', type=str, default='cos',
choices=['l1', 'l2', 'cos'],
help='Semi-supervised distnace function')
train_group.add_argument('--inst-conf-enable', action='store', const=True, default=False, nargs='?',
help='reweight inst loss with prediction confidence')
train_group.add_argument('--inst-normalize', action='store', const=True, default=False, nargs='?',
help='Semi-supervised feature pre-normalization.')
train_group.add_argument('--weight-class-inbalance', action='store', const=True, default=False, nargs='?',
help='Weather to compute a class-wise weight based on apearance in the data.')
# Sup-Contrastive loss
train_group.add_argument('--inst-temperature', type=float, default=0.07,
help='inst softmax temperature.')
train_group.add_argument('--inst-soft-temperature', type=float, default=0.0,
help='inst softmax temperature before integration.')
train_group.add_argument('--base-temperature', type=float, default=0.07,
help='softmax base temperature. final is computed: l = -(T/base_T) * rms_loss')
train_group.add_argument('--inst-pn-ratio', type=float, default=0.5,
help='Ratio between positive and negative examples for supervised contrastive learning')
train_group.add_argument('--sem-segment-reg-weight', type=float, default=0.0,
help='Weight of semantic segment consistency regularization')
train_group.add_argument('--inst-segment-reg-weight', type=float, default=0.0,
help='Weight of instance segment consistency regularization')
train_group.add_argument('--inst-segment-reg-epoch-start', type=float, default=-1,
help='Weight of instance segment consistency regularization')
train_group.add_argument('--optimize-val-extrinsics', action='store', const=True, default=False, nargs='?',
help='Optimize val extrinsics flag.')
train_group.add_argument('--val-extrinsics-start', type=int, default=0,
help='Val extrinsics start epoch')
train_group.add_argument('--val-extrinsics-every', type=int, default=0,
help='Optimize validation extrinsics every n epochs')
train_group.add_argument('--val-extrinsics-end', type=int, default=-1,
help='Val extrinsics end epoch')
###################
# Arguments for training
###################
valid_group = parser.add_argument_group('validation')
valid_group.add_argument('--valid-only', action='store', const=True, default=False, nargs='?',
help='Run validation only (and do not run training).')
valid_group.add_argument('--valid-every', type=int, default=-1,
help='Frequency of running validation.')
valid_group.add_argument('--valid-split', type=str, default='val',
help='Split to use for validation.')
###################
# Arguments for renderer
###################
renderer_group = parser.add_argument_group('renderer')
renderer_group.add_argument('--render-res', type=int, nargs=2, default=[512, 512],
help='Width/height to render at.')
renderer_group.add_argument('--render-batch', type=int, default=0,
help='Batch size (in number of rays) for batched rendering.')
renderer_group.add_argument('--camera-origin', type=float, nargs=3, default=[-2.8, 2.8, -2.8],
help='Camera origin.')
renderer_group.add_argument('--camera-lookat', type=float, nargs=3, default=[0, 0, 0],
help='Camera look-at/target point.')
renderer_group.add_argument('--camera-fov', type=float, default=30,
help='Camera field of view (FOV).')
renderer_group.add_argument('--camera-proj', type=str, choices=['ortho', 'persp'], default='persp',
help='Camera projection.')
renderer_group.add_argument('--camera-clamp', nargs=2, type=float, default=[0, 10],
help='Camera clipping bounds.')
renderer_group.add_argument('--tracer-type', type=str, default='PackedRFTracer',
help='The tracer to be used.')
renderer_group.add_argument('--num-val-frames-to-save', type=int, default=0,
help='number of validation frames to save')
# TODO(ttakikawa): In the future the interface will be such that you either select an absolute step size or
# you select the number of steps to take. Sphere tracing will take step-scales.
renderer_group.add_argument('--num-steps', type=int, default=128,
help='Number of steps for raymarching / spheretracing / etc')
renderer_group.add_argument('--step-size', type=float, default=1.0,
help='Scale of step size')
renderer_group.add_argument('--ray-max-travel', type=float, default=6.0,
help='ray travel distance in meters after hitting the grid')
# used only in voxel raymarching to increase resolution at the
# surface of the model
# Sphere tracing stuff
renderer_group.add_argument('--min-dis', type=float, default=0.0003,
help='Minimum distance away from surface for spheretracing')
# TODO(ttakikawa): Shader stuff... will be more modular in future
renderer_group.add_argument('--matcap-path', type=str,
default='data/matcaps/matcap_plastic_yellow.jpg',
help='Path to the matcap texture to render with.')
renderer_group.add_argument('--ao', action='store', const=True, default=False, nargs='?',
help='Use ambient occlusion.')
renderer_group.add_argument('--shadow', action='store', const=True, default=False, nargs='?',
help='Use shadowing.')
renderer_group.add_argument('--shading-mode', type=str, default='normal',
choices=['matcap', 'rb', 'normal'],
help='Shading mode.')
# Parse and run
if return_parser:
return parser
else:
return argparse_to_str(parser)
def parse_yaml_config(config_path, parser):
"""Parses and sets the parser defaults with a yaml config file.
Args:
config_path : path to the yaml config file.
parser : The parser for which the defaults will be set.
parent : True if parsing the parent yaml. Should never be set to True by the user.
"""
with open(config_path) as f:
config_dict = yaml.safe_load(f)
list_of_valid_fields = []
for group in parser._action_groups:
group_dict = {list_of_valid_fields.append(a.dest) for a in group._group_actions}
list_of_valid_fields = set(list_of_valid_fields)
defaults_dict = {}
# Load the parent config if it exists
parent_config_path = config_dict.pop("parent", None)
if parent_config_path is not None:
if not os.path.isabs(parent_config_path):
parent_config_path = os.path.join(os.path.split(config_path)[0], parent_config_path)
with open(parent_config_path) as f:
parent_config_dict = yaml.safe_load(f)
if "parent" in parent_config_dict.keys():
raise Exception("Hierarchical configs of more than 1 level deep are not allowed.")
for key in parent_config_dict:
for field in parent_config_dict[key]:
if field not in list_of_valid_fields:
raise ValueError(
f"ERROR: {field} is not a valid option. Check for typos in the config."
)
defaults_dict[field] = parent_config_dict[key][field]
# Loads child parent and overwrite the parent configs
# The yaml files assumes the argument groups, which aren't actually nested.
for key in config_dict:
for field in config_dict[key]:
if field not in list_of_valid_fields:
raise ValueError(
f"ERROR: {field} is not a valid option. Check for typos in the config."
)
defaults_dict[field] = config_dict[key][field]
parser.set_defaults(**defaults_dict)
def parse_config_dict(config_dict, parser):
"""Parses and sets the parser defaults with a yaml config file.
Args:
config_path : path to the yaml config file.
parser : The parser for which the defaults will be set.
parent : True if parsing the parent yaml. Should never be set to True by the user.
"""
list_of_valid_fields = []
for group in parser._action_groups:
group_dict = {list_of_valid_fields.append(a.dest) for a in group._group_actions}
list_of_valid_fields = set(list_of_valid_fields)
defaults_dict = {}
# Loads child parent and overwrite the parent configs
# The yaml files assumes the argument groups, which aren't actually nested.
for key in config_dict:
for field in config_dict[key]:
if field not in list_of_valid_fields:
raise ValueError(
f"ERROR: {field} is not a valid option. Check for typos in the config."
)
defaults_dict[field] = config_dict[key][field]
parser.set_defaults(**defaults_dict)
def argparse_to_str(parser, args=None, config_dict=None):
"""Convert parser to string representation for Tensorboard logging.
Args:
parser (argparse.parser): Parser object. Needed for the argument groups.
args : The parsed arguments. Will compute from the parser if None.
Returns:
args : The parsed arguments.
arg_str : The string to be printed.
"""
if args is None:
args = parser.parse_args()
if config_dict is not None:
parse_config_dict(config_dict, parser)
elif args.config is not None:
parse_yaml_config(args.config, parser)
args = parser.parse_args()
args_dict = {}
for group in parser._action_groups:
group_dict = {a.dest: getattr(args, a.dest, None) for a in group._group_actions}
args_dict[group.title] = vars(argparse.Namespace(**group_dict))
pp = pprint.PrettyPrinter(indent=2)
args_str = pp.pformat(args_dict)
args_str = f'```{args_str}```'
return args, args_str
def get_trainer(args):
return globals()[args.trainer_type]
def get_optimizer_from_config(args):
"""Utility function to get the optimizer from the parsed config.
"""
optim_cls = str2optim[args.optimizer_type]
if args.optimizer_type == 'adam':
optim_params = {'eps': 1e-15}
elif args.optimizer_type == 'sgd':
optim_params = {'momentum': 0.8}
else:
optim_params = {}
return optim_cls, optim_params
def get_modules_from_config(args):
"""Utility function to get the modules for training from the parsed config.
"""
val_dataset = None
if args.dataset_type == "multiview":
log.info('Loading training dataset...')
transform = SampleRays(args.num_rays_sampled_per_img)
train_dataset = MultiviewDataset(**vars(args), transform=transform)
train_dataset.init()
args.ray_max_travel = args.ray_max_travel * train_dataset.scale
if args.optimize_val_extrinsics:
log.info('Loading validation split for pose optimization only...')
val_dataset = MultiviewDataset(**vars(args), split='val', transform=transform)
val_dataset.init()
if 'semantic_info' in vars(train_dataset) and train_dataset.semantic_info is not None:
args.num_classes = train_dataset.semantic_info['num_classes']
args.num_instances = train_dataset.semantic_info['num_instances']
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
nef = globals()[args.nef_type](**vars(args))
tracer = globals()[args.tracer_type](**vars(args))
# Use a Bundle Adjustment pipeline if extriniscs need to be optimized
if args.optimize_extrinsics:
cameras = train_dataset.data['cameras']
# add validation cameras if val extrinsics need to be optimized
if args.optimize_val_extrinsics:
cameras.update(val_dataset.data['cameras'])
pipeline = BAPipeline(nef, cameras, tracer)
else:
pipeline = Pipeline(nef, tracer)
if args.dataset_type == "multiview":
if pipeline.nef.grid is not None:
if isinstance(pipeline.nef.grid, OctreeGrid):
if not args.valid_only and not pipeline.nef.grid.blas_initialized():
if args.multiview_dataset_format in ['rtmv']:
pipeline.nef.grid.init_from_pointcloud(train_dataset.coords)
else:
pipeline.nef.grid.init_dense() | elif isinstance(pipeline.nef.grid, PermutoGrid): | 1 | 2023-10-30 16:14:39+00:00 | 8k |
BIT-DA/Annotator | annotator/data/dataset/semantickitti/semantickitti.py | [
{
"identifier": "LEARNING_MAP_19",
"path": "annotator/data/dataset/semantickitti/semantickitti_utils.py",
"snippet": "LEARNING_MAP_19 = {\n 0: 0, # \"unlabeled\"\n 1: 0, # \"outlier\" mapped to \"unlabeled\" --------------------------mapped\n 10: 1, # \"car\"\n 11: 2, # \"bicycle\"\n ... | import os
import numpy as np
import torch
import random
from torch.utils import data
from .semantickitti_utils import LEARNING_MAP_19, LEARNING_MAP_12, LEARNING_MAP_7, LEARNING_MAP_11 | 3,964 | ABSOLUTE_PATH = os.path.dirname(os.path.abspath(__file__))
def absoluteFilePaths(directory):
for dirpath, _, filenames in os.walk(directory):
for f in filenames:
yield os.path.abspath(os.path.join(dirpath, f))
class SemantickittiDataset(data.Dataset):
def __init__(
self,
data_cfgs=None,
training: bool = True,
class_names: list = None,
root_path: str = None,
logger=None,
if_scribble: bool = False,
):
super().__init__()
self.data_cfgs = data_cfgs
self.root_path = root_path
self.training = training
self.logger = logger
self.class_names = class_names
self.tta = data_cfgs.get('TTA', False)
self.train_val = data_cfgs.get('TRAINVAL', False)
self.augment = data_cfgs.AUGMENT
self.if_scribble = if_scribble
self.num_classes = data_cfgs.NUM_CLASSES
if self.training and not self.train_val:
self.split = 'train'
else:
if self.training and self.train_val:
self.split = 'train_val'
else:
self.split = 'val'
if self.tta:
self.split = 'test'
if self.split == 'train':
self.seqs = ['00', '01', '02', '03', '04', '05', '06', '07', '09', '10']
elif self.split == 'val':
self.seqs = ['08']
elif self.split == 'train_val':
self.seqs = ['00', '01', '02', '03', '04', '05', '06', '07', '09', '10', '08']
elif self.split == 'test':
self.seqs = ['11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21']
else:
raise Exception('split must be train/val/train_val/test.')
self.annos = []
for seq in self.seqs:
self.annos += absoluteFilePaths('/'.join([self.root_path, str(seq).zfill(2), 'velodyne']))
self.annos.sort()
self.annos_another = self.annos.copy()
random.shuffle(self.annos_another)
print(f'The total sample is {len(self.annos)}')
self._sample_idx = np.arange(len(self.annos))
self.samples_per_epoch = self.data_cfgs.get('SAMPLES_PER_EPOCH', -1)
if self.samples_per_epoch == -1 or not self.training:
self.samples_per_epoch = len(self.annos)
if self.training:
self.resample()
else:
self.sample_idx = self._sample_idx
# init_path = os.path.join(ABSOLUTE_PATH, 'semantickitti_init.pkl')
self.scan_size = {}
# if not os.path.isfile(init_path):
for path in self.annos:
self.scan_size[path] = np.fromfile(path, dtype=np.float32).reshape((-1, 4)).shape[0]
# torch.save(self.scan_size, init_path)
# else:
# self.scan_size = torch.load(init_path)
def __len__(self):
return len(self.sample_idx)
def resample(self):
self.sample_idx = np.random.choice(self._sample_idx, self.samples_per_epoch)
def get_kitti_points_ringID(self, points):
scan_x = points[:, 0]
scan_y = points[:, 1]
yaw = -np.arctan2(scan_y, -scan_x)
proj_x = 0.5 * (yaw / np.pi + 1.0)
new_raw = np.nonzero((proj_x[1:] < 0.2) * (proj_x[:-1] > 0.8))[0] + 1
proj_y = np.zeros_like(proj_x)
proj_y[new_raw] = 1
ringID = np.cumsum(proj_y)
ringID = np.clip(ringID, 0, 63)
return ringID
def __getitem__(self, index):
raw_data = np.fromfile(self.annos[index], dtype=np.float32).reshape((-1, 4))
if self.split == 'test':
annotated_data = np.expand_dims(np.zeros_like(raw_data[:, 0], dtype=int), axis=1)
else:
if self.if_scribble: # ScribbleKITTI (weak label)
annos = self.annos[index].replace('SemanticKITTI', 'ScribbleKITTI')
annotated_data = np.fromfile(
annos.replace('velodyne', 'scribbles')[:-3] + 'label', dtype=np.uint32
).reshape((-1, 1))
else: # SemanticKITTI (full label)
annotated_data = np.fromfile(
self.annos[index].replace('velodyne', 'labels')[:-3] + 'label', dtype=np.uint32
).reshape((-1, 1))
annotated_data = annotated_data & 0xFFFF
if self.num_classes == 19:
annotated_data = np.vectorize(LEARNING_MAP_19.__getitem__)(annotated_data)
elif self.num_classes == 12:
annotated_data = np.vectorize(LEARNING_MAP_12.__getitem__)(annotated_data)
elif self.num_classes == 7:
|
# used for polarmix
instance_classes = [0, 1, 2, 3, 4, 5, 6, 7]
Omega = [np.random.random() * np.pi * 2 / 3, (np.random.random() + 1) * np.pi * 2 / 3]
ABSOLUTE_PATH = os.path.dirname(os.path.abspath(__file__))
def absoluteFilePaths(directory):
for dirpath, _, filenames in os.walk(directory):
for f in filenames:
yield os.path.abspath(os.path.join(dirpath, f))
class SemantickittiDataset(data.Dataset):
def __init__(
self,
data_cfgs=None,
training: bool = True,
class_names: list = None,
root_path: str = None,
logger=None,
if_scribble: bool = False,
):
super().__init__()
self.data_cfgs = data_cfgs
self.root_path = root_path
self.training = training
self.logger = logger
self.class_names = class_names
self.tta = data_cfgs.get('TTA', False)
self.train_val = data_cfgs.get('TRAINVAL', False)
self.augment = data_cfgs.AUGMENT
self.if_scribble = if_scribble
self.num_classes = data_cfgs.NUM_CLASSES
if self.training and not self.train_val:
self.split = 'train'
else:
if self.training and self.train_val:
self.split = 'train_val'
else:
self.split = 'val'
if self.tta:
self.split = 'test'
if self.split == 'train':
self.seqs = ['00', '01', '02', '03', '04', '05', '06', '07', '09', '10']
elif self.split == 'val':
self.seqs = ['08']
elif self.split == 'train_val':
self.seqs = ['00', '01', '02', '03', '04', '05', '06', '07', '09', '10', '08']
elif self.split == 'test':
self.seqs = ['11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21']
else:
raise Exception('split must be train/val/train_val/test.')
self.annos = []
for seq in self.seqs:
self.annos += absoluteFilePaths('/'.join([self.root_path, str(seq).zfill(2), 'velodyne']))
self.annos.sort()
self.annos_another = self.annos.copy()
random.shuffle(self.annos_another)
print(f'The total sample is {len(self.annos)}')
self._sample_idx = np.arange(len(self.annos))
self.samples_per_epoch = self.data_cfgs.get('SAMPLES_PER_EPOCH', -1)
if self.samples_per_epoch == -1 or not self.training:
self.samples_per_epoch = len(self.annos)
if self.training:
self.resample()
else:
self.sample_idx = self._sample_idx
# init_path = os.path.join(ABSOLUTE_PATH, 'semantickitti_init.pkl')
self.scan_size = {}
# if not os.path.isfile(init_path):
for path in self.annos:
self.scan_size[path] = np.fromfile(path, dtype=np.float32).reshape((-1, 4)).shape[0]
# torch.save(self.scan_size, init_path)
# else:
# self.scan_size = torch.load(init_path)
def __len__(self):
return len(self.sample_idx)
def resample(self):
self.sample_idx = np.random.choice(self._sample_idx, self.samples_per_epoch)
def get_kitti_points_ringID(self, points):
scan_x = points[:, 0]
scan_y = points[:, 1]
yaw = -np.arctan2(scan_y, -scan_x)
proj_x = 0.5 * (yaw / np.pi + 1.0)
new_raw = np.nonzero((proj_x[1:] < 0.2) * (proj_x[:-1] > 0.8))[0] + 1
proj_y = np.zeros_like(proj_x)
proj_y[new_raw] = 1
ringID = np.cumsum(proj_y)
ringID = np.clip(ringID, 0, 63)
return ringID
def __getitem__(self, index):
raw_data = np.fromfile(self.annos[index], dtype=np.float32).reshape((-1, 4))
if self.split == 'test':
annotated_data = np.expand_dims(np.zeros_like(raw_data[:, 0], dtype=int), axis=1)
else:
if self.if_scribble: # ScribbleKITTI (weak label)
annos = self.annos[index].replace('SemanticKITTI', 'ScribbleKITTI')
annotated_data = np.fromfile(
annos.replace('velodyne', 'scribbles')[:-3] + 'label', dtype=np.uint32
).reshape((-1, 1))
else: # SemanticKITTI (full label)
annotated_data = np.fromfile(
self.annos[index].replace('velodyne', 'labels')[:-3] + 'label', dtype=np.uint32
).reshape((-1, 1))
annotated_data = annotated_data & 0xFFFF
if self.num_classes == 19:
annotated_data = np.vectorize(LEARNING_MAP_19.__getitem__)(annotated_data)
elif self.num_classes == 12:
annotated_data = np.vectorize(LEARNING_MAP_12.__getitem__)(annotated_data)
elif self.num_classes == 7: | annotated_data = np.vectorize(LEARNING_MAP_7.__getitem__)(annotated_data) | 2 | 2023-10-31 08:11:57+00:00 | 8k |
thoddnn/open-datagen | opendatagen/data_generator.py | [
{
"identifier": "dict_to_string",
"path": "opendatagen/utils.py",
"snippet": "def dict_to_string(d):\n result = []\n for key, value in d.items():\n result.append(f'#{key}#:\\n\"\"\"')\n result.append(f'{value}')\n result.append('\"\"\"')\n return '\\n'.join(result)"
},
... | from dotenv import load_dotenv
from urllib.parse import quote
from re import findall
from typing import Dict, List, Union
from opendatagen.utils import dict_to_string, load_file, write_to_csv, generate_context_from_json, extract_website_details, create_type_message, find_strings_in_brackets
from opendatagen.utils import snake_case_to_title_case, title_case_to_snake_case
from opendatagen.utils import extract_content_from_internet, clean_string
from opendatagen.anonymizer import Anonymizer
from opendatagen.model import OpenAIChatModel, OpenAIInstructModel, OpenAIEmbeddingModel, ModelName, MistralChatModel, LlamaCPPModel
from opendatagen.template import Template, Variable, Variations, create_variable_from_name
from opendatagen.utils import function_to_call
from mistralai.client import MistralClient
from mistralai.models.chat_completion import ChatMessage
import numpy as np
import time
import random
import re
import json
import requests
import uuid | 5,946 |
load_dotenv()
class DataGenerator:
output_array = []
def __init__(self, template:Template):
self.template = template
def extract_variable_from_string(self, text:str):
return findall(r'\{(.*?)\}', text)
def extract_variable_dict_from_string(self, text:str):
list_of_variables = findall(r'\{(.*?)\}', text)
result = {}
for variable_id, variable in self.template.variables.items():
if variable_id in list_of_variables:
result[variable_id] = variable
return result
def anonymize_text(self, text_to_anonymize):
# Example usage:
anonymizer = Anonymizer()
anonymized_text = anonymizer.anonymize(text_to_anonymize)
return anonymized_text
def contextual_generation(self, prompt_text:str, variables:list, current_variation_dict:dict, fixed_variables: Dict[str, Variable], completion:str=None, parent_id:str=None):
# This will be the list to collect all dictionaries
result = []
if not variables:
# No more variables to process, generate final variation
return [current_variation_dict.copy()]
# Get the next variable
next_var = variables[0]
remaining_variables = variables[1:]
if completion:
formatted_template = completion.format(**{var: current_variation_dict.get(var, f'{{{var}}}').value if hasattr(current_variation_dict.get(var, f'{{{var}}}'), 'value') else current_variation_dict.get(var, f'{{{var}}}') for var in re.findall(r'\{(.*?)\}', completion)})
current_completion = formatted_template.split(f'{{{next_var}}}')[0] + f'{{{next_var}}}'
current_prompt = prompt_text
else:
formatted_template = prompt_text.format(**{var: current_variation_dict.get(var, f'{{{var}}}').value if hasattr(current_variation_dict.get(var, f'{{{var}}}'), 'value') else current_variation_dict.get(var, f'{{{var}}}') for var in re.findall(r'\{(.*?)\}', prompt_text)})
current_prompt = formatted_template.split(f'{{{next_var}}}')[0] + f'{{{next_var}}}'
current_completion = None
variable = fixed_variables[next_var]
variations = self.generate_variable(prompt_text=current_prompt,
completion_text=current_completion,
current_variable=variable,
variable_id_string=next_var,
parent_id=parent_id)
for id, variation in variations.items():
# Update the current variations dictionary with the new variation
updated_variation_dict = current_variation_dict.copy()
updated_variation_dict[next_var] = variation
# Recursively process the remaining variables
# and extend the all_variation_dicts list with the results
result.extend(self.contextual_generation(
prompt_text=prompt_text,
completion=completion,
variables=remaining_variables,
current_variation_dict=updated_variation_dict,
fixed_variables=fixed_variables,
parent_id=id
))
# Return the list of all variation dictionaries generated
return result
def generate_variable(self, prompt_text:str, current_variable:Variable, variable_id_string:str, completion_text:str=None, parent_id:str=None):
generation_number = current_variable.generation_number
variations = {}
if current_variable.get_value_from_localfile:
for _ in range(generation_number):
generated_value = current_variable.get_value_from_localfile.get_content_from_file()
if parent_id:
new_id = str(uuid.uuid4())
|
load_dotenv()
class DataGenerator:
output_array = []
def __init__(self, template:Template):
self.template = template
def extract_variable_from_string(self, text:str):
return findall(r'\{(.*?)\}', text)
def extract_variable_dict_from_string(self, text:str):
list_of_variables = findall(r'\{(.*?)\}', text)
result = {}
for variable_id, variable in self.template.variables.items():
if variable_id in list_of_variables:
result[variable_id] = variable
return result
def anonymize_text(self, text_to_anonymize):
# Example usage:
anonymizer = Anonymizer()
anonymized_text = anonymizer.anonymize(text_to_anonymize)
return anonymized_text
def contextual_generation(self, prompt_text:str, variables:list, current_variation_dict:dict, fixed_variables: Dict[str, Variable], completion:str=None, parent_id:str=None):
# This will be the list to collect all dictionaries
result = []
if not variables:
# No more variables to process, generate final variation
return [current_variation_dict.copy()]
# Get the next variable
next_var = variables[0]
remaining_variables = variables[1:]
if completion:
formatted_template = completion.format(**{var: current_variation_dict.get(var, f'{{{var}}}').value if hasattr(current_variation_dict.get(var, f'{{{var}}}'), 'value') else current_variation_dict.get(var, f'{{{var}}}') for var in re.findall(r'\{(.*?)\}', completion)})
current_completion = formatted_template.split(f'{{{next_var}}}')[0] + f'{{{next_var}}}'
current_prompt = prompt_text
else:
formatted_template = prompt_text.format(**{var: current_variation_dict.get(var, f'{{{var}}}').value if hasattr(current_variation_dict.get(var, f'{{{var}}}'), 'value') else current_variation_dict.get(var, f'{{{var}}}') for var in re.findall(r'\{(.*?)\}', prompt_text)})
current_prompt = formatted_template.split(f'{{{next_var}}}')[0] + f'{{{next_var}}}'
current_completion = None
variable = fixed_variables[next_var]
variations = self.generate_variable(prompt_text=current_prompt,
completion_text=current_completion,
current_variable=variable,
variable_id_string=next_var,
parent_id=parent_id)
for id, variation in variations.items():
# Update the current variations dictionary with the new variation
updated_variation_dict = current_variation_dict.copy()
updated_variation_dict[next_var] = variation
# Recursively process the remaining variables
# and extend the all_variation_dicts list with the results
result.extend(self.contextual_generation(
prompt_text=prompt_text,
completion=completion,
variables=remaining_variables,
current_variation_dict=updated_variation_dict,
fixed_variables=fixed_variables,
parent_id=id
))
# Return the list of all variation dictionaries generated
return result
def generate_variable(self, prompt_text:str, current_variable:Variable, variable_id_string:str, completion_text:str=None, parent_id:str=None):
generation_number = current_variable.generation_number
variations = {}
if current_variable.get_value_from_localfile:
for _ in range(generation_number):
generated_value = current_variable.get_value_from_localfile.get_content_from_file()
if parent_id:
new_id = str(uuid.uuid4())
| new_value = Variations(id=new_id, parent_id=parent_id, value=generated_value) | 20 | 2023-10-27 17:38:37+00:00 | 8k |
zhanggang001/HEDNet | pcdet/datasets/waymo/waymo_dataset.py | [
{
"identifier": "roiaware_pool3d_utils",
"path": "pcdet/ops/roiaware_pool3d/roiaware_pool3d_utils.py",
"snippet": "def points_in_boxes_cpu(points, boxes):\ndef points_in_boxes_gpu(points, boxes):\n def __init__(self, out_size, max_pts_each_voxel=128):\n def forward(self, rois, pts, pts_feature, po... | import os
import pickle
import copy
import numpy as np
import torch
import multiprocessing
import SharedArray
import torch.distributed as dist
import argparse
import yaml
from tqdm import tqdm
from pathlib import Path
from functools import partial
from ...ops.roiaware_pool3d import roiaware_pool3d_utils
from ...utils import box_utils, common_utils
from ..dataset import DatasetTemplate
from . import waymo_utils
from ..kitti.kitti_object_eval_python import eval as kitti_eval
from ..kitti import kitti_utils
from .waymo_eval import OpenPCDetWaymoDetectionMetricsEstimator
from easydict import EasyDict | 5,305 | # OpenPCDet PyTorch Dataloader and Evaluation Tools for Waymo Open Dataset
# Reference https://github.com/open-mmlab/OpenPCDet
# Written by Shaoshuai Shi, Chaoxu Guo
# All Rights Reserved.
class WaymoDataset(DatasetTemplate):
def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None):
super().__init__(
dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger
)
self.data_path = self.root_path / self.dataset_cfg.PROCESSED_DATA_TAG
self.split = self.dataset_cfg.DATA_SPLIT[self.mode]
split_dir = self.root_path / 'ImageSets' / (self.split + '.txt')
self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()]
self.infos = []
self.seq_name_to_infos = self.include_waymo_data(self.mode)
self.use_shared_memory = self.dataset_cfg.get('USE_SHARED_MEMORY', False) and self.training
if self.use_shared_memory:
self.shared_memory_file_limit = self.dataset_cfg.get('SHARED_MEMORY_FILE_LIMIT', 0x7FFFFFFF)
self.load_data_to_shared_memory()
if self.dataset_cfg.get('USE_PREDBOX', False):
self.pred_boxes_dict = self.load_pred_boxes_to_dict(
pred_boxes_path=self.dataset_cfg.ROI_BOXES_PATH[self.mode]
)
else:
self.pred_boxes_dict = {}
def set_split(self, split):
super().__init__(
dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training,
root_path=self.root_path, logger=self.logger
)
self.split = split
split_dir = self.root_path / 'ImageSets' / (self.split + '.txt')
self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()]
self.infos = []
self.seq_name_to_infos = self.include_waymo_data(self.mode)
def include_waymo_data(self, mode):
self.logger.info('Loading Waymo dataset')
waymo_infos = []
seq_name_to_infos = {}
num_skipped_infos = 0
for k in range(len(self.sample_sequence_list)):
sequence_name = os.path.splitext(self.sample_sequence_list[k])[0]
info_path = self.data_path / sequence_name / ('%s.pkl' % sequence_name)
info_path = self.check_sequence_name_with_all_version(info_path)
if not info_path.exists():
num_skipped_infos += 1
continue
with open(info_path, 'rb') as f:
infos = pickle.load(f)
waymo_infos.extend(infos)
seq_name_to_infos[infos[0]['point_cloud']['lidar_sequence']] = infos
self.infos.extend(waymo_infos[:])
self.logger.info('Total skipped info %s' % num_skipped_infos)
self.logger.info('Total samples for Waymo dataset: %d' % (len(waymo_infos)))
if self.dataset_cfg.SAMPLED_INTERVAL[mode] > 1:
sampled_waymo_infos = []
for k in range(0, len(self.infos), self.dataset_cfg.SAMPLED_INTERVAL[mode]):
sampled_waymo_infos.append(self.infos[k])
self.infos = sampled_waymo_infos
self.logger.info('Total sampled samples for Waymo dataset: %d' % len(self.infos))
use_sequence_data = self.dataset_cfg.get('SEQUENCE_CONFIG', None) is not None and self.dataset_cfg.SEQUENCE_CONFIG.ENABLED
if not use_sequence_data:
seq_name_to_infos = None
return seq_name_to_infos
def load_pred_boxes_to_dict(self, pred_boxes_path):
self.logger.info(f'Loading and reorganizing pred_boxes to dict from path: {pred_boxes_path}')
with open(pred_boxes_path, 'rb') as f:
pred_dicts = pickle.load(f)
pred_boxes_dict = {}
for index, box_dict in enumerate(pred_dicts):
seq_name = box_dict['frame_id'][:-4].replace('training_', '').replace('validation_', '')
sample_idx = int(box_dict['frame_id'][-3:])
if seq_name not in pred_boxes_dict:
pred_boxes_dict[seq_name] = {}
pred_labels = np.array([self.class_names.index(box_dict['name'][k]) + 1 for k in range(box_dict['name'].shape[0])])
pred_boxes = np.concatenate((box_dict['boxes_lidar'], box_dict['score'][:, np.newaxis], pred_labels[:, np.newaxis]), axis=-1)
pred_boxes_dict[seq_name][sample_idx] = pred_boxes
self.logger.info(f'Predicted boxes has been loaded, total sequences: {len(pred_boxes_dict)}')
return pred_boxes_dict
def load_data_to_shared_memory(self):
self.logger.info(f'Loading training data to shared memory (file limit={self.shared_memory_file_limit})')
| # OpenPCDet PyTorch Dataloader and Evaluation Tools for Waymo Open Dataset
# Reference https://github.com/open-mmlab/OpenPCDet
# Written by Shaoshuai Shi, Chaoxu Guo
# All Rights Reserved.
class WaymoDataset(DatasetTemplate):
def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None):
super().__init__(
dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger
)
self.data_path = self.root_path / self.dataset_cfg.PROCESSED_DATA_TAG
self.split = self.dataset_cfg.DATA_SPLIT[self.mode]
split_dir = self.root_path / 'ImageSets' / (self.split + '.txt')
self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()]
self.infos = []
self.seq_name_to_infos = self.include_waymo_data(self.mode)
self.use_shared_memory = self.dataset_cfg.get('USE_SHARED_MEMORY', False) and self.training
if self.use_shared_memory:
self.shared_memory_file_limit = self.dataset_cfg.get('SHARED_MEMORY_FILE_LIMIT', 0x7FFFFFFF)
self.load_data_to_shared_memory()
if self.dataset_cfg.get('USE_PREDBOX', False):
self.pred_boxes_dict = self.load_pred_boxes_to_dict(
pred_boxes_path=self.dataset_cfg.ROI_BOXES_PATH[self.mode]
)
else:
self.pred_boxes_dict = {}
def set_split(self, split):
super().__init__(
dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training,
root_path=self.root_path, logger=self.logger
)
self.split = split
split_dir = self.root_path / 'ImageSets' / (self.split + '.txt')
self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()]
self.infos = []
self.seq_name_to_infos = self.include_waymo_data(self.mode)
def include_waymo_data(self, mode):
self.logger.info('Loading Waymo dataset')
waymo_infos = []
seq_name_to_infos = {}
num_skipped_infos = 0
for k in range(len(self.sample_sequence_list)):
sequence_name = os.path.splitext(self.sample_sequence_list[k])[0]
info_path = self.data_path / sequence_name / ('%s.pkl' % sequence_name)
info_path = self.check_sequence_name_with_all_version(info_path)
if not info_path.exists():
num_skipped_infos += 1
continue
with open(info_path, 'rb') as f:
infos = pickle.load(f)
waymo_infos.extend(infos)
seq_name_to_infos[infos[0]['point_cloud']['lidar_sequence']] = infos
self.infos.extend(waymo_infos[:])
self.logger.info('Total skipped info %s' % num_skipped_infos)
self.logger.info('Total samples for Waymo dataset: %d' % (len(waymo_infos)))
if self.dataset_cfg.SAMPLED_INTERVAL[mode] > 1:
sampled_waymo_infos = []
for k in range(0, len(self.infos), self.dataset_cfg.SAMPLED_INTERVAL[mode]):
sampled_waymo_infos.append(self.infos[k])
self.infos = sampled_waymo_infos
self.logger.info('Total sampled samples for Waymo dataset: %d' % len(self.infos))
use_sequence_data = self.dataset_cfg.get('SEQUENCE_CONFIG', None) is not None and self.dataset_cfg.SEQUENCE_CONFIG.ENABLED
if not use_sequence_data:
seq_name_to_infos = None
return seq_name_to_infos
def load_pred_boxes_to_dict(self, pred_boxes_path):
self.logger.info(f'Loading and reorganizing pred_boxes to dict from path: {pred_boxes_path}')
with open(pred_boxes_path, 'rb') as f:
pred_dicts = pickle.load(f)
pred_boxes_dict = {}
for index, box_dict in enumerate(pred_dicts):
seq_name = box_dict['frame_id'][:-4].replace('training_', '').replace('validation_', '')
sample_idx = int(box_dict['frame_id'][-3:])
if seq_name not in pred_boxes_dict:
pred_boxes_dict[seq_name] = {}
pred_labels = np.array([self.class_names.index(box_dict['name'][k]) + 1 for k in range(box_dict['name'].shape[0])])
pred_boxes = np.concatenate((box_dict['boxes_lidar'], box_dict['score'][:, np.newaxis], pred_labels[:, np.newaxis]), axis=-1)
pred_boxes_dict[seq_name][sample_idx] = pred_boxes
self.logger.info(f'Predicted boxes has been loaded, total sequences: {len(pred_boxes_dict)}')
return pred_boxes_dict
def load_data_to_shared_memory(self):
self.logger.info(f'Loading training data to shared memory (file limit={self.shared_memory_file_limit})')
| cur_rank, num_gpus = common_utils.get_dist_info() | 2 | 2023-10-25 02:57:35+00:00 | 8k |
GaryGuTC/COMG_model | COMG_model_RL/modules/base_cmn.py | [
{
"identifier": "pack_wrapper",
"path": "COMG_model_RL/modules/att_model.py",
"snippet": "def pack_wrapper(module, att_feats, att_masks):\n if att_masks is not None:\n packed, inv_ix = sort_pack_padded_sequence(att_feats, att_masks.data.long().sum(1))\n return pad_unsort_packed_sequence... | import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .att_model import pack_wrapper, AttModel | 6,872 | self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
self.topk = topk
def forward(self, query, key, value, mask=None, layer_past=None):
if mask is not None:
mask = mask.unsqueeze(1)
nbatches = query.size(0)
if layer_past is not None and layer_past.shape[2] == key.shape[1] > 1:
query = self.linears[0](query)
key, value = layer_past[0], layer_past[1]
present = torch.stack([key, value])
else:
query, key, value = \
[l(x) for l, x in zip(self.linears, (query, key, value))]
if layer_past is not None and not (layer_past.shape[2] == key.shape[1] > 1):
past_key, past_value = layer_past[0], layer_past[1]
key = torch.cat((past_key, key), dim=1)
value = torch.cat((past_value, value), dim=1)
present = torch.stack([key, value])
query, key, value = \
[x.view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for x in [query, key, value]]
x, self.attn = memory_querying_responding(query, key, value, mask=mask, dropout=self.dropout, topk=self.topk)
x = x.transpose(1, 2).contiguous() \
.view(nbatches, -1, self.h * self.d_k)
if layer_past is not None:
return self.linears[-1](x), present
else:
return self.linears[-1](x)
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
def forward(self, query, key, value, mask=None, layer_past=None):
if mask is not None:
mask = mask.unsqueeze(1)
nbatches = query.size(0)
if layer_past is not None and layer_past.shape[2] == key.shape[1] > 1:
query = self.linears[0](query)
key, value = layer_past[0], layer_past[1]
present = torch.stack([key, value])
else:
query, key, value = \
[l(x) for l, x in zip(self.linears, (query, key, value))]
if layer_past is not None and not (layer_past.shape[2] == key.shape[1] > 1):
past_key, past_value = layer_past[0], layer_past[1]
key = torch.cat((past_key, key), dim=1)
value = torch.cat((past_value, value), dim=1)
present = torch.stack([key, value])
query, key, value = \
[x.view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for x in [query, key, value]]
x, self.attn = attention(query, key, value, mask=mask,
dropout=self.dropout)
x = x.transpose(1, 2).contiguous() \
.view(nbatches, -1, self.h * self.d_k)
if layer_past is not None:
return self.linears[-1](x), present
else:
return self.linears[-1](x)
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.w_2(self.dropout(F.relu(self.w_1(x))))
class Embeddings(nn.Module):
def __init__(self, d_model, vocab):
super(Embeddings, self).__init__()
self.lut = nn.Embedding(vocab, d_model)
self.d_model = d_model
def forward(self, x):
return self.lut(x) * math.sqrt(self.d_model)
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len).unsqueeze(1).float()
div_term = torch.exp(torch.arange(0, d_model, 2).float() *
-(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:, :x.size(1)]
return self.dropout(x)
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
def subsequent_mask(size):
attn_shape = (1, size, size)
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
return torch.from_numpy(subsequent_mask) == 0
def attention(query, key, value, mask=None, dropout=None):
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
p_attn = F.softmax(scores, dim=-1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn, value), p_attn
def memory_querying_responding(query, key, value, mask=None, dropout=None, topk=32):
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float('-inf'))
selected_scores, idx = scores.topk(topk)
dummy_value = value.unsqueeze(2).expand(idx.size(0), idx.size(1), idx.size(2), value.size(-2), value.size(-1))
dummy_idx = idx.unsqueeze(-1).expand(idx.size(0), idx.size(1), idx.size(2), idx.size(3), value.size(-1))
selected_value = torch.gather(dummy_value, 3, dummy_idx)
p_attn = F.softmax(selected_scores, dim=-1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn.unsqueeze(3), selected_value).squeeze(3), p_attn
class Transformer(nn.Module):
def __init__(self, encoder, decoder, src_embed, tgt_embed, cmn):
super(Transformer, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.src_embed = src_embed
self.tgt_embed = tgt_embed
self.cmn = cmn
def forward(self, src, tgt, src_mask, tgt_mask, memory_matrix):
return self.decode(self.encode(src, src_mask), src_mask, tgt, tgt_mask, memory_matrix=memory_matrix)
def encode(self, src, src_mask):
return self.encoder(self.src_embed(src), src_mask)
def decode(self, memory, src_mask, tgt, tgt_mask, past=None, memory_matrix=None):
text_embeddings = self.tgt_embed(tgt)
# Memory querying and responding for textual features
dummy_memory_matrix = memory_matrix.unsqueeze(0).expand(text_embeddings.size(0), memory_matrix.size(0), memory_matrix.size(1))
responses = self.cmn(text_embeddings, dummy_memory_matrix, dummy_memory_matrix)
embeddings = text_embeddings + responses
# Memory querying and responding for textual features
return text_embeddings, self.decoder(embeddings, memory, src_mask, tgt_mask, past=past)
class Encoder(nn.Module):
def __init__(self, layer, N):
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
for layer in self.layers:
x = layer(x, mask)
return self.norm(x)
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True) # bs,98,512 => 16,98,1
std = x.std(-1, keepdim=True) # # bs,98,512 => 16,98,1
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
class SublayerConnection(nn.Module):
def __init__(self, size, dropout):
super(SublayerConnection, self).__init__()
self.norm = LayerNorm(size)
self.dropout = nn.Dropout(dropout)
def forward(self, x, sublayer):
_x = sublayer(self.norm(x))
if type(_x) is tuple:
return x + self.dropout(_x[0]), _x[1]
return x + self.dropout(_x)
class EncoderLayer(nn.Module):
def __init__(self, size, self_attn, feed_forward, dropout):
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 2)
self.size = size
def forward(self, x, mask):
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward)
class Decoder(nn.Module):
def __init__(self, layer, N):
super(Decoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, memory, src_mask, tgt_mask, past=None):
if past is not None:
present = [[], []]
x = x[:, -1:]
tgt_mask = tgt_mask[:, -1:] if tgt_mask is not None else None
past = list(zip(past[0].split(2, dim=0), past[1].split(2, dim=0)))
else:
past = [None] * len(self.layers)
for i, (layer, layer_past) in enumerate(zip(self.layers, past)):
x = layer(x, memory, src_mask, tgt_mask,
layer_past)
if layer_past is not None:
present[0].append(x[1][0])
present[1].append(x[1][1])
x = x[0]
if past[0] is None:
return self.norm(x)
else:
return self.norm(x), [torch.cat(present[0], 0), torch.cat(present[1], 0)]
class DecoderLayer(nn.Module):
def __init__(self, size, self_attn, src_attn, feed_forward, dropout):
super(DecoderLayer, self).__init__()
self.size = size
self.self_attn = self_attn
self.src_attn = src_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 3)
def forward(self, x, memory, src_mask, tgt_mask, layer_past=None):
m = memory
if layer_past is None:
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))
x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))
return self.sublayer[2](x, self.feed_forward)
else:
present = [None, None]
x, present[0] = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask, layer_past[0]))
x, present[1] = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask, layer_past[1]))
return self.sublayer[2](x, self.feed_forward), present
class MultiThreadMemory(nn.Module):
def __init__(self, h, d_model, dropout=0.1, topk=32):
super(MultiThreadMemory, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
self.topk = topk
def forward(self, query, key, value, mask=None, layer_past=None):
if mask is not None:
mask = mask.unsqueeze(1)
nbatches = query.size(0)
if layer_past is not None and layer_past.shape[2] == key.shape[1] > 1:
query = self.linears[0](query)
key, value = layer_past[0], layer_past[1]
present = torch.stack([key, value])
else:
query, key, value = \
[l(x) for l, x in zip(self.linears, (query, key, value))]
if layer_past is not None and not (layer_past.shape[2] == key.shape[1] > 1):
past_key, past_value = layer_past[0], layer_past[1]
key = torch.cat((past_key, key), dim=1)
value = torch.cat((past_value, value), dim=1)
present = torch.stack([key, value])
query, key, value = \
[x.view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for x in [query, key, value]]
x, self.attn = memory_querying_responding(query, key, value, mask=mask, dropout=self.dropout, topk=self.topk)
x = x.transpose(1, 2).contiguous() \
.view(nbatches, -1, self.h * self.d_k)
if layer_past is not None:
return self.linears[-1](x), present
else:
return self.linears[-1](x)
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
def forward(self, query, key, value, mask=None, layer_past=None):
if mask is not None:
mask = mask.unsqueeze(1)
nbatches = query.size(0)
if layer_past is not None and layer_past.shape[2] == key.shape[1] > 1:
query = self.linears[0](query)
key, value = layer_past[0], layer_past[1]
present = torch.stack([key, value])
else:
query, key, value = \
[l(x) for l, x in zip(self.linears, (query, key, value))]
if layer_past is not None and not (layer_past.shape[2] == key.shape[1] > 1):
past_key, past_value = layer_past[0], layer_past[1]
key = torch.cat((past_key, key), dim=1)
value = torch.cat((past_value, value), dim=1)
present = torch.stack([key, value])
query, key, value = \
[x.view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for x in [query, key, value]]
x, self.attn = attention(query, key, value, mask=mask,
dropout=self.dropout)
x = x.transpose(1, 2).contiguous() \
.view(nbatches, -1, self.h * self.d_k)
if layer_past is not None:
return self.linears[-1](x), present
else:
return self.linears[-1](x)
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.w_2(self.dropout(F.relu(self.w_1(x))))
class Embeddings(nn.Module):
def __init__(self, d_model, vocab):
super(Embeddings, self).__init__()
self.lut = nn.Embedding(vocab, d_model)
self.d_model = d_model
def forward(self, x):
return self.lut(x) * math.sqrt(self.d_model)
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len).unsqueeze(1).float()
div_term = torch.exp(torch.arange(0, d_model, 2).float() *
-(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:, :x.size(1)]
return self.dropout(x)
| class BaseCMN(AttModel): | 1 | 2023-10-27 13:18:53+00:00 | 8k |
OpenProteinAI/PoET | poet/models/poet.py | [
{
"identifier": "Uniprot21",
"path": "poet/alphabets.py",
"snippet": "class Uniprot21(Alphabet):\n def __init__(\n self,\n mask=False,\n include_gap=False,\n include_startstop=False,\n distinct_startstop=False,\n ):\n chars = b\"ARNDCQEGHILKMFPSTWYV\"\n ... | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Union
from tqdm import tqdm
from poet.alphabets import Uniprot21
from poet.models.modules.activation import gelu
from poet.models.modules.attention import MultiheadAttention
from poet.models.modules.embedding import RotaryEmbedding
from poet.models.modules.packed_sequence import (
PackedTensorSequences,
get_mask,
pad_input,
unpad_input,
)
from poet.models.modules.transformer import TransformerEncoder
from poet.models.modules.transformer_rotary import TieredRotaryTransformerEncoderLayer | 7,172 |
def top_k_top_p_filtering(
logits: torch.Tensor,
top_k: Optional[int] = 0,
top_p: Optional[float] = 1.0,
filter_value: float = -float("Inf"),
min_tokens_to_keep: int = 1,
) -> torch.Tensor:
"""Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (batch size, vocabulary size)
if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
Make sure we keep at least min_tokens_to_keep per batch example in the output
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
Adapted from: https://huggingface.co/transformers/v3.2.0/_modules/transformers/generation_utils.html
"""
if top_k is not None:
top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check
# Remove all tokens with a probability less than the last token of the top-k
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = filter_value
if top_p is not None and top_p < 1.0:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold (token with 0 are kept)
sorted_indices_to_remove = cumulative_probs > top_p
if min_tokens_to_keep > 1:
# Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
# Shift the indices to the right to keep also the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
# scatter sorted tensors to original indexing
indices_to_remove = sorted_indices_to_remove.scatter(
1, sorted_indices, sorted_indices_to_remove
)
logits[indices_to_remove] = filter_value
return logits
class LogitsAllocateMemoryMixin(object):
"""
Stateless mixin providing methods for preallocating memory for logits calculations.
"""
@classmethod
def logits_allocate_memory(
cls,
|
def top_k_top_p_filtering(
logits: torch.Tensor,
top_k: Optional[int] = 0,
top_p: Optional[float] = 1.0,
filter_value: float = -float("Inf"),
min_tokens_to_keep: int = 1,
) -> torch.Tensor:
"""Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
Args:
logits: logits distribution shape (batch size, vocabulary size)
if top_k > 0: keep only top k tokens with highest probability (top-k filtering).
if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
Make sure we keep at least min_tokens_to_keep per batch example in the output
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
Adapted from: https://huggingface.co/transformers/v3.2.0/_modules/transformers/generation_utils.html
"""
if top_k is not None:
top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check
# Remove all tokens with a probability less than the last token of the top-k
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = filter_value
if top_p is not None and top_p < 1.0:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold (token with 0 are kept)
sorted_indices_to_remove = cumulative_probs > top_p
if min_tokens_to_keep > 1:
# Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below)
sorted_indices_to_remove[..., :min_tokens_to_keep] = 0
# Shift the indices to the right to keep also the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
# scatter sorted tensors to original indexing
indices_to_remove = sorted_indices_to_remove.scatter(
1, sorted_indices, sorted_indices_to_remove
)
logits[indices_to_remove] = filter_value
return logits
class LogitsAllocateMemoryMixin(object):
"""
Stateless mixin providing methods for preallocating memory for logits calculations.
"""
@classmethod
def logits_allocate_memory(
cls, | memory: Optional[list[PackedTensorSequences]], | 4 | 2023-10-28 01:30:26+00:00 | 8k |
Transconnectome/SwiFT | project/module/pl_classifier.py | [
{
"identifier": "load_model",
"path": "project/module/models/load_model.py",
"snippet": "def load_model(model_name, hparams=None):\n #number of transformer stages\n n_stages = len(hparams.depths)\n\n if hparams.precision == 16:\n to_float = False\n elif hparams.precision == 32:\n ... | import torch
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
import numpy as np
import os
import pickle
import scipy
import torchmetrics
import torchmetrics.classification
import monai.transforms as monai_t
import nibabel as nb
from torchmetrics.classification import BinaryAccuracy, BinaryAUROC, BinaryROC
from torchmetrics import PearsonCorrCoef # Accuracy,
from sklearn.metrics import accuracy_score, balanced_accuracy_score, roc_curve
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from .models.load_model import load_model
from .utils.metrics import Metrics
from .utils.parser import str2bool
from .utils.losses import NTXentLoss, global_local_temporal_contrastive
from .utils.lr_scheduler import WarmupCosineSchedule, CosineAnnealingWarmUpRestarts
from einops import rearrange
from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler, KBinsDiscretizer | 3,619 |
class LitClassifier(pl.LightningModule):
def __init__(self,data_module, **kwargs):
super().__init__()
self.save_hyperparameters(kwargs) # save hyperparameters except data_module (data_module cannot be pickled as a checkpoint)
# you should define target_values at the Dataset classes
target_values = data_module.train_dataset.target_values
if self.hparams.label_scaling_method == 'standardization':
scaler = StandardScaler()
normalized_target_values = scaler.fit_transform(target_values)
print(f'target_mean:{scaler.mean_[0]}, target_std:{scaler.scale_[0]}')
elif self.hparams.label_scaling_method == 'minmax':
scaler = MinMaxScaler()
normalized_target_values = scaler.fit_transform(target_values)
print(f'target_max:{scaler.data_max_[0]},target_min:{scaler.data_min_[0]}')
self.scaler = scaler
print(self.hparams.model)
|
class LitClassifier(pl.LightningModule):
def __init__(self,data_module, **kwargs):
super().__init__()
self.save_hyperparameters(kwargs) # save hyperparameters except data_module (data_module cannot be pickled as a checkpoint)
# you should define target_values at the Dataset classes
target_values = data_module.train_dataset.target_values
if self.hparams.label_scaling_method == 'standardization':
scaler = StandardScaler()
normalized_target_values = scaler.fit_transform(target_values)
print(f'target_mean:{scaler.mean_[0]}, target_std:{scaler.scale_[0]}')
elif self.hparams.label_scaling_method == 'minmax':
scaler = MinMaxScaler()
normalized_target_values = scaler.fit_transform(target_values)
print(f'target_max:{scaler.data_max_[0]},target_min:{scaler.data_min_[0]}')
self.scaler = scaler
print(self.hparams.model) | self.model = load_model(self.hparams.model, self.hparams) | 0 | 2023-10-28 09:26:03+00:00 | 8k |
deepsearch-ai/deepsearch | deepsearchai/app.py | [
{
"identifier": "EmbeddingModelsConfig",
"path": "deepsearchai/embedding_models_config.py",
"snippet": "class EmbeddingModelsConfig:\n def __init__(\n self,\n image_embedding_model: Optional[BaseEmbeddingModel] = None,\n audio_embedding_model: Optional[BaseEmbeddingModel] = None,... | from typing import Dict, List, Optional
from deepsearchai.embedding_models_config import EmbeddingModelsConfig
from deepsearchai.enums import MEDIA_TYPE
from deepsearchai.llms.base import BaseLLM
from deepsearchai.llms.openai import OpenAi
from deepsearchai.sources.utils import SourceUtils
from deepsearchai.types import MediaData, QueryResult
from deepsearchai.vector_databases.base import BaseVectorDatabase
from deepsearchai.vector_databases.chromadb import ChromaDB
import os
import subprocess
import streamlit | 5,101 |
class App:
def __init__(
self,
embedding_models_config: Optional[EmbeddingModelsConfig] = None,
vector_database: Optional[BaseVectorDatabase] = None,
llm: Optional[BaseLLM] = None,
):
self.embedding_models_config = (
embedding_models_config
if embedding_models_config
else EmbeddingModelsConfig()
)
self.vector_database = (
vector_database
if vector_database
else ChromaDB(embedding_models_config=self.embedding_models_config)
)
self.llm = llm if llm else OpenAi(self.vector_database)
self.source_utils = SourceUtils()
def add_data(self, source: str):
self.source_utils.add_data(
source, self.embedding_models_config, self.vector_database
)
def query(
self, query: str, media_types: List[MEDIA_TYPE] = [MEDIA_TYPE.IMAGE], n_results: int = 1
) -> QueryResult:
data = self.get_data(query, media_types, n_results)
response = self.llm.query(query, data)
return response
def get_data(
self, query: str, media_types: List[MEDIA_TYPE] = [MEDIA_TYPE.IMAGE], n_results: int = 1
|
class App:
def __init__(
self,
embedding_models_config: Optional[EmbeddingModelsConfig] = None,
vector_database: Optional[BaseVectorDatabase] = None,
llm: Optional[BaseLLM] = None,
):
self.embedding_models_config = (
embedding_models_config
if embedding_models_config
else EmbeddingModelsConfig()
)
self.vector_database = (
vector_database
if vector_database
else ChromaDB(embedding_models_config=self.embedding_models_config)
)
self.llm = llm if llm else OpenAi(self.vector_database)
self.source_utils = SourceUtils()
def add_data(self, source: str):
self.source_utils.add_data(
source, self.embedding_models_config, self.vector_database
)
def query(
self, query: str, media_types: List[MEDIA_TYPE] = [MEDIA_TYPE.IMAGE], n_results: int = 1
) -> QueryResult:
data = self.get_data(query, media_types, n_results)
response = self.llm.query(query, data)
return response
def get_data(
self, query: str, media_types: List[MEDIA_TYPE] = [MEDIA_TYPE.IMAGE], n_results: int = 1 | ) -> Dict[MEDIA_TYPE, List[MediaData]]: | 5 | 2023-10-27 06:46:22+00:00 | 8k |
Paulo-Lopes-Estevao/ci-generator | cigen/core/github/go_action_test.py | [
{
"identifier": "GoActionSteps",
"path": "cigen/core/github/go_action.py",
"snippet": "class GoActionSteps:\n def __init__(self, version) -> None:\n if version is None:\n raise TypeError('Version is required')\n self.version = version\n\n @staticmethod\n def step_checko... | import unittest
from cigen.core.github.go_action import GoActionSteps, ActionCIGenGolang, GoActionBuilderImpl
from cigen.core.github.github_action import On, Steps, Push, PullRequest, OnEventFactory, Action | 3,649 |
self.assertEqual(go_action.base(), {
'name': 'Go Action',
'on': {
'push': {
'branches': ['main']
},
'pull_request': {
'branches': ['main']
}
},
'jobs': {
'build': {
'name': 'Build',
'runs-on': 'ubuntu-latest',
'steps': [
go_action_steps.step_checkout(),
go_action_steps.step_setup_go(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
]
}
}
})
def test_base_push(self):
on = On(
Push(['main']),
PullRequest(['main'])
)
go_action_steps = GoActionSteps(['1.17'])
steps = Steps([
go_action_steps.step_checkout(),
go_action_steps.step_setup_go(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
])
go_action = Action(
'Go Action',
go_action_steps.version,
on.on_push(),
steps,
{
'GO_VERSION': '1.17'
}
)
self.assertEqual(go_action.base(), {
'name': 'Go Action',
'on': {
'push': {
'branches': ['main']
}
},
'jobs': {
'build': {
'name': 'Build',
'runs-on': 'ubuntu-latest',
'steps': [
go_action_steps.step_checkout(),
go_action_steps.step_setup_go(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
]
}
}
})
def test_go_runVersionWithRange(self):
on = On(
Push(['main']),
PullRequest(['main'])
)
go_action_steps = GoActionSteps(['1.19'])
steps = Steps([
go_action_steps.step_checkout(),
go_action_steps.step_setup_go_with_versions_matrix(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
])
go_action = Action(
'Go Action',
go_action_steps.version,
on.on_push(),
steps,
)
self.assertEqual(go_action.base_version_list(), {
'name': 'Go Action',
'on': {
'push': {
'branches': ['main']
}
},
'jobs': {
'build': {
'name': 'Build',
'runs-on': 'ubuntu-latest',
'strategy': {
'matrix': {
'go-version': go_action_steps.version
}
},
'steps': [
go_action_steps.step_checkout(),
go_action_steps.step_setup_go_with_versions_matrix(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
]
}
}
})
def test_action_ci_base(self):
action_ciGen_golang = ActionCIGenGolang()
|
class GoActionTestCase(unittest.TestCase):
def test_something(self):
self.assertNotEqual(True, False) # add assertion here
def test_base(self):
on = On(
Push(['main']),
PullRequest(['main'])
)
go_action_steps = GoActionSteps('1.17')
steps = Steps([
go_action_steps.step_checkout(),
go_action_steps.step_setup_go(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
])
go_action = Action(
'Go Action',
go_action_steps.version,
on.to_dict(),
steps,
{
'GO_VERSION': '1.17'
}
)
self.assertEqual(go_action.base(), {
'name': 'Go Action',
'on': {
'push': {
'branches': ['main']
},
'pull_request': {
'branches': ['main']
}
},
'jobs': {
'build': {
'name': 'Build',
'runs-on': 'ubuntu-latest',
'steps': [
go_action_steps.step_checkout(),
go_action_steps.step_setup_go(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
]
}
}
})
def test_base_push(self):
on = On(
Push(['main']),
PullRequest(['main'])
)
go_action_steps = GoActionSteps(['1.17'])
steps = Steps([
go_action_steps.step_checkout(),
go_action_steps.step_setup_go(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
])
go_action = Action(
'Go Action',
go_action_steps.version,
on.on_push(),
steps,
{
'GO_VERSION': '1.17'
}
)
self.assertEqual(go_action.base(), {
'name': 'Go Action',
'on': {
'push': {
'branches': ['main']
}
},
'jobs': {
'build': {
'name': 'Build',
'runs-on': 'ubuntu-latest',
'steps': [
go_action_steps.step_checkout(),
go_action_steps.step_setup_go(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
]
}
}
})
def test_go_runVersionWithRange(self):
on = On(
Push(['main']),
PullRequest(['main'])
)
go_action_steps = GoActionSteps(['1.19'])
steps = Steps([
go_action_steps.step_checkout(),
go_action_steps.step_setup_go_with_versions_matrix(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
])
go_action = Action(
'Go Action',
go_action_steps.version,
on.on_push(),
steps,
)
self.assertEqual(go_action.base_version_list(), {
'name': 'Go Action',
'on': {
'push': {
'branches': ['main']
}
},
'jobs': {
'build': {
'name': 'Build',
'runs-on': 'ubuntu-latest',
'strategy': {
'matrix': {
'go-version': go_action_steps.version
}
},
'steps': [
go_action_steps.step_checkout(),
go_action_steps.step_setup_go_with_versions_matrix(),
go_action_steps.step_run_build(),
go_action_steps.step_run_tests(),
]
}
}
})
def test_action_ci_base(self):
action_ciGen_golang = ActionCIGenGolang()
| on_event_push = OnEventFactory.create_push(['main', 'master']).to_dict() | 7 | 2023-10-31 03:36:36+00:00 | 8k |
TheCompAce/ShellSpeak | modules/shellSpeak.py | [
{
"identifier": "CommandResult",
"path": "modules/command_result.py",
"snippet": "class CommandResult:\n def __init__(self, stdout, stderr):\n self.out = stdout\n self.err = stderr"
},
{
"identifier": "LLM",
"path": "modules/llm.py",
"snippet": "class LLM:\n def __ini... | import asyncio
import datetime
import json
import os
import platform
import queue
import re
import subprocess
import logging
import signal
import base64
import threading
import spacy
from pygments import lexers
from modules.command_result import CommandResult
from modules.llm import LLM, ModelTypes
from modules.run_command import CommandRunner
from modules.utils import get_file_size, is_valid_filename, list_files_and_folders_with_sizes, load_settings, map_possible_commands, get_os_name, print_colored_text, capture_styled_input, read_file, redact_json_values, replace_placeholders, get_token_count, trim_to_right_token_count, trim_to_token_count
from functools import partial
from multiprocessing import Pool, TimeoutError | 6,759 | # Import necessary modules
# Load English tokenizer, POS tagger, parser, NER and word vectors
nlp = spacy.load("en_core_web_sm")
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class ShellSpeak:
def __init__(self, settings, base_path, vectorDb):
self.llm_len = int(settings.get("llm_size", 14000))
self.llm_history_len = int(settings.get("llm_history_size", 4000))
self.llm_file_len = int(settings.get("llm_file_size", 4000))
self.llm_folder_len = int(settings.get("llm_folder_size", 4000))
self.llm_slide_len = int(settings.get("llm_slide_len", 120))
self.temp_file = settings.get("temp_file", "temp")
self.llm_output_size = int(settings.get("llm_output_size", 4097))
self.use_cache = settings.get("use_cache", False)
self.cache_file = settings.get("cache_file", None)
self.vector_for_commands = settings.get("vector_for_commands", False)
self.vector_for_history = settings.get("vector_for_history", True)
self.vector_for_folders = settings.get("vector_for_folders", True)
self.data_file = 'path_to_your_data_file.json'
self.use_indexing = settings.get('use_indexing', False)
self.vector_db = vectorDb
self.settings = settings
self.command_history = ""
self.settingsRoot = base_path
self.files = []
| # Import necessary modules
# Load English tokenizer, POS tagger, parser, NER and word vectors
nlp = spacy.load("en_core_web_sm")
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class ShellSpeak:
def __init__(self, settings, base_path, vectorDb):
self.llm_len = int(settings.get("llm_size", 14000))
self.llm_history_len = int(settings.get("llm_history_size", 4000))
self.llm_file_len = int(settings.get("llm_file_size", 4000))
self.llm_folder_len = int(settings.get("llm_folder_size", 4000))
self.llm_slide_len = int(settings.get("llm_slide_len", 120))
self.temp_file = settings.get("temp_file", "temp")
self.llm_output_size = int(settings.get("llm_output_size", 4097))
self.use_cache = settings.get("use_cache", False)
self.cache_file = settings.get("cache_file", None)
self.vector_for_commands = settings.get("vector_for_commands", False)
self.vector_for_history = settings.get("vector_for_history", True)
self.vector_for_folders = settings.get("vector_for_folders", True)
self.data_file = 'path_to_your_data_file.json'
self.use_indexing = settings.get('use_indexing', False)
self.vector_db = vectorDb
self.settings = settings
self.command_history = ""
self.settingsRoot = base_path
self.files = []
| self.llm = LLM(model_type=ModelTypes(self.settings.get('model', "OpenAI")), use_cache=self.use_cache, cache_file=self.cache_file) #Zephyr7bBeta | 2 | 2023-10-31 23:35:19+00:00 | 8k |
qym7/SparseDiff | sparse_diffusion/metrics/spectre_utils.py | [
{
"identifier": "SparsePlaceHolder",
"path": "sparse_diffusion/utils.py",
"snippet": "class SparsePlaceHolder:\n def __init__(\n self, node, edge_index, edge_attr, y, ptr=None, batch=None, charge=None\n ):\n self.node = node # (N, dx)\n self.edge_index = edge_index # (2, M)\... | import os
import copy
import random
import dgl
import wandb
import pygsp as pg
import secrets
import torch
import torch.nn as nn
import numpy as np
import networkx as nx
import subprocess as sp
import concurrent.futures
import graph_tool.all as gt
from datetime import datetime
from scipy.linalg import eigvalsh
from scipy.stats import chi2
from string import ascii_uppercase, digits
from torch_geometric.utils import to_dense_adj, is_undirected, to_networkx
from sparse_diffusion.utils import SparsePlaceHolder
from sparse_diffusion.analysis.dist_helper import (
compute_mmd,
gaussian_emd,
gaussian,
emd,
gaussian_tv,
disc,
)
from sparse_diffusion.metrics.neural_metrics import (
FIDEvaluation,
MMDEvaluation,
load_feature_extractor
)
from sparse_diffusion.utils import SparsePlaceHolder | 7,134 |
def eval_fraction_isomorphic(fake_graphs, train_graphs):
count = 0
for fake_g in fake_graphs:
for train_g in train_graphs:
if nx.faster_could_be_isomorphic(fake_g, train_g):
if nx.is_isomorphic(fake_g, train_g):
count += 1
break
return count / float(len(fake_graphs))
def eval_fraction_unique(fake_graphs, precise=False):
count_non_unique = 0
fake_evaluated = []
for fake_g in fake_graphs:
unique = True
if not fake_g.number_of_nodes() == 0:
for fake_old in fake_evaluated:
if precise:
if nx.faster_could_be_isomorphic(fake_g, fake_old):
if nx.is_isomorphic(fake_g, fake_old):
count_non_unique += 1
unique = False
break
else:
if nx.faster_could_be_isomorphic(fake_g, fake_old):
if nx.could_be_isomorphic(fake_g, fake_old):
count_non_unique += 1
unique = False
break
if unique:
fake_evaluated.append(fake_g)
frac_unique = (float(len(fake_graphs)) - count_non_unique) / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs
return frac_unique
def eval_fraction_unique_non_isomorphic_valid(
fake_graphs, train_graphs, validity_func=(lambda x: True)
):
count_valid = 0
count_isomorphic = 0
count_non_unique = 0
fake_evaluated = []
for fake_g in fake_graphs:
unique = True
for fake_old in fake_evaluated:
if nx.faster_could_be_isomorphic(fake_g, fake_old):
if nx.is_isomorphic(fake_g, fake_old):
count_non_unique += 1
unique = False
break
if unique:
fake_evaluated.append(fake_g)
non_isomorphic = True
for train_g in train_graphs:
if nx.faster_could_be_isomorphic(fake_g, train_g):
if nx.is_isomorphic(fake_g, train_g):
count_isomorphic += 1
non_isomorphic = False
break
if non_isomorphic:
if validity_func(fake_g):
count_valid += 1
frac_unique = (float(len(fake_graphs)) - count_non_unique) / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs
frac_unique_non_isomorphic = (
float(len(fake_graphs)) - count_non_unique - count_isomorphic
) / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs that are not in the training set
frac_unique_non_isomorphic_valid = count_valid / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs that are not in the training set and are valid
return frac_unique, frac_unique_non_isomorphic, frac_unique_non_isomorphic_valid
class SpectreSamplingMetrics(nn.Module):
def __init__(self, dataloaders, compute_emd, metrics_list):
super().__init__()
self.train_graphs = self.loader_to_nx(dataloaders["train"])
self.val_graphs = self.loader_to_nx(dataloaders["val"])
self.test_graphs = self.loader_to_nx(dataloaders["test"])
self.num_graphs_test = len(self.test_graphs)
self.num_graphs_val = len(self.val_graphs)
print('num_train_graphs is', len(self.train_graphs))
print('num_graphs_test is', self.num_graphs_test)
print('num_graphs_val is', self.num_graphs_val)
self.compute_emd = compute_emd
self.metrics_list = metrics_list
def loader_to_nx(self, loader):
networkx_graphs = []
for i, batch in enumerate(loader):
data_list = batch.to_data_list()
for j, data in enumerate(data_list):
networkx_graphs.append(
to_networkx(
data,
node_attrs=None,
edge_attrs=None,
to_undirected=True,
remove_self_loops=True,
)
)
return networkx_graphs
def neural_metrics(self, generated):
# Neural metrics
gin_model = load_feature_extractor(device='cpu') # take a gin-model with predefined params and random weights
fid_evaluator = FIDEvaluation(model=gin_model)
| ###############################################################################
#
# Adapted from https://github.com/lrjconan/GRAN/ which in turn is adapted from https://github.com/JiaxuanYou/graph-generation
#
###############################################################################
##Navigate to the ./util/orca directory and compile orca.cpp
# g++ -O2 -std=c++11 -o orca orca.cpp
try:
except ModuleNotFoundError:
print("Graph tool could not be loaded")
PRINT_TIME = False
__all__ = [
"degree_stats",
"clustering_stats",
"orbit_stats_all",
"spectral_stats",
"eval_acc_lobster_graph",
]
def degree_worker(G):
return np.array(nx.degree_histogram(G))
def degree_stats(graph_ref_list, graph_pred_list, is_parallel=True, compute_emd=False):
"""Compute the distance between the degree distributions of two unordered sets of graphs.
Args:
graph_ref_list, graph_target_list: two lists of networkx graphs to be evaluated
"""
sample_ref = []
sample_pred = []
# in case an empty graph is generated
graph_pred_list_remove_empty = [
G for G in graph_pred_list if not G.number_of_nodes() == 0
]
prev = datetime.now()
if is_parallel:
with concurrent.futures.ThreadPoolExecutor() as executor:
for deg_hist in executor.map(degree_worker, graph_ref_list):
sample_ref.append(deg_hist)
with concurrent.futures.ThreadPoolExecutor() as executor:
for deg_hist in executor.map(degree_worker, graph_pred_list_remove_empty):
sample_pred.append(deg_hist)
else:
for i in range(len(graph_ref_list)):
degree_temp = np.array(nx.degree_histogram(graph_ref_list[i]))
sample_ref.append(degree_temp)
for i in range(len(graph_pred_list_remove_empty)):
degree_temp = np.array(nx.degree_histogram(graph_pred_list_remove_empty[i]))
sample_pred.append(degree_temp)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_emd)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=emd)
if compute_emd:
# EMD option uses the same computation as GraphRNN, the alternative is MMD as computed by GRAN
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=emd)
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_emd)
else:
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_tv)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian)
elapsed = datetime.now() - prev
if PRINT_TIME:
print("Time computing degree mmd: ", elapsed)
return mmd_dist
###############################################################################
def spectral_worker(G, n_eigvals=-1):
# eigs = nx.laplacian_spectrum(G)
try:
eigs = eigvalsh(nx.normalized_laplacian_matrix(G).todense())
except:
eigs = np.zeros(G.number_of_nodes())
if n_eigvals > 0:
eigs = eigs[1 : n_eigvals + 1]
spectral_pmf, _ = np.histogram(eigs, bins=200, range=(-1e-5, 2), density=False)
spectral_pmf = spectral_pmf / spectral_pmf.sum()
return spectral_pmf
def get_spectral_pmf(eigs, max_eig):
spectral_pmf, _ = np.histogram(
np.clip(eigs, 0, max_eig), bins=200, range=(-1e-5, max_eig), density=False
)
spectral_pmf = spectral_pmf / spectral_pmf.sum()
return spectral_pmf
def eigval_stats(
eig_ref_list, eig_pred_list, max_eig=20, is_parallel=True, compute_emd=False
):
"""Compute the distance between the degree distributions of two unordered sets of graphs.
Args:
graph_ref_list, graph_target_list: two lists of networkx graphs to be evaluated
"""
sample_ref = []
sample_pred = []
prev = datetime.now()
if is_parallel:
with concurrent.futures.ThreadPoolExecutor() as executor:
for spectral_density in executor.map(
get_spectral_pmf,
eig_ref_list,
[max_eig for i in range(len(eig_ref_list))],
):
sample_ref.append(spectral_density)
with concurrent.futures.ThreadPoolExecutor() as executor:
for spectral_density in executor.map(
get_spectral_pmf,
eig_pred_list,
[max_eig for i in range(len(eig_ref_list))],
):
sample_pred.append(spectral_density)
else:
for i in range(len(eig_ref_list)):
spectral_temp = get_spectral_pmf(eig_ref_list[i])
sample_ref.append(spectral_temp)
for i in range(len(eig_pred_list)):
spectral_temp = get_spectral_pmf(eig_pred_list[i])
sample_pred.append(spectral_temp)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_emd)
if compute_emd:
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=emd)
else:
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_tv)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian)
elapsed = datetime.now() - prev
if PRINT_TIME:
print("Time computing eig mmd: ", elapsed)
return mmd_dist
def eigh_worker(G):
L = nx.normalized_laplacian_matrix(G).todense()
try:
eigvals, eigvecs = np.linalg.eigh(L)
except:
eigvals = np.zeros(L[0, :].shape)
eigvecs = np.zeros(L.shape)
return (eigvals, eigvecs)
def compute_list_eigh(graph_list, is_parallel=False):
eigval_list = []
eigvec_list = []
if is_parallel:
with concurrent.futures.ThreadPoolExecutor() as executor:
for e_U in executor.map(eigh_worker, graph_list):
eigval_list.append(e_U[0])
eigvec_list.append(e_U[1])
else:
for i in range(len(graph_list)):
e_U = eigh_worker(graph_list[i])
eigval_list.append(e_U[0])
eigvec_list.append(e_U[1])
return eigval_list, eigvec_list
def get_spectral_filter_worker(eigvec, eigval, filters, bound=1.4):
ges = filters.evaluate(eigval)
linop = []
for ge in ges:
linop.append(eigvec @ np.diag(ge) @ eigvec.T)
linop = np.array(linop)
norm_filt = np.sum(linop**2, axis=2)
hist_range = [0, bound]
hist = np.array(
[np.histogram(x, range=hist_range, bins=100)[0] for x in norm_filt]
) # NOTE: change number of bins
return hist.flatten()
def spectral_filter_stats(
eigvec_ref_list,
eigval_ref_list,
eigvec_pred_list,
eigval_pred_list,
is_parallel=False,
compute_emd=False,
):
"""Compute the distance between the eigvector sets.
Args:
graph_ref_list, graph_target_list: two lists of networkx graphs to be evaluated
"""
prev = datetime.now()
class DMG(object):
"""Dummy Normalized Graph"""
lmax = 2
n_filters = 12
filters = pg.filters.Abspline(DMG, n_filters)
bound = np.max(filters.evaluate(np.arange(0, 2, 0.01)))
sample_ref = []
sample_pred = []
if is_parallel:
with concurrent.futures.ThreadPoolExecutor() as executor:
for spectral_density in executor.map(
get_spectral_filter_worker,
eigvec_ref_list,
eigval_ref_list,
[filters for i in range(len(eigval_ref_list))],
[bound for i in range(len(eigval_ref_list))],
):
sample_ref.append(spectral_density)
with concurrent.futures.ThreadPoolExecutor() as executor:
for spectral_density in executor.map(
get_spectral_filter_worker,
eigvec_pred_list,
eigval_pred_list,
[filters for i in range(len(eigval_ref_list))],
[bound for i in range(len(eigval_ref_list))],
):
sample_pred.append(spectral_density)
else:
for i in range(len(eigval_ref_list)):
try:
spectral_temp = get_spectral_filter_worker(
eigvec_ref_list[i], eigval_ref_list[i], filters, bound
)
sample_ref.append(spectral_temp)
except:
pass
for i in range(len(eigval_pred_list)):
try:
spectral_temp = get_spectral_filter_worker(
eigvec_pred_list[i], eigval_pred_list[i], filters, bound
)
sample_pred.append(spectral_temp)
except:
pass
if compute_emd:
# EMD option uses the same computation as GraphRNN, the alternative is MMD as computed by GRAN
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=emd)
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_emd)
else:
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_tv)
elapsed = datetime.now() - prev
if PRINT_TIME:
print("Time computing spectral filter stats: ", elapsed)
return mmd_dist
def spectral_stats(
graph_ref_list, graph_pred_list, is_parallel=True, n_eigvals=-1, compute_emd=False
):
"""Compute the distance between the degree distributions of two unordered sets of graphs.
Args:
graph_ref_list, graph_target_list: two lists of networkx graphs to be evaluated
"""
sample_ref = []
sample_pred = []
# in case an empty graph is generated
graph_pred_list_remove_empty = [
G for G in graph_pred_list if not G.number_of_nodes() == 0
]
prev = datetime.now()
if is_parallel:
with concurrent.futures.ThreadPoolExecutor() as executor:
for spectral_density in executor.map(
spectral_worker, graph_ref_list, [n_eigvals for i in graph_ref_list]
):
sample_ref.append(spectral_density)
with concurrent.futures.ThreadPoolExecutor() as executor:
for spectral_density in executor.map(
spectral_worker,
graph_pred_list_remove_empty,
[n_eigvals for i in graph_ref_list],
):
sample_pred.append(spectral_density)
else:
for i in range(len(graph_ref_list)):
spectral_temp = spectral_worker(graph_ref_list[i], n_eigvals)
sample_ref.append(spectral_temp)
for i in range(len(graph_pred_list_remove_empty)):
spectral_temp = spectral_worker(graph_pred_list_remove_empty[i], n_eigvals)
sample_pred.append(spectral_temp)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_emd)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=emd)
if compute_emd:
# EMD option uses the same computation as GraphRNN, the alternative is MMD as computed by GRAN
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=emd)
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_emd)
else:
mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian_tv)
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=gaussian)
elapsed = datetime.now() - prev
if PRINT_TIME:
print("Time computing degree mmd: ", elapsed)
return mmd_dist
###############################################################################
def clustering_worker(param):
G, bins = param
clustering_coeffs_list = list(nx.clustering(G).values())
hist, _ = np.histogram(
clustering_coeffs_list, bins=bins, range=(0.0, 1.0), density=False
)
return hist
def clustering_stats(
graph_ref_list, graph_pred_list, bins=100, is_parallel=True, compute_emd=False
):
sample_ref = []
sample_pred = []
graph_pred_list_remove_empty = [
G for G in graph_pred_list if not G.number_of_nodes() == 0
]
prev = datetime.now()
if is_parallel:
with concurrent.futures.ThreadPoolExecutor() as executor:
for clustering_hist in executor.map(
clustering_worker, [(G, bins) for G in graph_ref_list]
):
sample_ref.append(clustering_hist)
with concurrent.futures.ThreadPoolExecutor() as executor:
for clustering_hist in executor.map(
clustering_worker, [(G, bins) for G in graph_pred_list_remove_empty]
):
sample_pred.append(clustering_hist)
# check non-zero elements in hist
# total = 0
# for i in range(len(sample_pred)):
# nz = np.nonzero(sample_pred[i])[0].shape[0]
# total += nz
# print(total)
else:
for i in range(len(graph_ref_list)):
clustering_coeffs_list = list(nx.clustering(graph_ref_list[i]).values())
hist, _ = np.histogram(
clustering_coeffs_list, bins=bins, range=(0.0, 1.0), density=False
)
sample_ref.append(hist)
for i in range(len(graph_pred_list_remove_empty)):
clustering_coeffs_list = list(
nx.clustering(graph_pred_list_remove_empty[i]).values()
)
hist, _ = np.histogram(
clustering_coeffs_list, bins=bins, range=(0.0, 1.0), density=False
)
sample_pred.append(hist)
if compute_emd:
# EMD option uses the same computation as GraphRNN, the alternative is MMD as computed by GRAN
# mmd_dist = compute_mmd(sample_ref, sample_pred, kernel=emd, sigma=1.0 / 10)
mmd_dist = compute_mmd(
sample_ref,
sample_pred,
kernel=gaussian_emd,
sigma=1.0 / 10,
distance_scaling=bins,
)
else:
mmd_dist = compute_mmd(
sample_ref, sample_pred, kernel=gaussian_tv, sigma=1.0 / 10
)
elapsed = datetime.now() - prev
if PRINT_TIME:
print("Time computing clustering mmd: ", elapsed)
return mmd_dist
# maps motif/orbit name string to its corresponding list of indices from orca output
motif_to_indices = {
"3path": [1, 2],
"4cycle": [8],
}
COUNT_START_STR = "orbit counts:"
def edge_list_reindexed(G):
idx = 0
id2idx = dict()
for u in G.nodes():
id2idx[str(u)] = idx
idx += 1
edges = []
for u, v in G.edges():
edges.append((id2idx[str(u)], id2idx[str(v)]))
return edges
def orca(graph):
# tmp_fname = f'analysis/orca/tmp_{"".join(secrets.choice(ascii_uppercase + digits) for i in range(8))}.txt'
tmp_fname = f'../analysis/orca/tmp_{"".join(secrets.choice(ascii_uppercase + digits) for i in range(8))}.txt'
tmp_fname = os.path.join(os.path.dirname(os.path.realpath(__file__)), tmp_fname)
# print(tmp_fname, flush=True)
f = open(tmp_fname, "w")
f.write(str(graph.number_of_nodes()) + " " + str(graph.number_of_edges()) + "\n")
for u, v in edge_list_reindexed(graph):
f.write(str(u) + " " + str(v) + "\n")
f.close()
output = sp.check_output(
[
str(
os.path.join(
os.path.dirname(os.path.realpath(__file__)), "../analysis/orca/orca"
)
),
"node",
"4",
tmp_fname,
"std",
]
)
output = output.decode("utf8").strip()
idx = output.find(COUNT_START_STR) + len(COUNT_START_STR) + 2
output = output[idx:]
node_orbit_counts = np.array(
[
list(map(int, node_cnts.strip().split(" ")))
for node_cnts in output.strip("\n").split("\n")
]
)
try:
os.remove(tmp_fname)
except OSError:
pass
return node_orbit_counts
def motif_stats(
graph_ref_list,
graph_pred_list,
motif_type="4cycle",
ground_truth_match=None,
bins=100,
compute_emd=False,
):
# graph motif counts (int for each graph)
# normalized by graph size
total_counts_ref = []
total_counts_pred = []
num_matches_ref = []
num_matches_pred = []
graph_pred_list_remove_empty = [
G for G in graph_pred_list if not G.number_of_nodes() == 0
]
indices = motif_to_indices[motif_type]
for G in graph_ref_list:
orbit_counts = orca(G)
motif_counts = np.sum(orbit_counts[:, indices], axis=1)
if ground_truth_match is not None:
match_cnt = 0
for elem in motif_counts:
if elem == ground_truth_match:
match_cnt += 1
num_matches_ref.append(match_cnt / G.number_of_nodes())
# hist, _ = np.histogram(
# motif_counts, bins=bins, density=False)
motif_temp = np.sum(motif_counts) / G.number_of_nodes()
total_counts_ref.append(motif_temp)
for G in graph_pred_list_remove_empty:
orbit_counts = orca(G)
motif_counts = np.sum(orbit_counts[:, indices], axis=1)
if ground_truth_match is not None:
match_cnt = 0
for elem in motif_counts:
if elem == ground_truth_match:
match_cnt += 1
num_matches_pred.append(match_cnt / G.number_of_nodes())
motif_temp = np.sum(motif_counts) / G.number_of_nodes()
total_counts_pred.append(motif_temp)
total_counts_ref = np.array(total_counts_ref)[:, None]
total_counts_pred = np.array(total_counts_pred)[:, None]
if compute_emd:
# EMD option uses the same computation as GraphRNN, the alternative is MMD as computed by GRAN
# mmd_dist = compute_mmd(total_counts_ref, total_counts_pred, kernel=emd, is_hist=False)
mmd_dist = compute_mmd(
total_counts_ref, total_counts_pred, kernel=gaussian, is_hist=False
)
else:
mmd_dist = compute_mmd(
total_counts_ref, total_counts_pred, kernel=gaussian, is_hist=False
)
return mmd_dist
def orbit_stats_all(graph_ref_list, graph_pred_list, compute_emd=False):
total_counts_ref = []
total_counts_pred = []
graph_pred_list_remove_empty = [
G for G in graph_pred_list if not G.number_of_nodes() == 0
]
for G in graph_ref_list:
orbit_counts = orca(G)
orbit_counts_graph = np.sum(orbit_counts, axis=0) / G.number_of_nodes()
total_counts_ref.append(orbit_counts_graph)
for G in graph_pred_list:
orbit_counts = orca(G)
orbit_counts_graph = np.sum(orbit_counts, axis=0) / G.number_of_nodes()
total_counts_pred.append(orbit_counts_graph)
total_counts_ref = np.array(total_counts_ref)
total_counts_pred = np.array(total_counts_pred)
# mmd_dist = compute_mmd(
# total_counts_ref,
# total_counts_pred,
# kernel=gaussian,
# is_hist=False,
# sigma=30.0)
# mmd_dist = compute_mmd(
# total_counts_ref,
# total_counts_pred,
# kernel=gaussian_tv,
# is_hist=False,
# sigma=30.0)
if compute_emd:
# mmd_dist = compute_mmd(total_counts_ref, total_counts_pred, kernel=emd, sigma=30.0)
# EMD option uses the same computation as GraphRNN, the alternative is MMD as computed by GRAN
mmd_dist = compute_mmd(
total_counts_ref,
total_counts_pred,
kernel=gaussian,
is_hist=False,
sigma=30.0,
)
else:
mmd_dist = compute_mmd(
total_counts_ref,
total_counts_pred,
kernel=gaussian_tv,
is_hist=False,
sigma=30.0,
)
return mmd_dist
def eval_acc_lobster_graph(G_list):
G_list = [copy.deepcopy(gg) for gg in G_list]
count = 0
for gg in G_list:
if is_lobster_graph(gg):
count += 1
return count / float(len(G_list))
def eval_acc_tree_graph(G_list):
count = 0
for gg in G_list:
if nx.is_tree(gg):
count += 1
return count / float(len(G_list))
def eval_acc_grid_graph(G_list, grid_start=10, grid_end=20):
count = 0
for gg in G_list:
if is_grid_graph(gg):
count += 1
return count / float(len(G_list))
def eval_acc_sbm_graph(
G_list,
p_intra=0.3,
p_inter=0.005,
strict=True,
refinement_steps=1000,
is_parallel=True,
):
count = 0.0
if is_parallel:
with concurrent.futures.ThreadPoolExecutor() as executor:
for prob in executor.map(
is_sbm_graph,
[gg for gg in G_list],
[p_intra for i in range(len(G_list))],
[p_inter for i in range(len(G_list))],
[strict for i in range(len(G_list))],
[refinement_steps for i in range(len(G_list))],
):
count += prob
else:
for gg in G_list:
count += is_sbm_graph(
gg,
p_intra=p_intra,
p_inter=p_inter,
strict=strict,
refinement_steps=refinement_steps,
)
return count / float(len(G_list))
def eval_acc_planar_graph(G_list):
count = 0
for gg in G_list:
if is_planar_graph(gg):
count += 1
return count / float(len(G_list))
def is_planar_graph(G):
return nx.is_connected(G) and nx.check_planarity(G)[0]
def is_lobster_graph(G):
"""
Check a given graph is a lobster graph or not
Removing leaf nodes twice:
lobster -> caterpillar -> path
"""
### Check if G is a tree
if nx.is_tree(G):
G = G.copy()
### Check if G is a path after removing leaves twice
leaves = [n for n, d in G.degree() if d == 1]
G.remove_nodes_from(leaves)
leaves = [n for n, d in G.degree() if d == 1]
G.remove_nodes_from(leaves)
num_nodes = len(G.nodes())
num_degree_one = [d for n, d in G.degree() if d == 1]
num_degree_two = [d for n, d in G.degree() if d == 2]
if sum(num_degree_one) == 2 and sum(num_degree_two) == 2 * (num_nodes - 2):
return True
elif sum(num_degree_one) == 0 and sum(num_degree_two) == 0:
return True
else:
return False
else:
return False
def is_grid_graph(G):
"""
Check if the graph is grid, by comparing with all the real grids with the same node count
"""
all_grid_file = f"data/all_grids.pt"
if os.path.isfile(all_grid_file):
all_grids = torch.load(all_grid_file)
else:
all_grids = {}
for i in range(2, 20):
for j in range(2, 20):
G_grid = nx.grid_2d_graph(i, j)
n_nodes = f"{len(G_grid.nodes())}"
all_grids[n_nodes] = all_grids.get(n_nodes, []) + [G_grid]
torch.save(all_grids, all_grid_file)
n_nodes = f"{len(G.nodes())}"
if n_nodes in all_grids:
for G_grid in all_grids[n_nodes]:
if nx.faster_could_be_isomorphic(G, G_grid):
if nx.is_isomorphic(G, G_grid):
return True
return False
else:
return False
def is_sbm_graph(G, p_intra=0.3, p_inter=0.005, strict=True, refinement_steps=1000):
"""
Check if how closely given graph matches a SBM with given probabilites by computing mean probability of Wald test statistic for each recovered parameter
"""
adj = nx.adjacency_matrix(G).toarray()
idx = adj.nonzero()
g = gt.Graph()
g.add_edge_list(np.transpose(idx))
try:
state = gt.minimize_blockmodel_dl(g)
except ValueError:
if strict:
return False
else:
return 0.0
# Refine using merge-split MCMC
for i in range(refinement_steps):
state.multiflip_mcmc_sweep(beta=np.inf, niter=10)
b = state.get_blocks()
b = gt.contiguous_map(state.get_blocks())
state = state.copy(b=b)
e = state.get_matrix()
n_blocks = state.get_nonempty_B()
node_counts = state.get_nr().get_array()[:n_blocks]
edge_counts = e.todense()[:n_blocks, :n_blocks]
if strict:
if (
(node_counts > 40).sum() > 0
or (node_counts < 20).sum() > 0
or n_blocks > 5
or n_blocks < 2
):
return False
max_intra_edges = node_counts * (node_counts - 1)
est_p_intra = np.diagonal(edge_counts) / (max_intra_edges + 1e-6)
max_inter_edges = node_counts.reshape((-1, 1)) @ node_counts.reshape((1, -1))
np.fill_diagonal(edge_counts, 0)
est_p_inter = edge_counts / (max_inter_edges + 1e-6)
W_p_intra = (est_p_intra - p_intra) ** 2 / (est_p_intra * (1 - est_p_intra) + 1e-6)
W_p_inter = (est_p_inter - p_inter) ** 2 / (est_p_inter * (1 - est_p_inter) + 1e-6)
W = W_p_inter.copy()
np.fill_diagonal(W, W_p_intra)
p = 1 - chi2.cdf(abs(W), 1)
p = p.mean()
if strict:
return p > 0.9 # p value < 10 %
else:
return p
def eval_fraction_isomorphic(fake_graphs, train_graphs):
count = 0
for fake_g in fake_graphs:
for train_g in train_graphs:
if nx.faster_could_be_isomorphic(fake_g, train_g):
if nx.is_isomorphic(fake_g, train_g):
count += 1
break
return count / float(len(fake_graphs))
def eval_fraction_unique(fake_graphs, precise=False):
count_non_unique = 0
fake_evaluated = []
for fake_g in fake_graphs:
unique = True
if not fake_g.number_of_nodes() == 0:
for fake_old in fake_evaluated:
if precise:
if nx.faster_could_be_isomorphic(fake_g, fake_old):
if nx.is_isomorphic(fake_g, fake_old):
count_non_unique += 1
unique = False
break
else:
if nx.faster_could_be_isomorphic(fake_g, fake_old):
if nx.could_be_isomorphic(fake_g, fake_old):
count_non_unique += 1
unique = False
break
if unique:
fake_evaluated.append(fake_g)
frac_unique = (float(len(fake_graphs)) - count_non_unique) / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs
return frac_unique
def eval_fraction_unique_non_isomorphic_valid(
fake_graphs, train_graphs, validity_func=(lambda x: True)
):
count_valid = 0
count_isomorphic = 0
count_non_unique = 0
fake_evaluated = []
for fake_g in fake_graphs:
unique = True
for fake_old in fake_evaluated:
if nx.faster_could_be_isomorphic(fake_g, fake_old):
if nx.is_isomorphic(fake_g, fake_old):
count_non_unique += 1
unique = False
break
if unique:
fake_evaluated.append(fake_g)
non_isomorphic = True
for train_g in train_graphs:
if nx.faster_could_be_isomorphic(fake_g, train_g):
if nx.is_isomorphic(fake_g, train_g):
count_isomorphic += 1
non_isomorphic = False
break
if non_isomorphic:
if validity_func(fake_g):
count_valid += 1
frac_unique = (float(len(fake_graphs)) - count_non_unique) / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs
frac_unique_non_isomorphic = (
float(len(fake_graphs)) - count_non_unique - count_isomorphic
) / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs that are not in the training set
frac_unique_non_isomorphic_valid = count_valid / float(
len(fake_graphs)
) # Fraction of distinct isomorphism classes in the fake graphs that are not in the training set and are valid
return frac_unique, frac_unique_non_isomorphic, frac_unique_non_isomorphic_valid
class SpectreSamplingMetrics(nn.Module):
def __init__(self, dataloaders, compute_emd, metrics_list):
super().__init__()
self.train_graphs = self.loader_to_nx(dataloaders["train"])
self.val_graphs = self.loader_to_nx(dataloaders["val"])
self.test_graphs = self.loader_to_nx(dataloaders["test"])
self.num_graphs_test = len(self.test_graphs)
self.num_graphs_val = len(self.val_graphs)
print('num_train_graphs is', len(self.train_graphs))
print('num_graphs_test is', self.num_graphs_test)
print('num_graphs_val is', self.num_graphs_val)
self.compute_emd = compute_emd
self.metrics_list = metrics_list
def loader_to_nx(self, loader):
networkx_graphs = []
for i, batch in enumerate(loader):
data_list = batch.to_data_list()
for j, data in enumerate(data_list):
networkx_graphs.append(
to_networkx(
data,
node_attrs=None,
edge_attrs=None,
to_undirected=True,
remove_self_loops=True,
)
)
return networkx_graphs
def neural_metrics(self, generated):
# Neural metrics
gin_model = load_feature_extractor(device='cpu') # take a gin-model with predefined params and random weights
fid_evaluator = FIDEvaluation(model=gin_model) | rbf_evaluator = MMDEvaluation(model=gin_model, kernel='rbf', sigma='range', multiplier='mean') | 8 | 2023-10-30 12:12:16+00:00 | 8k |
cxyfreedom/website-hot-hub | main.py | [
{
"identifier": "WebsiteSSPai",
"path": "website_sspai.py",
"snippet": "class WebsiteSSPai:\n @staticmethod\n def get_raw() -> dict:\n ret = {}\n try:\n with request_session() as s:\n resp = s.get(url)\n ret = resp.json()\n except:\n ... | import concurrent.futures
from website_sspai import WebsiteSSPai
from website_36kr import WebSite36Kr
from website_bilibili import WebSiteBilibili
from website_douyin import WebSiteDouYin
from website_juejin import WebSiteJueJin
from website_weread import WebsiteWeRead
from website_kuaishou import WebsiteKuaiShou | 6,897 | # -*- coding: utf-8 -*-
def run_task(func, *args):
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.submit(func, *args)
def main():
website_sspai_obj = WebsiteSSPai()
website_36kr_obj = WebSite36Kr()
website_bilibili_obj = WebSiteBilibili()
website_douyin_obj = WebSiteDouYin()
website_juejin_obj = WebSiteJueJin()
| # -*- coding: utf-8 -*-
def run_task(func, *args):
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.submit(func, *args)
def main():
website_sspai_obj = WebsiteSSPai()
website_36kr_obj = WebSite36Kr()
website_bilibili_obj = WebSiteBilibili()
website_douyin_obj = WebSiteDouYin()
website_juejin_obj = WebSiteJueJin() | website_weread_obj = WebsiteWeRead() | 5 | 2023-10-25 14:31:11+00:00 | 8k |
ZhangLin-PKU/FedFTG | train.py | [
{
"identifier": "util_dataset",
"path": "utils/util_dataset.py",
"snippet": "COLOR_MAP = ['red', 'green', 'blue', 'black', 'brown', 'purple', 'yellow', 'pink', 'cyan', 'gray']\r\nclass DatasetObject:\r\nclass Dataset(torch.utils.data.Dataset):\r\nclass DatasetFromDir(data.Dataset):\r\n def __init__(s... | from utils import util_dataset, util_parser
from models import model_choose_fn
from methods import FedAvg, FedProx, SCAFFOLD, MOON, FedDyn
from methods import FedFTG, FedProxGAN, SCAFFOLDGAN, MOONGAN, FedDynGAN
import torch
import os
import random
import numpy as np
import matplotlib.pyplot as plt
| 4,019 | batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'], model_func=model_func,
init_model=init_model, sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedavg_res[-1]
elif conf['method'] == 'FedProx':
print('Train with FedProx+++++++++++++++++++++++++++++++')
fedprox_res = FedProx.train_FedProx(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model, sch_step=conf['sch_step'],
sch_gamma=conf['sch_gamma'], save_period=conf['save_period'], mu=conf['mu'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedprox_res[-1]
elif conf['method'] == 'FedDyn':
print('Train with FedDyn+++++++++++++++++++++++++++++++')
feddyn_res = FedDyn.train_FedDyn(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'], model_func=model_func,
init_model=init_model, alpha_coef=conf['coef_alpha'],
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = feddyn_res[-1]
elif conf['method'] == 'SCAFFOLD':
print('Train with SCAFFOLD+++++++++++++++++++++++++++++++')
fedscaffold_res = SCAFFOLD.train_SCAFFOLD(data_obj=data_obj, act_prob=conf['active_frac'],
learning_rate=conf['lr'], batch_size=conf['bs'],
n_minibatch=conf['n_minibatch'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model,
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedscaffold_res[-1]
elif conf['method'] == 'MOON':
print('Train with MOON+++++++++++++++++++++++++++++++')
moon_res = MOON.train_MOON(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'], model_func=model_func,
init_model=init_model, sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'], mu=conf['mu'], tau=conf['tau'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = moon_res[-1]
elif conf['method'] == 'FedFTG':
print('Train with FedFTG+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
fedavg_res = FedFTG.train_FedFTG(data_obj=data_obj, act_prob=conf['active_frac'],
learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'],
com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func,
init_model=init_model, init_g_model=init_g_model,
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'],
trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedavg_res[-1]
elif conf['method'] == 'FedProxGAN':
print('Train with FedProxGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
fedprox_res = FedProxGAN.train_FedProxGAN(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model, init_g_model=init_g_model, sch_step=conf['sch_step'],
sch_gamma=conf['sch_gamma'], save_period=conf['save_period'], mu=conf['mu'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'],
rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedprox_res[-1]
elif conf['method'] == 'FedDynGAN':
print('Train with FedDynGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
feddyn_res = FedDynGAN.train_FedDynGAN(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_g_model=init_g_model,
init_model=init_model, alpha_coef=conf['coef_alpha'],
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'],
rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = feddyn_res[-1]
elif conf['method'] == 'SCAFFOLDGAN':
print('Train with SCAFFOLDGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
fedscaffold_res = SCAFFOLDGAN.train_SCAFFOLDGAN(data_obj=data_obj, act_prob=conf['active_frac'],
learning_rate=conf['lr'], batch_size=conf['bs'],
n_minibatch=conf['n_minibatch'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model, init_g_model=init_g_model,
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedscaffold_res[-1]
elif conf['method'] == 'MOONGAN':
print('Train with MOONGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
|
def run(conf):
print('Init-------------------------')
root_path = os.getcwd()
# print(root_path)
if root_path.endswith('scripts'):
root_path = os.path.dirname(root_path)
conf['savepath'] = os.path.join(root_path, conf['savepath'].strip())
print('Data and results save path is: ', conf['savepath'])
######################################################
# Provide reproducibility
torch.manual_seed(conf['seed'])
random.seed(conf['seed'])
np.random.seed(conf['seed'])
in_channel = 3
out_channel = 10
######################################################
# Split the dataset
data_obj = util_dataset.DatasetObject(dataset=conf['dataset'],
n_client=conf['n_client'],
seed=conf['seed'],
rule=conf['rule'],
rule_arg=conf['alpha'],
unbalanced_sgm=conf['sgm'],
data_path=conf['savepath'].strip())
######################################################
# Model selection
if conf['dataset'] == 'CIFAR100':
out_channel = 100
in_channel = 3
g_model_arch = 'CGeneratorA'
nz = 256
elif conf['dataset'] == 'CIFAR10':
out_channel = 10
in_channel = 3
g_model_arch = 'CGeneratorA'
nz = 100
else:
raise RuntimeError('Wrong dataset or model_arch parameter setting.')
if (conf['model_arch'] == 'LeNet') or (conf['model_arch'] == 'FullDNN'):
model_func = lambda: model_choose_fn.choose_model(config['model_arch'],
in_channel=in_channel,
out_channel=out_channel)
else:
model_func = lambda: model_choose_fn.choose_model(config['model_arch'], num_classes=out_channel)
init_model = model_func()
######################################################
# build up the saving directory
if not os.path.exists(
'%sModel/%s/%s_%s_init_mdl.pt' % (conf['savepath'], data_obj.name, conf['dataset'], conf['model_arch'])):
if not os.path.exists('%sModel/%s/' % (conf['savepath'], data_obj.name)):
print("Create a new directory")
os.makedirs('%sModel/%s/' % (conf['savepath'], data_obj.name))
torch.save(init_model.state_dict(), '%sModel/%s/%s_%s_init_mdl.pt' % (
conf['savepath'], data_obj.name, conf['dataset'], conf['model_arch']))
else:
# Load model
init_model.load_state_dict(torch.load(
'%sModel/%s/%s_%s_init_mdl.pt' % (conf['savepath'], data_obj.name, conf['dataset'], conf['model_arch'])))
######################################################
# Begin to train with the specific method
res_all_performance = []
if conf['method'] == 'FedAvg':
print('Train with FedAvg+++++++++++++++++++++++++++++++')
fedavg_res = FedAvg.train_FedAvg(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'], model_func=model_func,
init_model=init_model, sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedavg_res[-1]
elif conf['method'] == 'FedProx':
print('Train with FedProx+++++++++++++++++++++++++++++++')
fedprox_res = FedProx.train_FedProx(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model, sch_step=conf['sch_step'],
sch_gamma=conf['sch_gamma'], save_period=conf['save_period'], mu=conf['mu'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedprox_res[-1]
elif conf['method'] == 'FedDyn':
print('Train with FedDyn+++++++++++++++++++++++++++++++')
feddyn_res = FedDyn.train_FedDyn(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'], model_func=model_func,
init_model=init_model, alpha_coef=conf['coef_alpha'],
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = feddyn_res[-1]
elif conf['method'] == 'SCAFFOLD':
print('Train with SCAFFOLD+++++++++++++++++++++++++++++++')
fedscaffold_res = SCAFFOLD.train_SCAFFOLD(data_obj=data_obj, act_prob=conf['active_frac'],
learning_rate=conf['lr'], batch_size=conf['bs'],
n_minibatch=conf['n_minibatch'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model,
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedscaffold_res[-1]
elif conf['method'] == 'MOON':
print('Train with MOON+++++++++++++++++++++++++++++++')
moon_res = MOON.train_MOON(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'], model_func=model_func,
init_model=init_model, sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'], mu=conf['mu'], tau=conf['tau'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = moon_res[-1]
elif conf['method'] == 'FedFTG':
print('Train with FedFTG+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
fedavg_res = FedFTG.train_FedFTG(data_obj=data_obj, act_prob=conf['active_frac'],
learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'],
com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func,
init_model=init_model, init_g_model=init_g_model,
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'],
trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedavg_res[-1]
elif conf['method'] == 'FedProxGAN':
print('Train with FedProxGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
fedprox_res = FedProxGAN.train_FedProxGAN(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model, init_g_model=init_g_model, sch_step=conf['sch_step'],
sch_gamma=conf['sch_gamma'], save_period=conf['save_period'], mu=conf['mu'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'],
rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedprox_res[-1]
elif conf['method'] == 'FedDynGAN':
print('Train with FedDynGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
feddyn_res = FedDynGAN.train_FedDynGAN(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
batch_size=conf['bs'], epoch=conf['localE'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_g_model=init_g_model,
init_model=init_model, alpha_coef=conf['coef_alpha'],
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'],
suffix=config['model_arch'], trial=False, data_path=conf['savepath'],
rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = feddyn_res[-1]
elif conf['method'] == 'SCAFFOLDGAN':
print('Train with SCAFFOLDGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
fedscaffold_res = SCAFFOLDGAN.train_SCAFFOLDGAN(data_obj=data_obj, act_prob=conf['active_frac'],
learning_rate=conf['lr'], batch_size=conf['bs'],
n_minibatch=conf['n_minibatch'], com_amount=conf['comm_amount'],
print_per=conf['print_freq'], weight_decay=conf['weight_decay'],
model_func=model_func, init_model=init_model, init_g_model=init_g_model,
sch_step=conf['sch_step'], sch_gamma=conf['sch_gamma'],
save_period=conf['save_period'], suffix=config['model_arch'], trial=False,
data_path=conf['savepath'], rand_seed=conf['seed'],
lr_decay_per_round=conf['lr_decay'])
res_all_performance = fedscaffold_res[-1]
elif conf['method'] == 'MOONGAN':
print('Train with MOONGAN+++++++++++++++++++++++++++++++')
g_model_func = lambda: model_choose_fn.choose_g_model(g_model_arch, nz=nz, nc=data_obj.channels,
img_size=data_obj.width, n_cls=out_channel)
init_g_model = g_model_func()
| moongan_res = MOONGAN.train_MOONGAN(data_obj=data_obj, act_prob=conf['active_frac'], learning_rate=conf['lr'],
| 11 | 2023-10-26 03:35:17+00:00 | 8k |
Shou-Hsu/Report.ai | main.py | [
{
"identifier": "credential_validation",
"path": "utils.py",
"snippet": "def credential_validation(vectorDB:str=False, temperature:float=0.1) -> None:\n from langchain.embeddings.openai import OpenAIEmbeddings\n from langchain.chat_models import AzureChatOpenAI\n from langchain.chat_models impo... | from utils import credential_validation, get_file_list, validation_and_filetype_check, detect_language
from s2t_whisper import speech2text, download_from_youtube, download_from_vimeo
from storage_vector import pinecone_storage, chroma_storage
from summarize import generate_summary
from divide import divide_article
import argparse, os | 6,414 |
def main():
parser = argparse.ArgumentParser(description='Build your own professional database')
parser.add_argument('file_path', type=str, help='file path')
parser.add_argument('-c', '--chunk', default=2000, type=int, help='chunk size')
parser.add_argument('-t', '--temperature', default=0.1, type=float, help='temperature of LLM')
parser.add_argument('-b', '--batch', default=False, action="store_true", help='batch process')
parser.add_argument('-o', '--output_dir', default='./docx', type=str, help='file path of output report')
parser.add_argument('-l', '--translated_language', default='zh-tw', help='the language that should be translated')
parser.add_argument('-v', '--vectorDB', default=None, choices=['pinecone', 'chroma', None], help='select the vectorDB')
parser.add_argument('-e', '--extract', default=False, action="store_true", help='Extract human voice from audio (not support in Apple silicon)')
parser.add_argument('-m', '--model', type=str, default='medium', help='the using model for ASR', choices=['tiny', 'base', 'small', 'medium', 'large-v3'])
args = parser.parse_args()
# credential validation
|
def main():
parser = argparse.ArgumentParser(description='Build your own professional database')
parser.add_argument('file_path', type=str, help='file path')
parser.add_argument('-c', '--chunk', default=2000, type=int, help='chunk size')
parser.add_argument('-t', '--temperature', default=0.1, type=float, help='temperature of LLM')
parser.add_argument('-b', '--batch', default=False, action="store_true", help='batch process')
parser.add_argument('-o', '--output_dir', default='./docx', type=str, help='file path of output report')
parser.add_argument('-l', '--translated_language', default='zh-tw', help='the language that should be translated')
parser.add_argument('-v', '--vectorDB', default=None, choices=['pinecone', 'chroma', None], help='select the vectorDB')
parser.add_argument('-e', '--extract', default=False, action="store_true", help='Extract human voice from audio (not support in Apple silicon)')
parser.add_argument('-m', '--model', type=str, default='medium', help='the using model for ASR', choices=['tiny', 'base', 'small', 'medium', 'large-v3'])
args = parser.parse_args()
# credential validation | credential_validation(vectorDB=args.vectorDB, temperature=args.temperature) | 0 | 2023-10-30 12:29:20+00:00 | 8k |
EnVision-Research/Defect_Spectrum | models/unet/ldmunet.py | [
{
"identifier": "checkpoint",
"path": "models/unet/util.py",
"snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at the expense of extra compute in the backward pass.\n :param func: the... | from abc import abstractmethod
from functools import partial
from typing import Iterable
from models.unet.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from models.modules.attention import SpatialTransformer
from omegaconf.listconfig import ListConfig
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F | 3,693 | 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=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
),
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=model_channels * mult,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = model_channels * mult
if ds in attention_resolutions:
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads_upsample,
num_head_channels=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
)
)
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, model_channels, out_channels, 3, padding=1)),
)
if self.predict_codebook_ids:
self.id_predictor = nn.Sequential(
normalization(ch),
conv_nd(dims, model_channels, n_embed, 1),
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
)
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, timesteps=None, context=None, y=None,**kwargs):
"""
Apply the model to an input batch.
:param x: an [N x C x ...] Tensor of inputs.
:param timesteps: a 1-D batch of timesteps.
:param context: conditioning plugged in via crossattn
: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"
hs = []
|
# dummy replace
def convert_module_to_f16(x):
pass
def convert_module_to_f32(x):
pass
## go
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, context=None):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
elif isinstance(layer, SpatialTransformer):
x = layer(x, context)
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, padding=1):
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=padding)
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 TransposedUpsample(nn.Module):
'Learned 2x upsampling without padding'
def __init__(self, channels, out_channels=None, ks=5):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
def forward(self,x):
return self.up(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,padding=1):
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=padding
)
else:
assert self.channels == self.out_channels
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
def forward(self, x):
assert x.shape[1] == self.channels
return self.op(x)
class ResBlock(TimestepBlock):
"""
A residual block that can optionally change the number of channels.
:param channels: the number of input channels.
:param emb_channels: the number of timestep embedding channels.
:param dropout: the rate of dropout.
:param out_channels: if specified, the number of out channels.
:param use_conv: if True and out_channels is specified, use a spatial
convolution instead of a smaller 1x1 convolution to change the
channels in the skip connection.
:param dims: determines if the signal is 1D, 2D, or 3D.
:param use_checkpoint: if True, use gradient checkpointing on this module.
:param up: if True, use this block for upsampling.
:param down: if True, use this block for downsampling.
"""
def __init__(
self,
channels,
emb_channels,
dropout,
out_channels=None,
use_conv=False,
use_scale_shift_norm=False,
dims=2,
use_checkpoint=False,
up=False,
down=False,
):
super().__init__()
self.channels = channels
self.emb_channels = emb_channels
self.dropout = dropout
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.use_checkpoint = use_checkpoint
self.use_scale_shift_norm = use_scale_shift_norm
self.in_layers = nn.Sequential(
normalization(channels),
nn.SiLU(),
conv_nd(dims, channels, self.out_channels, 3, padding=1),
)
self.updown = up or down
if up:
self.h_upd = Upsample(channels, False, dims)
self.x_upd = Upsample(channels, False, dims)
elif down:
self.h_upd = Downsample(channels, False, dims)
self.x_upd = Downsample(channels, False, dims)
else:
self.h_upd = self.x_upd = nn.Identity()
self.emb_layers = nn.Sequential(
nn.SiLU(),
linear(
emb_channels,
2 * self.out_channels if use_scale_shift_norm else self.out_channels,
),
)
self.out_layers = nn.Sequential(
normalization(self.out_channels),
nn.SiLU(),
nn.Dropout(p=dropout),
zero_module(
conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
),
)
if self.out_channels == channels:
self.skip_connection = nn.Identity()
elif use_conv:
self.skip_connection = conv_nd(
dims, channels, self.out_channels, 3, padding=1
)
else:
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
def forward(self, x, emb):
"""
Apply the block to a Tensor, conditioned on a timestep embedding.
:param x: an [N x C x ...] Tensor of features.
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
:return: an [N x C x ...] Tensor of outputs.
"""
return checkpoint(
self._forward, (x, emb), self.parameters(), self.use_checkpoint
)
def _forward(self, x, emb):
if self.updown:
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
h = in_rest(x)
h = self.h_upd(h)
x = self.x_upd(x)
h = in_conv(h)
else:
h = self.in_layers(x)
emb_out = self.emb_layers(emb).type(h.dtype)
while len(emb_out.shape) < len(h.shape):
emb_out = emb_out[..., None]
if self.use_scale_shift_norm:
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
scale, shift = th.chunk(emb_out, 2, dim=1)
h = out_norm(h) * (1 + scale) + shift
h = out_rest(h)
else:
h = h + emb_out
h = self.out_layers(h)
return self.skip_connection(x) + h
class AttentionBlock(nn.Module):
"""
An attention block that allows spatial positions to attend to each other.
Originally ported from here, but adapted to the N-d case.
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
"""
def __init__(
self,
channels,
num_heads=1,
num_head_channels=-1,
use_checkpoint=False,
use_new_attention_order=False,
):
super().__init__()
self.channels = channels
if num_head_channels == -1:
self.num_heads = num_heads
else:
assert (
channels % num_head_channels == 0
), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
self.num_heads = channels // num_head_channels
self.use_checkpoint = use_checkpoint
self.norm = normalization(channels)
self.qkv = conv_nd(1, channels, channels * 3, 1)
if use_new_attention_order:
# split qkv before split heads
self.attention = QKVAttention(self.num_heads)
else:
# split heads before split qkv
self.attention = QKVAttentionLegacy(self.num_heads)
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
def forward(self, x):
return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
#return pt_checkpoint(self._forward, x) # pytorch
def _forward(self, x):
b, c, *spatial = x.shape
x = x.reshape(b, c, -1)
qkv = self.qkv(self.norm(x))
h = self.attention(qkv)
h = self.proj_out(h)
return (x + h).reshape(b, c, *spatial)
def count_flops_attn(model, _x, y):
"""
A counter for the `thop` package to count the operations in an
attention operation.
Meant to be used like:
macs, params = thop.profile(
model,
inputs=(inputs, timestamps),
custom_ops={QKVAttention: QKVAttention.count_flops},
)
"""
b, c, *spatial = y[0].shape
num_spatial = int(np.prod(spatial))
# We perform two matmuls with the same number of ops.
# The first computes the weight matrix, the second computes
# the combination of the value vectors.
matmul_ops = 2 * b * (num_spatial ** 2) * c
model.total_ops += th.DoubleTensor([matmul_ops])
class QKVAttentionLegacy(nn.Module):
"""
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
"""
Apply QKV attention.
:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
:return: an [N x (H * C) x T] tensor after attention.
"""
bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
scale = 1 / math.sqrt(math.sqrt(ch))
weight = th.einsum(
"bct,bcs->bts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
a = th.einsum("bts,bcs->bct", weight, v)
return a.reshape(bs, -1, length)
@staticmethod
def count_flops(model, _x, y):
return count_flops_attn(model, _x, y)
class QKVAttention(nn.Module):
"""
A module which performs QKV attention and splits in a different order.
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
"""
Apply QKV attention.
:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
:return: an [N x (H * C) x T] tensor after attention.
"""
bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
q, k, v = qkv.chunk(3, dim=1)
scale = 1 / math.sqrt(math.sqrt(ch))
weight = th.einsum(
"bct,bcs->bts",
(q * scale).view(bs * self.n_heads, ch, length),
(k * scale).view(bs * self.n_heads, ch, length),
) # More stable with f16 than dividing afterwards
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
return a.reshape(bs, -1, length)
@staticmethod
def count_flops(model, _x, y):
return count_flops_attn(model, _x, y)
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,
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,
):
super().__init__()
if use_spatial_transformer:
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
if context_dim is not None:
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
if type(context_dim) == ListConfig:
context_dim = list(context_dim)
if num_heads_upsample == -1:
num_heads_upsample = num_heads
if num_heads == -1:
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
if num_head_channels == -1:
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
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
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:
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
self.input_blocks = nn.ModuleList(
[
TimestepEmbedSequential(
conv_nd(dims, in_channels, model_channels, 3, padding=1)
)
]
)
self._feature_size = model_channels
input_block_chans = [model_channels]
ch = model_channels
ds = 1
for level, mult in enumerate(channel_mult):
for _ in range(num_res_blocks):
layers = [
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=mult * model_channels,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = mult * model_channels
if ds in attention_resolutions:
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads,
num_head_channels=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
)
)
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
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
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=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
),
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=model_channels * mult,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = model_channels * mult
if ds in attention_resolutions:
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads_upsample,
num_head_channels=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
)
)
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, model_channels, out_channels, 3, padding=1)),
)
if self.predict_codebook_ids:
self.id_predictor = nn.Sequential(
normalization(ch),
conv_nd(dims, model_channels, n_embed, 1),
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
)
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, timesteps=None, context=None, y=None,**kwargs):
"""
Apply the model to an input batch.
:param x: an [N x C x ...] Tensor of inputs.
:param timesteps: a 1-D batch of timesteps.
:param context: conditioning plugged in via crossattn
: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"
hs = [] | t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) | 6 | 2023-10-26 10:28:26+00:00 | 8k |
ORI-Muchim/BEGANSing | AudioSR-Upsampling/audiosr/clap/open_clip/factory.py | [
{
"identifier": "CLAP",
"path": "AudioSR-Upsampling/audiosr/clap/open_clip/model.py",
"snippet": "class CLAP(nn.Module):\n def __init__(\n self,\n embed_dim: int,\n audio_cfg: CLAPAudioCfp,\n text_cfg: CLAPTextCfg,\n quick_gelu: bool = False,\n enable_fusion:... | import json
import logging
import os
import re
import torch
from copy import deepcopy
from pathlib import Path
from .model import CLAP, convert_weights_to_fp16
from .openai import load_openai_model
from .pretrained import get_pretrained_url, download_pretrained
from .transform import image_transform | 6,857 |
_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
def _natural_key(string_):
return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())]
def _rescan_model_configs():
global _MODEL_CONFIGS
config_ext = (".json",)
config_files = []
for config_path in _MODEL_CONFIG_PATHS:
if config_path.is_file() and config_path.suffix in config_ext:
config_files.append(config_path)
elif config_path.is_dir():
for ext in config_ext:
config_files.extend(config_path.glob(f"*{ext}"))
for cf in config_files:
if os.path.basename(cf)[0] == ".":
continue # Ignore hidden files
with open(cf, "r") as f:
model_cfg = json.load(f)
if all(a in model_cfg for a in ("embed_dim", "audio_cfg", "text_cfg")):
_MODEL_CONFIGS[cf.stem] = model_cfg
_MODEL_CONFIGS = {
k: v
for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))
}
_rescan_model_configs() # initial populate of model config registry
def load_state_dict(checkpoint_path: str, map_location="cpu", skip_params=True):
checkpoint = torch.load(checkpoint_path, map_location=map_location)
if isinstance(checkpoint, dict) and "state_dict" in checkpoint:
state_dict = checkpoint["state_dict"]
else:
state_dict = checkpoint
if skip_params:
if next(iter(state_dict.items()))[0].startswith("module"):
state_dict = {k[7:]: v for k, v in state_dict.items()}
# for k in state_dict:
# if k.startswith('transformer'):
# v = state_dict.pop(k)
# state_dict['text_branch.' + k[12:]] = v
return state_dict
def create_model(
amodel_name: str,
tmodel_name: str,
pretrained: str = "",
precision: str = "fp32",
device: torch.device = torch.device("cpu"),
jit: bool = False,
force_quick_gelu: bool = False,
openai_model_cache_dir: str = os.path.expanduser("~/.cache/clip"),
skip_params=True,
pretrained_audio: str = "",
pretrained_text: str = "",
enable_fusion: bool = False,
fusion_type: str = "None"
# pretrained_image: bool = False,
):
amodel_name = amodel_name.replace(
"/", "-"
) # for callers using old naming with / in ViT names
pretrained_orig = pretrained
pretrained = pretrained.lower()
if pretrained == "openai":
if amodel_name in _MODEL_CONFIGS:
logging.info(f"Loading {amodel_name} model config.")
model_cfg = deepcopy(_MODEL_CONFIGS[amodel_name])
else:
logging.error(
f"Model config for {amodel_name} not found; available models {list_models()}."
)
raise RuntimeError(f"Model config for {amodel_name} not found.")
logging.info(f"Loading pretrained ViT-B-16 text encoder from OpenAI.")
# Hard Code in model name
model_cfg["text_cfg"]["model_type"] = tmodel_name
|
_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"]
_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs
def _natural_key(string_):
return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())]
def _rescan_model_configs():
global _MODEL_CONFIGS
config_ext = (".json",)
config_files = []
for config_path in _MODEL_CONFIG_PATHS:
if config_path.is_file() and config_path.suffix in config_ext:
config_files.append(config_path)
elif config_path.is_dir():
for ext in config_ext:
config_files.extend(config_path.glob(f"*{ext}"))
for cf in config_files:
if os.path.basename(cf)[0] == ".":
continue # Ignore hidden files
with open(cf, "r") as f:
model_cfg = json.load(f)
if all(a in model_cfg for a in ("embed_dim", "audio_cfg", "text_cfg")):
_MODEL_CONFIGS[cf.stem] = model_cfg
_MODEL_CONFIGS = {
k: v
for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))
}
_rescan_model_configs() # initial populate of model config registry
def load_state_dict(checkpoint_path: str, map_location="cpu", skip_params=True):
checkpoint = torch.load(checkpoint_path, map_location=map_location)
if isinstance(checkpoint, dict) and "state_dict" in checkpoint:
state_dict = checkpoint["state_dict"]
else:
state_dict = checkpoint
if skip_params:
if next(iter(state_dict.items()))[0].startswith("module"):
state_dict = {k[7:]: v for k, v in state_dict.items()}
# for k in state_dict:
# if k.startswith('transformer'):
# v = state_dict.pop(k)
# state_dict['text_branch.' + k[12:]] = v
return state_dict
def create_model(
amodel_name: str,
tmodel_name: str,
pretrained: str = "",
precision: str = "fp32",
device: torch.device = torch.device("cpu"),
jit: bool = False,
force_quick_gelu: bool = False,
openai_model_cache_dir: str = os.path.expanduser("~/.cache/clip"),
skip_params=True,
pretrained_audio: str = "",
pretrained_text: str = "",
enable_fusion: bool = False,
fusion_type: str = "None"
# pretrained_image: bool = False,
):
amodel_name = amodel_name.replace(
"/", "-"
) # for callers using old naming with / in ViT names
pretrained_orig = pretrained
pretrained = pretrained.lower()
if pretrained == "openai":
if amodel_name in _MODEL_CONFIGS:
logging.info(f"Loading {amodel_name} model config.")
model_cfg = deepcopy(_MODEL_CONFIGS[amodel_name])
else:
logging.error(
f"Model config for {amodel_name} not found; available models {list_models()}."
)
raise RuntimeError(f"Model config for {amodel_name} not found.")
logging.info(f"Loading pretrained ViT-B-16 text encoder from OpenAI.")
# Hard Code in model name
model_cfg["text_cfg"]["model_type"] = tmodel_name | model = load_openai_model( | 2 | 2023-10-29 09:32:19+00:00 | 8k |
KenyonY/flaxkv | flaxkv/core.py | [
{
"identifier": "class_measure_time",
"path": "flaxkv/decorators.py",
"snippet": "def class_measure_time(logger=None, level=logging.INFO, prec=3):\r\n def decorate(func):\r\n \"\"\"Log the runtime of the decorated function.\"\"\"\r\n\r\n @wraps(func)\r\n def wrapper(self, *args, ... | import atexit
import threading
import time
import traceback
import numpy as np
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional, Type, TypeVar
from loguru import logger
from .decorators import class_measure_time
from .helper import SimpleQueue
from .log import setting_log
from .manager import DBManager
from .pack import check_pandas_type, decode, decode_key, encode
from httpx import Response
from litestar.exceptions import HTTPException
| 4,321 | """
Removes the key-value pair and returns the value.
Args:
key: The key to pop.
default: The default value to return if the key does not exist.
Returns:
value: The value associated with the key, or the default value.
"""
if key in self:
with self._buffer_lock:
self.delete_buffer_set.add(key)
self._buffered_count += 1
self._last_set_time = time.time()
if key in self.buffer_dict:
value = self.buffer_dict.pop(key)
if self._raw:
return decode(value)
else:
return value
else:
if self._cache_all_db:
value = self._cache_dict.pop(key)
else:
key = self._encode_key(key)
value = decode(self._static_view.get(key))
return value
else:
return default
def __contains__(self, key):
"""
Checks if a key exists in the buffer or database.
Args:
key: The key to check.
Returns:
bool: True if the key exists, False otherwise.
"""
with self._buffer_lock:
if key in self.buffer_dict:
return True
if key in self.delete_buffer_set:
return False
if self._cache_all_db:
return key in self._cache_dict
key = self._encode_key(key)
return (
self._static_view.get(key) is not None
) # self._static_view.get() return a binary value or None
def clear(self, wait=True):
"""
Clears the database and resets the buffer.
"""
self.close(write=False, wait=wait)
self._db_manager.rebuild_db()
self._init()
def destroy(self):
"""
Destroys the database by closing and deleting it.
"""
self.close(write=False)
self._unregister_auto_close()
self._db_manager.destroy()
self._logger.info(f"Destroyed database successfully.")
def __del__(self):
"""
Destructor for the BaseDBDict class. Closes the database before object deletion.
"""
self.close(write=True)
def __repr__(self):
return str(self.db_dict())
def __len__(self):
return self.stat()['count']
def close(self, write=True, wait=False):
"""
Closes the database and stops the background worker.
Args:
write (bool, optional): Whether to write the buffer to the database before closing. Defaults to True.
wait (bool, optional): Whether to wait for the background worker to finish. Defaults to False.
"""
self._close_background_worker(write=write, block=wait)
self._db_manager.close_static_view(self._static_view)
self._db_manager.close()
self._logger.info(f"Closed ({self._db_manager.db_type.upper()}) successfully")
def _get_status_info(
self,
return_key=False,
return_value=False,
return_buffer_dict=False,
return_view=True,
decode_raw=True,
):
static_view = None
buffer_keys_set, buffer_values_list = None, None
# shallow copy buffer data
with self._buffer_lock:
if return_view:
static_view = self._db_manager.new_static_view()
buffer_dict = self.buffer_dict.copy()
delete_buffer_set = self.delete_buffer_set.copy()
if self._raw and decode_raw:
| # Copyright (c) 2023 K.Y. 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.
from __future__ import annotations
if TYPE_CHECKING:
class BaseDBDict(ABC):
MAX_BUFFER_SIZE = 100 # unit: number of keys
COMMIT_TIME_INTERVAL = 10 * 60 # unit: second
_logger = logger
# Unused
@dataclass
class _enc_prefix:
str = b's'
int = b'i'
float = b'f'
bool = b'b'
list = b'l'
tuple = b't'
dict = b'd'
array = b'a'
def __init__(
self,
db_type,
root_path_or_url: str,
db_name: str,
rebuild=False,
raw=False,
cache=False,
**kwargs,
):
"""
Initializes the BaseDBDict class which provides a dictionary-like interface to a database.
Args:
db_type (str): Type of the database ("lmdb" or "leveldb" or "remote").
root_path_or_url (str): Root path or URL of the database.
rebuild (bool, optional): Whether to recreate the database. Defaults to False.
raw (bool): Only used by the server.
"""
log_level = kwargs.pop('log', None)
if log_level:
log_configs = setting_log(
level="DEBUG" if log_level is True else log_level,
stdout=kwargs.pop("stdout", False),
save_file=kwargs.pop('save_log', False),
)
log_ids = [logger.add(**log_conf) for log_conf in log_configs]
self._logger = logger.bind(flaxkv=True)
else:
logger.disable('flaxkv')
self._db_manager = DBManager(
db_type=db_type,
root_path_or_url=root_path_or_url,
db_name=db_name,
rebuild=rebuild,
**kwargs,
)
self._db_name = self._db_manager.db_name
self._raw = raw
self._cache_all_db = cache
self._register_auto_close()
self._init()
def _init(self):
self._static_view = self._db_manager.new_static_view()
self.buffer_dict = {}
self.delete_buffer_set = set()
self._buffered_count = 0
self._buffer_lock = threading.Lock()
self._stop_event = threading.Event()
self._last_set_time = None
self._write_complete = SimpleQueue(maxsize=1)
self._write_event = threading.Event()
self._latest_write_num = 0
self._write_queue = SimpleQueue(maxsize=1)
self._thread_running = True
self._thread = threading.Thread(target=self._background_worker)
self._thread.daemon = True
self._thread_write_monitor = threading.Thread(target=self._write_monitor)
self._thread_write_monitor.daemon = True
# Start the background worker
self._start()
self._cache_dict = {} # DB data that marked_delete has been deleted
if self._cache_all_db:
# load from db
self._pull_db_data_to_cache()
def _register_auto_close(self, func=None):
if func is None:
atexit.register(self.close)
else:
atexit.register(func)
def _unregister_auto_close(self, func=None):
if func is None:
atexit.unregister(self.close)
else:
atexit.unregister(func)
def _start(self):
"""
Starts the background worker thread.
"""
self._thread_running = True
self._thread.start()
self._thread_write_monitor.start()
@staticmethod
def _diff_buffer(a: dict, b: dict):
"""
Computes the difference between two buffers.
Find a dictionary containing key-value pairs that exist in `a` but not in `b`.
Args:
a (dict): The latest buffer.
b (dict): The older buffer.
Q: Why don't you need to worry about the key-value pair existing in 'b' but not in 'a'?
A: Because the absence of the key in 'a' indicates that the value has been deleted by the user,
and this information will be stored in the 'deleted_set'.
Returns:
dict: A dictionary containing key-value pairs that exist in `a` but not in `b`.
"""
result = {}
for key, value in a.items():
if key not in b:
result[key] = value
else:
if type(value) is not type(b[key]):
continue
if isinstance(value, np.ndarray):
if not np.array_equal(value, b[key]):
result[key] = value
elif check_pandas_type(value):
if not value.equals(b[key]):
result[key] = value
else:
if value != b[key]:
result[key] = value
return result
def _write_monitor(self):
self._logger.info("Write monitor started")
while not self._stop_event.is_set():
time.sleep(0.2)
if self._last_set_time is not None:
if (time.time() - self._last_set_time) >= 0.6:
self._logger.debug("Write monitor triggered")
self.write_immediately()
def _background_worker(self):
"""
Background worker function to periodically write buffer to the database.
"""
while self._thread_running or not self._write_queue.empty():
self._write_event.wait(timeout=self.COMMIT_TIME_INTERVAL)
self._write_event.clear()
if not self._write_queue.empty():
is_write = self._write_queue.get()
if is_write is False:
self._write_complete.put(True)
break
self._write_complete.clear()
try:
self._write_buffer_to_db(current_write_num=self._latest_write_num)
except:
# todo:
self._logger.warning(f"Write buffer to db failed. error")
traceback.print_exc()
self._write_complete.put(True)
def write_immediately(self, write=True, block=False):
"""
Triggers an immediate write of the buffer to the database.
"""
self._last_set_time = None
self._latest_write_num += 1
self._write_queue.put(write)
self._write_event.set()
if block:
self._write_complete.clear()
self._write_complete.get(block=True)
def wait_until_write_complete(self, timeout=None):
"""
Waits until the background worker thread has finished writing the buffer to the database.
"""
self._write_complete.get(block=True, timeout=timeout)
def _close_background_worker(self, write=True, block=False):
"""
Stops the background worker thread.
"""
self._stop_event.set()
self._latest_write_num += 1
self._thread_running = False
self.write_immediately(write=write, block=block)
self._thread.join(timeout=15)
self._thread_write_monitor.join(timeout=3)
if self._thread.is_alive():
self._logger.warning(
"Warning: Background thread did not finish in time. Some data might not be saved."
)
def _encode_key(self, key):
if self._raw:
return key
else:
return encode(key)
def _encode_value(self, value):
if self._raw:
return value
else:
return encode(value)
def get(self, key: Any, default=None):
"""
Retrieves the value associated with the given key.
Args:
key (Any): The key to retrieve.
default: The default value to set if the key does not exist.
Returns:
value: The value associated with the key, or None if the key is not found.
"""
with self._buffer_lock:
if key in self.delete_buffer_set:
return default
if key in self.buffer_dict:
return self.buffer_dict[key]
if self._cache_all_db:
return self._cache_dict.get(key, default)
key = self._encode_key(key)
value = self._static_view.get(key)
if value is None:
return default
return value if self._raw else decode(value)
def get_db_value(self, key: str):
"""
Directly retrieves the encoded value associated with the given key from the database.
Args:
key (str): The key to retrieve.
Returns:
value: The encoded value associated with the key.
"""
key = self._encode_key(key)
return self._static_view.get(key)
def get_batch(self, keys):
"""
Retrieves values for a batch of keys.
Args:
keys (list): A list of keys to retrieve.
Returns:
list: A list of values corresponding to the given keys.
"""
values = []
for key in keys:
if self.delete_buffer_set and key in self.delete_buffer_set:
values.append(None)
continue
if key in self.buffer_dict:
values.append(self.buffer_dict[key])
continue
if self._cache_all_db:
value = self._cache_dict.get(key)
else:
key = self._encode_key(key)
value = self._static_view.get(key)
if value is not None:
value = decode(value)
values.append(value)
return values
def _set(self, key, value):
"""
Sets the value for a given key in the buffer.
Args:
key: The key to set.
value: The value to associate with the key.
"""
with self._buffer_lock:
self.buffer_dict[key] = value
self.delete_buffer_set.discard(key)
self._buffered_count += 1
self._last_set_time = time.time()
# Trigger immediate write if buffer size exceeds MAX_BUFFER_SIZE
if self._buffered_count >= self.MAX_BUFFER_SIZE:
self._logger.debug("Trigger immediate write")
self._buffered_count = 0
self.write_immediately()
def setdefault(self, key, default=None):
"""
Retrieves the value for a given key. If the key does not exist, sets it to the default value.
Args:
key (Any): The key to retrieve.
default: The default value to set if the key does not exist.
Returns:
value: The value associated with the key.
"""
value = self.get(key)
if value is None:
self._set(key, default)
return default
return value
def update(self, d: dict):
"""
Updates the buffer with the given dictionary.
Args:
d (dict): A dictionary of key-value pairs to update.
"""
if not isinstance(d, dict):
raise ValueError("Input must be a dictionary.")
with self._buffer_lock:
for key, value in d.items():
if self._raw:
key, value = encode(key), encode(value)
self.buffer_dict[key] = value
self.delete_buffer_set.discard(key)
self._buffered_count += 1
self._last_set_time = time.time()
# Trigger immediate write if buffer size exceeds MAX_BUFFER_SIZE
if self._buffered_count >= self.MAX_BUFFER_SIZE:
self._logger.debug("Trigger immediate write")
self._buffered_count = 0
self.write_immediately()
# @class_measure_time()
def _write_buffer_to_db(
self,
current_write_num: int,
):
"""
Writes the current buffer to the database.
Args:
current_write_num (int): The current write operation number.
"""
with self._buffer_lock:
self._logger.debug(f"Trigger write")
self._logger.debug(f"{current_write_num=}")
if not (self.buffer_dict or self.delete_buffer_set):
self._logger.debug(
f"buffer is empty and delete_buffer_set is empty: {self._latest_write_num=} {current_write_num=}"
)
return
else:
# ensure atomicity (shallow copy)
buffer_dict_snapshot = self.buffer_dict.copy()
delete_buffer_set_snapshot = self.delete_buffer_set.copy()
cache_dict = self._cache_dict.copy()
# ensure atomicity
with self._db_manager.write() as wb:
try:
for key in delete_buffer_set_snapshot:
# delete from db
key = self._encode_key(key)
wb.delete(key)
for key, value in buffer_dict_snapshot.items():
# set key, value to cache
if self._cache_all_db:
cache_dict[key] = value
# set key, value to db
key, value = self._encode_key(key), self._encode_value(value)
wb.put(key, value)
except Exception as e:
traceback.print_exc()
self._logger.error(
f"Error writing to {self._db_manager.db_type}: {e}\n"
f"data will rollback"
)
raise
with self._buffer_lock:
self.delete_buffer_set = self.delete_buffer_set - delete_buffer_set_snapshot
self.buffer_dict = self._diff_buffer(self.buffer_dict, buffer_dict_snapshot)
self._cache_dict = cache_dict
self._db_manager.close_static_view(self._static_view)
self._static_view = self._db_manager.new_static_view()
self._logger.info(
f"write {self._db_manager.db_type.upper()} buffer to db successfully! "
f"current_num={current_write_num} latest_num={self._latest_write_num}"
)
def __iter__(self):
"""
Returns an iterator over the keys.
"""
return self.keys()
def __getitem__(self, key):
"""
Retrieves the value for a given key using the dictionary access syntax.
Args:
key: The key to retrieve.
Returns:
value: The value associated with the key.
"""
value = self.get(key, b'iamnone')
if isinstance(value, bytes) and value == b'iamnone':
raise KeyError(f"Key `{key}` not found in the database.")
return value
def __setitem__(self, key, value):
"""
Sets the value for a given key using the dictionary access syntax.
Args:
key: The key to set.
value: The value to associate with the key.
"""
self._set(key, value)
def __delitem__(self, key):
"""
Deletes a key-value pair using the dictionary access syntax.
Args:
key: The key to delete.
"""
if key in self:
with self._buffer_lock:
self.delete_buffer_set.add(key)
self._buffered_count += 1
self._last_set_time = time.time()
if key in self.buffer_dict:
del self.buffer_dict[key]
return
else:
if self._cache_all_db:
self._cache_dict.pop(key)
else:
raise KeyError(f"Key `{key}` not found in the database.")
def pop(self, key, default=None):
"""
Removes the key-value pair and returns the value.
Args:
key: The key to pop.
default: The default value to return if the key does not exist.
Returns:
value: The value associated with the key, or the default value.
"""
if key in self:
with self._buffer_lock:
self.delete_buffer_set.add(key)
self._buffered_count += 1
self._last_set_time = time.time()
if key in self.buffer_dict:
value = self.buffer_dict.pop(key)
if self._raw:
return decode(value)
else:
return value
else:
if self._cache_all_db:
value = self._cache_dict.pop(key)
else:
key = self._encode_key(key)
value = decode(self._static_view.get(key))
return value
else:
return default
def __contains__(self, key):
"""
Checks if a key exists in the buffer or database.
Args:
key: The key to check.
Returns:
bool: True if the key exists, False otherwise.
"""
with self._buffer_lock:
if key in self.buffer_dict:
return True
if key in self.delete_buffer_set:
return False
if self._cache_all_db:
return key in self._cache_dict
key = self._encode_key(key)
return (
self._static_view.get(key) is not None
) # self._static_view.get() return a binary value or None
def clear(self, wait=True):
"""
Clears the database and resets the buffer.
"""
self.close(write=False, wait=wait)
self._db_manager.rebuild_db()
self._init()
def destroy(self):
"""
Destroys the database by closing and deleting it.
"""
self.close(write=False)
self._unregister_auto_close()
self._db_manager.destroy()
self._logger.info(f"Destroyed database successfully.")
def __del__(self):
"""
Destructor for the BaseDBDict class. Closes the database before object deletion.
"""
self.close(write=True)
def __repr__(self):
return str(self.db_dict())
def __len__(self):
return self.stat()['count']
def close(self, write=True, wait=False):
"""
Closes the database and stops the background worker.
Args:
write (bool, optional): Whether to write the buffer to the database before closing. Defaults to True.
wait (bool, optional): Whether to wait for the background worker to finish. Defaults to False.
"""
self._close_background_worker(write=write, block=wait)
self._db_manager.close_static_view(self._static_view)
self._db_manager.close()
self._logger.info(f"Closed ({self._db_manager.db_type.upper()}) successfully")
def _get_status_info(
self,
return_key=False,
return_value=False,
return_buffer_dict=False,
return_view=True,
decode_raw=True,
):
static_view = None
buffer_keys_set, buffer_values_list = None, None
# shallow copy buffer data
with self._buffer_lock:
if return_view:
static_view = self._db_manager.new_static_view()
buffer_dict = self.buffer_dict.copy()
delete_buffer_set = self.delete_buffer_set.copy()
if self._raw and decode_raw:
| delete_buffer_set = {decode_key(i) for i in delete_buffer_set}
| 4 | 2023-10-27 15:53:02+00:00 | 8k |
hugoycj/light-hloc | lighthloc/matchers/lightglue.py | [
{
"identifier": "BaseModel",
"path": "lighthloc/utils/base_model.py",
"snippet": "class BaseModel(nn.Module, metaclass=ABCMeta):\n default_conf = {}\n required_inputs = []\n\n def __init__(self, conf):\n \"\"\"Perform some logic and call the _init method of the child model.\"\"\"\n ... | from ..utils.base_model import BaseModel
from .modules.lightglue import LightGlue as LightGlue_ | 3,692 |
class LightGlue(BaseModel):
default_conf = {
'features': 'superpoint',
'depth_confidence': 0.95,
'width_confidence': 0.99,
}
required_inputs = [
'image0', 'keypoints0', 'descriptors0',
'image1', 'keypoints1', 'descriptors1',
]
def _init(self, conf):
|
class LightGlue(BaseModel):
default_conf = {
'features': 'superpoint',
'depth_confidence': 0.95,
'width_confidence': 0.99,
}
required_inputs = [
'image0', 'keypoints0', 'descriptors0',
'image1', 'keypoints1', 'descriptors1',
]
def _init(self, conf): | self.net = LightGlue_(conf.pop('features'), **conf) | 0 | 2023-10-27 01:20:50+00:00 | 8k |
KUNLP/XAI_EvidenceExtraction | src/model/main_function_rnn.py | [
{
"identifier": "load_examples",
"path": "src/functions/utils.py",
"snippet": "def load_examples(args, tokenizer, evaluate=False, output_examples=False, do_predict=False, input_dict=None):\r\n '''\r\n\r\n :param args: 하이퍼 파라미터\r\n :param tokenizer: tokenization에 사용되는 tokenizer\r\n :param eva... | from torch.nn import functional as F
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from tqdm import tqdm
from nltk.translate.bleu_score import sentence_bleu
from transformers import (
AdamW,
get_linear_schedule_with_warmup
)
from src.functions.utils import load_examples, set_seed, to_list, load_input_data
from src.functions.processor_sent import SquadResult
from src.functions.evaluate_v1_0 import eval_during_train, f1_score
from src.functions.hotpotqa_metric import eval
from src.functions.squad_metric import (
compute_predictions_logits, restore_prediction, restore_prediction2
)
import os
import torch
import timeit
| 5,881 |
def train(args, model, tokenizer, logger):
# 학습에 사용하기 위한 dataset Load
examples, features = load_examples(args, tokenizer, evaluate=False, output_examples=True)
# optimization 최적화 schedule 을 위한 전체 training step 계산
t_total = len(features) // args.gradient_accumulation_steps * args.num_train_epochs
# Layer에 따른 가중치 decay 적용
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
]
# optimizer 및 scheduler 선언
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
)
# Training Step
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(features))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Train batch size per GPU = %d", args.train_batch_size)
logger.info(
" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size
* args.gradient_accumulation_steps)
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 1
tr_loss, logging_loss = 0.0, 0.0
# loss buffer 초기화
model.zero_grad()
|
def train(args, model, tokenizer, logger):
# 학습에 사용하기 위한 dataset Load
examples, features = load_examples(args, tokenizer, evaluate=False, output_examples=True)
# optimization 최적화 schedule 을 위한 전체 training step 계산
t_total = len(features) // args.gradient_accumulation_steps * args.num_train_epochs
# Layer에 따른 가중치 decay 적용
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": args.weight_decay,
},
{"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0},
]
# optimizer 및 scheduler 선언
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(
optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total
)
# Training Step
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(features))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Train batch size per GPU = %d", args.train_batch_size)
logger.info(
" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size
* args.gradient_accumulation_steps)
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 1
tr_loss, logging_loss = 0.0, 0.0
# loss buffer 초기화
model.zero_grad()
| set_seed(args)
| 1 | 2023-10-25 07:03:47+00:00 | 8k |
vlc-robot/polarnet | polarnet/dataloaders/pcd_keystep_dataset.py | [
{
"identifier": "get_assets_dir",
"path": "polarnet/utils/utils.py",
"snippet": "def get_assets_dir():\n return str(Path(polarnet.__file__).parent / \"assets\")"
},
{
"identifier": "pad_tensors",
"path": "polarnet/utils/ops.py",
"snippet": "def pad_tensors(tensors, lens=None, pad=0):\... | from typing import List, Dict, Optional
from PIL import Image
from scipy.spatial.transform import Rotation as R
from torch.utils.data import Dataset
from polarnet.utils.utils import get_assets_dir
from polarnet.utils.ops import pad_tensors, gen_seq_masks
from polarnet.dataloaders.keystep_dataset import KeystepDataset
from polarnet.config.constants import get_workspace
from polarnet.utils.coord_transforms import quaternion_to_discrete_euler
from torch.utils.data import DataLoader
import os
import numpy as np
import copy
import json
import open3d as o3d
import einops
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.transforms.functional as transforms_f
import lmdb
import msgpack
import msgpack_numpy
import time | 3,854 |
msgpack_numpy.patch()
def action_rot_quat_to_euler(action, resolution):
pos = action[:3]
quat = action[3:7]
open = action[7]
rot_disc = quaternion_to_discrete_euler(quat, resolution)
return np.concatenate([pos, rot_disc, [open]]).astype(np.float32)
def random_shift_pcd_and_action(pcd, action, shift_range, shift=None):
'''
pcd: (npoints, 3) or (T, 3, npoints)
action: (8) or (T, 8)
shift_range: float
'''
if shift is None:
shift = np.random.uniform(-shift_range, shift_range, size=(3, ))
if len(pcd.shape) == 2:
pcd = pcd + shift
action[:3] += shift
elif len(pcd.shape) == 3:
pcd = pcd + shift[None, :, None]
action[..., :3] += shift[None, :]
return pcd, action
def random_rotate_pcd_and_action(pcd, action, rot_range, rot=None):
'''
pcd: (npoints, 3) or (T, 3, npoints)
action: (8) or (T, 8)
shift_range: float
'''
if rot is None:
rot = np.random.uniform(-rot_range, rot_range)
r = R.from_euler('z', rot, degrees=True)
if len(pcd.shape) == 2:
pcd = r.apply(pcd)
action[:3] = r.apply(action[:3])
a_ori = R.from_quat(action[3:7])
a_new = r * a_ori
action[3:7] = a_new.as_quat()
elif len(pcd.shape) == 3:
pos_ori = einops.rearrange(pcd, 't c n -> (t n) c')
pos_new = r.apply(pos_ori)
pcd = einops.rearrange(pos_new, '(t n) c -> t c n', t=pcd.shape[0], n=pcd.shape[2])
action[..., :3] = r.apply(action[..., :3])
a_ori = R.from_quat(action[..., 3:7])
a_new = r * a_ori
action[..., 3:7] = a_new.as_quat()
return pcd, action
class PCDKeystepDataset(KeystepDataset):
def __init__(
self, data_dir, taskvars, instr_embed_file=None,
gripper_channel=False, camera_ids=None, cameras=..., use_instr_embed='none',
is_training=False, in_memory=False,
voxel_size=0.01, npoints=2048, use_color=True,
use_normal=True, use_height=True, pc_space='none',
color_drop=0, pc_center='point', pc_radius_norm=True, **kwargs
):
'''
- pc_space:
- none: no filter points
- workspace: filter points inside x_bbox, y_bbox, and z_bbox
- workspace_on_table: filter points inside 3 bboxes and above the table height
'''
super().__init__(
data_dir, taskvars, instr_embed_file, gripper_channel, camera_ids,
cameras, use_instr_embed, is_training, in_memory, **kwargs
)
self.voxel_size = voxel_size
self.npoints = npoints
self.use_normal = use_normal
self.use_height = use_height
self.use_color = use_color
self.color_drop = color_drop
self.pc_space = pc_space
self.pc_center = pc_center
self.pc_radius_norm = pc_radius_norm
self.rgb_augment = kwargs.get('rgb_augment', False)
self.max_steps_per_episode = kwargs.get('max_steps_per_episode', None)
self.add_pcd_noises = kwargs.get('add_pcd_noises', False)
self.pcd_noises_std = kwargs.get('pcd_noises_std', 0.01)
self.remove_pcd_outliers = kwargs.get('remove_pcd_outliers', False)
|
msgpack_numpy.patch()
def action_rot_quat_to_euler(action, resolution):
pos = action[:3]
quat = action[3:7]
open = action[7]
rot_disc = quaternion_to_discrete_euler(quat, resolution)
return np.concatenate([pos, rot_disc, [open]]).astype(np.float32)
def random_shift_pcd_and_action(pcd, action, shift_range, shift=None):
'''
pcd: (npoints, 3) or (T, 3, npoints)
action: (8) or (T, 8)
shift_range: float
'''
if shift is None:
shift = np.random.uniform(-shift_range, shift_range, size=(3, ))
if len(pcd.shape) == 2:
pcd = pcd + shift
action[:3] += shift
elif len(pcd.shape) == 3:
pcd = pcd + shift[None, :, None]
action[..., :3] += shift[None, :]
return pcd, action
def random_rotate_pcd_and_action(pcd, action, rot_range, rot=None):
'''
pcd: (npoints, 3) or (T, 3, npoints)
action: (8) or (T, 8)
shift_range: float
'''
if rot is None:
rot = np.random.uniform(-rot_range, rot_range)
r = R.from_euler('z', rot, degrees=True)
if len(pcd.shape) == 2:
pcd = r.apply(pcd)
action[:3] = r.apply(action[:3])
a_ori = R.from_quat(action[3:7])
a_new = r * a_ori
action[3:7] = a_new.as_quat()
elif len(pcd.shape) == 3:
pos_ori = einops.rearrange(pcd, 't c n -> (t n) c')
pos_new = r.apply(pos_ori)
pcd = einops.rearrange(pos_new, '(t n) c -> t c n', t=pcd.shape[0], n=pcd.shape[2])
action[..., :3] = r.apply(action[..., :3])
a_ori = R.from_quat(action[..., 3:7])
a_new = r * a_ori
action[..., 3:7] = a_new.as_quat()
return pcd, action
class PCDKeystepDataset(KeystepDataset):
def __init__(
self, data_dir, taskvars, instr_embed_file=None,
gripper_channel=False, camera_ids=None, cameras=..., use_instr_embed='none',
is_training=False, in_memory=False,
voxel_size=0.01, npoints=2048, use_color=True,
use_normal=True, use_height=True, pc_space='none',
color_drop=0, pc_center='point', pc_radius_norm=True, **kwargs
):
'''
- pc_space:
- none: no filter points
- workspace: filter points inside x_bbox, y_bbox, and z_bbox
- workspace_on_table: filter points inside 3 bboxes and above the table height
'''
super().__init__(
data_dir, taskvars, instr_embed_file, gripper_channel, camera_ids,
cameras, use_instr_embed, is_training, in_memory, **kwargs
)
self.voxel_size = voxel_size
self.npoints = npoints
self.use_normal = use_normal
self.use_height = use_height
self.use_color = use_color
self.color_drop = color_drop
self.pc_space = pc_space
self.pc_center = pc_center
self.pc_radius_norm = pc_radius_norm
self.rgb_augment = kwargs.get('rgb_augment', False)
self.max_steps_per_episode = kwargs.get('max_steps_per_episode', None)
self.add_pcd_noises = kwargs.get('add_pcd_noises', False)
self.pcd_noises_std = kwargs.get('pcd_noises_std', 0.01)
self.remove_pcd_outliers = kwargs.get('remove_pcd_outliers', False) | self.WORKSPACE = get_workspace(real_robot=kwargs.get('real_robot', False)) | 4 | 2023-10-29 21:41:09+00:00 | 8k |
stanleylsx/text_embedding | main.py | [
{
"identifier": "DataPrecess",
"path": "engines/data.py",
"snippet": "class DataPrecess:\n \"\"\"\n 文本处理\n \"\"\"\n\n def __init__(self, logger):\n super(DataPrecess, self).__init__()\n self.logger = logger\n self.max_sequence_length = configure['max_sequence_length']\n ... | from loguru import logger
from engines.data import DataPrecess
from config import use_cuda, cuda_device, mode, configure
from engines.train import Train
from engines.predict import Predictor
import random
import numpy as np
import os
import torch
import json | 4,693 | # -*- coding: utf-8 -*-
# @Time : 2023/10/27 22:05
# @Author : lishouxian
# @Email : gzlishouxian@gmail.com
# @File : main.py
# @Software: VSCode
def set_env(configure):
random.seed(configure.seed)
np.random.seed(configure.seed)
def fold_check(configure):
if configure['checkpoints_dir'] == '':
raise Exception('checkpoints_dir did not set...')
if not os.path.exists(configure['checkpoints_dir']):
print('checkpoints fold not found, creating...')
os.makedirs(configure['checkpoints_dir'])
if __name__ == '__main__':
log_name = './logs/' + mode + '.log'
logger.add(log_name, encoding='utf-8')
fold_check(configure)
if use_cuda:
if torch.cuda.is_available():
if cuda_device == -1:
device = torch.device('cuda')
else:
device = torch.device(f'cuda:{cuda_device}')
else:
raise ValueError(
"'use_cuda' set to True when cuda is unavailable."
" Make sure CUDA is available or set use_cuda=False."
)
else:
device = 'cpu'
logger.info(f'device: {device}')
logger.info(json.dumps(configure, indent=2, ensure_ascii=False))
data_manage = DataPrecess(logger)
if mode == 'train':
logger.info('stage: train')
| # -*- coding: utf-8 -*-
# @Time : 2023/10/27 22:05
# @Author : lishouxian
# @Email : gzlishouxian@gmail.com
# @File : main.py
# @Software: VSCode
def set_env(configure):
random.seed(configure.seed)
np.random.seed(configure.seed)
def fold_check(configure):
if configure['checkpoints_dir'] == '':
raise Exception('checkpoints_dir did not set...')
if not os.path.exists(configure['checkpoints_dir']):
print('checkpoints fold not found, creating...')
os.makedirs(configure['checkpoints_dir'])
if __name__ == '__main__':
log_name = './logs/' + mode + '.log'
logger.add(log_name, encoding='utf-8')
fold_check(configure)
if use_cuda:
if torch.cuda.is_available():
if cuda_device == -1:
device = torch.device('cuda')
else:
device = torch.device(f'cuda:{cuda_device}')
else:
raise ValueError(
"'use_cuda' set to True when cuda is unavailable."
" Make sure CUDA is available or set use_cuda=False."
)
else:
device = 'cpu'
logger.info(f'device: {device}')
logger.info(json.dumps(configure, indent=2, ensure_ascii=False))
data_manage = DataPrecess(logger)
if mode == 'train':
logger.info('stage: train') | trainer = Train(data_manage, device, logger) | 2 | 2023-10-27 07:47:02+00:00 | 8k |
akekic/causal-component-analysis | model/encoder.py | [
{
"identifier": "ParamMultiEnvCausalDistribution",
"path": "model/normalizing_flow/distribution.py",
"snippet": "class ParamMultiEnvCausalDistribution(MultiEnvCausalDistribution):\n \"\"\"\n Parametric multi-environment causal distribution.\n\n This class learns the parameters of the causal mec... | from typing import Optional
from torch import abs, det, log, Tensor
from .normalizing_flow import ParamMultiEnvCausalDistribution
from .normalizing_flow.distribution import NaiveMultiEnvCausalDistribution
from .normalizing_flow.nonparametric_distribution import (
NonparamMultiEnvCausalDistribution,
)
from .normalizing_flow.utils import make_spline_flows
import normflows as nf
import numpy as np
import torch
import torch.nn as nn | 4,909 |
class CauCAEncoder(nf.NormalizingFlow):
"""
CauCA encoder for multi-environment data.
The encoder maps from the observed data x to the latent space v_hat. The latent space is
assumed to have causal structure. The encoder is trained to maximize the likelihood of
the data under the causal model. x and v_hat are assumed to have the same dimension.
The encoder has two main components:
1. A causal base distribution q0 over the latent space. This encodes the latent
causal structure.
2. An unmixing function mapping from the observations to the latent space.
Attributes
----------
latent_dim: int
Dimension of the latent and observed variables.
adjacency_matrix: np.ndarray, shape (latent_dim, latent_dim)
Adjacency matrix of the latent causal graph.
intervention_targets_per_env: Tensor, shape (no_envs, latent_dim)
Which variables are intervened on in each environment.
fix_mechanisms: bool
Whether to fix some fixable mechanisms in the causal model. (See documentation of the
ParamMultiEnvCausalDistribution for details.) Default: False.
fix_all_intervention_targets: bool
Whether to fix all intervention targets in the causal model. (See documentation of the
ParamMultiEnvCausalDistribution for details.) Default: False.
nonparametric_base_distr: bool
Whether to use a nonparametric base distribution. If False, a parametric base distribution
assuming linear causal mechanisms is used. Default: False.
flows: Optional[list[nf.flows.Flow]]
List of normalizing flows to use for the unmixing function. Default: None.
q0: Optional[nf.distributions.BaseDistribution]
Base distribution over the latent space. Default: None.
K_cbn: int
Number of normalizing flows to use for the nonparametric base distribution. Default: 3.
net_hidden_dim_cbn: int
Hidden dimension of the neural network used in the nonparametric base distribution. Default: 128.
net_hidden_layers_cbn: int
Number of hidden layers in the neural network used in the nonparametric base distribution. Default: 3.
Methods
-------
multi_env_log_prob(x, e, intervention_targets) -> Tensor
Computes log probability of x in environment e.
forward(x) -> Tensor
Maps from the observed data x to the latent space v_hat.
"""
def __init__(
self,
latent_dim: int,
adjacency_matrix: np.ndarray,
intervention_targets_per_env: Optional[Tensor] = None,
fix_mechanisms: bool = False,
fix_all_intervention_targets: bool = False,
nonparametric_base_distr: bool = False,
flows: Optional[list[nf.flows.Flow]] = None,
q0: Optional[nf.distributions.BaseDistribution] = None,
K_cbn: int = 3,
net_hidden_dim_cbn: int = 128,
net_hidden_layers_cbn: int = 3,
) -> None:
self.latent_dim = latent_dim
self.adjacency_matrix = adjacency_matrix
self.intervention_targets_per_env = intervention_targets_per_env
self.fix_mechanisms = fix_mechanisms
self.fix_all_intervention_targets = fix_all_intervention_targets
self.nonparametric_base_distr = nonparametric_base_distr
self.K_cbn = K_cbn
self.net_hidden_dim_cbn = net_hidden_dim_cbn
self.net_hidden_layers_cbn = net_hidden_layers_cbn
if q0 is None:
if self.nonparametric_base_distr:
|
class CauCAEncoder(nf.NormalizingFlow):
"""
CauCA encoder for multi-environment data.
The encoder maps from the observed data x to the latent space v_hat. The latent space is
assumed to have causal structure. The encoder is trained to maximize the likelihood of
the data under the causal model. x and v_hat are assumed to have the same dimension.
The encoder has two main components:
1. A causal base distribution q0 over the latent space. This encodes the latent
causal structure.
2. An unmixing function mapping from the observations to the latent space.
Attributes
----------
latent_dim: int
Dimension of the latent and observed variables.
adjacency_matrix: np.ndarray, shape (latent_dim, latent_dim)
Adjacency matrix of the latent causal graph.
intervention_targets_per_env: Tensor, shape (no_envs, latent_dim)
Which variables are intervened on in each environment.
fix_mechanisms: bool
Whether to fix some fixable mechanisms in the causal model. (See documentation of the
ParamMultiEnvCausalDistribution for details.) Default: False.
fix_all_intervention_targets: bool
Whether to fix all intervention targets in the causal model. (See documentation of the
ParamMultiEnvCausalDistribution for details.) Default: False.
nonparametric_base_distr: bool
Whether to use a nonparametric base distribution. If False, a parametric base distribution
assuming linear causal mechanisms is used. Default: False.
flows: Optional[list[nf.flows.Flow]]
List of normalizing flows to use for the unmixing function. Default: None.
q0: Optional[nf.distributions.BaseDistribution]
Base distribution over the latent space. Default: None.
K_cbn: int
Number of normalizing flows to use for the nonparametric base distribution. Default: 3.
net_hidden_dim_cbn: int
Hidden dimension of the neural network used in the nonparametric base distribution. Default: 128.
net_hidden_layers_cbn: int
Number of hidden layers in the neural network used in the nonparametric base distribution. Default: 3.
Methods
-------
multi_env_log_prob(x, e, intervention_targets) -> Tensor
Computes log probability of x in environment e.
forward(x) -> Tensor
Maps from the observed data x to the latent space v_hat.
"""
def __init__(
self,
latent_dim: int,
adjacency_matrix: np.ndarray,
intervention_targets_per_env: Optional[Tensor] = None,
fix_mechanisms: bool = False,
fix_all_intervention_targets: bool = False,
nonparametric_base_distr: bool = False,
flows: Optional[list[nf.flows.Flow]] = None,
q0: Optional[nf.distributions.BaseDistribution] = None,
K_cbn: int = 3,
net_hidden_dim_cbn: int = 128,
net_hidden_layers_cbn: int = 3,
) -> None:
self.latent_dim = latent_dim
self.adjacency_matrix = adjacency_matrix
self.intervention_targets_per_env = intervention_targets_per_env
self.fix_mechanisms = fix_mechanisms
self.fix_all_intervention_targets = fix_all_intervention_targets
self.nonparametric_base_distr = nonparametric_base_distr
self.K_cbn = K_cbn
self.net_hidden_dim_cbn = net_hidden_dim_cbn
self.net_hidden_layers_cbn = net_hidden_layers_cbn
if q0 is None:
if self.nonparametric_base_distr: | q0 = NonparamMultiEnvCausalDistribution( | 2 | 2023-10-25 09:25:26+00:00 | 8k |
facebookresearch/verde | src/train/evaluator.py | [
{
"identifier": "TransformerModel",
"path": "src/train/model/transformer.py",
"snippet": "class TransformerModel(nn.Module):\n\n STORE_OUTPUTS = False\n\n def __init__(self, params, id2word, is_encoder, with_output):\n \"\"\"\n Transformer model (encoder or decoder).\n \"\"\"\... | import ast
import os
import time
import pickle
import numpy as np
import torch
from collections import OrderedDict
from logging import getLogger
from scipy import stats
from src.train.model import TransformerModel
from src.utils import to_cuda | 6,779 | except Exception as e:
logger.info(f'secret recovery: {self.secret_recovery}')
logger.info(f'Exception when saving secret_recovery details: {e}')
class Evaluator(object):
def __init__(self, trainer, test_dataloader):
"""
Initialize evaluator.
"""
self.trainer = trainer
self.iterator = test_dataloader
self.modules = trainer.modules
self.params = trainer.params
self.env = trainer.env
self.secret_check = SecretCheck(trainer, test_dataloader.dataset)
def run_all_evals(self):
"""
Run all evaluations.
"""
scores = OrderedDict({"epoch": self.trainer.epoch})
with torch.no_grad():
encoder = (
self.modules["encoder"].module
if self.params.multi_gpu
else self.modules["encoder"]
)
decoder = (
self.modules["decoder"].module
if self.params.multi_gpu and hasattr(self.modules["decoder"], 'module')
else self.modules["decoder"]
)
encoder.eval()
decoder.eval()
self.run_distinguisher(encoder, decoder)
self.run_direct_recovery(encoder, decoder)
self.recover_secret_from_crossattention(encoder, decoder, scores) # cross attention (+ circular regression)
self.hybrid()
self.secret_check.store_results(self.params.dump_path, self.trainer.epoch)
return scores
def ordered_idx_from_scores(self, secret_scores):
''' Takes bit-wise scores (length N) and return sorted list<(idx, score)> and sorted list<idx>. '''
idx_with_scores = list(enumerate(secret_scores)) # a list of (idx, score)
sorted_idx_by_scores = sorted(idx_with_scores, key=lambda item: item[1], reverse=True) # descending
return sorted_idx_by_scores, [t[0] for t in sorted_idx_by_scores]
def hybrid(self):
'''
Hybrid secret recovery that combines direct secret recovery, distinguisher and CA
'''
methods_dict = {
'direct': self.direct_results,
'distinguisher': self.distinguisher_results,
'ca': self.ca_results,
}
combos = [['direct', 'ca'], ['direct', 'distinguisher'], ['ca', 'distinguisher'], ['direct', 'ca', 'distinguisher']]
for combo in combos:
logger.info(f'Hybrid: {", ".join(combo)}')
self.hybrid_sub([methods_dict[m] for m in combo], ", ".join(combo))
def hybrid_sub(self, methods, combo_name):
for results in methods:
if max(results) == 0: # the scores are non-negative. Hybrid on this combo is useless.
return None
sum_and_max = np.zeros((4,self.params.N))
for results in methods:
# Normalized, sum and max
sum_and_max[0] += results/max(results)
sum_and_max[1] = np.max((sum_and_max[1], results/max(results)), axis=0)
# Ranking, sum and max
rank = stats.rankdata(results, method='min')
sum_and_max[2] += rank
sum_and_max[3] = np.max((sum_and_max[3], rank), axis=0)
for i, name in enumerate(['Sum Normalized', 'Max Normalized', 'Sum Rank', 'Max Rank']):
idx_w_scores, indices = self.ordered_idx_from_scores(sum_and_max[i])
self.secret_check.match_secret_iter(indices, idx_w_scores, f'{combo_name} - {name}')
########################################################
# CODE TO RUN DIRECT SECRET RECOVERY AND DISTINGUISHER #
########################################################
def run_beam_generation(self, x1_, len1_, encoder, decoder):
# Run beam generation to get output.
encoded = encoder("fwd", x=x1_, lengths=len1_, causal=False)
_, _, generations= decoder.generate_beam(encoded.transpose(0, 1), len1_,
beam_size=self.params.beam_size,
length_penalty=self.params.beam_length_penalty,
early_stopping=self.params.beam_early_stopping,
max_len=self.params.max_output_len)
beam_log = []
for i in range(len(generations)):
sorted_hyp = sorted(generations[i].hyp, key=lambda x: x[0], reverse=True)
if len(sorted_hyp) == 0:
beam_log.append(0)
else:
_, hyp = sorted_hyp[0]
output = [self.trainer.env.id2word[wid] for wid in hyp[1:].tolist()]
try:
beam_log.append(self.env.output_encoder.decode(output)[0])
except Exception as e:
beam_log.append(-1)
return beam_log
def predict_outputs(self, A, encoder, decoder, intermediate=False):
'''
if intermediate is False then output integers
if intermediate is True then output distributions
'''
preds = []
# Encodes data in format expected by model
encA = self.env.input_encoder.encode(A)
encA = [torch.LongTensor([self.env.word2id[w] for w in seq]) for seq in encA]
for k in range(0, len(encA), self.params.batch_size):
x = encA[k:k+self.params.batch_size]
x1, len1 = self.env.batch_sequences(x)
| # 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.
logger = getLogger()
class SecretCheck(object):
def __init__(self, trainer, dataset):
self.trainer = trainer
self.params = trainer.params
self.orig_A, self.orig_b = dataset.orig_A, dataset.orig_b
self.secret_recovery = { 'success': [] }
def match_secret(self, guess, method_name):
'''
Takes an int or bool (binary) list or array as secret guess and check against the original tiny dataset.
'''
guess = np.array(guess).astype(int)
if self.params.secret_type in ['gaussian', 'binomial']:
# only check if nonzeros are identified for gaussian and binomial secrets
matched = np.all((self.params.secret != 0) == (guess != 0))
elif self.orig_A is None: # Old data, original dataset not available. Directly check the secret.
matched = np.all(self.params.secret == guess)
else:
err_pred = (self.orig_A @ guess - self.orig_b) % self.params.Q
err_pred[err_pred > self.params.Q // 2] -= self.params.Q
matched = np.std(err_pred) < 2*self.params.sigma
if matched:
logger.info(f'{method_name}: all bits in secret have been recovered!')
if method_name not in self.secret_recovery['success']:
self.secret_recovery['success'].append(method_name)
self.trainer.secret_match = True
return True
def match_secret_iter(self, idx_list, sorted_idx_with_scores, method_name):
'''
Takes a list of indices sorted by scores (descending, high score means more likely to be 1)
and iteratively matches the secret.
'''
self.secret_recovery[method_name] = sorted_idx_with_scores or idx_list
guess = np.zeros(self.params.N)
for i in range(min(self.params.N // 5, len(idx_list))): # sparse assumption
guess[idx_list[i]] = 1
if self.match_secret(guess, method_name):
return True
logger.info(f'{method_name}: secret not predicted.')
return False
def add_log(self, k, v):
self.secret_recovery[k] = v
def store_results(self, path, epoch):
try:
pickle.dump(self.secret_recovery, open(os.path.join(path, f'secret_recovery_{epoch}.pkl'), 'wb'))
except Exception as e:
logger.info(f'secret recovery: {self.secret_recovery}')
logger.info(f'Exception when saving secret_recovery details: {e}')
class Evaluator(object):
def __init__(self, trainer, test_dataloader):
"""
Initialize evaluator.
"""
self.trainer = trainer
self.iterator = test_dataloader
self.modules = trainer.modules
self.params = trainer.params
self.env = trainer.env
self.secret_check = SecretCheck(trainer, test_dataloader.dataset)
def run_all_evals(self):
"""
Run all evaluations.
"""
scores = OrderedDict({"epoch": self.trainer.epoch})
with torch.no_grad():
encoder = (
self.modules["encoder"].module
if self.params.multi_gpu
else self.modules["encoder"]
)
decoder = (
self.modules["decoder"].module
if self.params.multi_gpu and hasattr(self.modules["decoder"], 'module')
else self.modules["decoder"]
)
encoder.eval()
decoder.eval()
self.run_distinguisher(encoder, decoder)
self.run_direct_recovery(encoder, decoder)
self.recover_secret_from_crossattention(encoder, decoder, scores) # cross attention (+ circular regression)
self.hybrid()
self.secret_check.store_results(self.params.dump_path, self.trainer.epoch)
return scores
def ordered_idx_from_scores(self, secret_scores):
''' Takes bit-wise scores (length N) and return sorted list<(idx, score)> and sorted list<idx>. '''
idx_with_scores = list(enumerate(secret_scores)) # a list of (idx, score)
sorted_idx_by_scores = sorted(idx_with_scores, key=lambda item: item[1], reverse=True) # descending
return sorted_idx_by_scores, [t[0] for t in sorted_idx_by_scores]
def hybrid(self):
'''
Hybrid secret recovery that combines direct secret recovery, distinguisher and CA
'''
methods_dict = {
'direct': self.direct_results,
'distinguisher': self.distinguisher_results,
'ca': self.ca_results,
}
combos = [['direct', 'ca'], ['direct', 'distinguisher'], ['ca', 'distinguisher'], ['direct', 'ca', 'distinguisher']]
for combo in combos:
logger.info(f'Hybrid: {", ".join(combo)}')
self.hybrid_sub([methods_dict[m] for m in combo], ", ".join(combo))
def hybrid_sub(self, methods, combo_name):
for results in methods:
if max(results) == 0: # the scores are non-negative. Hybrid on this combo is useless.
return None
sum_and_max = np.zeros((4,self.params.N))
for results in methods:
# Normalized, sum and max
sum_and_max[0] += results/max(results)
sum_and_max[1] = np.max((sum_and_max[1], results/max(results)), axis=0)
# Ranking, sum and max
rank = stats.rankdata(results, method='min')
sum_and_max[2] += rank
sum_and_max[3] = np.max((sum_and_max[3], rank), axis=0)
for i, name in enumerate(['Sum Normalized', 'Max Normalized', 'Sum Rank', 'Max Rank']):
idx_w_scores, indices = self.ordered_idx_from_scores(sum_and_max[i])
self.secret_check.match_secret_iter(indices, idx_w_scores, f'{combo_name} - {name}')
########################################################
# CODE TO RUN DIRECT SECRET RECOVERY AND DISTINGUISHER #
########################################################
def run_beam_generation(self, x1_, len1_, encoder, decoder):
# Run beam generation to get output.
encoded = encoder("fwd", x=x1_, lengths=len1_, causal=False)
_, _, generations= decoder.generate_beam(encoded.transpose(0, 1), len1_,
beam_size=self.params.beam_size,
length_penalty=self.params.beam_length_penalty,
early_stopping=self.params.beam_early_stopping,
max_len=self.params.max_output_len)
beam_log = []
for i in range(len(generations)):
sorted_hyp = sorted(generations[i].hyp, key=lambda x: x[0], reverse=True)
if len(sorted_hyp) == 0:
beam_log.append(0)
else:
_, hyp = sorted_hyp[0]
output = [self.trainer.env.id2word[wid] for wid in hyp[1:].tolist()]
try:
beam_log.append(self.env.output_encoder.decode(output)[0])
except Exception as e:
beam_log.append(-1)
return beam_log
def predict_outputs(self, A, encoder, decoder, intermediate=False):
'''
if intermediate is False then output integers
if intermediate is True then output distributions
'''
preds = []
# Encodes data in format expected by model
encA = self.env.input_encoder.encode(A)
encA = [torch.LongTensor([self.env.word2id[w] for w in seq]) for seq in encA]
for k in range(0, len(encA), self.params.batch_size):
x = encA[k:k+self.params.batch_size]
x1, len1 = self.env.batch_sequences(x) | x1_, len1_ = to_cuda(x1, len1) | 1 | 2023-10-30 17:53:57+00:00 | 8k |
andriioreshk1118/python-second | linear_algebra/src/test_linear_algebra.py | [
{
"identifier": "Matrix",
"path": "linear_algebra/src/lib.py",
"snippet": "class Matrix:\n \"\"\"\n class: Matrix\n This class represents an arbitrary matrix.\n\n Overview of the methods:\n\n __init__():\n __str__(): returns a string representation\n __add__(other: Matri... | import unittest
import pytest
from .lib import (
Matrix,
Vector,
axpy,
square_zero_matrix,
unit_basis_vector,
zero_vector,
) | 4,266 | """
Created on Mon Feb 26 15:40:07 2018
@author: Christian Bender
@license: MIT-license
This file contains the test-suite for the linear algebra library.
"""
class Test(unittest.TestCase):
def test_component(self) -> None:
"""
test for method component()
"""
x = Vector([1, 2, 3])
assert x.component(0) == 1
assert x.component(2) == 3
_ = Vector()
def test_str(self) -> None:
"""
test for method toString()
"""
x = Vector([0, 0, 0, 0, 0, 1])
assert str(x) == "(0,0,0,0,0,1)"
def test_size(self) -> None:
"""
test for method size()
"""
x = Vector([1, 2, 3, 4])
assert len(x) == 4
def test_euclidean_length(self) -> None:
"""
test for method euclidean_length()
"""
x = Vector([1, 2])
y = Vector([1, 2, 3, 4, 5])
z = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
w = Vector([1, -1, 1, -1, 2, -3, 4, -5])
assert x.euclidean_length() == pytest.approx(2.236, abs=1e-3)
assert y.euclidean_length() == pytest.approx(7.416, abs=1e-3)
assert z.euclidean_length() == 0
assert w.euclidean_length() == pytest.approx(7.616, abs=1e-3)
def test_add(self) -> None:
"""
test for + operator
"""
x = Vector([1, 2, 3])
y = Vector([1, 1, 1])
assert (x + y).component(0) == 2
assert (x + y).component(1) == 3
assert (x + y).component(2) == 4
def test_sub(self) -> None:
"""
test for - operator
"""
x = Vector([1, 2, 3])
y = Vector([1, 1, 1])
assert (x - y).component(0) == 0
assert (x - y).component(1) == 1
assert (x - y).component(2) == 2
def test_mul(self) -> None:
"""
test for * operator
"""
x = Vector([1, 2, 3])
a = Vector([2, -1, 4]) # for test of dot product
b = Vector([1, -2, -1])
assert str(x * 3.0) == "(3.0,6.0,9.0)"
assert a * b == 0
def test_zero_vector(self) -> None:
"""
test for global function zero_vector()
"""
assert str(zero_vector(10)).count("0") == 10
def test_unit_basis_vector(self) -> None:
"""
test for global function unit_basis_vector()
"""
assert str(unit_basis_vector(3, 1)) == "(0,1,0)"
def test_axpy(self) -> None:
"""
test for global function axpy() (operation)
"""
x = Vector([1, 2, 3])
y = Vector([1, 0, 1])
| """
Created on Mon Feb 26 15:40:07 2018
@author: Christian Bender
@license: MIT-license
This file contains the test-suite for the linear algebra library.
"""
class Test(unittest.TestCase):
def test_component(self) -> None:
"""
test for method component()
"""
x = Vector([1, 2, 3])
assert x.component(0) == 1
assert x.component(2) == 3
_ = Vector()
def test_str(self) -> None:
"""
test for method toString()
"""
x = Vector([0, 0, 0, 0, 0, 1])
assert str(x) == "(0,0,0,0,0,1)"
def test_size(self) -> None:
"""
test for method size()
"""
x = Vector([1, 2, 3, 4])
assert len(x) == 4
def test_euclidean_length(self) -> None:
"""
test for method euclidean_length()
"""
x = Vector([1, 2])
y = Vector([1, 2, 3, 4, 5])
z = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
w = Vector([1, -1, 1, -1, 2, -3, 4, -5])
assert x.euclidean_length() == pytest.approx(2.236, abs=1e-3)
assert y.euclidean_length() == pytest.approx(7.416, abs=1e-3)
assert z.euclidean_length() == 0
assert w.euclidean_length() == pytest.approx(7.616, abs=1e-3)
def test_add(self) -> None:
"""
test for + operator
"""
x = Vector([1, 2, 3])
y = Vector([1, 1, 1])
assert (x + y).component(0) == 2
assert (x + y).component(1) == 3
assert (x + y).component(2) == 4
def test_sub(self) -> None:
"""
test for - operator
"""
x = Vector([1, 2, 3])
y = Vector([1, 1, 1])
assert (x - y).component(0) == 0
assert (x - y).component(1) == 1
assert (x - y).component(2) == 2
def test_mul(self) -> None:
"""
test for * operator
"""
x = Vector([1, 2, 3])
a = Vector([2, -1, 4]) # for test of dot product
b = Vector([1, -2, -1])
assert str(x * 3.0) == "(3.0,6.0,9.0)"
assert a * b == 0
def test_zero_vector(self) -> None:
"""
test for global function zero_vector()
"""
assert str(zero_vector(10)).count("0") == 10
def test_unit_basis_vector(self) -> None:
"""
test for global function unit_basis_vector()
"""
assert str(unit_basis_vector(3, 1)) == "(0,1,0)"
def test_axpy(self) -> None:
"""
test for global function axpy() (operation)
"""
x = Vector([1, 2, 3])
y = Vector([1, 0, 1]) | assert str(axpy(2, x, y)) == "(3,4,7)" | 2 | 2023-10-26 12:00:23+00:00 | 8k |
Doubling-Open-Source/git_calculator | tests/test_git_obj.py | [
{
"identifier": "ToyRepoCreator",
"path": "src/util/toy_repo.py",
"snippet": "class ToyRepoCreator:\n \"\"\"\n A utility class for creating and managing a Git repository with custom commit patterns.\n\n This class allows for initializing a new Git repository in a specified directory \n and c... | import pytest
import tempfile
import logging
import subprocess
import os
from src.util.toy_repo import ToyRepoCreator
from src.git_ir import all_objects, git_obj, git_log
from src.util.git_util import git_run | 3,850 |
@pytest.fixture(scope="function")
def setup_logging():
logging.basicConfig(
level=logging.DEBUG, # Set the desired log level
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
@pytest.fixture(scope="function")
def temp_directory():
# Create a temporary directory for each test function
temp_dir = tempfile.mkdtemp()
yield temp_dir # Provide the temporary directory as a fixture
# Clean up: remove the temporary directory and its contents
subprocess.run(['rm', '-rf', temp_dir])
def test_new_object_creation(temp_directory):
"""
Test the __new__ method to ensure no duplicate objects are created for the same SHA.
"""
trc = ToyRepoCreator(temp_directory)
even_intervals = [7 * i for i in range(12)] # Weekly intervals
trc.create_custom_commits(even_intervals)
res = git_run('log')
def test_all_objects(temp_directory):
"""
Test the all_objects() method.
"""
trc = ToyRepoCreator(temp_directory)
even_intervals = [7 * i for i in range(12)] # Weekly intervals
trc.create_custom_commits(even_intervals)
|
@pytest.fixture(scope="function")
def setup_logging():
logging.basicConfig(
level=logging.DEBUG, # Set the desired log level
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
@pytest.fixture(scope="function")
def temp_directory():
# Create a temporary directory for each test function
temp_dir = tempfile.mkdtemp()
yield temp_dir # Provide the temporary directory as a fixture
# Clean up: remove the temporary directory and its contents
subprocess.run(['rm', '-rf', temp_dir])
def test_new_object_creation(temp_directory):
"""
Test the __new__ method to ensure no duplicate objects are created for the same SHA.
"""
trc = ToyRepoCreator(temp_directory)
even_intervals = [7 * i for i in range(12)] # Weekly intervals
trc.create_custom_commits(even_intervals)
res = git_run('log')
def test_all_objects(temp_directory):
"""
Test the all_objects() method.
"""
trc = ToyRepoCreator(temp_directory)
even_intervals = [7 * i for i in range(12)] # Weekly intervals
trc.create_custom_commits(even_intervals) | result = all_objects() | 1 | 2023-10-28 13:43:03+00:00 | 8k |
sisl/SceneInformer | sceneinformer/model/model.py | [
{
"identifier": "Encoder",
"path": "sceneinformer/model/encoder.py",
"snippet": "class Encoder(pl.LightningModule):\n def __init__(self, config: dict) -> None:\n super(Encoder, self).__init__()\n self.config = config\n\n self.hidden_dim = config['d_model']\n\n if 'point_en... | import torch
import lightning.pytorch as pl
from sceneinformer.model.encoder import Encoder
from sceneinformer.model.decoder import Decoder
from sceneinformer.model.loss import compute_loss | 3,733 |
class SceneInformer(pl.LightningModule):
def __init__(self, config):
super(SceneInformer, self).__init__()
config.decoder.num_modes = config.k_modes
config.decoder.predictor.out_dim = config.k_modes * (config.n_future_steps) * config.step_dim
config.decoder.classifier_traj.out_dim = config.k_modes
self.config = config
self.learning_rate = config.learning_rate
self.loss_config = config.loss
self.encoder = Encoder(config.encoder)
self.decoder = Decoder(config.decoder)
self.decoder.step_dim = config.step_dim
self.batch = None
def forward(self, sample):
encoder_dict = self.encoder(sample)
decoder_dict = self.decoder(sample['anchors'], encoder_dict['encoded_obs'], encoder_dict['src_key_padding_mask'])
return decoder_dict
def training_step(self, batch, batch_idx):
prediction_dict = self(batch)
|
class SceneInformer(pl.LightningModule):
def __init__(self, config):
super(SceneInformer, self).__init__()
config.decoder.num_modes = config.k_modes
config.decoder.predictor.out_dim = config.k_modes * (config.n_future_steps) * config.step_dim
config.decoder.classifier_traj.out_dim = config.k_modes
self.config = config
self.learning_rate = config.learning_rate
self.loss_config = config.loss
self.encoder = Encoder(config.encoder)
self.decoder = Decoder(config.decoder)
self.decoder.step_dim = config.step_dim
self.batch = None
def forward(self, sample):
encoder_dict = self.encoder(sample)
decoder_dict = self.decoder(sample['anchors'], encoder_dict['encoded_obs'], encoder_dict['src_key_padding_mask'])
return decoder_dict
def training_step(self, batch, batch_idx):
prediction_dict = self(batch) | loss, metrics = compute_loss(prediction_dict, batch, self.loss_config) | 2 | 2023-10-31 08:08:26+00:00 | 8k |
artificial-scientist-lab/XLuminA | xlumina/vectorized_optics.py | [
{
"identifier": "profile",
"path": "xlumina/toolbox.py",
"snippet": "def profile(data_2d, x, y, point1='', point2=''):\n \"\"\"\n Determine profile for a given input without using interpolation.\n \n Parameters:\n data_2d (jnp.array): Input 2D array from which extract the profile.\n ... | import numpy as np
import jax.numpy as jnp
import matplotlib.pyplot as plt
import time
from jax import jit, vmap, config
from functools import partial
from .toolbox import profile
from .wave_optics import build_grid, RS_propagation_jit, build_CZT_grid, CZT_jit, CZT_for_high_NA_jit | 5,598 | quality_factor = dr_ideal / dr_real
# Stack the input field in a (3, N, N) shape and pass to jit.
E_in = jnp.stack([self.Ex, self.Ey, Ez], axis=0)
E_out = VRS_propagation_jit(E_in, z, nx, ny, dx, dy, Xext, Yext, self.k)
E_out = jnp.moveaxis(E_out, [0, 1, 2], [2, 0, 1])
# Define the output light:
light_out = VectorizedLight(self.x, self.y, self.wavelength)
light_out.Ex = E_out[:, :, 0]
light_out.Ey = E_out[:, :, 1]
light_out.Ez = E_out[:, :, 2]
print("Time taken to perform one VRS propagation (in seconds):", time.perf_counter() - tic)
return light_out, quality_factor
def get_VRS_minimum_z(self, n=1, quality_factor=1):
"""
Given a quality factor, determines the minimum available (trustworthy) distance for VRS_propagation().
[Ref 1: Laser Phys. Lett., 10(6), 065004 (2013)].
Parameters:
n (float): refraction index of the surrounding medium.
quality_factor (int): Defaults to 1.
Returns the minimum distance z (in microns) necessary to achieve qualities larger than quality_factor.
>> Diffractio-adapted function (https://pypi.org/project/diffractio/) <<
"""
# Check sampling
range_x = self.x[-1] - self.x[0]
range_y = self.y[-1] - self.y[0]
num_x = jnp.size(self.x)
num_y = jnp.size(self.y)
dx = range_x / num_x
dy = range_y / num_y
# Delta rho
dr_real = jnp.sqrt(dx**2 + dy**2)
# Rho
rmax = jnp.sqrt(range_x**2 + range_y**2)
factor = (((quality_factor * dr_real + rmax)**2 - (self.wavelength / n)**2 - rmax**2) / (2 * self.wavelength / n))**2 - rmax**2
if factor > 0:
z_min = jnp.sqrt(factor)
else:
z_min = 0
return print("Minimum distance to propagate (in um):", z_min)
def VCZT(self, z, xout, yout):
"""
Vectorial version of the Chirped z-transform propagation - efficient RS diffraction using the Bluestein method.
Useful for imaging light in the focal plane: allows high resolution zoom in z-plane.
[Ref] Hu, Y., et al. Light Sci Appl 9, 119 (2020).
Parameters:
z (float): Propagation distance.
xout (jnp.array): Array with the x-positions for the output plane.
Returns VectorizedLight object after propagation.
"""
tic = time.perf_counter()
if xout is None:
xout = self.x
if yout is None:
yout = self.y
# Define r:
r = jnp.sqrt(self.X ** 2 + self.Y ** 2 + z ** 2)
# Set the value of Ez:
Ez = jnp.array((self.Ex * self.X / r + self.Ey * self.Y / r) * z / r)
# Define main set of parameters
nx, ny, dx, dy, Xout, Yout, Dm, fy_1, fy_2, fx_1, fx_2 = build_CZT_grid(z, self.wavelength, self.x, self.y, xout, yout)
# Stack the input field in a (3, N, N) shape and pass to jit.
E_in = jnp.stack([self.Ex, self.Ey, Ez], axis=0)
E_out = VCZT_jit(E_in, z, self.wavelength, self.k, nx, ny, dx, dy, Xout, Yout, self.X, self.Y, Dm, fy_1, fy_2, fx_1, fx_2)
E_out = jnp.moveaxis(E_out, [0, 1, 2], [2, 0, 1])
# Define the output light:
light_out = VectorizedLight(xout, yout, self.wavelength)
light_out.Ex = E_out[:, :, 0]
light_out.Ey = E_out[:, :, 1]
light_out.Ez = E_out[:, :, 2]
print("Time taken to perform one VCZT propagation (in seconds):", time.perf_counter() - tic)
return light_out
@partial(jit, static_argnums=(2, 3, 4, 5, 8))
def VRS_propagation_jit(input_field, z, nx, ny, dx, dy, Xext, Yext, k):
"""[From VRS_propagation]: JIT function that vectorizes the propagation and calls RS_propagation_jit from wave_optics.py."""
# Input field has (3, N, N) shape
vectorized_RS_propagation = vmap(RS_propagation_jit,
in_axes=(0, None, None, None, None, None, None, None, None))
# Call the vectorized function
E_out = vectorized_RS_propagation(input_field, z, nx, ny, dx, dy, Xext, Yext, k)
return E_out # (3, N, N) -> ([Ex, Ey, Ez], N, N)
def VCZT_jit(field, z, wavelength, k, nx, ny, dx, dy, Xout, Yout, X, Y, Dm, fy_1, fy_2, fx_1, fx_2):
"""[From CZT]: JIT function that vectorizes the propagation and calls CZT_jit from wave_optics.py."""
# Input field has (3, N, N) shape
vectorized_CZT = vmap(CZT_jit,
in_axes=(0, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None))
# Call the vectorized function
E_out = vectorized_CZT(field, z, wavelength, k, nx, ny, dx, dy, Xout, Yout, X, Y, Dm, fy_1, fy_2, fx_1, fx_2)
return E_out # (3, N, N) -> ([Ex, Ey, Ez], N, N)
def vectorized_CZT_for_high_NA(field, nx, ny, Dm, fy_1, fy_2, fx_1, fx_2):
"""[From VCZT_objective_lens - in optical_elements.py]: JIT function that vectorizes the propagation and calls CZT_for_high_NA_jit from wave_optics.py."""
# Input field has (3, N, N) shape
|
# Comment this line if float32 is enough precision for you.
config.update("jax_enable_x64", True)
"""
Module for vectorized optical fields:
- VectorizedLight:
- draw
- draw_intensity_profile
- VRS_propagation
- get_VRS_minimum_z
- VCZT
- VRS_propagation_jit
- VCZT_jit
- vectorized_CZT_for_high_NA
- PolarizedLightSource:
- gaussian_beam
- plane_wave
"""
class VectorizedLight:
""" Class for Vectorial EM fields - (Ex, Ey, Ez) """
def __init__(self, x=None, y=None, wavelength=None):
self.x = x
self.y = y
self.X, self.Y = jnp.meshgrid(self.x, self.y)
self.wavelength = wavelength
self.k = 2 * jnp.pi / wavelength
self.n = 1
shape = (jnp.shape(x)[0], jnp.shape(y)[0])
self.Ex = jnp.zeros(shape, dtype=jnp.complex128)
self.Ey = jnp.zeros(shape, dtype=jnp.complex128)
self.Ez = jnp.zeros(shape, dtype=jnp.complex128)
self.info = 'Vectorized light'
def draw(self, xlim='', ylim='', kind='', extra_title='', save_file=False, filename=''):
"""
Plots VectorizedLight.
Parameters:
xlim (float, float): x-axis limit for plot purpose.
ylim (float, float): y-axis limit for plot purpose.
kind (str): Feature to plot: 'Intensity', 'Phase' or 'Field'.
extra_title (str): Adds extra info to the plot title.
save_file (bool): If True, saves the figure.
filename (str): Name of the figure.
"""
extent = [xlim[0], xlim[1], ylim[0], ylim[1]]
if kind == 'Intensity':
# Compute intensity
Ix = jnp.abs(self.Ex) ** 2 # Ex
Iy = jnp.abs(self.Ey) ** 2 # Ey
Iz = jnp.abs(self.Ez) ** 2 # Ez
Ir = Ix + Iy # Er
fig, axes = plt.subplots(2, 3, figsize=(14, 7))
cmap = 'gist_heat'
ax = axes[0,0]
im = ax.imshow(Ix, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Intensity x. {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=jnp.min(Ix), vmax=jnp.max(Ix))
ax = axes[0,1]
im = ax.imshow(Iy, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Intensity y. {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=jnp.min(Iy), vmax=jnp.max(Iy))
ax = axes[1,0]
im = ax.imshow(Iz, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Intensity z. {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=jnp.min(Iz), vmax=jnp.max(Iz))
ax = axes[0,2]
im = ax.imshow(Ir, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Intensity r. {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=jnp.min(Ir), vmax=jnp.max(Ir))
axes[1,1].axis('off')
axes[1,2].axis('off')
plt.subplots_adjust(wspace=0.6, hspace=0.6)
elif kind == 'Phase':
# Compute phase
phi_x = jnp.angle(self.Ex) # Ex
phi_y = jnp.angle(self.Ey) # Ey
phi_z = jnp.angle(self.Ez) # Ez
fig, axes = plt.subplots(1, 3, figsize=(14, 3))
cmap = 'twilight'
ax = axes[0]
im = ax.imshow(phi_x, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Phase x (in radians). {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=-jnp.pi, vmax=jnp.pi)
ax = axes[1]
im = ax.imshow(phi_y, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Phase y (in radians). {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=-jnp.pi, vmax=jnp.pi)
ax = axes[2]
im = ax.imshow(phi_z, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Phase z (in radians). {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=-jnp.pi, vmax=jnp.pi)
elif kind == 'Field':
# Compute field amplitudes
Ax = jnp.abs(self.Ex) # Ex
Ay = jnp.abs(self.Ey) # Ey
Az = jnp.abs(self.Ez) # Ez
fig, axes = plt.subplots(1, 3, figsize=(14, 3))
cmap = 'viridis'
ax = axes[0]
im = ax.imshow(Ax, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Amplitude x. {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=jnp.min(Ax), vmax=jnp.max(Ax))
ax = axes[1]
im = ax.imshow(Ay, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Amplitude y. {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=jnp.min(Ay), vmax=jnp.max(Ay))
ax = axes[2]
im = ax.imshow(Az, cmap=cmap, extent=extent, origin='lower')
ax.set_title(f"Amplitude z. {extra_title}")
ax.set_xlabel('$x (\mu m)$')
ax.set_ylabel('$y (\mu m)$')
fig.colorbar(im, ax=ax)
im.set_clim(vmin=jnp.min(Az), vmax=jnp.max(Az))
else:
raise ValueError(f"Invalid kind option: {kind}. Please choose 'Intensity', 'Phase' or 'Field'.")
plt.tight_layout()
if save_file is True:
plt.savefig(filename)
print(f"Plot saved as {filename}")
plt.show()
def draw_intensity_profile(self, p1='', p2=''):
"""
Draws the intensity profile of VectorizedLight.
Parameters:
p1 (float, float): Initial point.
p2 (float, float): Final point.
"""
h, z_profile_x = profile(jnp.abs(self.Ex)**2, self.x, self.y, point1=p1, point2=p2)
_, z_profile_y = profile(jnp.abs(self.Ey)**2, self.x, self.y, point1=p1, point2=p2)
_, z_profile_z = profile(jnp.abs(self.Ez)**2, self.x, self.y, point1=p1, point2=p2)
_, z_profile_r = profile(jnp.abs(self.Ex)**2 + jnp.abs(self.Ey)**2, self.x, self.y, point1=p1, point2=p2)
_, z_profile_total = profile(jnp.abs(self.Ex)**2 + jnp.abs(self.Ey)**2 + jnp.abs(self.Ez)**2, self.x, self.y, point1=p1, point2=p2)
fig, axes = plt.subplots(3, 2, figsize=(14, 14))
ax = axes[0, 0]
im = ax.plot(h, z_profile_x, 'k', lw=2)
ax.set_title(f"Ix profile")
ax.set_xlabel('$\mu m$')
ax.set_ylabel('$Ix$')
ax.set(xlim=(h.min(), h.max()), ylim=(z_profile_x.min(), z_profile_x.max()))
ax = axes[0, 1]
im = ax.plot(h, z_profile_y, 'k', lw=2)
ax.set_title(f"Iy profile")
ax.set_xlabel('$\mu m$')
ax.set_ylabel('$Iy$')
ax.set(xlim=(h.min(), h.max()), ylim=(z_profile_y.min(), z_profile_y.max()))
ax = axes[1, 0]
im = ax.plot(h, z_profile_z, 'k', lw=2)
ax.set_title(f"Iz profile")
ax.set_xlabel('$\mu m$')
ax.set_ylabel('$Iz$')
ax.set(xlim=(h.min(), h.max()), ylim=(z_profile_z.min(), z_profile_z.max()))
ax = axes[1, 1]
im = ax.plot(h, z_profile_r, 'k', lw=2)
ax.set_title(f"Ir profile")
ax.set_xlabel('$\mu m$')
ax.set_ylabel('$Ir$')
ax.set(xlim=(h.min(), h.max()), ylim=(z_profile_r.min(), z_profile_r.max()))
ax = axes[2, 0]
im = ax.plot(h, z_profile_total, 'k', lw=2)
ax.set_title(f"Itotal profile")
ax.set_xlabel('$\mu m$')
ax.set_ylabel('$Itotal$')
ax.set(xlim=(h.min(), h.max()), ylim=(z_profile_total.min(), z_profile_total.max()))
axes[2, 1].axis('off')
plt.subplots_adjust(wspace=0.3, hspace=0.4)
plt.show()
def VRS_propagation(self, z):
"""
Rayleigh-Sommerfeld diffraction integral in both, z>0 and z<0, for VectorizedLight.
[Ref 1: Laser Phys. Lett., 10(6), 065004 (2013)].
[Ref 2: Optics and laser tech., 39(4), 10.1016/j.optlastec.2006.03.006].
[Ref 3: J. Li, Z. Fan, Y. Fu, Proc. SPIE 4915, (2002)].
Parameters:
z (float): Distance to propagate.
Returns VectorizedLight object after propagation and the quality factor of the algorithm.
"""
tic = time.perf_counter()
# Define r [From Ref 1, eq. 1a-1c]:
r = jnp.sqrt(self.X ** 2 + self.Y ** 2 + z ** 2)
# Set the value of Ez:
Ez = jnp.array(self.Ex * self.X / r + self.Ey * self.Y / r)
nx, ny, dx, dy, Xext, Yext = build_grid(self.x, self.y)
# Quality factor for accurate simulation [Eq. 22 in Ref1]:
dr_real = jnp.sqrt(dx**2 + dy**2)
# Rho
rmax = jnp.sqrt(jnp.max(self.x**2) + jnp.max(self.y**2))
# Delta rho ideal
dr_ideal = jnp.sqrt((self.wavelength)**2 + rmax**2 + 2 * (self.wavelength) * jnp.sqrt(rmax**2 + z**2)) - rmax
quality_factor = dr_ideal / dr_real
# Stack the input field in a (3, N, N) shape and pass to jit.
E_in = jnp.stack([self.Ex, self.Ey, Ez], axis=0)
E_out = VRS_propagation_jit(E_in, z, nx, ny, dx, dy, Xext, Yext, self.k)
E_out = jnp.moveaxis(E_out, [0, 1, 2], [2, 0, 1])
# Define the output light:
light_out = VectorizedLight(self.x, self.y, self.wavelength)
light_out.Ex = E_out[:, :, 0]
light_out.Ey = E_out[:, :, 1]
light_out.Ez = E_out[:, :, 2]
print("Time taken to perform one VRS propagation (in seconds):", time.perf_counter() - tic)
return light_out, quality_factor
def get_VRS_minimum_z(self, n=1, quality_factor=1):
"""
Given a quality factor, determines the minimum available (trustworthy) distance for VRS_propagation().
[Ref 1: Laser Phys. Lett., 10(6), 065004 (2013)].
Parameters:
n (float): refraction index of the surrounding medium.
quality_factor (int): Defaults to 1.
Returns the minimum distance z (in microns) necessary to achieve qualities larger than quality_factor.
>> Diffractio-adapted function (https://pypi.org/project/diffractio/) <<
"""
# Check sampling
range_x = self.x[-1] - self.x[0]
range_y = self.y[-1] - self.y[0]
num_x = jnp.size(self.x)
num_y = jnp.size(self.y)
dx = range_x / num_x
dy = range_y / num_y
# Delta rho
dr_real = jnp.sqrt(dx**2 + dy**2)
# Rho
rmax = jnp.sqrt(range_x**2 + range_y**2)
factor = (((quality_factor * dr_real + rmax)**2 - (self.wavelength / n)**2 - rmax**2) / (2 * self.wavelength / n))**2 - rmax**2
if factor > 0:
z_min = jnp.sqrt(factor)
else:
z_min = 0
return print("Minimum distance to propagate (in um):", z_min)
def VCZT(self, z, xout, yout):
"""
Vectorial version of the Chirped z-transform propagation - efficient RS diffraction using the Bluestein method.
Useful for imaging light in the focal plane: allows high resolution zoom in z-plane.
[Ref] Hu, Y., et al. Light Sci Appl 9, 119 (2020).
Parameters:
z (float): Propagation distance.
xout (jnp.array): Array with the x-positions for the output plane.
Returns VectorizedLight object after propagation.
"""
tic = time.perf_counter()
if xout is None:
xout = self.x
if yout is None:
yout = self.y
# Define r:
r = jnp.sqrt(self.X ** 2 + self.Y ** 2 + z ** 2)
# Set the value of Ez:
Ez = jnp.array((self.Ex * self.X / r + self.Ey * self.Y / r) * z / r)
# Define main set of parameters
nx, ny, dx, dy, Xout, Yout, Dm, fy_1, fy_2, fx_1, fx_2 = build_CZT_grid(z, self.wavelength, self.x, self.y, xout, yout)
# Stack the input field in a (3, N, N) shape and pass to jit.
E_in = jnp.stack([self.Ex, self.Ey, Ez], axis=0)
E_out = VCZT_jit(E_in, z, self.wavelength, self.k, nx, ny, dx, dy, Xout, Yout, self.X, self.Y, Dm, fy_1, fy_2, fx_1, fx_2)
E_out = jnp.moveaxis(E_out, [0, 1, 2], [2, 0, 1])
# Define the output light:
light_out = VectorizedLight(xout, yout, self.wavelength)
light_out.Ex = E_out[:, :, 0]
light_out.Ey = E_out[:, :, 1]
light_out.Ez = E_out[:, :, 2]
print("Time taken to perform one VCZT propagation (in seconds):", time.perf_counter() - tic)
return light_out
@partial(jit, static_argnums=(2, 3, 4, 5, 8))
def VRS_propagation_jit(input_field, z, nx, ny, dx, dy, Xext, Yext, k):
"""[From VRS_propagation]: JIT function that vectorizes the propagation and calls RS_propagation_jit from wave_optics.py."""
# Input field has (3, N, N) shape
vectorized_RS_propagation = vmap(RS_propagation_jit,
in_axes=(0, None, None, None, None, None, None, None, None))
# Call the vectorized function
E_out = vectorized_RS_propagation(input_field, z, nx, ny, dx, dy, Xext, Yext, k)
return E_out # (3, N, N) -> ([Ex, Ey, Ez], N, N)
def VCZT_jit(field, z, wavelength, k, nx, ny, dx, dy, Xout, Yout, X, Y, Dm, fy_1, fy_2, fx_1, fx_2):
"""[From CZT]: JIT function that vectorizes the propagation and calls CZT_jit from wave_optics.py."""
# Input field has (3, N, N) shape
vectorized_CZT = vmap(CZT_jit,
in_axes=(0, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None))
# Call the vectorized function
E_out = vectorized_CZT(field, z, wavelength, k, nx, ny, dx, dy, Xout, Yout, X, Y, Dm, fy_1, fy_2, fx_1, fx_2)
return E_out # (3, N, N) -> ([Ex, Ey, Ez], N, N)
def vectorized_CZT_for_high_NA(field, nx, ny, Dm, fy_1, fy_2, fx_1, fx_2):
"""[From VCZT_objective_lens - in optical_elements.py]: JIT function that vectorizes the propagation and calls CZT_for_high_NA_jit from wave_optics.py."""
# Input field has (3, N, N) shape | vectorized = vmap(CZT_for_high_NA_jit, in_axes=(0, None, None, None, None, None, None, None)) | 5 | 2023-10-26 13:17:50+00:00 | 8k |
LFhase/GALA | models/ciga.py | [
{
"identifier": "relabel",
"path": "utils/get_subgraph.py",
"snippet": "def relabel(x, edge_index, batch, pos=None):\n\n num_nodes = x.size(0)\n sub_nodes = torch.unique(edge_index)\n x = x[sub_nodes]\n batch = batch[sub_nodes]\n row, col = edge_index\n # remapping the nodes in the exp... | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_geometric.data.batch as DataBatch
import torch_scatter
from torch_geometric.nn import (ASAPooling, global_add_pool, global_max_pool,
global_mean_pool)
from utils.get_subgraph import relabel, split_batch
from utils.mask import clear_masks, set_masks
from models.conv import GNN_node, GNN_node_Virtualnode
from models.gnn import GNN, LeGNN
from torch.distributions.normal import Normal
from torch_geometric.nn import InstanceNorm
from torch_geometric.utils import degree
from torch_geometric.utils import degree
from torch_geometric.utils import degree | 7,076 | self.prior = discrete_gaussian(self.num_envs)
def get_env_loss(self,batch,criterion):
h_graph = self.gnn.forward_rep(batch)
y_part = torch.nan_to_num(batch.y).float().unsqueeze(1)
env_prob = self.env_pred_linear(torch.cat([h_graph, y_part], dim=-1))
q_e = torch.softmax(env_prob, dim=-1)
batch_size = h_graph.size(0)
device = h_graph.device
losses = []
for dom in range(self.num_envs):
domain_info = torch.ones(batch_size).long().to(device)
domain_feat = torch.index_select(self.class_emb, 0, domain_info*dom)
p_ye = self.env_label_pred_linear(torch.cat([h_graph, domain_feat], dim=1))
labeled = batch.y == batch.y
# there are nan in the labels so use this to mask them
# and this is a multitask binary classification
# data_belong = torch.arange(batch_size).long()
# data_belong = data_belong.unsqueeze(dim=-1).to(device)
# data_belong = data_belong.repeat(1, self.num_tasks)
# [batch_size, num_tasks] same as p_ye
loss = criterion(p_ye[labeled], batch.y[labeled],reduction='none')
# shape: [numbers of not nan gts]
# batch_loss = torch_scatter.scatter(
# loss, dim=0, index=data_belong[labeled],
# reduce='mean'
# ) # [batch_size]
# considering the dataset is a multitask binary
# classification task, the process above is to
# get a average loss among all the tasks,
# when there is only one task, it's equilvant to
# bce_with_logit without reduction
losses.append(loss)
losses = torch.stack(losses, dim=1) # [batch_size, num_domain]
Eq = torch.mean(torch.sum(q_e * losses, dim=-1))
ELBO = Eq + KLDist(q_e, self.prior.to(device))
return ELBO
def forward_env(self,batch,criterion):
batch_size = batch.y.size(0)
device = batch.y.device
labeled = batch.y == batch.y
data_belong = torch.arange(batch_size).long()
data_belong = data_belong.unsqueeze(dim=-1).to(device)
data_belong = data_belong.repeat(1, self.num_tasks)
with torch.no_grad():
self.eval()
h_graph = self.gnn.forward_rep(batch)
cond_result = []
for dom in range(self.num_envs):
domain_info = torch.ones(batch_size).long().to(device)
# domain_info = (domain_info * dom).to(device)
domain_feat = torch.index_select(self.class_emb, 0, domain_info*dom)
cond_term = criterion(
self.env_label_pred_linear(torch.cat([h_graph, domain_feat], dim=1))[labeled],
batch.y[labeled],
reduction='none'
)
# cond_term = torch_scatter.scatter(
# cond_term, dim=0, index=data_belong[labeled],
# reduce='mean'
# )
cond_result.append(cond_term)
cond_result = torch.stack(cond_result, dim=0)
# [num_domain, batch_size]
cond_result = torch.matmul(self.prior.to(device), cond_result)
# cond_result = torch.mean(cond_result, dim=0)
# [batch_size]
y_part = torch.nan_to_num(batch.y).unsqueeze(1).float()
env_prob = self.env_pred_linear(torch.cat([h_graph, y_part], dim=-1))
env = torch.argmax(env_prob, dim=-1)
# [batch_size]
return env, cond_result, data_belong
def forward(self, batch, return_data="pred"):
causal_pred, causal_rep = self.gnn(batch, get_rep=True)
if return_data.lower() == "pred":
return causal_pred
elif return_data.lower() == "rep":
return causal_pred, causal_rep
elif return_data.lower() == "feat":
#Nothing will happen for ERM
return causal_pred, causal_rep
else:
raise Exception("Not support return type")
class GNNPooling(nn.Module):
def __init__(self,
input_dim,
out_dim,
edge_dim=-1,
emb_dim=300,
num_layers=5,
ratio=0.25,
pooling='asap',
gnn_type='gin',
virtual_node=True,
residual=False,
drop_ratio=0.5,
JK="last",
graph_pooling="mean"):
super(GNNPooling, self).__init__()
if pooling.lower() == 'asap':
# Cancel out the edge attribute when using ASAP pooling
# since (1) ASAP not compatible with edge attr
# (2) performance of DrugOOD will not be affected w/o edge attr
self.pool = ASAPooling(emb_dim, ratio, dropout=drop_ratio)
edge_dim = -1
### GNN to generate node embeddings
if gnn_type.lower() == "le":
self.gnn_encoder = LeGNN(in_channels=input_dim,
hid_channels=emb_dim,
num_layer=num_layers,
drop_ratio=drop_ratio,
num_classes=out_dim,
edge_dim=edge_dim)
else:
if virtual_node:
|
class GNNERM(nn.Module):
def __init__(self,
input_dim,
out_dim,
edge_dim=-1,
emb_dim=300,
num_layers=5,
ratio=0.25,
gnn_type='gin',
virtual_node=True,
residual=False,
drop_ratio=0.5,
JK="last",
graph_pooling="mean"):
super(GNNERM, self).__init__()
self.classifier = GNN(gnn_type=gnn_type,
input_dim=input_dim,
num_class=out_dim,
num_layer=num_layers,
emb_dim=emb_dim,
drop_ratio=drop_ratio,
virtual_node=virtual_node,
graph_pooling=graph_pooling,
residual=residual,
JK=JK,
edge_dim=edge_dim)
def forward(self, batch, return_data="pred"):
causal_pred, causal_rep = self.classifier(batch, get_rep=True)
if return_data.lower() == "pred":
return causal_pred
elif return_data.lower() == "rep":
return causal_pred, causal_rep
elif return_data.lower() == "feat":
#Nothing will happen for ERM
return causal_pred, causal_rep
else:
raise Exception("Not support return type")
def bce_log(pred, gt, eps=1e-8):
prob = torch.sigmoid(pred)
return -(gt * torch.log(prob + eps) + (1 - gt) * torch.log(1 - prob + eps))
def discrete_gaussian(nums, std=1):
Dist = Normal(loc=0, scale=1)
plen, halflen = std * 6 / nums, std * 3 / nums
posx = torch.arange(-3 * std + halflen, 3 * std, plen)
result = Dist.cdf(posx + halflen) - Dist.cdf(posx - halflen)
return result / result.sum()
def KLDist(p, q, eps=1e-8):
log_p, log_q = torch.log(p + eps), torch.log(q + eps)
return torch.sum(p * (log_p - log_q))
class GNNEnv(nn.Module):
def __init__(self,
input_dim,
out_dim,
edge_dim=-1,
emb_dim=300,
num_layers=5,
ratio=0.25,
gnn_type='gin',
virtual_node=True,
residual=False,
drop_ratio=0.5,
JK="last",
graph_pooling="mean",
num_envs=2,
prior="uniform"):
super(GNNEnv, self).__init__()
self.gnn = GNN(gnn_type=gnn_type,
input_dim=input_dim,
num_class=out_dim,
num_layer=num_layers,
emb_dim=emb_dim,
drop_ratio=drop_ratio,
virtual_node=virtual_node,
graph_pooling=graph_pooling,
residual=residual,
JK=JK,
edge_dim=edge_dim)
self.num_envs = num_envs
self.num_tasks = out_dim
# env inference
self.env_pred_linear = torch.nn.Linear(emb_dim+1, num_envs)
# conditional gnn
self.class_emb = torch.nn.Parameter(
torch.zeros(num_envs, emb_dim)
)
self.env_label_pred_linear = torch.nn.Linear(emb_dim + emb_dim, out_dim)
# main gnn
self.graph_label_pred_linear = torch.nn.Linear(emb_dim, out_dim)
if prior == 'uniform':
self.prior = torch.ones(self.num_envs) / self.num_envs
else:
self.prior = discrete_gaussian(self.num_envs)
def get_env_loss(self,batch,criterion):
h_graph = self.gnn.forward_rep(batch)
y_part = torch.nan_to_num(batch.y).float().unsqueeze(1)
env_prob = self.env_pred_linear(torch.cat([h_graph, y_part], dim=-1))
q_e = torch.softmax(env_prob, dim=-1)
batch_size = h_graph.size(0)
device = h_graph.device
losses = []
for dom in range(self.num_envs):
domain_info = torch.ones(batch_size).long().to(device)
domain_feat = torch.index_select(self.class_emb, 0, domain_info*dom)
p_ye = self.env_label_pred_linear(torch.cat([h_graph, domain_feat], dim=1))
labeled = batch.y == batch.y
# there are nan in the labels so use this to mask them
# and this is a multitask binary classification
# data_belong = torch.arange(batch_size).long()
# data_belong = data_belong.unsqueeze(dim=-1).to(device)
# data_belong = data_belong.repeat(1, self.num_tasks)
# [batch_size, num_tasks] same as p_ye
loss = criterion(p_ye[labeled], batch.y[labeled],reduction='none')
# shape: [numbers of not nan gts]
# batch_loss = torch_scatter.scatter(
# loss, dim=0, index=data_belong[labeled],
# reduce='mean'
# ) # [batch_size]
# considering the dataset is a multitask binary
# classification task, the process above is to
# get a average loss among all the tasks,
# when there is only one task, it's equilvant to
# bce_with_logit without reduction
losses.append(loss)
losses = torch.stack(losses, dim=1) # [batch_size, num_domain]
Eq = torch.mean(torch.sum(q_e * losses, dim=-1))
ELBO = Eq + KLDist(q_e, self.prior.to(device))
return ELBO
def forward_env(self,batch,criterion):
batch_size = batch.y.size(0)
device = batch.y.device
labeled = batch.y == batch.y
data_belong = torch.arange(batch_size).long()
data_belong = data_belong.unsqueeze(dim=-1).to(device)
data_belong = data_belong.repeat(1, self.num_tasks)
with torch.no_grad():
self.eval()
h_graph = self.gnn.forward_rep(batch)
cond_result = []
for dom in range(self.num_envs):
domain_info = torch.ones(batch_size).long().to(device)
# domain_info = (domain_info * dom).to(device)
domain_feat = torch.index_select(self.class_emb, 0, domain_info*dom)
cond_term = criterion(
self.env_label_pred_linear(torch.cat([h_graph, domain_feat], dim=1))[labeled],
batch.y[labeled],
reduction='none'
)
# cond_term = torch_scatter.scatter(
# cond_term, dim=0, index=data_belong[labeled],
# reduce='mean'
# )
cond_result.append(cond_term)
cond_result = torch.stack(cond_result, dim=0)
# [num_domain, batch_size]
cond_result = torch.matmul(self.prior.to(device), cond_result)
# cond_result = torch.mean(cond_result, dim=0)
# [batch_size]
y_part = torch.nan_to_num(batch.y).unsqueeze(1).float()
env_prob = self.env_pred_linear(torch.cat([h_graph, y_part], dim=-1))
env = torch.argmax(env_prob, dim=-1)
# [batch_size]
return env, cond_result, data_belong
def forward(self, batch, return_data="pred"):
causal_pred, causal_rep = self.gnn(batch, get_rep=True)
if return_data.lower() == "pred":
return causal_pred
elif return_data.lower() == "rep":
return causal_pred, causal_rep
elif return_data.lower() == "feat":
#Nothing will happen for ERM
return causal_pred, causal_rep
else:
raise Exception("Not support return type")
class GNNPooling(nn.Module):
def __init__(self,
input_dim,
out_dim,
edge_dim=-1,
emb_dim=300,
num_layers=5,
ratio=0.25,
pooling='asap',
gnn_type='gin',
virtual_node=True,
residual=False,
drop_ratio=0.5,
JK="last",
graph_pooling="mean"):
super(GNNPooling, self).__init__()
if pooling.lower() == 'asap':
# Cancel out the edge attribute when using ASAP pooling
# since (1) ASAP not compatible with edge attr
# (2) performance of DrugOOD will not be affected w/o edge attr
self.pool = ASAPooling(emb_dim, ratio, dropout=drop_ratio)
edge_dim = -1
### GNN to generate node embeddings
if gnn_type.lower() == "le":
self.gnn_encoder = LeGNN(in_channels=input_dim,
hid_channels=emb_dim,
num_layer=num_layers,
drop_ratio=drop_ratio,
num_classes=out_dim,
edge_dim=edge_dim)
else:
if virtual_node: | self.gnn_encoder = GNN_node_Virtualnode(num_layers, | 5 | 2023-10-30 16:57:56+00:00 | 8k |
Graph-and-Geometric-Learning/D4Explainer | evaluation/robustness.py | [
{
"identifier": "feature_dict",
"path": "constants.py",
"snippet": ""
},
{
"identifier": "Explainer",
"path": "explainers/base.py",
"snippet": "class Explainer(object):\n def __init__(self, device, gnn_model_path, task=\"gc\"):\n self.device = device\n self.model = torch... | import argparse
import copy
import math
import os
import sys
import numpy as np
import torch
from torch_geometric.data import DataLoader
from tqdm import tqdm
from constants import feature_dict, task_type
from explainers import *
from explainers.base import Explainer as BaseExplainer
from explainers.diff_explainer import Powerful, sparsity
from explainers.diffusion.graph_utils import (
gen_list_of_data_single,
generate_mask,
graph2tensor,
)
from gnns import *
from utils.dataset import get_datasets | 5,397 | sys.path.append("..")
class DiffExplainer(BaseExplainer):
def __init__(self, device, gnn_model_path, task, args):
super(DiffExplainer, self).__init__(device, gnn_model_path, task)
self.device = device
self.model = Powerful(args).to(args.device)
exp_dir = f"{args.root}/{args.dataset}/"
self.model.load_state_dict(torch.load(os.path.join(exp_dir, "best_model.pth"), map_location="cuda:0")["model"])
self.model.eval()
def explain_graph(self, model, graph, adj_b, x_b, node_flag_b, sigma_list, args):
sigma_list = [sigma / 20 for sigma in sigma_list]
_, _, _, test_noise_adj_b, _ = gen_list_of_data_single(x_b, adj_b, node_flag_b, sigma_list, args)
test_noise_adj_b_chunked = test_noise_adj_b.chunk(len(sigma_list), dim=0)
score = []
| sys.path.append("..")
class DiffExplainer(BaseExplainer):
def __init__(self, device, gnn_model_path, task, args):
super(DiffExplainer, self).__init__(device, gnn_model_path, task)
self.device = device
self.model = Powerful(args).to(args.device)
exp_dir = f"{args.root}/{args.dataset}/"
self.model.load_state_dict(torch.load(os.path.join(exp_dir, "best_model.pth"), map_location="cuda:0")["model"])
self.model.eval()
def explain_graph(self, model, graph, adj_b, x_b, node_flag_b, sigma_list, args):
sigma_list = [sigma / 20 for sigma in sigma_list]
_, _, _, test_noise_adj_b, _ = gen_list_of_data_single(x_b, adj_b, node_flag_b, sigma_list, args)
test_noise_adj_b_chunked = test_noise_adj_b.chunk(len(sigma_list), dim=0)
score = [] | mask = generate_mask(node_flag_b) | 4 | 2023-10-28 19:58:40+00:00 | 8k |
pytabular-ai/auto-scikit-dl | models/node_model.py | [
{
"identifier": "TabModel",
"path": "models/abstract.py",
"snippet": "class TabModel(ABC):\n def __init__(self):\n self.model: Optional[nn.Module] = None # true model\n self.base_name = None # model type name\n self.device = None\n self.saved_model_config = None\n s... | import time
import math
import typing as ty
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import models.node as node
from pathlib import Path
from torch.utils.data import DataLoader
from torch import Tensor
from models.abstract import TabModel, check_dir | 5,387 | # %%
# %%
class _NODE(nn.Module):
def __init__(
self,
*,
d_in: int,
num_layers: int,
layer_dim: int,
depth: int,
tree_dim: int,
choice_function: str,
bin_function: str,
d_out: int,
categories: ty.Optional[ty.List[int]],
d_embedding: int,
) -> None:
super().__init__()
if categories is not None:
d_in += len(categories) * d_embedding
category_offsets = torch.tensor([0] + categories[:-1]).cumsum(0)
self.register_buffer('category_offsets', category_offsets)
self.category_embeddings = nn.Embedding(sum(categories), d_embedding)
nn.init.kaiming_uniform_(self.category_embeddings.weight, a=math.sqrt(5))
print(f'{self.category_embeddings.weight.shape}')
self.d_out = d_out
self.block = node.DenseBlock(
input_dim=d_in,
num_layers=num_layers,
layer_dim=layer_dim,
depth=depth,
tree_dim=tree_dim,
bin_function=getattr(node, bin_function),
choice_function=getattr(node, choice_function),
flatten_output=False,
)
def forward(self, x_num: Tensor, x_cat: Tensor) -> Tensor:
if x_cat is not None:
x_cat = self.category_embeddings(x_cat + self.category_offsets[None])
x = torch.cat([x_num, x_cat.view(x_cat.size(0), -1)], dim=-1)
else:
x = x_num
x = self.block(x)
x = x[..., : self.d_out].mean(dim=-2)
x = x.squeeze(-1)
return x
# %%
| # %%
# %%
class _NODE(nn.Module):
def __init__(
self,
*,
d_in: int,
num_layers: int,
layer_dim: int,
depth: int,
tree_dim: int,
choice_function: str,
bin_function: str,
d_out: int,
categories: ty.Optional[ty.List[int]],
d_embedding: int,
) -> None:
super().__init__()
if categories is not None:
d_in += len(categories) * d_embedding
category_offsets = torch.tensor([0] + categories[:-1]).cumsum(0)
self.register_buffer('category_offsets', category_offsets)
self.category_embeddings = nn.Embedding(sum(categories), d_embedding)
nn.init.kaiming_uniform_(self.category_embeddings.weight, a=math.sqrt(5))
print(f'{self.category_embeddings.weight.shape}')
self.d_out = d_out
self.block = node.DenseBlock(
input_dim=d_in,
num_layers=num_layers,
layer_dim=layer_dim,
depth=depth,
tree_dim=tree_dim,
bin_function=getattr(node, bin_function),
choice_function=getattr(node, choice_function),
flatten_output=False,
)
def forward(self, x_num: Tensor, x_cat: Tensor) -> Tensor:
if x_cat is not None:
x_cat = self.category_embeddings(x_cat + self.category_offsets[None])
x = torch.cat([x_num, x_cat.view(x_cat.size(0), -1)], dim=-1)
else:
x = x_num
x = self.block(x)
x = x[..., : self.d_out].mean(dim=-2)
x = x.squeeze(-1)
return x
# %% | class NODE(TabModel): | 0 | 2023-10-30 14:55:44+00:00 | 8k |
amazon-science/adaptive-in-context-learning | annotation_methods.py | [
{
"identifier": "reliability_plot",
"path": "utils.py",
"snippet": "def reliability_plot(args, label_map, train_examples, phase=0, bins=10, do_plot=False):\n \"\"\"\n Generate a binned reliability plot.\n\n Parameters\n ----------\n bins (int): Number of bins to perform binned statist... | import random
import os
import json
from utils import reliability_plot, embedding_plot
from algorithms import cluster, fast_votek_mod, uncertainty_ranking, votek_mod
from algorithms import density_max_coverage | 6,899 |
def selective_annotation_single_phase(args,**kwargs):
"""
Single-step annotation methods: random, fast-votek, votek, hardest, adaicl-base
Args:
args
Returns:
list: selected data points for annotation
"""
random.seed(args.seed)
init_size = args.init_size
print("init: ", args.init)
print("init size: ", args.init_size)
### Initial annotated pool $L_0$ (random, clustering, or none)
if args.init == 'random':
init_ind = random.sample(range(len(kwargs['train_examples'])),init_size)
pool_idx = list(range(len(kwargs['embeddings'])))
for i in init_ind:
pool_idx.remove(i)
#naive clustering -- assign cluster centroids on random points
cur_examples = [kwargs["train_examples"][idx] for idx in init_ind]
|
def selective_annotation_single_phase(args,**kwargs):
"""
Single-step annotation methods: random, fast-votek, votek, hardest, adaicl-base
Args:
args
Returns:
list: selected data points for annotation
"""
random.seed(args.seed)
init_size = args.init_size
print("init: ", args.init)
print("init size: ", args.init_size)
### Initial annotated pool $L_0$ (random, clustering, or none)
if args.init == 'random':
init_ind = random.sample(range(len(kwargs['train_examples'])),init_size)
pool_idx = list(range(len(kwargs['embeddings'])))
for i in init_ind:
pool_idx.remove(i)
#naive clustering -- assign cluster centroids on random points
cur_examples = [kwargs["train_examples"][idx] for idx in init_ind] | _, clustering_model = cluster(embeddings=kwargs['embeddings'][init_ind],select_num=init_size, examples=cur_examples, thres=False, reverse=False) | 2 | 2023-10-30 16:34:21+00:00 | 8k |
endo-yuki-t/MAG | ldm/modules/diffusionmodules/openaimodel.py | [
{
"identifier": "checkpoint",
"path": "ldm/modules/diffusionmodules/util.py",
"snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at the expense of extra compute in the backward pass.\n ... | from abc import abstractmethod
from ldm.modules.diffusionmodules.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from ldm.modules.attention import SpatialTransformer
from ldm.util import exists
from omegaconf.listconfig import ListConfig
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F | 4,068 | ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
use_checkpoint=use_checkpoint
),
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(self.num_res_blocks[level] + 1):
ich = input_block_chans.pop()
layers = [
ResBlock(
ch + ich,
time_embed_dim,
dropout,
out_channels=model_channels * mult,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = model_channels * mult
if ds in attention_resolutions:
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
if exists(disable_self_attentions):
disabled_sa = disable_self_attentions[level]
else:
disabled_sa = False
if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads_upsample,
num_head_channels=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
use_checkpoint=use_checkpoint
)
)
if level and i == self.num_res_blocks[level]:
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, model_channels, out_channels, 3, padding=1)),
)
if self.predict_codebook_ids:
self.id_predictor = nn.Sequential(
normalization(ch),
conv_nd(dims, model_channels, n_embed, 1),
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
)
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, timesteps=None, context=None, y=None, att_mask=None, **kwargs):
"""
Apply the model to an input batch.
:param x: an [N x C x ...] Tensor of inputs.
:param timesteps: a 1-D batch of timesteps.
:param context: conditioning plugged in via crossattn
: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"
hs = []
|
# dummy replace
def convert_module_to_f16(x):
pass
def convert_module_to_f32(x):
pass
## go
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, context=None, att_mask=None):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
elif isinstance(layer, SpatialTransformer):
x = layer(x, context, mask2=att_mask)
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, padding=1):
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=padding)
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 TransposedUpsample(nn.Module):
'Learned 2x upsampling without padding'
def __init__(self, channels, out_channels=None, ks=5):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
def forward(self,x):
return self.up(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,padding=1):
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=padding
)
else:
assert self.channels == self.out_channels
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
def forward(self, x):
assert x.shape[1] == self.channels
return self.op(x)
class ResBlock(TimestepBlock):
"""
A residual block that can optionally change the number of channels.
:param channels: the number of input channels.
:param emb_channels: the number of timestep embedding channels.
:param dropout: the rate of dropout.
:param out_channels: if specified, the number of out channels.
:param use_conv: if True and out_channels is specified, use a spatial
convolution instead of a smaller 1x1 convolution to change the
channels in the skip connection.
:param dims: determines if the signal is 1D, 2D, or 3D.
:param use_checkpoint: if True, use gradient checkpointing on this module.
:param up: if True, use this block for upsampling.
:param down: if True, use this block for downsampling.
"""
def __init__(
self,
channels,
emb_channels,
dropout,
out_channels=None,
use_conv=False,
use_scale_shift_norm=False,
dims=2,
use_checkpoint=False,
up=False,
down=False,
):
super().__init__()
self.channels = channels
self.emb_channels = emb_channels
self.dropout = dropout
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.use_checkpoint = use_checkpoint
self.use_scale_shift_norm = use_scale_shift_norm
self.in_layers = nn.Sequential(
normalization(channels),
nn.SiLU(),
conv_nd(dims, channels, self.out_channels, 3, padding=1),
)
self.updown = up or down
if up:
self.h_upd = Upsample(channels, False, dims)
self.x_upd = Upsample(channels, False, dims)
elif down:
self.h_upd = Downsample(channels, False, dims)
self.x_upd = Downsample(channels, False, dims)
else:
self.h_upd = self.x_upd = nn.Identity()
self.emb_layers = nn.Sequential(
nn.SiLU(),
linear(
emb_channels,
2 * self.out_channels if use_scale_shift_norm else self.out_channels,
),
)
self.out_layers = nn.Sequential(
normalization(self.out_channels),
nn.SiLU(),
nn.Dropout(p=dropout),
zero_module(
conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
),
)
if self.out_channels == channels:
self.skip_connection = nn.Identity()
elif use_conv:
self.skip_connection = conv_nd(
dims, channels, self.out_channels, 3, padding=1
)
else:
self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
def forward(self, x, emb):
"""
Apply the block to a Tensor, conditioned on a timestep embedding.
:param x: an [N x C x ...] Tensor of features.
:param emb: an [N x emb_channels] Tensor of timestep embeddings.
:return: an [N x C x ...] Tensor of outputs.
"""
return checkpoint(
self._forward, (x, emb), self.parameters(), self.use_checkpoint
)
def _forward(self, x, emb):
if self.updown:
in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
h = in_rest(x)
h = self.h_upd(h)
x = self.x_upd(x)
h = in_conv(h)
else:
h = self.in_layers(x)
emb_out = self.emb_layers(emb).type(h.dtype)
while len(emb_out.shape) < len(h.shape):
emb_out = emb_out[..., None]
if self.use_scale_shift_norm:
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
scale, shift = th.chunk(emb_out, 2, dim=1)
h = out_norm(h) * (1 + scale) + shift
h = out_rest(h)
else:
h = h + emb_out
h = self.out_layers(h)
return self.skip_connection(x) + h
class AttentionBlock(nn.Module):
"""
An attention block that allows spatial positions to attend to each other.
Originally ported from here, but adapted to the N-d case.
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
"""
def __init__(
self,
channels,
num_heads=1,
num_head_channels=-1,
use_checkpoint=False,
use_new_attention_order=False,
):
super().__init__()
self.channels = channels
if num_head_channels == -1:
self.num_heads = num_heads
else:
assert (
channels % num_head_channels == 0
), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
self.num_heads = channels // num_head_channels
self.use_checkpoint = use_checkpoint
self.norm = normalization(channels)
self.qkv = conv_nd(1, channels, channels * 3, 1)
if use_new_attention_order:
# split qkv before split heads
self.attention = QKVAttention(self.num_heads)
else:
# split heads before split qkv
self.attention = QKVAttentionLegacy(self.num_heads)
self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
def forward(self, x):
return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
#return pt_checkpoint(self._forward, x) # pytorch
def _forward(self, x):
b, c, *spatial = x.shape
x = x.reshape(b, c, -1)
qkv = self.qkv(self.norm(x))
h = self.attention(qkv)
h = self.proj_out(h)
return (x + h).reshape(b, c, *spatial)
def count_flops_attn(model, _x, y):
"""
A counter for the `thop` package to count the operations in an
attention operation.
Meant to be used like:
macs, params = thop.profile(
model,
inputs=(inputs, timestamps),
custom_ops={QKVAttention: QKVAttention.count_flops},
)
"""
b, c, *spatial = y[0].shape
num_spatial = int(np.prod(spatial))
# We perform two matmuls with the same number of ops.
# The first computes the weight matrix, the second computes
# the combination of the value vectors.
matmul_ops = 2 * b * (num_spatial ** 2) * c
model.total_ops += th.DoubleTensor([matmul_ops])
class QKVAttentionLegacy(nn.Module):
"""
A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
"""
Apply QKV attention.
:param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
:return: an [N x (H * C) x T] tensor after attention.
"""
bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
scale = 1 / math.sqrt(math.sqrt(ch))
weight = th.einsum(
"bct,bcs->bts", q * scale, k * scale
) # More stable with f16 than dividing afterwards
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
a = th.einsum("bts,bcs->bct", weight, v)
return a.reshape(bs, -1, length)
@staticmethod
def count_flops(model, _x, y):
return count_flops_attn(model, _x, y)
class QKVAttention(nn.Module):
"""
A module which performs QKV attention and splits in a different order.
"""
def __init__(self, n_heads):
super().__init__()
self.n_heads = n_heads
def forward(self, qkv):
"""
Apply QKV attention.
:param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
:return: an [N x (H * C) x T] tensor after attention.
"""
bs, width, length = qkv.shape
assert width % (3 * self.n_heads) == 0
ch = width // (3 * self.n_heads)
q, k, v = qkv.chunk(3, dim=1)
scale = 1 / math.sqrt(math.sqrt(ch))
weight = th.einsum(
"bct,bcs->bts",
(q * scale).view(bs * self.n_heads, ch, length),
(k * scale).view(bs * self.n_heads, ch, length),
) # More stable with f16 than dividing afterwards
weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
return a.reshape(bs, -1, length)
@staticmethod
def count_flops(model, _x, y):
return count_flops_attn(model, _x, y)
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,
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__()
if use_spatial_transformer:
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
if context_dim is not None:
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
if type(context_dim) == ListConfig:
context_dim = list(context_dim)
if num_heads_upsample == -1:
num_heads_upsample = num_heads
if num_heads == -1:
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
if num_head_channels == -1:
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
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 = 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
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(
conv_nd(dims, in_channels, model_channels, 3, padding=1)
)
]
)
self._feature_size = model_channels
input_block_chans = [model_channels]
ch = model_channels
ds = 1
for level, mult in enumerate(channel_mult):
for nr in range(self.num_res_blocks[level]):
layers = [
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=mult * model_channels,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = mult * model_channels
if ds in attention_resolutions:
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
if exists(disable_self_attentions):
disabled_sa = disable_self_attentions[level]
else:
disabled_sa = False
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads,
num_head_channels=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
use_checkpoint=use_checkpoint
)
)
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
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
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=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
use_checkpoint=use_checkpoint
),
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(self.num_res_blocks[level] + 1):
ich = input_block_chans.pop()
layers = [
ResBlock(
ch + ich,
time_embed_dim,
dropout,
out_channels=model_channels * mult,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = model_channels * mult
if ds in attention_resolutions:
if num_head_channels == -1:
dim_head = ch // num_heads
else:
num_heads = ch // num_head_channels
dim_head = num_head_channels
if legacy:
#num_heads = 1
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
if exists(disable_self_attentions):
disabled_sa = disable_self_attentions[level]
else:
disabled_sa = False
if not exists(num_attention_blocks) or i < num_attention_blocks[level]:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads_upsample,
num_head_channels=dim_head,
use_new_attention_order=use_new_attention_order,
) if not use_spatial_transformer else SpatialTransformer(
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
use_checkpoint=use_checkpoint
)
)
if level and i == self.num_res_blocks[level]:
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, model_channels, out_channels, 3, padding=1)),
)
if self.predict_codebook_ids:
self.id_predictor = nn.Sequential(
normalization(ch),
conv_nd(dims, model_channels, n_embed, 1),
#nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
)
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, timesteps=None, context=None, y=None, att_mask=None, **kwargs):
"""
Apply the model to an input batch.
:param x: an [N x C x ...] Tensor of inputs.
:param timesteps: a 1-D batch of timesteps.
:param context: conditioning plugged in via crossattn
: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"
hs = [] | t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) | 6 | 2023-10-27 06:56:37+00:00 | 8k |
alexeichhorn/typegpt | tests/test_openai.py | [
{
"identifier": "BaseLLMResponse",
"path": "typegpt/base.py",
"snippet": "class BaseLLMResponse(_InternalBaseLLMResponse, metaclass=LLMBaseMeta):\n if TYPE_CHECKING:\n # populated by the metaclass (ClassPlaceholder used to prevent showing up as type suggestion)\n __raw_completion__: str... | import os
import sys
import pytest
from typing import List, Optional, Union
from unittest.mock import Mock
from openai import AsyncOpenAI
from openai.types.chat import ChatCompletion
from openai.types.chat.chat_completion import Choice
from openai.types.chat.chat_completion_message import ChatCompletionMessage
from typegpt import BaseLLMResponse, LLMArrayOutput, LLMOutput, PromptTemplate
from typegpt.exceptions import LLMTokenLimitExceeded
from typegpt.openai import AsyncTypeAzureOpenAI, AsyncTypeOpenAI, OpenAIChatModel, TypeAzureOpenAI, TypeOpenAI | 3,676 | message=ChatCompletionMessage(role="assistant", content=content_res),
)
],
)
mocker.patch("typegpt.openai._async.chat_completion.AsyncTypeChatCompletion.create", new=async_mock)
@pytest.mark.asyncio
async def test_mock_end_to_end_parse_retry(self, mock_openai_retry_completion):
class FullExamplePrompt(PromptTemplate):
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
class Output(BaseLLMResponse):
title: str
items: list[str] = LLMArrayOutput((1, 2), instruction=lambda _: "Put the items here")
count: int
client = AsyncTypeOpenAI(api_key="mock")
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo", prompt=FullExamplePrompt(), max_output_tokens=100, retry_on_parse_error=5
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "Some title n"
assert result.items == ["abc"]
assert result.count == 42
@pytest.mark.asyncio
async def test_mock_reduce_prompt(self, mock_openai_completion):
class NonAutomaticReducingPrompt(PromptTemplate):
def __init__(self, number: int):
self.lines = [f"This is line {i}" for i in range(number)]
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "My lines:\n\n" + "\n".join(self.lines)
class Output(BaseLLMResponse):
lines: list[str]
non_reducing_prompt_100 = NonAutomaticReducingPrompt(100)
client = AsyncTypeOpenAI(api_key="mock")
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=non_reducing_prompt_100,
max_output_tokens=100,
)
non_reducing_prompt_1000 = NonAutomaticReducingPrompt(1000)
with pytest.raises(LLMTokenLimitExceeded):
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=non_reducing_prompt_1000,
max_output_tokens=100,
)
class ReducingTestPrompt(PromptTemplate):
def __init__(self, number: int):
self.lines = [f"This is line {i}" for i in range(number)]
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "My lines:\n\n" + "\n".join(self.lines)
class Output(BaseLLMResponse):
lines: list[str]
def reduce_if_possible(self) -> bool:
if len(self.lines) > 10:
# remove last 10 lines
self.lines = self.lines[:-10]
return True
return False
reducing_prompt_100 = ReducingTestPrompt(100)
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=reducing_prompt_100,
max_output_tokens=100,
)
assert len(reducing_prompt_100.lines) == 100
reducing_prompt_1000 = ReducingTestPrompt(1000)
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=reducing_prompt_1000,
max_output_tokens=100,
)
# -
def test_dynamic_output_type(self, mock_openai_completion_sync):
class FullExamplePrompt(PromptTemplate):
def __init__(self, name: str):
self.name = name
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
@property
def Output(self):
class Output(BaseLLMResponse):
|
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + "/../")
class TestOpenAIChatCompletion:
def test_token_counter(self):
test_messages = [
{"role": "system", "content": "This is a system message"},
{"role": "user", "content": "This is a user message 🧑🏾"},
]
# check if test covers all models (increase if new models are added)
assert len(OpenAIChatModel.__args__) == 14 # type: ignore
client = AsyncTypeOpenAI(api_key="mock")
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-3.5-turbo") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-3.5-turbo-0301") == 29
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-3.5-turbo-0613") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-3.5-turbo-1106") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-3.5-turbo-16k") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-3.5-turbo-16k-0613") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4-0314") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4-0613") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4-32k") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4-32k-0314") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4-32k-0613") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4-1106-preview") == 27
assert client.chat.completions.num_tokens_from_messages(test_messages, model="gpt-4-vision-preview") == 27
# -
@pytest.fixture
def mock_openai_completion(self, mocker):
async def async_mock(*args, **kwargs):
return ChatCompletion(
id="test",
model="gpt-3.5-turbo",
object="chat.completion",
created=123,
choices=[
Choice(
finish_reason="stop",
index=1,
message=ChatCompletionMessage(role="assistant", content="TITLE: This is a test completion\nCOUNT: 09"),
)
],
)
mocker.patch("typegpt.openai._async.chat_completion.AsyncTypeChatCompletion.create", new=async_mock)
@pytest.mark.asyncio
async def test_mock_end_to_end(self, mock_openai_completion):
class FullExamplePrompt(PromptTemplate):
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
class Output(BaseLLMResponse):
title: str
count: int
client = AsyncTypeOpenAI(api_key="mock")
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=FullExamplePrompt.Output,
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
result_base = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
# -
class AlternativeOutput(BaseLLMResponse):
count: int
result_alt = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=AlternativeOutput,
max_output_tokens=100,
)
assert isinstance(result_alt, AlternativeOutput)
assert result_alt.count == 9
assert not hasattr(result_alt, "title")
@pytest.mark.asyncio
async def test_mock_end_to_end_azure(Self, mock_openai_completion):
class FullExamplePrompt(PromptTemplate):
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
class Output(BaseLLMResponse):
title: str
count: int
client = AsyncTypeAzureOpenAI(api_key="mock", azure_endpoint="mock", api_version="mock")
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=FullExamplePrompt.Output,
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
result_base = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
# -
class AlternativeOutput(BaseLLMResponse):
count: int
result_alt = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=AlternativeOutput,
max_output_tokens=100,
)
assert isinstance(result_alt, AlternativeOutput)
assert result_alt.count == 9
assert not hasattr(result_alt, "title")
@pytest.fixture
def mock_openai_completion_sync(self, mocker):
def sync_mock(*args, **kwargs):
return ChatCompletion(
id="test",
model="gpt-3.5-turbo",
object="chat.completion",
created=123,
choices=[
Choice(
finish_reason="stop",
index=1,
message=ChatCompletionMessage(role="assistant", content="TITLE: This is a test completion\nCOUNT: 09"),
)
],
)
mocker.patch("typegpt.openai._sync.chat_completion.TypeChatCompletion.create", new=sync_mock)
def test_mock_end_to_end_sync(self, mock_openai_completion_sync):
class FullExamplePrompt(PromptTemplate):
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
class Output(BaseLLMResponse):
title: str
count: int
client = TypeOpenAI(api_key="mock")
result = client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=FullExamplePrompt.Output,
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
result_base = client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
# -
class AlternativeOutput(BaseLLMResponse):
count: int
result_alt = client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=AlternativeOutput,
max_output_tokens=100,
)
assert isinstance(result_alt, AlternativeOutput)
assert result_alt.count == 9
assert not hasattr(result_alt, "title")
def test_mock_end_to_end_sync_azure(self, mock_openai_completion_sync):
class FullExamplePrompt(PromptTemplate):
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
class Output(BaseLLMResponse):
title: str
count: int
client = TypeAzureOpenAI(api_key="mock", azure_endpoint="mock", api_version="mock")
result = client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=FullExamplePrompt.Output,
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
result_base = client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
max_output_tokens=100,
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "This is a test completion"
assert result.count == 9
# -
class AlternativeOutput(BaseLLMResponse):
count: int
result_alt = client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=FullExamplePrompt(),
output_type=AlternativeOutput,
max_output_tokens=100,
)
assert isinstance(result_alt, AlternativeOutput)
assert result_alt.count == 9
assert not hasattr(result_alt, "title")
@pytest.fixture
def mock_openai_retry_completion(self, mocker):
call_count = 0
async def async_mock(*args, **kwargs):
nonlocal call_count
call_count += 1
if call_count == 6:
content_res = "TITLE: Some title n\nCOUNT: 42\nITEM 1: abc"
elif call_count == 5:
content_res = "TITLE: Some title n\nCOUNT: 42"
elif call_count == 4:
content_res = "Random stuff" # no content
elif call_count == 3:
content_res = "TITLE: Some title\nCOUNT: 99999\nITEM 1: abc\nITEM 2: def\nITEM 3: ghi" # too many items
elif call_count == 2:
content_res = "TITLE: Some title\nCOUNT: random string\nITEM 1: abc" # wrong type
else:
content_res = "TITLE: Only title\nITEM 1: abc"
return ChatCompletion(
id="test",
model="gpt-3.5-turbo",
object="chat.completion",
created=123,
choices=[
Choice(
finish_reason="stop",
index=1,
message=ChatCompletionMessage(role="assistant", content=content_res),
)
],
)
mocker.patch("typegpt.openai._async.chat_completion.AsyncTypeChatCompletion.create", new=async_mock)
@pytest.mark.asyncio
async def test_mock_end_to_end_parse_retry(self, mock_openai_retry_completion):
class FullExamplePrompt(PromptTemplate):
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
class Output(BaseLLMResponse):
title: str
items: list[str] = LLMArrayOutput((1, 2), instruction=lambda _: "Put the items here")
count: int
client = AsyncTypeOpenAI(api_key="mock")
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo", prompt=FullExamplePrompt(), max_output_tokens=100, retry_on_parse_error=5
)
assert isinstance(result, FullExamplePrompt.Output)
assert result.title == "Some title n"
assert result.items == ["abc"]
assert result.count == 42
@pytest.mark.asyncio
async def test_mock_reduce_prompt(self, mock_openai_completion):
class NonAutomaticReducingPrompt(PromptTemplate):
def __init__(self, number: int):
self.lines = [f"This is line {i}" for i in range(number)]
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "My lines:\n\n" + "\n".join(self.lines)
class Output(BaseLLMResponse):
lines: list[str]
non_reducing_prompt_100 = NonAutomaticReducingPrompt(100)
client = AsyncTypeOpenAI(api_key="mock")
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=non_reducing_prompt_100,
max_output_tokens=100,
)
non_reducing_prompt_1000 = NonAutomaticReducingPrompt(1000)
with pytest.raises(LLMTokenLimitExceeded):
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=non_reducing_prompt_1000,
max_output_tokens=100,
)
class ReducingTestPrompt(PromptTemplate):
def __init__(self, number: int):
self.lines = [f"This is line {i}" for i in range(number)]
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "My lines:\n\n" + "\n".join(self.lines)
class Output(BaseLLMResponse):
lines: list[str]
def reduce_if_possible(self) -> bool:
if len(self.lines) > 10:
# remove last 10 lines
self.lines = self.lines[:-10]
return True
return False
reducing_prompt_100 = ReducingTestPrompt(100)
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=reducing_prompt_100,
max_output_tokens=100,
)
assert len(reducing_prompt_100.lines) == 100
reducing_prompt_1000 = ReducingTestPrompt(1000)
result = await client.chat.completions.generate_output(
model="gpt-3.5-turbo",
prompt=reducing_prompt_1000,
max_output_tokens=100,
)
# -
def test_dynamic_output_type(self, mock_openai_completion_sync):
class FullExamplePrompt(PromptTemplate):
def __init__(self, name: str):
self.name = name
def system_prompt(self) -> str:
return "This is a random system prompt"
def user_prompt(self) -> str:
return "This is a random user prompt"
@property
def Output(self):
class Output(BaseLLMResponse): | title: str = LLMOutput(f"The title of {self.name}") | 2 | 2023-10-25 22:17:27+00:00 | 8k |
andriioreshk1118/python-storage-main | tests/unit/test_bucket.py | [
{
"identifier": "DEFAULT_RETRY",
"path": "google/cloud/storage/retry.py",
"snippet": "DEFAULT_RETRY = retry.Retry(predicate=_should_retry)"
},
{
"identifier": "DEFAULT_RETRY_IF_ETAG_IN_JSON",
"path": "google/cloud/storage/retry.py",
"snippet": "DEFAULT_RETRY_IF_ETAG_IN_JSON = Conditional... | import datetime
import unittest
import mock
import pytest
import google.auth.credentials
import datetime
import datetime
import datetime
import datetime
import datetime
import datetime
import datetime
import datetime
import datetime
import datetime
import datetime
import operator
import operator
import base64
import json
from google.cloud.storage.retry import DEFAULT_RETRY
from google.cloud.storage.retry import DEFAULT_RETRY_IF_ETAG_IN_JSON
from google.cloud.storage.retry import DEFAULT_RETRY_IF_GENERATION_SPECIFIED
from google.cloud.storage.retry import DEFAULT_RETRY_IF_METAGENERATION_SPECIFIED
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_ENFORCED
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_INHERITED
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_UNSPECIFIED
from google.cloud.storage.constants import RPO_DEFAULT
from google.cloud.storage.constants import RPO_ASYNC_TURBO
from google.cloud.storage.bucket import _blobs_page_start
from google.cloud.storage.bucket import _item_to_blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.bucket import LifecycleRuleConditions
from google.cloud.storage.bucket import LifecycleRuleDelete
from google.cloud.storage.bucket import LifecycleRuleSetStorageClass
from google.cloud.storage.bucket import (
LifecycleRuleAbortIncompleteMultipartUpload,
)
from google.cloud.storage.bucket import IAMConfiguration
from google.cloud.storage.bucket import Bucket
from google.cloud._helpers import UTC
from google.cloud._helpers import UTC
from google.cloud._helpers import UTC
from google.cloud._helpers import UTC
from google.cloud._helpers import _datetime_to_rfc3339
from google.cloud.storage.bucket import Bucket
from google.cloud.storage.constants import _DEFAULT_TIMEOUT
from google.cloud.storage.client import Client
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.notification import BucketNotification
from google.cloud.storage.notification import NONE_PAYLOAD_FORMAT
from google.cloud.storage.notification import (
BucketNotification,
OBJECT_FINALIZE_EVENT_TYPE,
OBJECT_DELETE_EVENT_TYPE,
JSON_API_V1_PAYLOAD_FORMAT,
)
from google.cloud.exceptions import NotFound
from google.cloud.storage.acl import BucketACL
from google.cloud.storage.acl import DefaultObjectACL
from google.cloud.exceptions import NotFound
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import Blob
from google.cloud.storage.blob import _get_encryption_headers
from google.cloud.storage.bucket import _item_to_notification
from google.cloud.storage.bucket import _item_to_notification
from google.cloud.exceptions import NotFound
from google.cloud.storage.notification import BucketNotification
from google.cloud.storage.notification import _TOPIC_REF_FMT
from google.cloud.storage.notification import JSON_API_V1_PAYLOAD_FORMAT
from google.cloud.exceptions import NotFound
from google.cloud.exceptions import NotFound
from google.cloud.exceptions import NotFound
from google.cloud.exceptions import NotFound
from google.cloud.exceptions import NotFound
from google.cloud.storage.blob import Blob
from google.cloud.storage.acl import ObjectACL
from google.cloud.storage import bucket as bucket_module
from google.cloud.storage.bucket import IAMConfiguration
from google.cloud._helpers import UTC
from google.cloud._helpers import _datetime_to_rfc3339
from google.cloud.storage.bucket import IAMConfiguration
from google.cloud.storage.bucket import (
LifecycleRuleDelete,
LifecycleRuleSetStorageClass,
LifecycleRuleAbortIncompleteMultipartUpload,
)
from google.cloud.storage.bucket import (
LifecycleRuleDelete,
LifecycleRuleSetStorageClass,
)
from google.cloud.storage.constants import REGION_LOCATION_TYPE
from google.cloud._helpers import _datetime_to_rfc3339
from google.cloud._helpers import UTC
from google.cloud.storage import constants
from google.cloud._helpers import _datetime_to_rfc3339
from google.cloud._helpers import UTC
from google.cloud.storage.constants import NEARLINE_STORAGE_CLASS
from google.cloud.storage.constants import STANDARD_STORAGE_CLASS
from google.cloud.storage.constants import NEARLINE_STORAGE_CLASS
from google.cloud.storage.constants import COLDLINE_STORAGE_CLASS
from google.cloud.storage.constants import ARCHIVE_STORAGE_CLASS
from google.cloud.storage.constants import MULTI_REGIONAL_LEGACY_STORAGE_CLASS
from google.cloud.storage.constants import REGIONAL_LEGACY_STORAGE_CLASS
from google.cloud.storage.constants import (
DURABLE_REDUCED_AVAILABILITY_LEGACY_STORAGE_CLASS,
)
from google.cloud._helpers import _RFC3339_MICROS
from google.cloud._helpers import UTC
from google.cloud.storage.iam import STORAGE_OWNER_ROLE
from google.cloud.storage.iam import STORAGE_EDITOR_ROLE
from google.cloud.storage.iam import STORAGE_VIEWER_ROLE
from google.api_core.iam import Policy
from google.api_core.iam import Policy
from google.cloud.storage.iam import STORAGE_OWNER_ROLE
from google.cloud.storage.iam import STORAGE_OWNER_ROLE
from google.cloud.storage.iam import STORAGE_EDITOR_ROLE
from google.cloud.storage.iam import STORAGE_VIEWER_ROLE
from google.api_core.iam import Policy
from google.cloud.storage.iam import STORAGE_OWNER_ROLE
from google.cloud.storage.iam import STORAGE_EDITOR_ROLE
from google.cloud.storage.iam import STORAGE_VIEWER_ROLE
from google.api_core.iam import Policy
from google.cloud.storage.iam import STORAGE_OBJECTS_LIST
from google.cloud.storage.iam import STORAGE_BUCKETS_GET
from google.cloud.storage.iam import STORAGE_BUCKETS_UPDATE
from google.cloud.storage.iam import STORAGE_OBJECTS_LIST
from google.cloud.storage.iam import STORAGE_BUCKETS_GET
from google.cloud.storage.iam import STORAGE_BUCKETS_UPDATE
from google.cloud.storage.acl import _ACLEntity
from google.cloud.storage.acl import _ACLEntity
from google.cloud.storage.acl import _ACLEntity
from google.cloud.storage.acl import _ACLEntity
from google.cloud.storage.acl import _ACLEntity
from google.cloud._helpers import _datetime_to_rfc3339
from google.cloud._helpers import _datetime_to_rfc3339
from urllib import parse
from google.cloud._helpers import UTC
from google.cloud.storage._helpers import _bucket_bound_hostname_url
from google.cloud.storage.blob import _API_ACCESS_ENDPOINT
from google.cloud.storage.bucket import Bucket
from google.cloud.storage.bucket import Bucket
from google.cloud.storage.bucket import Bucket
from google.cloud._helpers import UTC
from google.cloud.storage.bucket import _item_to_notification
from google.cloud.storage.notification import BucketNotification
from google.cloud.storage.notification import _TOPIC_REF_FMT
from google.cloud.storage.notification import NONE_PAYLOAD_FORMAT | 4,158 | rule = self._make_one(age=10, matches_storage_class=["COLDLINE"])
expected = {
"action": {"type": "Delete"},
"condition": {"age": 10, "matchesStorageClass": ["COLDLINE"]},
}
self.assertEqual(dict(rule), expected)
def test_from_api_repr(self):
klass = self._get_target_class()
conditions = {
"age": 10,
"createdBefore": "2018-08-01",
"isLive": True,
"matchesStorageClass": ["COLDLINE"],
"numNewerVersions": 3,
}
resource = {"action": {"type": "Delete"}, "condition": conditions}
rule = klass.from_api_repr(resource)
self.assertEqual(dict(rule), resource)
class Test_LifecycleRuleSetStorageClass(unittest.TestCase):
@staticmethod
def _get_target_class():
return LifecycleRuleSetStorageClass
def _make_one(self, **kw):
return self._get_target_class()(**kw)
def test_ctor_wo_conditions(self):
with self.assertRaises(ValueError):
self._make_one(storage_class="COLDLINE")
def test_ctor_w_condition(self):
rule = self._make_one(
storage_class="COLDLINE", age=10, matches_storage_class=["NEARLINE"]
)
expected = {
"action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
"condition": {"age": 10, "matchesStorageClass": ["NEARLINE"]},
}
self.assertEqual(dict(rule), expected)
def test_from_api_repr(self):
klass = self._get_target_class()
conditions = {
"age": 10,
"createdBefore": "2018-08-01",
"isLive": True,
"matchesStorageClass": ["NEARLINE"],
"numNewerVersions": 3,
}
resource = {
"action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
"condition": conditions,
}
rule = klass.from_api_repr(resource)
self.assertEqual(dict(rule), resource)
class Test_LifecycleRuleAbortIncompleteMultipartUpload(unittest.TestCase):
@staticmethod
def _get_target_class():
return LifecycleRuleAbortIncompleteMultipartUpload
def _make_one(self, **kw):
return self._get_target_class()(**kw)
def test_ctor_wo_conditions(self):
with self.assertRaises(ValueError):
self._make_one()
def test_ctor_w_condition(self):
rule = self._make_one(age=10)
expected = {
"action": {"type": "AbortIncompleteMultipartUpload"},
"condition": {"age": 10},
}
self.assertEqual(dict(rule), expected)
def test_from_api_repr(self):
klass = self._get_target_class()
conditions = {
"age": 10,
}
resource = {
"action": {"type": "AbortIncompleteMultipartUpload"},
"condition": conditions,
}
rule = klass.from_api_repr(resource)
self.assertEqual(dict(rule), resource)
class Test_IAMConfiguration(unittest.TestCase):
@staticmethod
def _get_target_class():
return IAMConfiguration
def _make_one(self, bucket, **kw):
return self._get_target_class()(bucket, **kw)
@staticmethod
def _make_bucket():
return mock.create_autospec(Bucket, instance=True)
def test_ctor_defaults(self):
bucket = self._make_bucket()
config = self._make_one(bucket)
self.assertIs(config.bucket, bucket)
self.assertFalse(config.uniform_bucket_level_access_enabled)
self.assertIsNone(config.uniform_bucket_level_access_locked_time)
# TODO: Remove unspecified after changeover is complete
self.assertIn(
config.public_access_prevention,
| # Copyright 2014 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
def _create_signing_credentials():
class _SigningCredentials(
google.auth.credentials.Credentials, google.auth.credentials.Signing
):
pass
credentials = mock.Mock(spec=_SigningCredentials)
return credentials
class Test__blobs_page_start(unittest.TestCase):
@staticmethod
def _call_fut(iterator, page, response):
return _blobs_page_start(iterator, page, response)
def test_wo_any_prefixes(self):
iterator = mock.Mock(spec=["prefixes"], prefixes=set())
page = mock.Mock(spec=["prefixes"])
response = {}
self._call_fut(iterator, page, response)
self.assertEqual(page.prefixes, ())
self.assertEqual(iterator.prefixes, set())
def test_w_prefixes(self):
iterator_prefixes = set(["foo/", "qux/"])
iterator = mock.Mock(spec=["prefixes"], prefixes=iterator_prefixes)
page = mock.Mock(spec=["prefixes"])
page_prefixes = ["foo/", "bar/", "baz/"]
response = {"prefixes": page_prefixes}
self._call_fut(iterator, page, response)
self.assertEqual(page.prefixes, tuple(page_prefixes))
self.assertEqual(iterator.prefixes, iterator_prefixes.union(page_prefixes))
class Test__item_to_blob(unittest.TestCase):
@staticmethod
def _call_fut(iterator, item):
return _item_to_blob(iterator, item)
def test_wo_extra_properties(self):
blob_name = "blob-name"
bucket = mock.Mock(spec=[])
iterator = mock.Mock(spec=["bucket"], bucket=bucket)
item = {"name": blob_name}
blob = self._call_fut(iterator, item)
self.assertIsInstance(blob, Blob)
self.assertIs(blob.bucket, bucket)
self.assertEqual(blob.name, blob_name)
self.assertEqual(blob._properties, item)
def test_w_extra_properties(self):
blob_name = "blob-name"
bucket = mock.Mock(spec=[])
iterator = mock.Mock(spec=["bucket"], bucket=bucket)
item = {
"name": blob_name,
"generation": 123,
"contentType": "text/plain",
"contentLanguage": "en-US",
}
blob = self._call_fut(iterator, item)
self.assertIsInstance(blob, Blob)
self.assertIs(blob.bucket, bucket)
self.assertEqual(blob.name, blob_name)
self.assertEqual(blob._properties, item)
class Test_LifecycleRuleConditions(unittest.TestCase):
@staticmethod
def _get_target_class():
return LifecycleRuleConditions
def _make_one(self, **kw):
return self._get_target_class()(**kw)
def test_ctor_wo_conditions(self):
with self.assertRaises(ValueError):
self._make_one()
def test_ctor_w_age_and_matches_storage_class(self):
conditions = self._make_one(age=10, matches_storage_class=["COLDLINE"])
expected = {"age": 10, "matchesStorageClass": ["COLDLINE"]}
self.assertEqual(dict(conditions), expected)
self.assertEqual(conditions.age, 10)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertEqual(conditions.matches_storage_class, ["COLDLINE"])
self.assertIsNone(conditions.number_of_newer_versions)
def test_ctor_w_created_before_and_is_live(self):
before = datetime.date(2018, 8, 1)
conditions = self._make_one(created_before=before, is_live=False)
expected = {"createdBefore": "2018-08-01", "isLive": False}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertEqual(conditions.created_before, before)
self.assertEqual(conditions.is_live, False)
self.assertIsNone(conditions.matches_storage_class)
self.assertIsNone(conditions.number_of_newer_versions)
self.assertIsNone(conditions.days_since_custom_time)
self.assertIsNone(conditions.custom_time_before)
self.assertIsNone(conditions.noncurrent_time_before)
def test_ctor_w_number_of_newer_versions(self):
conditions = self._make_one(number_of_newer_versions=3)
expected = {"numNewerVersions": 3}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertIsNone(conditions.matches_storage_class)
self.assertEqual(conditions.number_of_newer_versions, 3)
def test_ctor_w_days_since_custom_time(self):
conditions = self._make_one(
number_of_newer_versions=3, days_since_custom_time=2
)
expected = {"numNewerVersions": 3, "daysSinceCustomTime": 2}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertIsNone(conditions.matches_storage_class)
self.assertEqual(conditions.number_of_newer_versions, 3)
self.assertEqual(conditions.days_since_custom_time, 2)
def test_ctor_w_days_since_noncurrent_time(self):
conditions = self._make_one(
number_of_newer_versions=3, days_since_noncurrent_time=2
)
expected = {"numNewerVersions": 3, "daysSinceNoncurrentTime": 2}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertIsNone(conditions.matches_storage_class)
self.assertEqual(conditions.number_of_newer_versions, 3)
self.assertEqual(conditions.days_since_noncurrent_time, 2)
def test_ctor_w_custom_time_before(self):
custom_time_before = datetime.date(2018, 8, 1)
conditions = self._make_one(
number_of_newer_versions=3, custom_time_before=custom_time_before
)
expected = {
"numNewerVersions": 3,
"customTimeBefore": custom_time_before.isoformat(),
}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertIsNone(conditions.matches_storage_class)
self.assertEqual(conditions.number_of_newer_versions, 3)
self.assertEqual(conditions.custom_time_before, custom_time_before)
def test_ctor_w_noncurrent_time_before(self):
noncurrent_before = datetime.date(2018, 8, 1)
conditions = self._make_one(
number_of_newer_versions=3, noncurrent_time_before=noncurrent_before
)
expected = {
"numNewerVersions": 3,
"noncurrentTimeBefore": noncurrent_before.isoformat(),
}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertIsNone(conditions.matches_storage_class)
self.assertEqual(conditions.number_of_newer_versions, 3)
self.assertEqual(conditions.noncurrent_time_before, noncurrent_before)
def test_ctor_w_matches_prefix(self):
conditions = self._make_one(matches_prefix=["test-prefix"])
expected = {"matchesPrefix": ["test-prefix"]}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertIsNone(conditions.matches_storage_class)
self.assertIsNone(conditions.matches_suffix)
self.assertEqual(conditions.matches_prefix, ["test-prefix"])
def test_ctor_w_matches_suffix(self):
conditions = self._make_one(matches_suffix=["test-suffix"])
expected = {"matchesSuffix": ["test-suffix"]}
self.assertEqual(dict(conditions), expected)
self.assertIsNone(conditions.age)
self.assertIsNone(conditions.created_before)
self.assertIsNone(conditions.is_live)
self.assertIsNone(conditions.matches_storage_class)
self.assertIsNone(conditions.matches_prefix)
self.assertEqual(conditions.matches_suffix, ["test-suffix"])
def test_from_api_repr(self):
custom_time_before = datetime.date(2018, 8, 1)
noncurrent_before = datetime.date(2018, 8, 1)
before = datetime.date(2018, 8, 1)
klass = self._get_target_class()
resource = {
"age": 10,
"createdBefore": "2018-08-01",
"isLive": True,
"matchesStorageClass": ["COLDLINE"],
"numNewerVersions": 3,
"daysSinceCustomTime": 2,
"customTimeBefore": custom_time_before.isoformat(),
"daysSinceNoncurrentTime": 2,
"noncurrentTimeBefore": noncurrent_before.isoformat(),
}
conditions = klass.from_api_repr(resource)
self.assertEqual(conditions.age, 10)
self.assertEqual(conditions.created_before, before)
self.assertEqual(conditions.is_live, True)
self.assertEqual(conditions.matches_storage_class, ["COLDLINE"])
self.assertEqual(conditions.number_of_newer_versions, 3)
self.assertEqual(conditions.days_since_custom_time, 2)
self.assertEqual(conditions.custom_time_before, custom_time_before)
self.assertEqual(conditions.days_since_noncurrent_time, 2)
self.assertEqual(conditions.noncurrent_time_before, noncurrent_before)
class Test_LifecycleRuleDelete(unittest.TestCase):
@staticmethod
def _get_target_class():
return LifecycleRuleDelete
def _make_one(self, **kw):
return self._get_target_class()(**kw)
def test_ctor_wo_conditions(self):
with self.assertRaises(ValueError):
self._make_one()
def test_ctor_w_condition(self):
rule = self._make_one(age=10, matches_storage_class=["COLDLINE"])
expected = {
"action": {"type": "Delete"},
"condition": {"age": 10, "matchesStorageClass": ["COLDLINE"]},
}
self.assertEqual(dict(rule), expected)
def test_from_api_repr(self):
klass = self._get_target_class()
conditions = {
"age": 10,
"createdBefore": "2018-08-01",
"isLive": True,
"matchesStorageClass": ["COLDLINE"],
"numNewerVersions": 3,
}
resource = {"action": {"type": "Delete"}, "condition": conditions}
rule = klass.from_api_repr(resource)
self.assertEqual(dict(rule), resource)
class Test_LifecycleRuleSetStorageClass(unittest.TestCase):
@staticmethod
def _get_target_class():
return LifecycleRuleSetStorageClass
def _make_one(self, **kw):
return self._get_target_class()(**kw)
def test_ctor_wo_conditions(self):
with self.assertRaises(ValueError):
self._make_one(storage_class="COLDLINE")
def test_ctor_w_condition(self):
rule = self._make_one(
storage_class="COLDLINE", age=10, matches_storage_class=["NEARLINE"]
)
expected = {
"action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
"condition": {"age": 10, "matchesStorageClass": ["NEARLINE"]},
}
self.assertEqual(dict(rule), expected)
def test_from_api_repr(self):
klass = self._get_target_class()
conditions = {
"age": 10,
"createdBefore": "2018-08-01",
"isLive": True,
"matchesStorageClass": ["NEARLINE"],
"numNewerVersions": 3,
}
resource = {
"action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
"condition": conditions,
}
rule = klass.from_api_repr(resource)
self.assertEqual(dict(rule), resource)
class Test_LifecycleRuleAbortIncompleteMultipartUpload(unittest.TestCase):
@staticmethod
def _get_target_class():
return LifecycleRuleAbortIncompleteMultipartUpload
def _make_one(self, **kw):
return self._get_target_class()(**kw)
def test_ctor_wo_conditions(self):
with self.assertRaises(ValueError):
self._make_one()
def test_ctor_w_condition(self):
rule = self._make_one(age=10)
expected = {
"action": {"type": "AbortIncompleteMultipartUpload"},
"condition": {"age": 10},
}
self.assertEqual(dict(rule), expected)
def test_from_api_repr(self):
klass = self._get_target_class()
conditions = {
"age": 10,
}
resource = {
"action": {"type": "AbortIncompleteMultipartUpload"},
"condition": conditions,
}
rule = klass.from_api_repr(resource)
self.assertEqual(dict(rule), resource)
class Test_IAMConfiguration(unittest.TestCase):
@staticmethod
def _get_target_class():
return IAMConfiguration
def _make_one(self, bucket, **kw):
return self._get_target_class()(bucket, **kw)
@staticmethod
def _make_bucket():
return mock.create_autospec(Bucket, instance=True)
def test_ctor_defaults(self):
bucket = self._make_bucket()
config = self._make_one(bucket)
self.assertIs(config.bucket, bucket)
self.assertFalse(config.uniform_bucket_level_access_enabled)
self.assertIsNone(config.uniform_bucket_level_access_locked_time)
# TODO: Remove unspecified after changeover is complete
self.assertIn(
config.public_access_prevention, | [PUBLIC_ACCESS_PREVENTION_UNSPECIFIED, PUBLIC_ACCESS_PREVENTION_INHERITED], | 6 | 2023-10-31 10:36:21+00:00 | 8k |
worldbank/blackmarblepy | src/blackmarble/raster.py | [
{
"identifier": "BlackMarbleDownloader",
"path": "src/blackmarble/download.py",
"snippet": "class BlackMarbleDownloader(BaseModel):\n \"\"\"A downloader to retrieve `NASA Black Marble <https://blackmarble.gsfc.nasa.gov>`_ data.\n\n Attributes\n ----------\n bearer: str\n NASA EarthDat... | import datetime
import re
import tempfile
import geopandas
import h5py
import numpy as np
import pandas as pd
import rasterio
import rioxarray
import xarray as xr
from pathlib import Path
from typing import List, Optional
from pydantic import ConfigDict, validate_call
from rasterio.transform import from_origin
from rioxarray.merge import merge_arrays
from shapely.geometry import mapping
from tqdm.auto import tqdm
from .download import BlackMarbleDownloader
from .types import Product | 3,957 | height, width = da.shape
return from_origin(
left,
top,
(right - left) / width,
(top - bottom) / height,
)
def _pivot_paths_by_date(paths: List[Path]):
"""Return dictionary of paths by date
Returns
-------
dict
"""
results = {}
for p in paths:
key = datetime.datetime.strptime(p.stem.split(".")[1], "A%Y%j").date()
if key not in results:
results[key] = []
results[key].append(p)
return results
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def bm_raster(
gdf: geopandas.GeoDataFrame,
product_id: Product,
date_range: datetime.date | List[datetime.date],
bearer: str,
variable: Optional[str] = None,
quality_flag_rm: List[int] = [255],
check_all_tiles_exist: bool = True,
file_directory: Optional[Path] = None,
file_prefix: Optional[str] = None,
file_skip_if_exists: bool = True,
):
"""Create a stack of nighttime lights rasters by retrieiving from `NASA Black Marble <https://blackmarble.gsfc.nasa.gov>`_ data.
Parameters
----------
roi: geopandas.GeoDataFrame
Region of interest
product_id: Product
NASA Black Marble product suite (VNP46) identifier. The available products are shown in following list:
- ``VNP46A1``: Daily (raw)
- ``VNP46A2``: Daily (corrected)
- ``VNP46A3``: Monthly
- ``VNP46A4``: Annual
date_range: datetime.date | List[datetime.date]
Date range (single date or list of dates) for which to retrieve NASA Black Marble data.
bearer: str
NASA Earthdata Bearer token. Please refer to the `documentation <https://worldbank.github.io/blackmarblepy/examples/blackmarblepy.html#nasa-earthdata-bearer-token>`_.
variable: str, default = None
Variable to create GeoTIFF raster. Further information, pleae see the `NASA Black Marble User Guide <https://ladsweb.modaps.eosdis.nasa.gov/api/v2/content/archives/Document%20Archive/Science%20Data%20Product%20Documentation/VIIRS_Black_Marble_UG_v1.2_April_2021.pdf>`_ for `VNP46A1`, see Table 3; for `VNP46A2` see Table 6; for `VNP46A3` and `VNP46A4`, see Table 9. By default, it uses the following default variables:
- For ``VNP46A1``, uses ``DNB_At_Sensor_Radiance_500m``
- For ``VNP46A2``, uses ``Gap_Filled_DNB_BRDF-Corrected_NTL``
- For ``VNP46A3``, uses ``NearNadir_Composite_Snow_Free``.
- For ``VNP46A4``, uses ``NearNadir_Composite_Snow_Free``.
quality_flag: List[int], default = [255]
Quality flag values to use to set values to ``NA``. Each pixel has a quality flag value, where low quality values can be removed. Values are set to ``NA`` for each value in ther ``quality_flag_rm`` vector.
For ``VNP46A1`` and ``VNP46A2`` (daily data):
- ``0``: High-quality, Persistent nighttime lights
- ``1``: High-quality, Ephemeral nighttime Lights
- ``2``: Poor-quality, Outlier, potential cloud contamination, or other issues
- ``255``: No retrieval, Fill value (masked out on ingestion)
For ``VNP46A3`` and ``VNP46A4`` (monthly and annual data):
- ``0``: Good-quality, The number of observations used for the composite is larger than 3
- ``1``: Poor-quality, The number of observations used for the composite is less than or equal to 3
- ``2``: Gap filled NTL based on historical data
- ``255``: Fill value
check_all_tiles_exist: bool, default=True
Check whether all Black Marble nighttime light tiles exist for the region of interest. Sometimes not all tiles are available, so the full region of interest may not be covered. By default (True), it skips cases where not all tiles are available.
file_directory: pathlib.Path, optional
Where to produce output. By default, the output will be procuded onto a temporary directory.
file_prefix: str, optional
Prefix
file_skip_if_exists: bool, default=True
Whether to skip downloading or extracting data if the data file for that date already exists.
Returns
-------
xarray.Dataset
A Xarray dataset contaning a stack of nighttime lights rasters
"""
# Validate and fix args
if not isinstance(quality_flag_rm, list):
quality_flag_rm = [quality_flag_rm]
if not isinstance(date_range, list):
date_range = [date_range]
if variable is None:
variable = VARIABLE_DEFAULT.get(product_id)
match product_id:
case Product.VNP46A3:
date_range = sorted(set([d.replace(day=1) for d in date_range]))
case Product.VNP46A4:
date_range = sorted(set([d.replace(day=1, month=1) for d in date_range]))
# Download and construct Dataset
with file_directory if file_directory else tempfile.TemporaryDirectory() as d:
|
VARIABLE_DEFAULT = {
Product.VNP46A1: "DNB_At_Sensor_Radiance_500m",
Product.VNP46A2: "Gap_Filled_DNB_BRDF-Corrected_NTL",
Product.VNP46A3: "NearNadir_Composite_Snow_Free",
Product.VNP46A4: "NearNadir_Composite_Snow_Free",
}
def h5_to_geotiff(
f: Path,
/,
variable: str = None,
quality_flag_rm=[255],
output_directory: Path = None,
output_prefix: str = None,
):
"""
Convert HDF5 file to GeoTIFF for a selected (or default) variable from NASA Black Marble data
Parameters
----------
f: Path
H5DF filename
variable: str, default = None
Variable to create GeoTIFF raster. Further information, pleae see the `NASA Black Marble User Guide <https://ladsweb.modaps.eosdis.nasa.gov/api/v2/content/archives/Document%20Archive/Science%20Data%20Product%20Documentation/VIIRS_Black_Marble_UG_v1.2_April_2021.pdf>`_ for `VNP46A1`, see Table 3; for `VNP46A2` see Table 6; for `VNP46A3` and `VNP46A4`, see Table 9. By default, it uses the following default variables:
- For ``VNP46A1``, uses ``DNB_At_Sensor_Radiance_500m``
- For ``VNP46A2``, uses ``Gap_Filled_DNB_BRDF-Corrected_NTL``
- For ``VNP46A3``, uses ``NearNadir_Composite_Snow_Free``.
- For ``VNP46A4``, uses ``NearNadir_Composite_Snow_Free``.
Returns
------
output_path: Path
Path to which export GeoTIFF file
"""
output_path = Path(output_directory, f.name).with_suffix(".tif")
product_id = Product(f.stem.split(".")[0])
if variable is None:
variable = VARIABLE_DEFAULT.get(product_id)
with h5py.File(f, "r") as h5_data:
attrs = h5_data.attrs
if product_id in [Product.VNP46A1, Product.VNP46A2]:
dataset = h5_data["HDFEOS"]["GRIDS"]["VNP_Grid_DNB"]["Data Fields"][
variable
]
left, bottom, right, top = (
attrs.get("WestBoundingCoord"),
attrs.get("SouthBoundingCoord"),
attrs.get("EastBoundingCoord"),
attrs.get("NorthBoundingCoord"),
)
qf = h5_data["HDFEOS"]["GRIDS"]["VNP_Grid_DNB"]["Data Fields"][
"Mandatory_Quality_Flag"
]
else:
dataset = h5_data["HDFEOS"]["GRIDS"]["VIIRS_Grid_DNB_2d"]["Data Fields"][
variable
]
lat = h5_data["HDFEOS"]["GRIDS"]["VIIRS_Grid_DNB_2d"]["Data Fields"]["lat"]
lon = h5_data["HDFEOS"]["GRIDS"]["VIIRS_Grid_DNB_2d"]["Data Fields"]["lon"]
left, bottom, right, top = min(lon), min(lat), max(lon), max(lat)
if len(quality_flag_rm) > 0:
variable_short = variable
variable_short = re.sub("_Num", "", variable_short)
variable_short = re.sub("_Std", "", variable_short)
h5_names = list(
h5_data["HDFEOS"]["GRIDS"]["VIIRS_Grid_DNB_2d"][
"Data Fields"
].keys()
)
if (qf_name := f"{variable_short}_Quality") in h5_names:
qf = h5_data["HDFEOS"]["GRIDS"]["VIIRS_Grid_DNB_2d"]["Data Fields"][
qf_name
]
if variable in h5_names:
qf = h5_data["HDFEOS"]["GRIDS"]["VIIRS_Grid_DNB_2d"]["Data Fields"][
variable
]
# Extract data and attributes
scale_factor = dataset.attrs.get("scale_factor", 1)
offset = dataset.attrs.get("offset", 0)
data = scale_factor * dataset[:] + offset
qf = qf[:]
for val in quality_flag_rm:
data = np.where(qf == val, np.nan, data)
# Get geospatial metadata (coordinates and attributes)
height, width = data.shape
transform = from_origin(
left,
top,
(right - left) / width,
(top - bottom) / height,
)
with rasterio.open(
output_path,
"w",
driver="GTiff",
height=height,
width=width,
count=1,
dtype=data.dtype,
crs="EPSG:4326",
transform=transform,
) as dst:
dst.write(data, 1)
dst.update_tags(**attrs)
return output_path
def transform(da: xr.DataArray):
"""Return Affice transformation"""
left, bottom, right, top = (
da["x"].min(),
da["y"].min(),
da["x"].max(),
da["y"].max(),
)
height, width = da.shape
return from_origin(
left,
top,
(right - left) / width,
(top - bottom) / height,
)
def _pivot_paths_by_date(paths: List[Path]):
"""Return dictionary of paths by date
Returns
-------
dict
"""
results = {}
for p in paths:
key = datetime.datetime.strptime(p.stem.split(".")[1], "A%Y%j").date()
if key not in results:
results[key] = []
results[key].append(p)
return results
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def bm_raster(
gdf: geopandas.GeoDataFrame,
product_id: Product,
date_range: datetime.date | List[datetime.date],
bearer: str,
variable: Optional[str] = None,
quality_flag_rm: List[int] = [255],
check_all_tiles_exist: bool = True,
file_directory: Optional[Path] = None,
file_prefix: Optional[str] = None,
file_skip_if_exists: bool = True,
):
"""Create a stack of nighttime lights rasters by retrieiving from `NASA Black Marble <https://blackmarble.gsfc.nasa.gov>`_ data.
Parameters
----------
roi: geopandas.GeoDataFrame
Region of interest
product_id: Product
NASA Black Marble product suite (VNP46) identifier. The available products are shown in following list:
- ``VNP46A1``: Daily (raw)
- ``VNP46A2``: Daily (corrected)
- ``VNP46A3``: Monthly
- ``VNP46A4``: Annual
date_range: datetime.date | List[datetime.date]
Date range (single date or list of dates) for which to retrieve NASA Black Marble data.
bearer: str
NASA Earthdata Bearer token. Please refer to the `documentation <https://worldbank.github.io/blackmarblepy/examples/blackmarblepy.html#nasa-earthdata-bearer-token>`_.
variable: str, default = None
Variable to create GeoTIFF raster. Further information, pleae see the `NASA Black Marble User Guide <https://ladsweb.modaps.eosdis.nasa.gov/api/v2/content/archives/Document%20Archive/Science%20Data%20Product%20Documentation/VIIRS_Black_Marble_UG_v1.2_April_2021.pdf>`_ for `VNP46A1`, see Table 3; for `VNP46A2` see Table 6; for `VNP46A3` and `VNP46A4`, see Table 9. By default, it uses the following default variables:
- For ``VNP46A1``, uses ``DNB_At_Sensor_Radiance_500m``
- For ``VNP46A2``, uses ``Gap_Filled_DNB_BRDF-Corrected_NTL``
- For ``VNP46A3``, uses ``NearNadir_Composite_Snow_Free``.
- For ``VNP46A4``, uses ``NearNadir_Composite_Snow_Free``.
quality_flag: List[int], default = [255]
Quality flag values to use to set values to ``NA``. Each pixel has a quality flag value, where low quality values can be removed. Values are set to ``NA`` for each value in ther ``quality_flag_rm`` vector.
For ``VNP46A1`` and ``VNP46A2`` (daily data):
- ``0``: High-quality, Persistent nighttime lights
- ``1``: High-quality, Ephemeral nighttime Lights
- ``2``: Poor-quality, Outlier, potential cloud contamination, or other issues
- ``255``: No retrieval, Fill value (masked out on ingestion)
For ``VNP46A3`` and ``VNP46A4`` (monthly and annual data):
- ``0``: Good-quality, The number of observations used for the composite is larger than 3
- ``1``: Poor-quality, The number of observations used for the composite is less than or equal to 3
- ``2``: Gap filled NTL based on historical data
- ``255``: Fill value
check_all_tiles_exist: bool, default=True
Check whether all Black Marble nighttime light tiles exist for the region of interest. Sometimes not all tiles are available, so the full region of interest may not be covered. By default (True), it skips cases where not all tiles are available.
file_directory: pathlib.Path, optional
Where to produce output. By default, the output will be procuded onto a temporary directory.
file_prefix: str, optional
Prefix
file_skip_if_exists: bool, default=True
Whether to skip downloading or extracting data if the data file for that date already exists.
Returns
-------
xarray.Dataset
A Xarray dataset contaning a stack of nighttime lights rasters
"""
# Validate and fix args
if not isinstance(quality_flag_rm, list):
quality_flag_rm = [quality_flag_rm]
if not isinstance(date_range, list):
date_range = [date_range]
if variable is None:
variable = VARIABLE_DEFAULT.get(product_id)
match product_id:
case Product.VNP46A3:
date_range = sorted(set([d.replace(day=1) for d in date_range]))
case Product.VNP46A4:
date_range = sorted(set([d.replace(day=1, month=1) for d in date_range]))
# Download and construct Dataset
with file_directory if file_directory else tempfile.TemporaryDirectory() as d: | downloader = BlackMarbleDownloader(bearer, d) | 0 | 2023-10-26 09:17:26+00:00 | 8k |
TopGuru777/badsecrets | tests/all_modules_test.py | [
{
"identifier": "check_all_modules",
"path": "badsecrets/base.py",
"snippet": "def check_all_modules(*args, **kwargs):\n for m in BadsecretsBase.__subclasses__():\n x = m(custom_resource=kwargs.get(\"custom_resource\", None))\n r = x.check_secret(*args[0 : x.check_secret_args])\n ... | import requests
import requests_mock
from badsecrets.base import check_all_modules, carve_all_modules | 7,123 |
tests = [
"yJrdyJV6tkmHLII2uDq1Sl509UeDg9xGI4u3tb6dm9BQS4wD08KTkyXKST4PeQs00giqSA==",
"eyJoZWxsbyI6IndvcmxkIn0.XDtqeQ.1qsBdjyRJLokwRzJdzXMVCSyRTA",
"vpwClvnLODIx9te2vO%2F4e06KzbKkjtwmNnMx09D1Dmau0dPliYzgpqB9MnEqhPNe3fWemQyH25eLULJi8KiYHXeHvjfS1TZAL2o5Gku1gJbLuqusRXZQYTNlU2Aq4twXO0o0CgVUTfknU89iw0ceyaKjSteOhxGvaE3VEDfiKDd8%2B9j9vD3qso0mLMqn%2Btxirc%2FkIq5oBbzOCgMrJjkaPMa2SJpc5QI2amffBJ%2BsAN25VH%2BwabEJXrjRy%2B8NlYCoUQQKrI%2BEzRSdBsiMOxQTD4vz2TCjSKrK5JEeFMTyE7J39MhXFG38Bq%2FZMDO%2FETHHdsBtTTkqzJ2odVArcOzrce3Kt2%2FqgTUPW%2BCjFtkSNmh%2FzlB9BhbxB1kJt1NkNsjywvP9j7PvNoOBJsa8OwpEyrPTT3Gm%2BfhDwtjvwpvN7l7oIfbcERGExAFrAMENOOt4WGlYhF%2F8c9NcDv0Bv3YJrJoGq0rRurXSh9kcwum9nB%2FGWcjPikqTDm6p3Z48hEnQCVuJNkwJwIKEsYxJqCL95IEdX3PzR81zf36uXPlEa3YdeAgM1RD8YGlwlIXnrLhvMbRvQW0W9eoPzE%2FjP68JGUIZc1TwTQusIWjnuVubFTEUMDLfDNk12tMwM9mfnwT8lWFTMjv9pF70W5OtO7gVN%2BOmCxqAuQmScRVExNds%2FF%2FPli4oxRKfgI7FhAaC%2Fu1DopZ6vvBdUq1pBQE66fQ9SnxRTmIClCpULUhNO90ULTpUi9ga2UtBCTzI8z6Sb6qyQ52NopNZMFdrn9orzdP8oqFeyYpF%2BQEtbp%2F5AMENkFkWUxHZn8NoSlO8P6G6ubSyDdY4QJPaFS4FxNhhm85WlZC9xfEZ1AGSSBOu9JJVYiKxXnL1yYLqrlWp5mfBHZeUBwEa%2FMjGxZEVYDhXo4PiU0jxN7fYmjaobp3DSgA5H3BcFuNG5d8CUnOlQcEie5b%2BUHOpI9zAk7qcuEUXbaZ5Mvh0t2jXCRALRKYDyBdbHlWAFo10dTIM6L3aSTM5uEz9%2FalXLXoWlMo7dTDpuO5bBfTq7YkoPExL3g3JJX47UhuLq85i3%2Bzxfvd7r%2Fmid69kbD3PnX%2Bj0QxaiShhyOZg6jl1HMeRRXvZap3FPCIfxbCf7j2TRqB5gYefBIIdGYjrdiL6HS8SbjXcROMwh2Fxnt505X4jmkmDcGmneU3z%2B84TSSFewcSpxGEGvHVkkU4OaT6vyFwsxCmdrR187tQZ7gn3ZkAiTps%2FfOPcL5QWXja06Z%2FHT3zboq6Hj9v9NBHzpC1eAK0YN8r4V2UMI3P0%2FsIPQYXhovoeLjJwq6snKZTX37ulE1mbS1uOY%2BZrvFYbLN5DdNL%2B%2Bl%2F%2BcWIpc0RSYBLo19xHpKeoeLjU2sxaYzK%2B92D4zKANdPPvsHPqJD1Y%2FBwCL%2FfZKaJfRK9Bj09ez1Z1ixTEKjIRCwuxijnJGq33faZchbwpMPpTfv43jEriGwXwoqOo9Mbj9ggPAil7O81XZxNT4vv4RoxXTN93V100rt3ClXauL%2BlNID%2BseN2CEZZqnygpTDf2an%2FVsmJGJJcc0goW3l43mhx2U79zeuT94cFPGpvITEbMtjmuNsUbOBuw6nqm5rAs%2FxjIsDRqfQxGQWfS0kuwuU6RRmiME2Ps0NrBENIbZzcbgw6%2BRIwClWkvEG%2BK%2FPdcAdfmRkAPWUNadxnhjeU2jNnzI1yYNIOhziUBPxgFEcAT45E7rWvf8ghT08HZvphzytPmD%2FxuvJaDdRgb6a30TjSpa7i%2BEHkIMxM5eH1kiwhN6xkTcBsJ87epGdFRWKhTGKYwCbaYid1nRs7%2BvQEU7MRYghok8KMTueELipohm3otuKo8V4a7w4TgTSBvPE%2BLPLJRwhM8KcjGlcpzF1NowRo6zeJJhbdPpouUH2NJzDcp7P4uUuUB9Cxt9B986My6zDnz1eyBvRMzj7TABfmfPFPoY3RfzBUzDm%2FA9lOGsM6d9WZj2CH0WxqiLDGmP1Ts9DWX%2FsYyqEGK5R1Xpnp7kRIarPtYliecp50ZIH6nqSkoCBllMCCE6JN%2BdoXobTpulALdmQV0%2Bppv%2FAjzIJrTHgX7jwRGEAeRgAxTomtemmIaH5NtV7xt8XS%2BqwghdJl1D06%2FWhpMtJ1%2FoQGoJ0%2F7ChYyefyAfsiQNWsO66UNVyl71RVPwATnbRO5K5mtxn0M2wuXXpAARNh6pQTcVX%2FTJ4jmosyKwhI6I870NEOsSaWlKVyOdb97C3Bt0pvzq8BagV5FMsNtJKmqIIM0HRkMkalIyfow9iS%2B5xGN5eKM8NE4E6hO4CvmpG%2BH2xFHTSNzloV0FjLdDmj5UfMjhUuEb3rkKK1bGAVaaherp6Ai6N4YJQzh%2FDdpo6al95EZN2OYolzxitgDgsWVGhMvddyQTwnRqRY04hdVJTwdhi4TiCPbLJ1Wcty2ozy6VDs4w77EOAQ5JnxUmDVPA3vXmADJZR0hIJEsuxXfYg%2BRIdV4fzGunV4%2B9jpiyM9G11iiesURK82o%2BdcG7FaCkkun2K2bvD6qGcL61uhoxNeLVpAxjrRjaEBrXsexZ9rExpMlFD8e3NM%2B0K0LQJvdEvpWYS5UTG9cAbNAzBs%3DpDsPXFGf2lEMcyGaK1ouARHUfqU0fzkeVwjXU9ORI%2Fs%3D",
"qAAAAAQDAgEBAAAAvAIAAAAAAAAsAAAABABTaGRyAk4AdQg4AC4AMQAwABRhZGwcBykRPNQv++kTK0KePPqVVGgAAAAFAFNkYXRhXHicHYc7DkBQAATnIUqVa3jxLRzApxJBrxA18bmdw1l2k9nZG/Bcxxjt4/An3NnYOVlZOMRL7ld0NAQ9IzUTMy0DeUpMqkYkso+ZGFNiKbRW//Pyb0Guzwtozw4Q",
".eJxVjLsOAiEURP-F2hAuL8HSfr-BAPciq4ZNlt3K-O9KsoU2U8w5My8W4r7VsHdaw4zswoCdfrsU84PaAHiP7bbwvLRtnRMfCj9o59OC9Lwe7t9Bjb2OtbMkAEGQtQjekykmJy9JZIW-6CgUaCGsA6eSyV65s1Qya_xGKZrY-wPVYjdw:1ojOrE:bfOktjgLlUykwCIRIpvaTZRQMM3-UypscEN57ECtXis",
"dUEvRldLekFNcklGZ3ZSbU1XaHJ0ZGxsLzhYTHlNTW43T3BVN05kZXE3WUhQOVVKbVA3Rm5WaSs5eG5QQ1VIRVBzeDFNTnNpZ0xCM1FKbzFZTEJISzhaNzFmVGYzME0waDFURVpCYm5TQlJFRmRFclYzNUZhR3VuN29PMmlkVHBrRi8wb3AwZWgvWmxObkFOYnpkeHR1YWpWZ3lnN0Y4ZW9xSk9LNVlQd0U4MmFsbWtLZUI5VzkzRkM4YXBFWXBWLS15L00xME1nVFp2ZTlmUWcxZVlpelpnPT0=--7efe7919a5210cfd1ac4c6228e3ff82c0600d841",
"eyJhbGciOiJIUzI1NiJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkJhZFNlY3JldHMiLCJleHAiOjE1OTMxMzM0ODMsImlhdCI6MTQ2NjkwMzA4M30.ovqRikAo_0kKJ0GVrAwQlezymxrLGjcEiW_s3UJMMCo",
"owOnMokk%2F4N7IMo6gznRP56OYIT34dZ1Bh0KBbXlFgztgiNNEBYrgWRYDBkDlX8BIFYBcBztC3NMwoT%2FtNF%2Ff2nCsA37ORIgfBem1foENqumZvmcTpQuoiXXbMWW8oDjs270y6LDAmHhCRsl4Itox4NSBwDgMIOsoMhNrMigV7o7jlgU16L3ezISSmVqFektKmu9qATIXme63u4IKk9UL%2BGP%2Fk3NPv9MsTEVH1wMEf4MApH5KfWBX96TRIc9nlp3IE5BEWNMvI1Gd%2BWXbY5cSY%2Buey2mXQ%2BAFuXAernruJDm%2BxK8ZZ09TNsn5UREutvNtFRrePA8tz3r7p14yG756E0vrU7uBz5TQlTPNUeN3shdxlMK5Qzw1EqxRZmjhaRpMN0YZgmjIpzFgrTnT0%2Bo0f6keaL8Z9TY8vJN8%2BEUPoq%2F7AJiHKm1C8GNc3woVzs5mJKZxMUP398HwGTDv9KSwwkSpHeXFsZofbaWyG0WuNldHNzM%2FgyWMsnGxY6S086%2F477xEQkWdWG5UE%2FowesockebyTTEn3%2B%2FqiVy%2FIOxXvMpvrLel5nVY%2FSouHp5n2URRyRsfo%2B%2BOXJZo7yxKQoYBSSkmxdehJqKJmbgxNp5Ew8m89xAS5g99Hzzg382%2BxFp8yoDVZMOiTEuw0J%2B4G6KizqRW9cis%2FELd0aDE1V7TUuJnFrX%2BlCLOiv100tKpeJ0ePMOYrmvSn0wx7JhswNuj%2BgdKqvCnMSLakGWiOHxu5m9Qqdm3s5sk7nsaxMkh8IqV%2BSzB9A2K1kYEUlY40II1Wun67OSdLlYfdCFQk4ED0N%2BV4kES%2F1xpGiaPhxjboFiiV%2BkvCyJfkuotYuN%2B42CqFyAyepXPA%2BR5jVSThT6OIN2n1UahUnrD%2BwKKGMA9QpVPTSiGLen2KSnJtXISbrl2%2BA2AnQNH%2BMEwYVNjseM0%2BAosbgVfNde2ukMyugo%2FRfrRM27cbdVlE0ms0uXhlgKAYJ2ZN54w1tPWhpGxvZtB0keWpZan0YPh8CBgzsAIMa04HMYLCtgUTqxKqANoKXSy7VIJUzg3fl%2F2WUELjpXK9gRcgexNWDNB1E0rHd9PUo0PvpB4fxSrRpb1LRryipqsuoJ8mrpOVrVMvjracBvtoykK3GrN%2FDUlXkSG%2FAeBQN7HwDJ9QPi3AtEOohp78Op3nmbItXo7IJUSjzBNzUYR8YPj6Ud7Fje9LZSwMBngvgx%2BOKy6HsV4ofOAU2%2FK1%2BfxI0KkCeoSso9NJHWgBD7ijfXUa1Hrc%2FuNU3mTlSSVp3VStQrJbQCkr4paaHYWeeO4pRZCDSBNUzs9qq3TDePwpEQc4QROrw5htdniRk26lFIFm%2Fzk2nC77Pg%2BrkRC1W%2BlRv0lyXsmXVBCe8F1szpWXHCxHNAJwKH%2FBb%2BV1k6AXFXVWPW5vADbXUvRu0s6KLaqu6a0KCB7dt3K2Ni%2FI6O%2FmISYXzknbMrwwakNfajbRF2ibodgR9R9xvoCoCXa3ka7%2Fejr%2BmsZ2HvPKUAffd2fNIWCQrejfpuIoOWiYx6ufN8E41HetCbYfvsI6JQfPOEdOYWI2px%2BLdfO3Nybq99%2BRSQOhjNZakBP54ozlCUfwgpLOmTBwsswZexv1RK5MIi8%2FWtjlJ%2FKjkYxdkFUlwggGS2xDwzcyl2%2FakNCQ5YmxjU8cRY7jZQRMo%2F8uTw5qa2MNZPaQGI18uRgr0i%2FTX3t57fJYCpMLXSaUKIdO7O%2FCQhIyGTS6KrPN%2B3%2FgUb%2BPQ1viGhpnWfGEYF9vhIlK57z8G8G82UQ3DpttD7M8mQ0KsmCOq75ECx9CWrWGk51vADlm%2BLEZ5oWjVMs%2FThki40B7tL7gzFrBuQksWXYeubMzZfFo4ZQ49di4wupHG5kRsyL2fJUzgpaLDP%2BSe6%2FjCnc52C7lZ3Ls0cHJVf9HRwDNXWM%2B4h8donNy5637QWK%2BV7mlH%2FL4xBZCfU9l6sIz%2FWHMtRaQprEem6a%2FRwPRDBiP65I2EwZLKGY8I%2F1uXJncwC8egLu82JY9maweI0VmJSmRcTf0evxqqe7vc9MqpsUlpSVNh4bFnxVIo5E4PGX70kVaTFe0vu1YdGKmFX5PLvkmWIf%2FnwfgPMqYsa0%2F09trboJ5LGDEQRXSBb7ldG%2FwLdOiqocYKAb91SMpn1fXVPBgkPM27QZxHnSAmWVbJR2%2FIhO%2BIVNzkgFAJlptiEPPPTxuBh%2BTT7CaIQE3oZbbJeQKvRkrt4bawTCOzciU%2F1zFGxubTJTSyInjQ8%2F1tVo7KjnxPKqGSfwZQN%2FeWL6R%2FpvCb%2BE6D4pdyczoJRUWsSNXNnA7QrdjgGNWhyOMiKvkDf3RD4mrXbul18WYVTsLyp0hvQsbdwBWOh7VlwfrWdy%2BklsttFi%2B%2BadKR7DbwjLTcxvdNpTx1WJhXROR8jwW26VEYSXPVqWnYvfyZo4DojKHMSDMbAakbuSJdkGP1d5w0AYbKlAcVQOqp9hbAvfwwLy4ErdIsOg0YEeCcnQVRAXwaCI9JvWWmM%2FzYJzE3X45A6lU9Pe7TAbft810MYh7lmV6Keb5HI6qXFiD%2B8khBZqi%2FsK6485k0a86aWLxOb4Eqnoc41x%2BYPv5CWfvP6cebsENo%3D%2BIUg0f64C4y77N4FZ6C82m5wMpvDQIHqx0ZFIHLhwMg%3D",
"8H61sylBH/Ad3thZCGDVLyaso2g499GnjAuqpNapesoJgoo5Zk3nxDqXoWfRDwzmKk6eDLTyWViTRTdnr8Su7+XzW6MMAcZo+Fa7UwdfE4pKJ2+z6OYK58l+/93LHZmgVUF5dqI3G8mLr3uI",
"H4sIAAAAAAAAAAG4BEf7SqmRq5Y9DfCIR9QLZ9wfMXuwWMtbz4CYqd0%2FCCMNXbRgEOJmkCbpKBJXQ%2BAz78OO%2FufCpa1k1nqcEgNxRzRnKKNVBBPMov%2FE%2BXFqh%2Bb5KZLhJvXicwGSIuVshN1XYpSRzKrosUB0ykN8j9hA90IA5AulHsXIofHj07FlFC%2BTbQqVZ7jKeHDurUkVhf8WQ1up%2BVO9KZwQU6WZzsF5y6AkidThF411avCLTxGAtIC7uZBnzMLL4duUf7YtdIDHt4UWGsXCI7ItciWv4Dzk9w5bKeWRRLp1W1pbniEQY01lTulTZBYPuLtna6pB0I3EJ5bV4c3Gktdd1YAVQcBQ2Yy5TW92YEclM99vW9mwu6xD8ZRYJNIb622TjjFMvmR4u4sNh%2BdgL5MlagVpvQjIxUmP7TzelScfku0PrKnKve2zzG6m8czF2WgbQcSLk%2B6TJAijmezo0byTzBsc0FbiI16jm7OBn%2Bi4xCBJQ0AHtu%2Bj2kUE3SUp3wnwgvCR9EnQIw%2F8p2PIp1h6FG6QOIKamihDeY9r5RCW7yLds5vwmUgT9mPTfN%2B%2Fjpzp4U4axfZv5yrVyMSpsuDEhj0H0CjYQMssn%2BsXMYOJGLqv%2FF0SrGrtcAGYv12%2B17PybzbqrXGe8xYR%2B9wHaKX3CD5Ak3IE0CiILhEIZrDICPTifm8%2FygUDztVZmHwpM6HBpF2inkGbaX6Fa8BOrMJaEqZWAualYYBth37jWyqCKV01TWFfHtS7y7kvkWOPwYYORzx9IKO5yyFrftg4hCH7f5vtHsMoyP8CcWPh9c82O70CIlscfLURWeoAyXv1FYtgC6pBLVlgdHEjMzjKvK7DRtJliNPl0VGazg5jTAYHtuwdc23jIjwBfG0MXpPjkw%2BVR179clfwK4t1VfJTJF8F02EXZXaZzCA7cH%2B%2B3bQaXOpvZBTFGdD9JnwRp2vEhy8%2BWMXhd7C%2BcmliOvraOoK%2Fksa9PNarTZJTTJuZupvYwBWhx%2F2vVDEdCM81Z7bFgb0wGd9ViHIOz0MH8v%2FIgn6qd2ojjnkJ29MfSfhtRi%2BXAvmgFXoIhlIBXBwapozxsKcDXOc5JRWpK%2F7y4naW7Fuogp1oU1fHXOXnQh8FAsjgyqn3J0acyY7FDKtkAjxDTMThh1GrA4dLvvLjPx%2FKUMeCQSZ1Y01X%2BNVRbxXBLGLkDbcBHNmkTTaxbsctSBBMSyOYQfG5W9%2Bhw9D2AFSWwFAuz%2BCDvsPSze0CYDoG9lbuYnW2wseNiKYItaSQhUbnq3SGVcjy1JouogVK63TDGTwE8Cy3UoNrAz%2FzV7AaoVjytyuMBqOTYBS%2BSLif1R2qqeut0ID%2BCudcjrKJvcP1J8rHV%2F5h2lRNj7tW0wVQS4XtqpnPy90BhF%2BgcfCy7FtRJbH8i5HAl5FY1OpZQ68ig12imShpNI%2FgHuO2q3n5%2FVUFia7fwHqkkuZBRZHreEvEyPlUpgwJhpCBS3F8b1ViO2G5zsTNF9TR%2BzW8UJVG2lhMdcvZw92dg%2F74tndJ8LzhVrQrG5au9yu6fUExO5MNz6izVMFzOxG6FqxUcm8otgf6qqSBi23jrMceNzAT8LcREGoVvjmj8uINrJbJt9ZfXb%2BaIYsMGsc2uAQAAA%3D%3D",
"https://localhost/_fragment?_path=_controller%3Dsystem%26command%3Did%26return_value%3Dnull&_hash=Xnsvx/yLVQaimEd1CfepgH0rEXr422JnRSn/uaCE3gs=",
"s%3A8FnPwdeM9kdGTZlWvdaVtQ0S1BCOhY5G.qys7H2oGSLLdRsEq7sqh7btOohHsaRKqyjV4LiVnBvc",
"eyJpdiI6IlhlNTZ2UjZUQWZKVHdIcG9nZFkwcGc9PSIsInZhbHVlIjoiRlUvY2grU1F1b01lSXdveXJ0T3N1WGJqeVVmZlNRQjNVOWxiSzljL1Z3RDhqYUdDbjZxMU9oSThWRzExT0YvUmthVzVKRE9kL0RvTEw1cFRhQkphOGw4S2loV1ZrMkkwTHd4am9sZkJQd2VCZ3R0VlFSeFo3ay9wTlBMb3lLSG8iLCJtYWMiOiJkMmU3M2ExNDc2NTc5YjAwMGMwMTdkYTQ1NThkMjRkNTY2YTE4OTg2MzY5MzE5NGZmOTM4YWVjOGZmMWU4NTk2IiwidGFnIjoiIn0%3D",
]
negative_tests = [
"AAAAAAAA",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZFNpZ25hdHVyZSIsImlhdCI6MTUxNjIzOTAyMn0.S_8lg9Pzezv8JhXT3cppPZcz046cFM8H1o1GJYYAAAA",
"AAAA℗",
]
def test_check_all():
# Confirm each of the examples produced a positive result
for test in tests:
|
tests = [
"yJrdyJV6tkmHLII2uDq1Sl509UeDg9xGI4u3tb6dm9BQS4wD08KTkyXKST4PeQs00giqSA==",
"eyJoZWxsbyI6IndvcmxkIn0.XDtqeQ.1qsBdjyRJLokwRzJdzXMVCSyRTA",
"vpwClvnLODIx9te2vO%2F4e06KzbKkjtwmNnMx09D1Dmau0dPliYzgpqB9MnEqhPNe3fWemQyH25eLULJi8KiYHXeHvjfS1TZAL2o5Gku1gJbLuqusRXZQYTNlU2Aq4twXO0o0CgVUTfknU89iw0ceyaKjSteOhxGvaE3VEDfiKDd8%2B9j9vD3qso0mLMqn%2Btxirc%2FkIq5oBbzOCgMrJjkaPMa2SJpc5QI2amffBJ%2BsAN25VH%2BwabEJXrjRy%2B8NlYCoUQQKrI%2BEzRSdBsiMOxQTD4vz2TCjSKrK5JEeFMTyE7J39MhXFG38Bq%2FZMDO%2FETHHdsBtTTkqzJ2odVArcOzrce3Kt2%2FqgTUPW%2BCjFtkSNmh%2FzlB9BhbxB1kJt1NkNsjywvP9j7PvNoOBJsa8OwpEyrPTT3Gm%2BfhDwtjvwpvN7l7oIfbcERGExAFrAMENOOt4WGlYhF%2F8c9NcDv0Bv3YJrJoGq0rRurXSh9kcwum9nB%2FGWcjPikqTDm6p3Z48hEnQCVuJNkwJwIKEsYxJqCL95IEdX3PzR81zf36uXPlEa3YdeAgM1RD8YGlwlIXnrLhvMbRvQW0W9eoPzE%2FjP68JGUIZc1TwTQusIWjnuVubFTEUMDLfDNk12tMwM9mfnwT8lWFTMjv9pF70W5OtO7gVN%2BOmCxqAuQmScRVExNds%2FF%2FPli4oxRKfgI7FhAaC%2Fu1DopZ6vvBdUq1pBQE66fQ9SnxRTmIClCpULUhNO90ULTpUi9ga2UtBCTzI8z6Sb6qyQ52NopNZMFdrn9orzdP8oqFeyYpF%2BQEtbp%2F5AMENkFkWUxHZn8NoSlO8P6G6ubSyDdY4QJPaFS4FxNhhm85WlZC9xfEZ1AGSSBOu9JJVYiKxXnL1yYLqrlWp5mfBHZeUBwEa%2FMjGxZEVYDhXo4PiU0jxN7fYmjaobp3DSgA5H3BcFuNG5d8CUnOlQcEie5b%2BUHOpI9zAk7qcuEUXbaZ5Mvh0t2jXCRALRKYDyBdbHlWAFo10dTIM6L3aSTM5uEz9%2FalXLXoWlMo7dTDpuO5bBfTq7YkoPExL3g3JJX47UhuLq85i3%2Bzxfvd7r%2Fmid69kbD3PnX%2Bj0QxaiShhyOZg6jl1HMeRRXvZap3FPCIfxbCf7j2TRqB5gYefBIIdGYjrdiL6HS8SbjXcROMwh2Fxnt505X4jmkmDcGmneU3z%2B84TSSFewcSpxGEGvHVkkU4OaT6vyFwsxCmdrR187tQZ7gn3ZkAiTps%2FfOPcL5QWXja06Z%2FHT3zboq6Hj9v9NBHzpC1eAK0YN8r4V2UMI3P0%2FsIPQYXhovoeLjJwq6snKZTX37ulE1mbS1uOY%2BZrvFYbLN5DdNL%2B%2Bl%2F%2BcWIpc0RSYBLo19xHpKeoeLjU2sxaYzK%2B92D4zKANdPPvsHPqJD1Y%2FBwCL%2FfZKaJfRK9Bj09ez1Z1ixTEKjIRCwuxijnJGq33faZchbwpMPpTfv43jEriGwXwoqOo9Mbj9ggPAil7O81XZxNT4vv4RoxXTN93V100rt3ClXauL%2BlNID%2BseN2CEZZqnygpTDf2an%2FVsmJGJJcc0goW3l43mhx2U79zeuT94cFPGpvITEbMtjmuNsUbOBuw6nqm5rAs%2FxjIsDRqfQxGQWfS0kuwuU6RRmiME2Ps0NrBENIbZzcbgw6%2BRIwClWkvEG%2BK%2FPdcAdfmRkAPWUNadxnhjeU2jNnzI1yYNIOhziUBPxgFEcAT45E7rWvf8ghT08HZvphzytPmD%2FxuvJaDdRgb6a30TjSpa7i%2BEHkIMxM5eH1kiwhN6xkTcBsJ87epGdFRWKhTGKYwCbaYid1nRs7%2BvQEU7MRYghok8KMTueELipohm3otuKo8V4a7w4TgTSBvPE%2BLPLJRwhM8KcjGlcpzF1NowRo6zeJJhbdPpouUH2NJzDcp7P4uUuUB9Cxt9B986My6zDnz1eyBvRMzj7TABfmfPFPoY3RfzBUzDm%2FA9lOGsM6d9WZj2CH0WxqiLDGmP1Ts9DWX%2FsYyqEGK5R1Xpnp7kRIarPtYliecp50ZIH6nqSkoCBllMCCE6JN%2BdoXobTpulALdmQV0%2Bppv%2FAjzIJrTHgX7jwRGEAeRgAxTomtemmIaH5NtV7xt8XS%2BqwghdJl1D06%2FWhpMtJ1%2FoQGoJ0%2F7ChYyefyAfsiQNWsO66UNVyl71RVPwATnbRO5K5mtxn0M2wuXXpAARNh6pQTcVX%2FTJ4jmosyKwhI6I870NEOsSaWlKVyOdb97C3Bt0pvzq8BagV5FMsNtJKmqIIM0HRkMkalIyfow9iS%2B5xGN5eKM8NE4E6hO4CvmpG%2BH2xFHTSNzloV0FjLdDmj5UfMjhUuEb3rkKK1bGAVaaherp6Ai6N4YJQzh%2FDdpo6al95EZN2OYolzxitgDgsWVGhMvddyQTwnRqRY04hdVJTwdhi4TiCPbLJ1Wcty2ozy6VDs4w77EOAQ5JnxUmDVPA3vXmADJZR0hIJEsuxXfYg%2BRIdV4fzGunV4%2B9jpiyM9G11iiesURK82o%2BdcG7FaCkkun2K2bvD6qGcL61uhoxNeLVpAxjrRjaEBrXsexZ9rExpMlFD8e3NM%2B0K0LQJvdEvpWYS5UTG9cAbNAzBs%3DpDsPXFGf2lEMcyGaK1ouARHUfqU0fzkeVwjXU9ORI%2Fs%3D",
"qAAAAAQDAgEBAAAAvAIAAAAAAAAsAAAABABTaGRyAk4AdQg4AC4AMQAwABRhZGwcBykRPNQv++kTK0KePPqVVGgAAAAFAFNkYXRhXHicHYc7DkBQAATnIUqVa3jxLRzApxJBrxA18bmdw1l2k9nZG/Bcxxjt4/An3NnYOVlZOMRL7ld0NAQ9IzUTMy0DeUpMqkYkso+ZGFNiKbRW//Pyb0Guzwtozw4Q",
".eJxVjLsOAiEURP-F2hAuL8HSfr-BAPciq4ZNlt3K-O9KsoU2U8w5My8W4r7VsHdaw4zswoCdfrsU84PaAHiP7bbwvLRtnRMfCj9o59OC9Lwe7t9Bjb2OtbMkAEGQtQjekykmJy9JZIW-6CgUaCGsA6eSyV65s1Qya_xGKZrY-wPVYjdw:1ojOrE:bfOktjgLlUykwCIRIpvaTZRQMM3-UypscEN57ECtXis",
"dUEvRldLekFNcklGZ3ZSbU1XaHJ0ZGxsLzhYTHlNTW43T3BVN05kZXE3WUhQOVVKbVA3Rm5WaSs5eG5QQ1VIRVBzeDFNTnNpZ0xCM1FKbzFZTEJISzhaNzFmVGYzME0waDFURVpCYm5TQlJFRmRFclYzNUZhR3VuN29PMmlkVHBrRi8wb3AwZWgvWmxObkFOYnpkeHR1YWpWZ3lnN0Y4ZW9xSk9LNVlQd0U4MmFsbWtLZUI5VzkzRkM4YXBFWXBWLS15L00xME1nVFp2ZTlmUWcxZVlpelpnPT0=--7efe7919a5210cfd1ac4c6228e3ff82c0600d841",
"eyJhbGciOiJIUzI1NiJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkJhZFNlY3JldHMiLCJleHAiOjE1OTMxMzM0ODMsImlhdCI6MTQ2NjkwMzA4M30.ovqRikAo_0kKJ0GVrAwQlezymxrLGjcEiW_s3UJMMCo",
"owOnMokk%2F4N7IMo6gznRP56OYIT34dZ1Bh0KBbXlFgztgiNNEBYrgWRYDBkDlX8BIFYBcBztC3NMwoT%2FtNF%2Ff2nCsA37ORIgfBem1foENqumZvmcTpQuoiXXbMWW8oDjs270y6LDAmHhCRsl4Itox4NSBwDgMIOsoMhNrMigV7o7jlgU16L3ezISSmVqFektKmu9qATIXme63u4IKk9UL%2BGP%2Fk3NPv9MsTEVH1wMEf4MApH5KfWBX96TRIc9nlp3IE5BEWNMvI1Gd%2BWXbY5cSY%2Buey2mXQ%2BAFuXAernruJDm%2BxK8ZZ09TNsn5UREutvNtFRrePA8tz3r7p14yG756E0vrU7uBz5TQlTPNUeN3shdxlMK5Qzw1EqxRZmjhaRpMN0YZgmjIpzFgrTnT0%2Bo0f6keaL8Z9TY8vJN8%2BEUPoq%2F7AJiHKm1C8GNc3woVzs5mJKZxMUP398HwGTDv9KSwwkSpHeXFsZofbaWyG0WuNldHNzM%2FgyWMsnGxY6S086%2F477xEQkWdWG5UE%2FowesockebyTTEn3%2B%2FqiVy%2FIOxXvMpvrLel5nVY%2FSouHp5n2URRyRsfo%2B%2BOXJZo7yxKQoYBSSkmxdehJqKJmbgxNp5Ew8m89xAS5g99Hzzg382%2BxFp8yoDVZMOiTEuw0J%2B4G6KizqRW9cis%2FELd0aDE1V7TUuJnFrX%2BlCLOiv100tKpeJ0ePMOYrmvSn0wx7JhswNuj%2BgdKqvCnMSLakGWiOHxu5m9Qqdm3s5sk7nsaxMkh8IqV%2BSzB9A2K1kYEUlY40II1Wun67OSdLlYfdCFQk4ED0N%2BV4kES%2F1xpGiaPhxjboFiiV%2BkvCyJfkuotYuN%2B42CqFyAyepXPA%2BR5jVSThT6OIN2n1UahUnrD%2BwKKGMA9QpVPTSiGLen2KSnJtXISbrl2%2BA2AnQNH%2BMEwYVNjseM0%2BAosbgVfNde2ukMyugo%2FRfrRM27cbdVlE0ms0uXhlgKAYJ2ZN54w1tPWhpGxvZtB0keWpZan0YPh8CBgzsAIMa04HMYLCtgUTqxKqANoKXSy7VIJUzg3fl%2F2WUELjpXK9gRcgexNWDNB1E0rHd9PUo0PvpB4fxSrRpb1LRryipqsuoJ8mrpOVrVMvjracBvtoykK3GrN%2FDUlXkSG%2FAeBQN7HwDJ9QPi3AtEOohp78Op3nmbItXo7IJUSjzBNzUYR8YPj6Ud7Fje9LZSwMBngvgx%2BOKy6HsV4ofOAU2%2FK1%2BfxI0KkCeoSso9NJHWgBD7ijfXUa1Hrc%2FuNU3mTlSSVp3VStQrJbQCkr4paaHYWeeO4pRZCDSBNUzs9qq3TDePwpEQc4QROrw5htdniRk26lFIFm%2Fzk2nC77Pg%2BrkRC1W%2BlRv0lyXsmXVBCe8F1szpWXHCxHNAJwKH%2FBb%2BV1k6AXFXVWPW5vADbXUvRu0s6KLaqu6a0KCB7dt3K2Ni%2FI6O%2FmISYXzknbMrwwakNfajbRF2ibodgR9R9xvoCoCXa3ka7%2Fejr%2BmsZ2HvPKUAffd2fNIWCQrejfpuIoOWiYx6ufN8E41HetCbYfvsI6JQfPOEdOYWI2px%2BLdfO3Nybq99%2BRSQOhjNZakBP54ozlCUfwgpLOmTBwsswZexv1RK5MIi8%2FWtjlJ%2FKjkYxdkFUlwggGS2xDwzcyl2%2FakNCQ5YmxjU8cRY7jZQRMo%2F8uTw5qa2MNZPaQGI18uRgr0i%2FTX3t57fJYCpMLXSaUKIdO7O%2FCQhIyGTS6KrPN%2B3%2FgUb%2BPQ1viGhpnWfGEYF9vhIlK57z8G8G82UQ3DpttD7M8mQ0KsmCOq75ECx9CWrWGk51vADlm%2BLEZ5oWjVMs%2FThki40B7tL7gzFrBuQksWXYeubMzZfFo4ZQ49di4wupHG5kRsyL2fJUzgpaLDP%2BSe6%2FjCnc52C7lZ3Ls0cHJVf9HRwDNXWM%2B4h8donNy5637QWK%2BV7mlH%2FL4xBZCfU9l6sIz%2FWHMtRaQprEem6a%2FRwPRDBiP65I2EwZLKGY8I%2F1uXJncwC8egLu82JY9maweI0VmJSmRcTf0evxqqe7vc9MqpsUlpSVNh4bFnxVIo5E4PGX70kVaTFe0vu1YdGKmFX5PLvkmWIf%2FnwfgPMqYsa0%2F09trboJ5LGDEQRXSBb7ldG%2FwLdOiqocYKAb91SMpn1fXVPBgkPM27QZxHnSAmWVbJR2%2FIhO%2BIVNzkgFAJlptiEPPPTxuBh%2BTT7CaIQE3oZbbJeQKvRkrt4bawTCOzciU%2F1zFGxubTJTSyInjQ8%2F1tVo7KjnxPKqGSfwZQN%2FeWL6R%2FpvCb%2BE6D4pdyczoJRUWsSNXNnA7QrdjgGNWhyOMiKvkDf3RD4mrXbul18WYVTsLyp0hvQsbdwBWOh7VlwfrWdy%2BklsttFi%2B%2BadKR7DbwjLTcxvdNpTx1WJhXROR8jwW26VEYSXPVqWnYvfyZo4DojKHMSDMbAakbuSJdkGP1d5w0AYbKlAcVQOqp9hbAvfwwLy4ErdIsOg0YEeCcnQVRAXwaCI9JvWWmM%2FzYJzE3X45A6lU9Pe7TAbft810MYh7lmV6Keb5HI6qXFiD%2B8khBZqi%2FsK6485k0a86aWLxOb4Eqnoc41x%2BYPv5CWfvP6cebsENo%3D%2BIUg0f64C4y77N4FZ6C82m5wMpvDQIHqx0ZFIHLhwMg%3D",
"8H61sylBH/Ad3thZCGDVLyaso2g499GnjAuqpNapesoJgoo5Zk3nxDqXoWfRDwzmKk6eDLTyWViTRTdnr8Su7+XzW6MMAcZo+Fa7UwdfE4pKJ2+z6OYK58l+/93LHZmgVUF5dqI3G8mLr3uI",
"H4sIAAAAAAAAAAG4BEf7SqmRq5Y9DfCIR9QLZ9wfMXuwWMtbz4CYqd0%2FCCMNXbRgEOJmkCbpKBJXQ%2BAz78OO%2FufCpa1k1nqcEgNxRzRnKKNVBBPMov%2FE%2BXFqh%2Bb5KZLhJvXicwGSIuVshN1XYpSRzKrosUB0ykN8j9hA90IA5AulHsXIofHj07FlFC%2BTbQqVZ7jKeHDurUkVhf8WQ1up%2BVO9KZwQU6WZzsF5y6AkidThF411avCLTxGAtIC7uZBnzMLL4duUf7YtdIDHt4UWGsXCI7ItciWv4Dzk9w5bKeWRRLp1W1pbniEQY01lTulTZBYPuLtna6pB0I3EJ5bV4c3Gktdd1YAVQcBQ2Yy5TW92YEclM99vW9mwu6xD8ZRYJNIb622TjjFMvmR4u4sNh%2BdgL5MlagVpvQjIxUmP7TzelScfku0PrKnKve2zzG6m8czF2WgbQcSLk%2B6TJAijmezo0byTzBsc0FbiI16jm7OBn%2Bi4xCBJQ0AHtu%2Bj2kUE3SUp3wnwgvCR9EnQIw%2F8p2PIp1h6FG6QOIKamihDeY9r5RCW7yLds5vwmUgT9mPTfN%2B%2Fjpzp4U4axfZv5yrVyMSpsuDEhj0H0CjYQMssn%2BsXMYOJGLqv%2FF0SrGrtcAGYv12%2B17PybzbqrXGe8xYR%2B9wHaKX3CD5Ak3IE0CiILhEIZrDICPTifm8%2FygUDztVZmHwpM6HBpF2inkGbaX6Fa8BOrMJaEqZWAualYYBth37jWyqCKV01TWFfHtS7y7kvkWOPwYYORzx9IKO5yyFrftg4hCH7f5vtHsMoyP8CcWPh9c82O70CIlscfLURWeoAyXv1FYtgC6pBLVlgdHEjMzjKvK7DRtJliNPl0VGazg5jTAYHtuwdc23jIjwBfG0MXpPjkw%2BVR179clfwK4t1VfJTJF8F02EXZXaZzCA7cH%2B%2B3bQaXOpvZBTFGdD9JnwRp2vEhy8%2BWMXhd7C%2BcmliOvraOoK%2Fksa9PNarTZJTTJuZupvYwBWhx%2F2vVDEdCM81Z7bFgb0wGd9ViHIOz0MH8v%2FIgn6qd2ojjnkJ29MfSfhtRi%2BXAvmgFXoIhlIBXBwapozxsKcDXOc5JRWpK%2F7y4naW7Fuogp1oU1fHXOXnQh8FAsjgyqn3J0acyY7FDKtkAjxDTMThh1GrA4dLvvLjPx%2FKUMeCQSZ1Y01X%2BNVRbxXBLGLkDbcBHNmkTTaxbsctSBBMSyOYQfG5W9%2Bhw9D2AFSWwFAuz%2BCDvsPSze0CYDoG9lbuYnW2wseNiKYItaSQhUbnq3SGVcjy1JouogVK63TDGTwE8Cy3UoNrAz%2FzV7AaoVjytyuMBqOTYBS%2BSLif1R2qqeut0ID%2BCudcjrKJvcP1J8rHV%2F5h2lRNj7tW0wVQS4XtqpnPy90BhF%2BgcfCy7FtRJbH8i5HAl5FY1OpZQ68ig12imShpNI%2FgHuO2q3n5%2FVUFia7fwHqkkuZBRZHreEvEyPlUpgwJhpCBS3F8b1ViO2G5zsTNF9TR%2BzW8UJVG2lhMdcvZw92dg%2F74tndJ8LzhVrQrG5au9yu6fUExO5MNz6izVMFzOxG6FqxUcm8otgf6qqSBi23jrMceNzAT8LcREGoVvjmj8uINrJbJt9ZfXb%2BaIYsMGsc2uAQAAA%3D%3D",
"https://localhost/_fragment?_path=_controller%3Dsystem%26command%3Did%26return_value%3Dnull&_hash=Xnsvx/yLVQaimEd1CfepgH0rEXr422JnRSn/uaCE3gs=",
"s%3A8FnPwdeM9kdGTZlWvdaVtQ0S1BCOhY5G.qys7H2oGSLLdRsEq7sqh7btOohHsaRKqyjV4LiVnBvc",
"eyJpdiI6IlhlNTZ2UjZUQWZKVHdIcG9nZFkwcGc9PSIsInZhbHVlIjoiRlUvY2grU1F1b01lSXdveXJ0T3N1WGJqeVVmZlNRQjNVOWxiSzljL1Z3RDhqYUdDbjZxMU9oSThWRzExT0YvUmthVzVKRE9kL0RvTEw1cFRhQkphOGw4S2loV1ZrMkkwTHd4am9sZkJQd2VCZ3R0VlFSeFo3ay9wTlBMb3lLSG8iLCJtYWMiOiJkMmU3M2ExNDc2NTc5YjAwMGMwMTdkYTQ1NThkMjRkNTY2YTE4OTg2MzY5MzE5NGZmOTM4YWVjOGZmMWU4NTk2IiwidGFnIjoiIn0%3D",
]
negative_tests = [
"AAAAAAAA",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZFNpZ25hdHVyZSIsImlhdCI6MTUxNjIzOTAyMn0.S_8lg9Pzezv8JhXT3cppPZcz046cFM8H1o1GJYYAAAA",
"AAAA℗",
]
def test_check_all():
# Confirm each of the examples produced a positive result
for test in tests: | r = check_all_modules(test) | 0 | 2023-10-30 12:52:39+00:00 | 8k |
mlvlab/UP-NeRF | tto.py | [
{
"identifier": "get_from_path",
"path": "configs/config.py",
"snippet": "def get_from_path(config_path):\n config = default()\n if config_path is not None:\n merge_from_file(config, config_path)\n\n return config"
},
{
"identifier": "NeRFSystemOptimize",
"path": "models/nerf... | import argparse
import os
import random
import numpy as np
import pandas as pd
import torch
import wandb
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint, TQDMProgressBar
from pytorch_lightning.loggers import WandbLogger
from tqdm import tqdm
from configs.config import get_from_path
from models.nerf_system_optmize import NeRFSystemOptimize | 3,747 |
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def main(hparams):
setup_seed(hparams["seed"])
|
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def main(hparams):
setup_seed(hparams["seed"]) | system = NeRFSystemOptimize(hparams) | 1 | 2023-10-25 08:43:24+00:00 | 8k |
Redrrx/ProxyNest | API.py | [
{
"identifier": "get_current_user",
"path": "auth.py",
"snippet": "class User(BaseModel):\nclass ResetPasswordRequest(BaseModel):\nclass DBCON(BaseModel):\n DB_URL: str\n DB_NAME: str\n DB_USER: str\n DB_PASSWORD: str\nasync def admincheck():\nasync def get_current_user(credentials: HTTPBasi... | import asyncio
import os
import bcrypt
import uvicorn
from typing import Optional, List, Dict, Union
from fastapi import FastAPI, Query, Depends, HTTPException
from starlette import status
from starlette.responses import JSONResponse
from auth import get_current_user, collection, ResetPasswordRequest, admincheck
from proxynest import ProxyManagement, ProxyModel, SettingsModel | 6,143 |
proxy_management = ProxyManagement(
db_url=os.getenv('DB_URL'),
db_name=os.getenv('DB_NAME'),
db_user=os.getenv('DB_USER'),
db_password=os.getenv('DB_PASSWORD'),
)
app = FastAPI(title="ProxyNest",
description="ProxyNest is a proxy managment API",
version="1.0.0",
redoc_url="/redoc")
@app.post("/add_proxies", dependencies=[Depends(get_current_user)])
async def add_proxy(proxy: ProxyModel):
result = await proxy_management.add_proxy(proxy)
return result
@app.get("/proxies", dependencies=[Depends(get_current_user)])
async def get_proxies(tags: Optional[List[str]] = Query(None)):
proxies = await proxy_management.get_proxies(tags=tags)
return proxies
@app.post("/assign_proxy", dependencies=[Depends(get_current_user)])
async def assign_proxy_to_instance(instance_id: str, country_code: Optional[str] = Query(None),
tags: Optional[List[str]] = Query(None)):
result = await proxy_management.assign_proxy_to_instance(instance_id, country_code, tags)
return result
@app.post("/update_proxy/{proxy_id}", dependencies=[Depends(get_current_user)])
async def update_proxy(proxy_id: str, proxy: Dict[str, Optional[Union[str, int, List[str]]]]):
result = await proxy_management.edit_proxy(proxy_id, proxy)
return result
@app.post("/delete_proxy/{proxy_id}", dependencies=[Depends(get_current_user)])
async def delete_proxy(proxy_id: str):
result = await proxy_management.delete_proxy(proxy_id)
return result
@app.post("/refresh_proxy_usage/{proxy_id}", dependencies=[Depends(get_current_user)])
async def refresh_proxy_usage(proxy_id: str, instance_id: Optional[str] = None):
result = await proxy_management.update_last_used(proxy_id, instance_id)
if result:
if instance_id:
return {"status": "success", "message": f"Proxy {proxy_id} usage refreshed for instance {instance_id}"}
else:
return {"status": "success", "message": f"Proxy {proxy_id} usage refreshed for all instances"}
else:
return {"status": "error", "message": "Failed to refresh proxy usage"}
@app.post("/clear_instance_proxies/{instance_id}", dependencies=[Depends(get_current_user)])
async def clear_instance_reservation(instance_id: str):
return await proxy_management.clear_instance_reservation(instance_id)
@app.post("/clear_instance_from_specific_proxy/{proxy_id}/{instance_id}", dependencies=[Depends(get_current_user)])
async def clear_instance_from_specific_proxy(proxy_id: str, instance_id: str) -> JSONResponse:
result = await proxy_management.clear_instance_from_specific_proxy(proxy_id, instance_id)
return JSONResponse(content=result)
@app.post("/reset_all_proxies", dependencies=[Depends(get_current_user)])
async def reset_all_proxies():
result = await proxy_management.reset_all_proxies()
return result
@app.post("/reset-password/")
async def reset_password(
|
proxy_management = ProxyManagement(
db_url=os.getenv('DB_URL'),
db_name=os.getenv('DB_NAME'),
db_user=os.getenv('DB_USER'),
db_password=os.getenv('DB_PASSWORD'),
)
app = FastAPI(title="ProxyNest",
description="ProxyNest is a proxy managment API",
version="1.0.0",
redoc_url="/redoc")
@app.post("/add_proxies", dependencies=[Depends(get_current_user)])
async def add_proxy(proxy: ProxyModel):
result = await proxy_management.add_proxy(proxy)
return result
@app.get("/proxies", dependencies=[Depends(get_current_user)])
async def get_proxies(tags: Optional[List[str]] = Query(None)):
proxies = await proxy_management.get_proxies(tags=tags)
return proxies
@app.post("/assign_proxy", dependencies=[Depends(get_current_user)])
async def assign_proxy_to_instance(instance_id: str, country_code: Optional[str] = Query(None),
tags: Optional[List[str]] = Query(None)):
result = await proxy_management.assign_proxy_to_instance(instance_id, country_code, tags)
return result
@app.post("/update_proxy/{proxy_id}", dependencies=[Depends(get_current_user)])
async def update_proxy(proxy_id: str, proxy: Dict[str, Optional[Union[str, int, List[str]]]]):
result = await proxy_management.edit_proxy(proxy_id, proxy)
return result
@app.post("/delete_proxy/{proxy_id}", dependencies=[Depends(get_current_user)])
async def delete_proxy(proxy_id: str):
result = await proxy_management.delete_proxy(proxy_id)
return result
@app.post("/refresh_proxy_usage/{proxy_id}", dependencies=[Depends(get_current_user)])
async def refresh_proxy_usage(proxy_id: str, instance_id: Optional[str] = None):
result = await proxy_management.update_last_used(proxy_id, instance_id)
if result:
if instance_id:
return {"status": "success", "message": f"Proxy {proxy_id} usage refreshed for instance {instance_id}"}
else:
return {"status": "success", "message": f"Proxy {proxy_id} usage refreshed for all instances"}
else:
return {"status": "error", "message": "Failed to refresh proxy usage"}
@app.post("/clear_instance_proxies/{instance_id}", dependencies=[Depends(get_current_user)])
async def clear_instance_reservation(instance_id: str):
return await proxy_management.clear_instance_reservation(instance_id)
@app.post("/clear_instance_from_specific_proxy/{proxy_id}/{instance_id}", dependencies=[Depends(get_current_user)])
async def clear_instance_from_specific_proxy(proxy_id: str, instance_id: str) -> JSONResponse:
result = await proxy_management.clear_instance_from_specific_proxy(proxy_id, instance_id)
return JSONResponse(content=result)
@app.post("/reset_all_proxies", dependencies=[Depends(get_current_user)])
async def reset_all_proxies():
result = await proxy_management.reset_all_proxies()
return result
@app.post("/reset-password/")
async def reset_password( | reset_request: ResetPasswordRequest, | 0 | 2023-10-27 15:45:30+00:00 | 8k |
QutacQuantum/qugen | qugen/main/generator/discrete_qgan_model_handler.py | [
{
"identifier": "compute_gradient_JAX",
"path": "qugen/main/generator/quantum_circuits/discrete_generator_pennylane.py",
"snippet": "@partial(jax.jit, static_argnames=[\"discriminator\"])\ndef compute_gradient_JAX(samples, discriminator, discriminator_weights):\n def criterion(outputs):\n retu... | from pathlib import Path
from itertools import chain
from typing import Optional
from tqdm import tqdm
from qugen.main.generator.quantum_circuits.discrete_generator_pennylane import compute_gradient_JAX
from qugen.main.generator.base_model_handler import BaseModelHandler
from qugen.main.data.helper import CustomDataset
from qugen.main.data.data_handler import PITNormalizer, MinMaxNormalizer
from qugen.main.data.helper import kl_divergence
from qugen.main.discriminator.discriminator import Discriminator_JAX
from qugen.main.data.discretization import compute_discretization
from jax.config import config
from qugen.main.generator.quantum_circuits.discrete_generator_pennylane \
import discrete_copula_circuit_JAX as get_generator
from qugen.main.generator.quantum_circuits.discrete_generator_pennylane \
import discrete_standard_circuit_JAX as get_generator
from qugen.main.generator.quantum_circuits.discrete_generator_pennylane import \
discrete_copula_circuit_JAX as get_generator
from qugen.main.generator.quantum_circuits.discrete_generator_pennylane import \
discrete_standard_circuit_JAX as get_generator
import json
import time
import hashlib
import os
import warnings
import jax
import jax.numpy as jnp
import numpy as np
import optax
import pickle
import matplotlib.pyplot as plt
import matplotlib as mpl | 6,167 | train_dataset = self.normalizer.fit_transform(train_dataset)
self.reverse_lookup = self.normalizer.reverse_lookup
if self.save_artifacts:
with open(self.path_to_models + "/" + "meta.json", "w+") as file:
json.dump(self.metadata, file)
jnp.save(self.path_to_models + "/" + 'reverse_lookup.npy', self.reverse_lookup)
self.dict_bins = compute_discretization(self.n_qubits, self.n_registers)
n = 2 ** (self.n_qubits // self.n_registers)
nns = tuple(n for _ in range(self.n_registers))
nns_nq = nns + tuple((self.n_qubits,))
inverse_bins = np.zeros(nns_nq)
for key, value in self.dict_bins.items():
id_n = value[0]
inverse_bins[id_n] = jnp.array([int(bit) for bit in key])
coordinates = np.floor(train_dataset * n).astype(int)
train_dataset = [
inverse_bins[tuple([xy[ii] for ii in range(self.n_registers)])]
for xy in coordinates
]
train_dataset = jnp.array(train_dataset).astype(jnp.float32)
distribution_pit = np.zeros(nns)
for xy in coordinates:
indices = tuple(xy[ii] for ii in range(self.n_registers))
distribution_pit[indices] += 1
distribution_pit /= np.sum(distribution_pit)
distribution_pit = jnp.array(distribution_pit)
optimizer_discriminator = optax.adam(
learning_rate=initial_learning_rate_discriminator,
b1=self.beta_1,
b2=0.999,
)
optimizer_state_d = optimizer_discriminator.init(self.discriminator_weights)
optimizer_generator = optax.sgd(learning_rate=initial_learning_rate_generator)
self.random_key, subkey = jax.random.split(self.random_key)
optimizer_state_g = optimizer_generator.init(self.generator_weights)
kl_list_transformed_space = []
it_list = []
# create shifts in advance, leads to less code at application
elementary_shift = 1
shifts = [
[elementary_shift * e_i, -elementary_shift * e_i]
for e_i in jnp.eye(self.generator_weights.size)
]
shifts = list(chain(*shifts))
shifts = [shift.reshape(self.generator_weights.shape) for shift in shifts]
parameters = []
epsilon = 1e-10
X_train = CustomDataset(train_dataset.astype("float32"))
def cost_fn_discriminator(X, generator_weights, discriminator_weights):
self.random_key, subkey = jax.random.split(self.random_key)
G_samples = self.generator(
subkey,
generator_weights,
n_shots=len(X),
)
D_fake = self.D.apply(discriminator_weights, G_samples)
D_real = self.D.apply(discriminator_weights, X)
loss_1 = -jnp.mean(jnp.log(D_real + epsilon))
loss_2 = -jnp.mean(jnp.log(1.0 - D_fake + epsilon))
D_loss = loss_1 + loss_2
return D_loss
def cost_fn_generator(X, generator_weights, discriminator_weights):
self.random_key, subkey = jax.random.split(self.random_key)
G_samples = self.generator(
subkey,
weights=generator_weights,
n_shots=len(X),
)
D_fake = self.D.apply(discriminator_weights, G_samples)
G_loss = -jnp.mean(jnp.log(D_fake + epsilon)) # Vanilla GAN
return G_loss
progress = tqdm(range(n_epochs), mininterval=10 if self.slower_progress_update else None)
for it in progress:
if self.save_artifacts:
self.save(
f"{self.path_to_models}/parameters_training_iteration={it + self.previous_trained_epochs }.pickle",
overwrite=False,
)
data = X_train.next_batch(self.batch_size)
discriminator_training_steps = 1 # How many times is the discriminator updates per generator update
for _ in range(discriminator_training_steps):
cost_discriminator, grad_d = jax.value_and_grad(
lambda w: cost_fn_discriminator(data, self.generator_weights, w)
)(self.discriminator_weights)
updates, optimizer_state_d = optimizer_discriminator.update(
grad_d, optimizer_state_d
)
self.discriminator_weights = optax.apply_updates(
self.discriminator_weights, updates
)
# This is the method using the old manual gradient
cost_generator = cost_fn_generator(
data, self.generator_weights, self.discriminator_weights
)
self.random_key, *subkeys = jax.random.split(self.random_key, num=len(shifts) + 1)
G_samples = [
self.generator(
subkey,
self.generator_weights + parameter_shift,
n_shots=self.batch_size,
)
for subkey, parameter_shift in zip(subkeys, shifts)
]
| # Copyright 2023 QUTAC, BASF Digital Solutions GmbH, BMW Group,
# Lufthansa Industry Solutions AS GmbH, Merck KGaA (Darmstadt, Germany),
# Munich Re, SAP SE.
# 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.
config.update("jax_enable_x64", True)
mpl.use("Agg")
class DiscreteQGANModelHandler(BaseModelHandler):
def __init__(self):
"""Initialize the parameters specific to this model handler by assigning defaults to all attributes which should immediately be available across all methods."""
super().__init__()
self.n_qubits = None
self.n_registers = None
self.circuit_depth = None
self.weights = None
self.generator = None
self.num_generator_params = None
self.circuit = None
self.n_epochs = None
self.generator_weights = None
self.discriminator_weights = None
self.random_key = None
self.reverse_lookup = None
self.save_artifacts = None
self.slower_progress_update = None
self.normalizer = None
def build(
self,
model_name: str,
data_set_name: str,
n_qubits=8,
n_registers=2,
circuit_depth=1,
random_seed=42,
transformation="pit",
circuit_type="copula",
save_artifacts=True,
slower_progress_update=False,
) -> BaseModelHandler:
"""Build the discrete QGAN model.
This defines the architecture of the model, including the circuit ansatz, data transformation and whether the artifacts are saved.
Args:
model_name (str): The name which will be used to save the data to disk.
data_set_name (str): The name of the data set which is set as part of the model name
n_qubits (int, optional): Number of qubits. Defaults to 8.
n_registers (int): Number of dimensions of the data.
circuit_depth (int, optional): Number of repetitions of qml.StronglyEntanglingLayers. Defaults to 1.
random_seed (int, optional): Random seed for reproducibility. Defaults to 42.
transformation (str, optional): Type of normalization, either "minmax" or "pit". Defaults to "pit".
circuit_type (string, optional): name of the circuit anstaz to be used for the QGAN, either "copula" or "standard". Defaults to "copula"
save_artifacts (bool, optional): Whether to save the artifacts to disk. Defaults to True.
slower_progress_update (bool, optional): Controls how often the progress bar is updated. If set to True, update every 10 seconds at most, otherwise use tqdm defaults. Defaults to False.
Returns:
BaseModelHandler: Return the built model handler. It is not strictly necessary to overwrite the existing variable with this
since all changes are made in place.
"""
self.slower_progress_update = slower_progress_update
self.n_qubits = n_qubits
self.n_registers = n_registers
self.circuit_depth = circuit_depth
self.data_set_name = data_set_name
self.transformation = transformation
self.circuit_type = circuit_type
self.performed_trainings = 0
self.save_artifacts = save_artifacts
time_str = str(time.time()).encode('utf-8')
uniq = hashlib.md5(time_str).hexdigest()[:4]
self.model_name = model_name + '_' + self.data_set_name + '_' + self.circuit_type + '_' + self.transformation+ '_' + 'qgan_' + uniq
self.device = 'cpu'
self.beta_1 = 0.5
self.real_label = 1.
self.fake_label = 0.
self.n_samples = 10000
self.path_to_models = "experiments/" + self.model_name
self.metadata = dict({
'model_name': self.model_name,
'n_qubits': self.n_qubits,
'n_registers': self.n_registers,
'circuit_type': self.circuit_type,
'circuit_depth': self.circuit_depth,
'transformation': self.transformation,
'data_set ': self.data_set_name,
'n_epochs': self.n_epochs,
'discriminator': 'digital',
"training_data": {},
})
# save artifacts only when save_artifacts flag is true, used for testing
if save_artifacts:
# create experiments folder
os.makedirs('experiments/' + self.model_name)
print('model_name', self.model_name)
with open(
self.path_to_models + "/" + "meta.json", "w"
) as fp:
json.dump(self.metadata, fp)
# jax specific
self.random_key = jax.random.PRNGKey(random_seed)
self.D = Discriminator_JAX()
self.D.apply = jax.jit(self.D.apply)
self.random_key, subkey1, subkey2 = jax.random.split(self.random_key, num=3)
self.discriminator_weights = self.D.init(
subkey2,
jax.random.uniform(
subkey1,
(
1,
self.n_qubits,
),
),
) # Use dummy input for init
if self.transformation == 'minmax':
self.normalizer = MinMaxNormalizer(epsilon=1e-6)
elif self.transformation == 'pit':
self.normalizer = PITNormalizer(epsilon=1e-6)
else:
raise ValueError("Transformation value must be either 'minmax' or 'pit'")
if self.circuit_type == 'copula':
elif self.circuit_type == 'standard':
else:
raise ValueError("Circuit value must be either 'standard' or 'copula'")
self.generator, self.num_generator_params = get_generator(self.n_qubits, self.n_registers, self.circuit_depth)
self.random_key, subkey = jax.random.split(self.random_key)
# Draw from interval [0, pi) because that is how it was before
self.generator_weights = jax.random.uniform(subkey, shape=(self.num_generator_params,)) * jnp.pi
print(f"{self.num_generator_params=}")
def save(self, file_path: Path, overwrite: bool = True) -> BaseModelHandler:
"""Save the generator and discriminator weights to disk.
Args:
file_path (Path): The paths where the pickled tuple of generator and discriminator weights will be placed.
overwrite (bool, optional): Whether to overwrite the file if it already exists. Defaults to True.
Returns:
BaseModelHandler: The model, unchanged.
"""
if overwrite or not os.path.exists(file_path):
with open(file_path, "wb") as file:
pickle.dump((self.generator_weights, self.discriminator_weights), file)
return self
def reload(
self, model_name: str, epoch: int, random_seed: Optional[int] = None
) -> BaseModelHandler:
"""Reload the model from the artifacts including the parameters for the generator and the discriminator,
the metadata and the data transformation file (reverse lookup table or original min and max of the training data).
Args:
model_name (str): The name of the model to reload.
epoch (int): The epoch to reload.
random_seed (int, Optional): Specify a random seed for reproducibility.
Returns:
BaseModelHandler: The reloaded model, but changes have been made in place as well.
"""
self.model_name = model_name
self.path_to_models = "experiments/" + self.model_name
weights_file = "experiments/" + model_name + "/" + "parameters_training_iteration={0}.pickle".format(str(epoch))
meta_file = "experiments/"+ model_name + "/" + "meta.json"
reverse_file = "experiments/" + model_name + "/" + 'reverse_lookup.npy'
with open(weights_file, "rb") as file:
self.generator_weights, self.discriminator_weights = pickle.load(file)
with open(meta_file, 'r') as f:
self.metadata = json.load(f)
self.reverse_lookup = jnp.load(reverse_file)
self.n_qubits = self.metadata["n_qubits"]
self.transformation = self.metadata["transformation"]
self.circuit_depth = self.metadata["circuit_depth"]
self.performed_trainings = len(self.metadata["training_data"])
self.n_registers = self.metadata['n_registers']
self.circuit_type = self.metadata['circuit_type']
if random_seed is None:
if self.random_key is None:
self.random_key = jax.random.PRNGKey(2)
else:
if self.random_key is not None:
warnings.warn(
"Random state already initialized in the model handler, but a random_seed was specified when reloading. "
"Re-initializing with the random_seed."
)
self.random_key = jax.random.PRNGKey(random_seed)
if self.normalizer is None:
if self.transformation == 'minmax':
self.normalizer = MinMaxNormalizer(epsilon=1e-6)
elif self.transformation == 'pit':
self.normalizer = PITNormalizer(epsilon=1e-6)
else:
raise ValueError("Transformation value must be either 'minmax' or 'pit'")
self.normalizer.reverse_lookup = self.reverse_lookup
if self.generator is None:
if self.circuit_type == 'copula':
elif self.circuit_type == 'standard':
else:
raise ValueError("Circuit value must be either 'standard' or 'copula'")
self.generator, self.num_generator_params = get_generator(self.n_qubits, self.n_registers, self.circuit_depth)
return self
def train(
self,
train_dataset: np.array,
n_epochs: int,
initial_learning_rate_generator: float,
initial_learning_rate_discriminator: float,
batch_size = 1000,
) -> BaseModelHandler:
"""Train the discrete QGAN.
Args:
train_dataset (np.array): The training data in the original space.
n_epochs (int): Technically, we are not passing the number of passes through the training data, but the number of iterations of the training loop.
initial_learning_rate_generator (float, optional): Learning rate for the quantum generator.
initial_learning_rate_discriminator (float, optional): Learning rate for the classical discriminator.
batch_size (int, optional): Batch size. Defaults to None, and the whole training data is used in each iteration.
Raises:
ValueError: Raises ValueError if the training dataset has dimension (number of columns) not equal to 2 or 3.
Returns:
BaseModelHandler: The trained model.
"""
self.batch_size = batch_size
self.n_epochs = n_epochs
if self.performed_trainings == 0:
self.previous_trained_epochs = 0
else:
self.previous_trained_epochs = sum([self.metadata["training_data"][str(i)]["n_epochs"] for i in range(self.performed_trainings)])
training_data = {}
training_data["n_epochs"] = self.n_epochs
training_data["batch_size"] = self.batch_size
training_data["learning_rate_generator"] = initial_learning_rate_generator
training_data["learning_rate_discriminator"] = initial_learning_rate_discriminator
self.metadata["training_data"][str(self.performed_trainings)] = training_data
self.performed_trainings += 1
train_dataset = self.normalizer.fit_transform(train_dataset)
self.reverse_lookup = self.normalizer.reverse_lookup
if self.save_artifacts:
with open(self.path_to_models + "/" + "meta.json", "w+") as file:
json.dump(self.metadata, file)
jnp.save(self.path_to_models + "/" + 'reverse_lookup.npy', self.reverse_lookup)
self.dict_bins = compute_discretization(self.n_qubits, self.n_registers)
n = 2 ** (self.n_qubits // self.n_registers)
nns = tuple(n for _ in range(self.n_registers))
nns_nq = nns + tuple((self.n_qubits,))
inverse_bins = np.zeros(nns_nq)
for key, value in self.dict_bins.items():
id_n = value[0]
inverse_bins[id_n] = jnp.array([int(bit) for bit in key])
coordinates = np.floor(train_dataset * n).astype(int)
train_dataset = [
inverse_bins[tuple([xy[ii] for ii in range(self.n_registers)])]
for xy in coordinates
]
train_dataset = jnp.array(train_dataset).astype(jnp.float32)
distribution_pit = np.zeros(nns)
for xy in coordinates:
indices = tuple(xy[ii] for ii in range(self.n_registers))
distribution_pit[indices] += 1
distribution_pit /= np.sum(distribution_pit)
distribution_pit = jnp.array(distribution_pit)
optimizer_discriminator = optax.adam(
learning_rate=initial_learning_rate_discriminator,
b1=self.beta_1,
b2=0.999,
)
optimizer_state_d = optimizer_discriminator.init(self.discriminator_weights)
optimizer_generator = optax.sgd(learning_rate=initial_learning_rate_generator)
self.random_key, subkey = jax.random.split(self.random_key)
optimizer_state_g = optimizer_generator.init(self.generator_weights)
kl_list_transformed_space = []
it_list = []
# create shifts in advance, leads to less code at application
elementary_shift = 1
shifts = [
[elementary_shift * e_i, -elementary_shift * e_i]
for e_i in jnp.eye(self.generator_weights.size)
]
shifts = list(chain(*shifts))
shifts = [shift.reshape(self.generator_weights.shape) for shift in shifts]
parameters = []
epsilon = 1e-10
X_train = CustomDataset(train_dataset.astype("float32"))
def cost_fn_discriminator(X, generator_weights, discriminator_weights):
self.random_key, subkey = jax.random.split(self.random_key)
G_samples = self.generator(
subkey,
generator_weights,
n_shots=len(X),
)
D_fake = self.D.apply(discriminator_weights, G_samples)
D_real = self.D.apply(discriminator_weights, X)
loss_1 = -jnp.mean(jnp.log(D_real + epsilon))
loss_2 = -jnp.mean(jnp.log(1.0 - D_fake + epsilon))
D_loss = loss_1 + loss_2
return D_loss
def cost_fn_generator(X, generator_weights, discriminator_weights):
self.random_key, subkey = jax.random.split(self.random_key)
G_samples = self.generator(
subkey,
weights=generator_weights,
n_shots=len(X),
)
D_fake = self.D.apply(discriminator_weights, G_samples)
G_loss = -jnp.mean(jnp.log(D_fake + epsilon)) # Vanilla GAN
return G_loss
progress = tqdm(range(n_epochs), mininterval=10 if self.slower_progress_update else None)
for it in progress:
if self.save_artifacts:
self.save(
f"{self.path_to_models}/parameters_training_iteration={it + self.previous_trained_epochs }.pickle",
overwrite=False,
)
data = X_train.next_batch(self.batch_size)
discriminator_training_steps = 1 # How many times is the discriminator updates per generator update
for _ in range(discriminator_training_steps):
cost_discriminator, grad_d = jax.value_and_grad(
lambda w: cost_fn_discriminator(data, self.generator_weights, w)
)(self.discriminator_weights)
updates, optimizer_state_d = optimizer_discriminator.update(
grad_d, optimizer_state_d
)
self.discriminator_weights = optax.apply_updates(
self.discriminator_weights, updates
)
# This is the method using the old manual gradient
cost_generator = cost_fn_generator(
data, self.generator_weights, self.discriminator_weights
)
self.random_key, *subkeys = jax.random.split(self.random_key, num=len(shifts) + 1)
G_samples = [
self.generator(
subkey,
self.generator_weights + parameter_shift,
n_shots=self.batch_size,
)
for subkey, parameter_shift in zip(subkeys, shifts)
]
| grad_g = compute_gradient_JAX( | 0 | 2023-10-27 12:25:58+00:00 | 8k |
loliverhennigh/PhantomGaze | phantomgaze/render/contour.py | [
{
"identifier": "ScreenBuffer",
"path": "phantomgaze/buffers.py",
"snippet": "class ScreenBuffer:\n \"\"\"\n Create a screen buffer.\n The screen buffer stores fragment information for rendering.\n\n Parameters\n ----------\n height : int\n The height of the screen buffer\n w... | import cupy as cp
import numba
from numba import cuda
from phantomgaze import ScreenBuffer
from phantomgaze import Colormap, SolidColor
from phantomgaze.render.camera import calculate_ray_direction
from phantomgaze.render.utils import sample_array, sample_array_derivative, ray_intersect_box
from phantomgaze.utils.math import normalize, dot, cross
from phantomgaze.render.color import scalar_to_color | 5,522 | The volume data.
spacing : tuple
The spacing of the volume data.
origin : tuple
The origin of the volume data.
camera_position : tuple
The position of the camera.
camera_focal : tuple
The focal point of the camera.
camera_up : tuple
The up vector of the camera.
max_depth : float
The maximum depth, used for Weighted Blended Order-Independent Transparency.
threshold : float
The threshold to use for the contour.
color_array : ndarray
The color data.
color_map_array : ndarray
The color map array.
vmin : float
The minimum value of the scalar range.
vmax : float
The maximum value of the scalar range.
nan_color : tuple
The color to use for NaN values.
nan_opacity : float
The opacity to use for NaN values.
opaque : bool
Whether the geometry is opaque or not.
opaque_pixel_buffer : ndarray
The opaque pixel buffer.
depth_buffer : ndarray
The depth buffer.
normal_buffer : ndarray
The normal buffer.
transparent_pixel_buffer : ndarray
The transparent pixel buffer.
revealage_buffer : ndarray
The reveal buffer.
"""
# Get the x and y indices
x, y = cuda.grid(2)
# Make sure the indices are in bounds
if x >= opaque_pixel_buffer.shape[1] or y >= opaque_pixel_buffer.shape[0]:
return
# Get ray direction
ray_direction = calculate_ray_direction(
x, y, opaque_pixel_buffer.shape,
camera_position, camera_focal, camera_up)
# Get volume upper bound
volume_upper = (
origin[0] + spacing[0] * volume_array.shape[0],
origin[1] + spacing[1] * volume_array.shape[1],
origin[2] + spacing[2] * volume_array.shape[2]
)
# Get the intersection of the ray with the volume
t0, t1 = ray_intersect_box(
origin, volume_upper, camera_position, ray_direction)
# If there is no intersection, return
if t0 > t1:
return
# Get the starting point of the ray
ray_pos = (
camera_position[0] + t0 * ray_direction[0],
camera_position[1] + t0 * ray_direction[1],
camera_position[2] + t0 * ray_direction[2]
)
# Get the step size
step_size = min(spacing[0], min(spacing[1], spacing[2]))
# Set starting value to lowest possible value
value = sample_array(volume_array, spacing, origin, ray_pos)
# Inside-outside stored in the sign
sign = 1 if value > threshold else -1
# Start the ray marching
distance = t0
for step in range(int((t1 - t0) / step_size)):
# Check if distance is greater then current depth
if (distance > depth_buffer[y, x]):
return
# Get next step position
next_ray_pos = (
ray_pos[0] + step_size * ray_direction[0],
ray_pos[1] + step_size * ray_direction[1],
ray_pos[2] + step_size * ray_direction[2]
)
# Get the value in the next step
next_value = sample_array(volume_array, spacing, origin, next_ray_pos)
# If contour is crossed, set the color and depth
if (next_value - threshold) * sign < 0:
# Update the sign
sign = -sign
# Linearly interpolate the position
t = (threshold - value) / (next_value - value)
pos_contour = (
ray_pos[0] + t * step_size * ray_direction[0],
ray_pos[1] + t * step_size * ray_direction[1],
ray_pos[2] + t * step_size * ray_direction[2]
)
# Get gradient
gradient = sample_array_derivative(
volume_array, spacing, origin, pos_contour)
gradient = normalize(gradient)
# Calculate intensity
| # Render functions for rendering a contour of a volume.
@cuda.jit
def contour_kernel(
volume_array,
spacing,
origin,
camera_position,
camera_focal,
camera_up,
max_depth,
threshold,
color_array,
color_map_array,
vmin,
vmax,
nan_color,
nan_opacity,
opaque,
opaque_pixel_buffer,
depth_buffer,
normal_buffer,
transparent_pixel_buffer,
revealage_buffer):
"""Kernel for rendering a contour of a volume.
Parameters
----------
volume_array : ndarray
The volume data.
spacing : tuple
The spacing of the volume data.
origin : tuple
The origin of the volume data.
camera_position : tuple
The position of the camera.
camera_focal : tuple
The focal point of the camera.
camera_up : tuple
The up vector of the camera.
max_depth : float
The maximum depth, used for Weighted Blended Order-Independent Transparency.
threshold : float
The threshold to use for the contour.
color_array : ndarray
The color data.
color_map_array : ndarray
The color map array.
vmin : float
The minimum value of the scalar range.
vmax : float
The maximum value of the scalar range.
nan_color : tuple
The color to use for NaN values.
nan_opacity : float
The opacity to use for NaN values.
opaque : bool
Whether the geometry is opaque or not.
opaque_pixel_buffer : ndarray
The opaque pixel buffer.
depth_buffer : ndarray
The depth buffer.
normal_buffer : ndarray
The normal buffer.
transparent_pixel_buffer : ndarray
The transparent pixel buffer.
revealage_buffer : ndarray
The reveal buffer.
"""
# Get the x and y indices
x, y = cuda.grid(2)
# Make sure the indices are in bounds
if x >= opaque_pixel_buffer.shape[1] or y >= opaque_pixel_buffer.shape[0]:
return
# Get ray direction
ray_direction = calculate_ray_direction(
x, y, opaque_pixel_buffer.shape,
camera_position, camera_focal, camera_up)
# Get volume upper bound
volume_upper = (
origin[0] + spacing[0] * volume_array.shape[0],
origin[1] + spacing[1] * volume_array.shape[1],
origin[2] + spacing[2] * volume_array.shape[2]
)
# Get the intersection of the ray with the volume
t0, t1 = ray_intersect_box(
origin, volume_upper, camera_position, ray_direction)
# If there is no intersection, return
if t0 > t1:
return
# Get the starting point of the ray
ray_pos = (
camera_position[0] + t0 * ray_direction[0],
camera_position[1] + t0 * ray_direction[1],
camera_position[2] + t0 * ray_direction[2]
)
# Get the step size
step_size = min(spacing[0], min(spacing[1], spacing[2]))
# Set starting value to lowest possible value
value = sample_array(volume_array, spacing, origin, ray_pos)
# Inside-outside stored in the sign
sign = 1 if value > threshold else -1
# Start the ray marching
distance = t0
for step in range(int((t1 - t0) / step_size)):
# Check if distance is greater then current depth
if (distance > depth_buffer[y, x]):
return
# Get next step position
next_ray_pos = (
ray_pos[0] + step_size * ray_direction[0],
ray_pos[1] + step_size * ray_direction[1],
ray_pos[2] + step_size * ray_direction[2]
)
# Get the value in the next step
next_value = sample_array(volume_array, spacing, origin, next_ray_pos)
# If contour is crossed, set the color and depth
if (next_value - threshold) * sign < 0:
# Update the sign
sign = -sign
# Linearly interpolate the position
t = (threshold - value) / (next_value - value)
pos_contour = (
ray_pos[0] + t * step_size * ray_direction[0],
ray_pos[1] + t * step_size * ray_direction[1],
ray_pos[2] + t * step_size * ray_direction[2]
)
# Get gradient
gradient = sample_array_derivative(
volume_array, spacing, origin, pos_contour)
gradient = normalize(gradient)
# Calculate intensity | intensity = dot(gradient, ray_direction) | 8 | 2023-10-26 23:53:16+00:00 | 8k |
vTuanpham/Large_dataset_translator | examples/OpenOrca/OpenOrca_Parser.py | [
{
"identifier": "BaseConfig",
"path": "configs/base_config.py",
"snippet": "class BaseConfig(Config):\r\n \"\"\"\r\n A single training/test example for base config.\r\n \"\"\"\r\n system_prompt: str\r\n\r\n question_text: str\r\n\r\n orig_answer_texts: str = None\r\n answer_lengths:... | import sys
from tqdm.auto import tqdm
from datasets import load_dataset
from configs import BaseConfig
from translator import DataParser
| 5,573 | sys.path.insert(0,r'./')
PARSER_NAME = "OpenOrca"
class OpenOrcaParser(DataParser):
def __init__(self, file_path: str, output_path: str):
super().__init__(file_path, output_path,
parser_name=PARSER_NAME,
| sys.path.insert(0,r'./')
PARSER_NAME = "OpenOrca"
class OpenOrcaParser(DataParser):
def __init__(self, file_path: str, output_path: str):
super().__init__(file_path, output_path,
parser_name=PARSER_NAME,
| target_config=BaseConfig, # The data config to be validated to check if self implement "convert" function is correct or not,
| 0 | 2023-10-27 08:55:44+00:00 | 8k |
Khushiyant/dockerpulse | dockerpulse/lgbert/bert_pytorch/train_log.py | [
{
"identifier": "BERT",
"path": "dockerpulse/lgbert/bert_pytorch/model/bert.py",
"snippet": "class BERT(nn.Module):\r\n \"\"\"\r\n BERT model : Bidirectional Encoder Representations from Transformers.\r\n \"\"\"\r\n\r\n def __init__(self, vocab_size, max_len=512, hidden=768, n_layers=12,\r\n... | from torch.utils.data import DataLoader
from .model import BERT
from .trainer import BERTTrainer
from .dataset import LogDataset, WordVocab
from .dataset.sample import generate_train_valid
from .dataset.utils import save_parameters
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import torch
import tqdm
import gc
| 5,629 |
class Trainer():
def __init__(self, options):
self.device = options["device"]
self.model_dir = options["model_dir"]
self.model_path = options["model_path"]
self.vocab_path = options["vocab_path"]
self.output_path = options["output_dir"]
self.window_size = options["window_size"]
self.adaptive_window = options["adaptive_window"]
self.sample_ratio = options["train_ratio"]
self.valid_ratio = options["valid_ratio"]
self.seq_len = options["seq_len"]
self.max_len = options["max_len"]
self.corpus_lines = options["corpus_lines"]
self.on_memory = options["on_memory"]
self.batch_size = options["batch_size"]
self.num_workers = options["num_workers"]
self.lr = options["lr"]
self.adam_beta1 = options["adam_beta1"]
self.adam_beta2 = options["adam_beta2"]
self.adam_weight_decay = options["adam_weight_decay"]
self.with_cuda = options["with_cuda"]
self.cuda_devices = options["cuda_devices"]
self.log_freq = options["log_freq"]
self.epochs = options["epochs"]
self.hidden = options["hidden"]
self.layers = options["layers"]
self.attn_heads = options["attn_heads"]
self.is_logkey = options["is_logkey"]
self.is_time = options["is_time"]
self.scale = options["scale"]
self.scale_path = options["scale_path"]
self.n_epochs_stop = options["n_epochs_stop"]
self.hypersphere_loss = options["hypersphere_loss"]
self.mask_ratio = options["mask_ratio"]
self.min_len = options['min_len']
print("Save options parameters")
save_parameters(options, self.model_dir + "parameters.txt")
def train(self):
print("Loading vocab", self.vocab_path)
|
class Trainer():
def __init__(self, options):
self.device = options["device"]
self.model_dir = options["model_dir"]
self.model_path = options["model_path"]
self.vocab_path = options["vocab_path"]
self.output_path = options["output_dir"]
self.window_size = options["window_size"]
self.adaptive_window = options["adaptive_window"]
self.sample_ratio = options["train_ratio"]
self.valid_ratio = options["valid_ratio"]
self.seq_len = options["seq_len"]
self.max_len = options["max_len"]
self.corpus_lines = options["corpus_lines"]
self.on_memory = options["on_memory"]
self.batch_size = options["batch_size"]
self.num_workers = options["num_workers"]
self.lr = options["lr"]
self.adam_beta1 = options["adam_beta1"]
self.adam_beta2 = options["adam_beta2"]
self.adam_weight_decay = options["adam_weight_decay"]
self.with_cuda = options["with_cuda"]
self.cuda_devices = options["cuda_devices"]
self.log_freq = options["log_freq"]
self.epochs = options["epochs"]
self.hidden = options["hidden"]
self.layers = options["layers"]
self.attn_heads = options["attn_heads"]
self.is_logkey = options["is_logkey"]
self.is_time = options["is_time"]
self.scale = options["scale"]
self.scale_path = options["scale_path"]
self.n_epochs_stop = options["n_epochs_stop"]
self.hypersphere_loss = options["hypersphere_loss"]
self.mask_ratio = options["mask_ratio"]
self.min_len = options['min_len']
print("Save options parameters")
save_parameters(options, self.model_dir + "parameters.txt")
def train(self):
print("Loading vocab", self.vocab_path)
| vocab = WordVocab.load_vocab(self.vocab_path)
| 2 | 2023-10-29 09:52:36+00:00 | 8k |
audiodude/rainfall | rainfall/main.py | [
{
"identifier": "file",
"path": "rainfall/blueprint/file.py",
"snippet": "def delete_file(file_id, user):"
},
{
"identifier": "UserBlueprintFactory",
"path": "rainfall/blueprint/user.py",
"snippet": "class UserBlueprintFactory:\n\n def __init__(self, csrf):\n self.csrf = csrf\n\n de... | import logging
import os
import time
import flask
import sqlalchemy
from uuid import UUID
from flask_seasurf import SeaSurf
from werkzeug.utils import secure_filename
from rainfall.blueprint.file import file as file_blueprint
from rainfall.blueprint.user import UserBlueprintFactory
from rainfall.blueprint.release import release as release_blueprint
from rainfall.blueprint.site import site as site_blueprint
from rainfall.db import db
from rainfall.decorators import with_current_site, with_current_user
from rainfall.models.file import File
from rainfall.models.release import Release
from rainfall.models.site import Site
from rainfall.models.user import User
from rainfall.site import generate_site, generate_zip, public_dir, release_path, site_exists, zip_file_path | 3,960 | app.config['TESTING'] = True
csrf = SeaSurf(app)
os.makedirs(app.config['DATA_DIR'], exist_ok=True)
os.makedirs(app.config['PREVIEW_DIR'], exist_ok=True)
app.register_blueprint(UserBlueprintFactory(csrf).get_blueprint(),
url_prefix='/api/v1')
app.register_blueprint(site_blueprint, url_prefix='/api/v1')
app.register_blueprint(release_blueprint, url_prefix='/api/v1')
app.register_blueprint(file_blueprint, url_prefix='/api/v1')
FRONTEND_DIR = '../rainfall-frontend/dist'
@app.route('/api/v1/upload', methods=['POST'])
@with_current_user
def upload(user):
def allowed_file(filename):
if '.' not in filename:
return False
return '.' + filename.rsplit('.', 1)[1].lower() in ALLOWED_SONG_EXTS
def check_song_file_types(song_files):
for f in song_files:
if not allowed_file(f.filename):
return flask.jsonify(
status=400,
error='File %s is not an allowed file type (%s)' %
(f.filename, ' '.join(ALLOWED_SONG_EXTS))), 400
release_id = flask.request.form.get('release_id')
if release_id is None:
return flask.jsonify(status=400, error='No release id given'), 400
release = db.session.get(Release, UUID(release_id))
site = release.site
upload_user = site.user
if upload_user.id != user.id:
return flask.jsonify(status=401,
error='Cannot upload data to that release'), 401
song_files = flask.request.files.getlist("song[]")
if not song_files:
return flask.jsonify(status=400, error='No songs uploaded'), 400
resp = check_song_file_types(song_files)
if resp is not None:
return resp
cur_release_path = release_path(app.config['DATA_DIR'], release)
os.makedirs(cur_release_path, exist_ok=True)
for song in song_files:
name = secure_filename(song.filename)
if len(name) > 1024:
return flask.jsonify(status=400,
error=f'File name {name} is too long'), 400
file = File(filename=name)
release.files.append(file)
# Give the file a new name if it's a dupe. This must be done after
# the file is added to the release.
file.maybe_rename()
# Write the file to the filesystem.
song.save(os.path.join(cur_release_path, file.filename))
db.session.add(release)
db.session.commit()
return '', 204
@app.route('/api/v1/preview/<site_id>', methods=['GET', 'POST'])
@with_current_user
@with_current_site
def create_preview(site, user):
if len(site.releases) == 0 or not any(f for release in site.releases
for f in release.files):
return flask.jsonify(
status=400, error='Cannot preview site without releases/files'), 400
if flask.request.method == 'GET':
if site_exists(app.config['PREVIEW_DIR'], str(site.id)):
return '', 204
else:
return '', 404
result = generate_site(app.config['DATA_DIR'], app.config['PREVIEW_DIR'],
str(site.id))
if result[0]:
return '', 204
else:
return flask.jsonify(status=500, error=result[1])
@app.route('/preview/<site_id>/')
@with_current_user
@with_current_site
def preview_index(site, user):
# The decorators ensure that the site belongs to the user.
return flask.send_from_directory(
os.path.join('..', app.config['PREVIEW_DIR'], public_dir(site)),
'index.html')
@app.route('/preview/<site_id>/<path:filename>')
@with_current_user
@with_current_site
def preview_asset(site, user, filename):
# The decorators ensure that the site belongs to the user.
if filename.endswith('/'):
filename += 'index.html'
return flask.send_from_directory(
os.path.join('..', app.config['PREVIEW_DIR'], public_dir(site)),
filename)
@app.route('/api/v1/zip/<site_id>')
@with_current_user
@with_current_site
def zip(site, user):
generate_zip(app.config['PREVIEW_DIR'], str(site.id))
|
ALLOWED_SONG_EXTS = ['.aiff', '.aif', '.flac', '.mp3', '.ogg', '.opus', '.wav']
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
def create_app():
app = flask.Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']
app.config['SECRET_KEY'] = os.environ['FLASK_SECRET_KEY']
app.config['GOOGLE_CLIENT_ID'] = os.environ['GOOGLE_CLIENT_ID']
app.config['RAINFALL_FRONTEND_URL'] = os.environ['RAINFALL_FRONTEND_URL']
app.config['DATA_DIR'] = os.environ['DATA_DIR']
app.config['PREVIEW_DIR'] = os.environ['PREVIEW_DIR']
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100 MB max upload
if os.environ.get('RAINFALL_ENV') != 'test':
db.init_app(app)
else:
app.config['TESTING'] = True
csrf = SeaSurf(app)
os.makedirs(app.config['DATA_DIR'], exist_ok=True)
os.makedirs(app.config['PREVIEW_DIR'], exist_ok=True)
app.register_blueprint(UserBlueprintFactory(csrf).get_blueprint(),
url_prefix='/api/v1')
app.register_blueprint(site_blueprint, url_prefix='/api/v1')
app.register_blueprint(release_blueprint, url_prefix='/api/v1')
app.register_blueprint(file_blueprint, url_prefix='/api/v1')
FRONTEND_DIR = '../rainfall-frontend/dist'
@app.route('/api/v1/upload', methods=['POST'])
@with_current_user
def upload(user):
def allowed_file(filename):
if '.' not in filename:
return False
return '.' + filename.rsplit('.', 1)[1].lower() in ALLOWED_SONG_EXTS
def check_song_file_types(song_files):
for f in song_files:
if not allowed_file(f.filename):
return flask.jsonify(
status=400,
error='File %s is not an allowed file type (%s)' %
(f.filename, ' '.join(ALLOWED_SONG_EXTS))), 400
release_id = flask.request.form.get('release_id')
if release_id is None:
return flask.jsonify(status=400, error='No release id given'), 400
release = db.session.get(Release, UUID(release_id))
site = release.site
upload_user = site.user
if upload_user.id != user.id:
return flask.jsonify(status=401,
error='Cannot upload data to that release'), 401
song_files = flask.request.files.getlist("song[]")
if not song_files:
return flask.jsonify(status=400, error='No songs uploaded'), 400
resp = check_song_file_types(song_files)
if resp is not None:
return resp
cur_release_path = release_path(app.config['DATA_DIR'], release)
os.makedirs(cur_release_path, exist_ok=True)
for song in song_files:
name = secure_filename(song.filename)
if len(name) > 1024:
return flask.jsonify(status=400,
error=f'File name {name} is too long'), 400
file = File(filename=name)
release.files.append(file)
# Give the file a new name if it's a dupe. This must be done after
# the file is added to the release.
file.maybe_rename()
# Write the file to the filesystem.
song.save(os.path.join(cur_release_path, file.filename))
db.session.add(release)
db.session.commit()
return '', 204
@app.route('/api/v1/preview/<site_id>', methods=['GET', 'POST'])
@with_current_user
@with_current_site
def create_preview(site, user):
if len(site.releases) == 0 or not any(f for release in site.releases
for f in release.files):
return flask.jsonify(
status=400, error='Cannot preview site without releases/files'), 400
if flask.request.method == 'GET':
if site_exists(app.config['PREVIEW_DIR'], str(site.id)):
return '', 204
else:
return '', 404
result = generate_site(app.config['DATA_DIR'], app.config['PREVIEW_DIR'],
str(site.id))
if result[0]:
return '', 204
else:
return flask.jsonify(status=500, error=result[1])
@app.route('/preview/<site_id>/')
@with_current_user
@with_current_site
def preview_index(site, user):
# The decorators ensure that the site belongs to the user.
return flask.send_from_directory(
os.path.join('..', app.config['PREVIEW_DIR'], public_dir(site)),
'index.html')
@app.route('/preview/<site_id>/<path:filename>')
@with_current_user
@with_current_site
def preview_asset(site, user, filename):
# The decorators ensure that the site belongs to the user.
if filename.endswith('/'):
filename += 'index.html'
return flask.send_from_directory(
os.path.join('..', app.config['PREVIEW_DIR'], public_dir(site)),
filename)
@app.route('/api/v1/zip/<site_id>')
@with_current_user
@with_current_site
def zip(site, user):
generate_zip(app.config['PREVIEW_DIR'], str(site.id)) | zip_path = zip_file_path(app.config['PREVIEW_DIR'], str(site.id)) | 16 | 2023-10-30 04:43:03+00:00 | 8k |
LasticXYZ/price-simulation | main.py | [
{
"identifier": "Config",
"path": "config.py",
"snippet": "class Config:\n def __init__(\n self,\n interlude_length,\n leadin_length,\n region_length,\n ideal_bulk_proportion,\n limit_cores_offered,\n renewal_bump,\n ):\n # The length in bloc... | from config import Config
from price import CalculatePrice
from streamlitapp import StreamlitApp | 5,114 |
BLOCKS_PER_DAY = 5
SALE_START = 0
def main():
# Initial configuration
|
BLOCKS_PER_DAY = 5
SALE_START = 0
def main():
# Initial configuration | config = Config( | 0 | 2023-10-30 12:49:00+00:00 | 8k |
dangeng/flowmag | flow_models/gmflow/gmflow.py | [
{
"identifier": "CNNEncoder",
"path": "flow_models/gmflow/backbone.py",
"snippet": "class CNNEncoder(nn.Module):\n def __init__(self, output_dim=128,\n norm_layer=nn.InstanceNorm2d,\n num_output_scales=1,\n **kwargs,\n ):\n super(... | import torch
import torch.nn as nn
import torch.nn.functional as F
from .backbone import CNNEncoder
from .transformer import FeatureTransformer, FeatureFlowAttention
from .matching import global_correlation_softmax, local_correlation_softmax
from .geometry import flow_warp
from .utils import normalize_img, feature_add_position | 6,065 | ):
super(GMFlow, self).__init__()
self.num_scales = num_scales
self.feature_channels = feature_channels
self.upsample_factor = upsample_factor
self.attention_type = attention_type
self.num_transformer_layers = num_transformer_layers
# CNN backbone
self.backbone = CNNEncoder(output_dim=feature_channels, num_output_scales=num_scales)
# Transformer
self.transformer = FeatureTransformer(num_layers=num_transformer_layers,
d_model=feature_channels,
nhead=num_head,
attention_type=attention_type,
ffn_dim_expansion=ffn_dim_expansion,
)
# flow propagation with self-attn
self.feature_flow_attn = FeatureFlowAttention(in_channels=feature_channels)
# convex upsampling: concat feature0 and flow as input
self.upsampler = nn.Sequential(nn.Conv2d(2 + feature_channels, 256, 3, 1, 1),
nn.ReLU(inplace=True),
nn.Conv2d(256, upsample_factor ** 2 * 9, 1, 1, 0))
def extract_feature(self, img0, img1):
concat = torch.cat((img0, img1), dim=0) # [2B, C, H, W]
features = self.backbone(concat) # list of [2B, C, H, W], resolution from high to low
# reverse: resolution from low to high
features = features[::-1]
feature0, feature1 = [], []
for i in range(len(features)):
feature = features[i]
chunks = torch.chunk(feature, 2, 0) # tuple
feature0.append(chunks[0])
feature1.append(chunks[1])
return feature0, feature1
def upsample_flow(self, flow, feature, bilinear=False, upsample_factor=8,
):
if bilinear:
up_flow = F.interpolate(flow, scale_factor=upsample_factor,
mode='bilinear', align_corners=True) * upsample_factor
else:
# convex upsampling
concat = torch.cat((flow, feature), dim=1)
mask = self.upsampler(concat)
b, flow_channel, h, w = flow.shape
mask = mask.view(b, 1, 9, self.upsample_factor, self.upsample_factor, h, w) # [B, 1, 9, K, K, H, W]
mask = torch.softmax(mask, dim=2)
up_flow = F.unfold(self.upsample_factor * flow, [3, 3], padding=1)
up_flow = up_flow.view(b, flow_channel, 9, 1, 1, h, w) # [B, 2, 9, 1, 1, H, W]
up_flow = torch.sum(mask * up_flow, dim=2) # [B, 2, K, K, H, W]
up_flow = up_flow.permute(0, 1, 4, 2, 5, 3) # [B, 2, K, H, K, W]
up_flow = up_flow.reshape(b, flow_channel, self.upsample_factor * h,
self.upsample_factor * w) # [B, 2, K*H, K*W]
return up_flow
def forward(self, img0, img1,
attn_splits_list=None,
corr_radius_list=None,
prop_radius_list=None,
pred_bidir_flow=False,
**kwargs,
):
results_dict = {}
flow_preds = []
img0, img1 = normalize_img(img0, img1) # [B, 3, H, W]
# resolution low to high
feature0_list, feature1_list = self.extract_feature(img0, img1) # list of features
flow = None
assert len(attn_splits_list) == len(corr_radius_list) == len(prop_radius_list) == self.num_scales
for scale_idx in range(self.num_scales):
feature0, feature1 = feature0_list[scale_idx], feature1_list[scale_idx]
if pred_bidir_flow and scale_idx > 0:
# predicting bidirectional flow with refinement
feature0, feature1 = torch.cat((feature0, feature1), dim=0), torch.cat((feature1, feature0), dim=0)
upsample_factor = self.upsample_factor * (2 ** (self.num_scales - 1 - scale_idx))
if scale_idx > 0:
flow = F.interpolate(flow, scale_factor=2, mode='bilinear', align_corners=True) * 2
if flow is not None:
flow = flow.detach()
feature1 = flow_warp(feature1, flow) # [B, C, H, W]
attn_splits = attn_splits_list[scale_idx]
corr_radius = corr_radius_list[scale_idx]
prop_radius = prop_radius_list[scale_idx]
# add position to features
feature0, feature1 = feature_add_position(feature0, feature1, attn_splits, self.feature_channels)
# Transformer
feature0, feature1 = self.transformer(feature0, feature1, attn_num_splits=attn_splits)
# correlation and softmax
if corr_radius == -1: # global matching
flow_pred = global_correlation_softmax(feature0, feature1, pred_bidir_flow)[0]
else: # local matching
|
class GMFlow(nn.Module):
def __init__(self,
num_scales=1,
upsample_factor=8,
feature_channels=128,
attention_type='swin',
num_transformer_layers=6,
ffn_dim_expansion=4,
num_head=1,
**kwargs,
):
super(GMFlow, self).__init__()
self.num_scales = num_scales
self.feature_channels = feature_channels
self.upsample_factor = upsample_factor
self.attention_type = attention_type
self.num_transformer_layers = num_transformer_layers
# CNN backbone
self.backbone = CNNEncoder(output_dim=feature_channels, num_output_scales=num_scales)
# Transformer
self.transformer = FeatureTransformer(num_layers=num_transformer_layers,
d_model=feature_channels,
nhead=num_head,
attention_type=attention_type,
ffn_dim_expansion=ffn_dim_expansion,
)
# flow propagation with self-attn
self.feature_flow_attn = FeatureFlowAttention(in_channels=feature_channels)
# convex upsampling: concat feature0 and flow as input
self.upsampler = nn.Sequential(nn.Conv2d(2 + feature_channels, 256, 3, 1, 1),
nn.ReLU(inplace=True),
nn.Conv2d(256, upsample_factor ** 2 * 9, 1, 1, 0))
def extract_feature(self, img0, img1):
concat = torch.cat((img0, img1), dim=0) # [2B, C, H, W]
features = self.backbone(concat) # list of [2B, C, H, W], resolution from high to low
# reverse: resolution from low to high
features = features[::-1]
feature0, feature1 = [], []
for i in range(len(features)):
feature = features[i]
chunks = torch.chunk(feature, 2, 0) # tuple
feature0.append(chunks[0])
feature1.append(chunks[1])
return feature0, feature1
def upsample_flow(self, flow, feature, bilinear=False, upsample_factor=8,
):
if bilinear:
up_flow = F.interpolate(flow, scale_factor=upsample_factor,
mode='bilinear', align_corners=True) * upsample_factor
else:
# convex upsampling
concat = torch.cat((flow, feature), dim=1)
mask = self.upsampler(concat)
b, flow_channel, h, w = flow.shape
mask = mask.view(b, 1, 9, self.upsample_factor, self.upsample_factor, h, w) # [B, 1, 9, K, K, H, W]
mask = torch.softmax(mask, dim=2)
up_flow = F.unfold(self.upsample_factor * flow, [3, 3], padding=1)
up_flow = up_flow.view(b, flow_channel, 9, 1, 1, h, w) # [B, 2, 9, 1, 1, H, W]
up_flow = torch.sum(mask * up_flow, dim=2) # [B, 2, K, K, H, W]
up_flow = up_flow.permute(0, 1, 4, 2, 5, 3) # [B, 2, K, H, K, W]
up_flow = up_flow.reshape(b, flow_channel, self.upsample_factor * h,
self.upsample_factor * w) # [B, 2, K*H, K*W]
return up_flow
def forward(self, img0, img1,
attn_splits_list=None,
corr_radius_list=None,
prop_radius_list=None,
pred_bidir_flow=False,
**kwargs,
):
results_dict = {}
flow_preds = []
img0, img1 = normalize_img(img0, img1) # [B, 3, H, W]
# resolution low to high
feature0_list, feature1_list = self.extract_feature(img0, img1) # list of features
flow = None
assert len(attn_splits_list) == len(corr_radius_list) == len(prop_radius_list) == self.num_scales
for scale_idx in range(self.num_scales):
feature0, feature1 = feature0_list[scale_idx], feature1_list[scale_idx]
if pred_bidir_flow and scale_idx > 0:
# predicting bidirectional flow with refinement
feature0, feature1 = torch.cat((feature0, feature1), dim=0), torch.cat((feature1, feature0), dim=0)
upsample_factor = self.upsample_factor * (2 ** (self.num_scales - 1 - scale_idx))
if scale_idx > 0:
flow = F.interpolate(flow, scale_factor=2, mode='bilinear', align_corners=True) * 2
if flow is not None:
flow = flow.detach()
feature1 = flow_warp(feature1, flow) # [B, C, H, W]
attn_splits = attn_splits_list[scale_idx]
corr_radius = corr_radius_list[scale_idx]
prop_radius = prop_radius_list[scale_idx]
# add position to features
feature0, feature1 = feature_add_position(feature0, feature1, attn_splits, self.feature_channels)
# Transformer
feature0, feature1 = self.transformer(feature0, feature1, attn_num_splits=attn_splits)
# correlation and softmax
if corr_radius == -1: # global matching
flow_pred = global_correlation_softmax(feature0, feature1, pred_bidir_flow)[0]
else: # local matching | flow_pred = local_correlation_softmax(feature0, feature1, corr_radius)[0] | 4 | 2023-10-27 05:23:08+00:00 | 8k |
Gene-Weaver/VoucherVision | vouchervision/VoucherVision_Config_Builder.py | [
{
"identifier": "get_default_download_folder",
"path": "vouchervision/LeafMachine2_Config_Builder.py",
"snippet": "def get_default_download_folder():\n system_platform = platform.system() # Gets the system platform, e.g., 'Linux', 'Windows', 'Darwin'\n\n if system_platform == \"Windows\":\n ... | import os, yaml, platform, traceback
from vouchervision.LeafMachine2_Config_Builder import get_default_download_folder, write_config_file
from vouchervision.general_utils import validate_dir, print_main_fail
from vouchervision.vouchervision_main import voucher_vision
from general_utils import get_cfg_from_full_path | 3,796 | 'save_individual_csv_files_measurements': False,
'save_individual_csv_files_landmarks': False,
'save_individual_efd_files': False,
'include_darwin_core_data_from_combined_file': False,
'do_apply_conversion_factor': False
}
overlay_section = {
'save_overlay_to_pdf': False,
'save_overlay_to_jpgs': True,
'overlay_dpi': 300, # Between 100 to 300
'overlay_background_color': 'black', # Either 'white' or 'black'
'show_archival_detections': True,
'show_plant_detections': True,
'show_segmentations': True,
'show_landmarks': True,
'ignore_archival_detections_classes': [],
'ignore_plant_detections_classes': ['leaf_whole', 'specimen'], # Could also include 'leaf_partial' and others if needed
'ignore_landmark_classes': [],
'line_width_archival': 12, # Previous value given was 2
'line_width_plant': 12, # Previous value given was 6
'line_width_seg': 12, # 12 is specified as "thick"
'line_width_efd': 12, # 3 is specified as "thick" but 12 is given here
'alpha_transparency_archival': 0.3,
'alpha_transparency_plant': 0,
'alpha_transparency_seg_whole_leaf': 0.4,
'alpha_transparency_seg_partial_leaf': 0.3
}
archival_component_detector_section = {
'detector_type': 'Archival_Detector',
'detector_version': 'PREP_final',
'detector_iteration': 'PREP_final',
'detector_weights': 'best.pt',
'minimum_confidence_threshold': 0.5, # Default is 0.5
'do_save_prediction_overlay_images': True,
'ignore_objects_for_overlay': []
}
# Add the sections to the 'leafmachine' key
config_data['leafmachine']['do'] = do_section
config_data['leafmachine']['print'] = print_section
config_data['leafmachine']['logging'] = logging_section
config_data['leafmachine']['project'] = project_section
config_data['leafmachine']['LLM_version'] = LLM_version
config_data['leafmachine']['use_RGB_label_images'] = use_RGB_label_images
config_data['leafmachine']['do_create_OCR_helper_image'] = do_create_OCR_helper_image
config_data['leafmachine']['cropped_components'] = cropped_components_section
config_data['leafmachine']['modules'] = modules_section
config_data['leafmachine']['data'] = data_section
config_data['leafmachine']['overlay'] = overlay_section
config_data['leafmachine']['archival_component_detector'] = archival_component_detector_section
return config_data, dir_home
def build_api_tests(api):
dir_home = os.path.dirname(os.path.dirname(__file__))
path_to_configs = os.path.join(dir_home,'demo','demo_configs')
dir_home = os.path.dirname(os.path.dirname(__file__))
dir_images_local = os.path.join(dir_home,'demo','demo_images')
validate_dir(os.path.join(dir_home,'demo','demo_configs'))
path_domain_knowledge = os.path.join(dir_home,'domain_knowledge','SLTP_UM_AllAsiaMinimalInRegion.xlsx')
embeddings_database_name = os.path.splitext(os.path.basename(path_domain_knowledge))[0]
prefix_removal = ''
suffix_removal = ''
catalog_numerical_only = False
batch_size = 500
do_create_OCR_helper_image = False
# ### Option 1: "GPT 4" of ["GPT 4", "GPT 3.5", "Azure GPT 4", "Azure GPT 3.5", "PaLM 2"]
# LLM_version_user = 'Azure GPT 4'
# ### Option 2: False of [False, True]
# use_LeafMachine2_collage_images = False
# ### Option 3: False of [False, True]
# use_domain_knowledge = True
test_results = {}
if api == 'openai':
OPT1, OPT2, OPT3 = TestOptionsAPI_openai.get_options()
elif api == 'palm':
OPT1, OPT2, OPT3 = TestOptionsAPI_palm.get_options()
elif api == 'azure_openai':
OPT1, OPT2, OPT3 = TestOptionsAPI_azure_openai.get_options()
else:
raise
ind = -1
ind_opt1 = -1
ind_opt2 = -1
ind_opt3 = -1
for opt1 in OPT1:
ind_opt1+= 1
for opt2 in OPT2:
ind_opt2 += 1
for opt3 in OPT3:
ind += 1
ind_opt3 += 1
LLM_version_user = opt1
use_LeafMachine2_collage_images = opt2
prompt_version = opt3
filename = f"{ind}__OPT1-{ind_opt1}__OPT2-{ind_opt2}__OPT3-{ind_opt3}.yaml"
run_name = f"{ind}__OPT1-{ind_opt1}__OPT2-{ind_opt2}__OPT3-{ind_opt3}"
dir_output = os.path.join(dir_home,'demo','demo_output','run_name')
validate_dir(dir_output)
config_data, dir_home = assemble_config(dir_home, run_name, dir_images_local,dir_output,
prefix_removal,suffix_removal,catalog_numerical_only,LLM_version_user,batch_size,
path_domain_knowledge,embeddings_database_name,use_LeafMachine2_collage_images,
prompt_version,do_create_OCR_helper_image)
|
def build_VV_config():
#############################################
############ Set common defaults ############
#############################################
# Changing the values below will set new
# default values each time you open the
# VoucherVision user interface
#############################################
#############################################
#############################################
dir_home = os.path.dirname(os.path.dirname(__file__))
run_name = 'test'
# dir_images_local = 'D:/Dropbox/LM2_Env/Image_Datasets/GBIF_BroadSample_3SppPerFamily1'
dir_images_local = os.path.join(dir_home,'demo','demo_images')
# The default output location is the computer's "Downloads" folder
# You can set dir_output directly by typing the folder path,
# OR you can uncomment the line "dir_output = default_output_folder"
# to have VoucherVision save to the Downloads folder by default
default_output_folder = get_default_download_folder()
dir_output = default_output_folder
# dir_output = 'D:/D_Desktop/LM2'
prefix_removal = '' #'MICH-V-'
suffix_removal = ''
catalog_numerical_only = False
LLM_version_user = 'Azure GPT 4'
prompt_version = 'Version 2' # from ["Version 1", "Version 1 No Domain Knowledge", "Version 2"]
use_LeafMachine2_collage_images = False # Use LeafMachine2 collage images
do_create_OCR_helper_image = False
batch_size = 500
path_domain_knowledge = os.path.join(dir_home,'domain_knowledge','SLTP_UM_AllAsiaMinimalInRegion.xlsx')
embeddings_database_name = os.path.splitext(os.path.basename(path_domain_knowledge))[0]
#############################################
#############################################
########## DO NOT EDIT BELOW HERE ###########
#############################################
#############################################
return assemble_config(dir_home, run_name, dir_images_local,dir_output,
prefix_removal,suffix_removal,catalog_numerical_only,LLM_version_user,batch_size,
path_domain_knowledge,embeddings_database_name,use_LeafMachine2_collage_images,
prompt_version, do_create_OCR_helper_image, use_domain_knowledge=False)
def assemble_config(dir_home, run_name, dir_images_local,dir_output,
prefix_removal,suffix_removal,catalog_numerical_only,LLM_version_user,batch_size,
path_domain_knowledge,embeddings_database_name,use_LeafMachine2_collage_images,
prompt_version, do_create_OCR_helper_image_user, use_domain_knowledge=False):
# Initialize the base structure
config_data = {
'leafmachine': {}
}
# Modular sections to be added to 'leafmachine'
do_section = {
'check_for_illegal_filenames': False,
'check_for_corrupt_images_make_vertical': True,
}
print_section = {
'verbose': True,
'optional_warnings': True
}
logging_section = {
'log_level': None
}
project_section = {
'dir_output': dir_output,
'run_name': run_name,
'image_location': 'local',
'batch_size': batch_size,
'num_workers': 1,
'dir_images_local': dir_images_local,
'continue_run_from_partial_xlsx': '',
'prefix_removal': prefix_removal,
'suffix_removal': suffix_removal,
'catalog_numerical_only': catalog_numerical_only,
'use_domain_knowledge': use_domain_knowledge,
'embeddings_database_name': embeddings_database_name,
'build_new_embeddings_database': False,
'path_to_domain_knowledge_xlsx': path_domain_knowledge,
'prompt_version': prompt_version,
'delete_all_temps': False,
'delete_temps_keep_VVE': False,
}
modules_section = {
'specimen_crop': True
}
LLM_version = LLM_version_user
use_RGB_label_images = use_LeafMachine2_collage_images # Use LeafMachine2 collage images
do_create_OCR_helper_image = do_create_OCR_helper_image_user
cropped_components_section = {
'do_save_cropped_annotations': True,
'save_cropped_annotations': ['label','barcode'],
'save_per_image': False,
'save_per_annotation_class': True,
'binarize_labels': False,
'binarize_labels_skeletonize': False
}
data_section = {
'save_json_rulers': False,
'save_json_measurements': False,
'save_individual_csv_files_rulers': False,
'save_individual_csv_files_measurements': False,
'save_individual_csv_files_landmarks': False,
'save_individual_efd_files': False,
'include_darwin_core_data_from_combined_file': False,
'do_apply_conversion_factor': False
}
overlay_section = {
'save_overlay_to_pdf': False,
'save_overlay_to_jpgs': True,
'overlay_dpi': 300, # Between 100 to 300
'overlay_background_color': 'black', # Either 'white' or 'black'
'show_archival_detections': True,
'show_plant_detections': True,
'show_segmentations': True,
'show_landmarks': True,
'ignore_archival_detections_classes': [],
'ignore_plant_detections_classes': ['leaf_whole', 'specimen'], # Could also include 'leaf_partial' and others if needed
'ignore_landmark_classes': [],
'line_width_archival': 12, # Previous value given was 2
'line_width_plant': 12, # Previous value given was 6
'line_width_seg': 12, # 12 is specified as "thick"
'line_width_efd': 12, # 3 is specified as "thick" but 12 is given here
'alpha_transparency_archival': 0.3,
'alpha_transparency_plant': 0,
'alpha_transparency_seg_whole_leaf': 0.4,
'alpha_transparency_seg_partial_leaf': 0.3
}
archival_component_detector_section = {
'detector_type': 'Archival_Detector',
'detector_version': 'PREP_final',
'detector_iteration': 'PREP_final',
'detector_weights': 'best.pt',
'minimum_confidence_threshold': 0.5, # Default is 0.5
'do_save_prediction_overlay_images': True,
'ignore_objects_for_overlay': []
}
# Add the sections to the 'leafmachine' key
config_data['leafmachine']['do'] = do_section
config_data['leafmachine']['print'] = print_section
config_data['leafmachine']['logging'] = logging_section
config_data['leafmachine']['project'] = project_section
config_data['leafmachine']['LLM_version'] = LLM_version
config_data['leafmachine']['use_RGB_label_images'] = use_RGB_label_images
config_data['leafmachine']['do_create_OCR_helper_image'] = do_create_OCR_helper_image
config_data['leafmachine']['cropped_components'] = cropped_components_section
config_data['leafmachine']['modules'] = modules_section
config_data['leafmachine']['data'] = data_section
config_data['leafmachine']['overlay'] = overlay_section
config_data['leafmachine']['archival_component_detector'] = archival_component_detector_section
return config_data, dir_home
def build_api_tests(api):
dir_home = os.path.dirname(os.path.dirname(__file__))
path_to_configs = os.path.join(dir_home,'demo','demo_configs')
dir_home = os.path.dirname(os.path.dirname(__file__))
dir_images_local = os.path.join(dir_home,'demo','demo_images')
validate_dir(os.path.join(dir_home,'demo','demo_configs'))
path_domain_knowledge = os.path.join(dir_home,'domain_knowledge','SLTP_UM_AllAsiaMinimalInRegion.xlsx')
embeddings_database_name = os.path.splitext(os.path.basename(path_domain_knowledge))[0]
prefix_removal = ''
suffix_removal = ''
catalog_numerical_only = False
batch_size = 500
do_create_OCR_helper_image = False
# ### Option 1: "GPT 4" of ["GPT 4", "GPT 3.5", "Azure GPT 4", "Azure GPT 3.5", "PaLM 2"]
# LLM_version_user = 'Azure GPT 4'
# ### Option 2: False of [False, True]
# use_LeafMachine2_collage_images = False
# ### Option 3: False of [False, True]
# use_domain_knowledge = True
test_results = {}
if api == 'openai':
OPT1, OPT2, OPT3 = TestOptionsAPI_openai.get_options()
elif api == 'palm':
OPT1, OPT2, OPT3 = TestOptionsAPI_palm.get_options()
elif api == 'azure_openai':
OPT1, OPT2, OPT3 = TestOptionsAPI_azure_openai.get_options()
else:
raise
ind = -1
ind_opt1 = -1
ind_opt2 = -1
ind_opt3 = -1
for opt1 in OPT1:
ind_opt1+= 1
for opt2 in OPT2:
ind_opt2 += 1
for opt3 in OPT3:
ind += 1
ind_opt3 += 1
LLM_version_user = opt1
use_LeafMachine2_collage_images = opt2
prompt_version = opt3
filename = f"{ind}__OPT1-{ind_opt1}__OPT2-{ind_opt2}__OPT3-{ind_opt3}.yaml"
run_name = f"{ind}__OPT1-{ind_opt1}__OPT2-{ind_opt2}__OPT3-{ind_opt3}"
dir_output = os.path.join(dir_home,'demo','demo_output','run_name')
validate_dir(dir_output)
config_data, dir_home = assemble_config(dir_home, run_name, dir_images_local,dir_output,
prefix_removal,suffix_removal,catalog_numerical_only,LLM_version_user,batch_size,
path_domain_knowledge,embeddings_database_name,use_LeafMachine2_collage_images,
prompt_version,do_create_OCR_helper_image)
| write_config_file(config_data, os.path.join(dir_home,'demo','demo_configs'),filename=filename) | 1 | 2023-10-30 23:25:20+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.