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 |
|---|---|---|---|---|---|---|---|---|---|---|
pchunduri6/rag-demystified | complex_qa.py | [
{
"identifier": "generate_subquestions",
"path": "subquestion_generator.py",
"snippet": "def generate_subquestions(\n question,\n file_names: List[str] = None,\n system_prompt=DEFAULT_SUBQUESTION_GENERATOR_PROMPT,\n user_task=DEFAULT_USER_TASK,\n llm_model=\"gpt-4-0613\",\n):\n \"\"\"G... | import os
import requests
import warnings
import evadb
from dotenv import load_dotenv
from pathlib import Path
from subquestion_generator import generate_subquestions
from openai_utils import llm_call | 2,410 | """
res_batch = cursor.query(
f"""SELECT data FROM {doc_name}_features
ORDER BY Similarity(SentenceFeatureExtractor('{question}'),features)
LIMIT 3;"""
).df()
context_list = []
for i in range(len(res_batch)):
context_list.append(res_batch["data"][i])
context = "\n".join(context_list)
user_prompt = f"""You are an assistant for question-answering tasks.
Use the following pieces of retrieved context to answer the question.
If you don't know the answer, just say that you don't know.
Use three sentences maximum and keep the answer concise.
Question: {question}
Context: {context}
Answer:"""
response, cost = llm_call(model=llm_model, user_prompt=user_prompt)
answer = response.choices[0].message.content
return answer, cost
def summary_retrieval(llm_model, question, doc):
"""Returns the answer to a summarization question over the document using summary retrieval.
"""
# context_length = OPENAI_MODEL_CONTEXT_LENGTH[llm_model]
# total_tokens = get_num_tokens_simple(llm_model, wiki_docs[doc])
user_prompt = f"""Here is some context: {doc}
Use only the provided context to answer the question.
Here is the question: {question}"""
response, cost = llm_call(model=llm_model, user_prompt=user_prompt)
answer = response.choices[0].message.content
return answer, cost
# load max of context_length tokens from the document
def response_aggregator(llm_model, question, responses):
"""Aggregates the responses from the subquestions to generate the final response.
"""
print("-------> ⭐ Aggregating responses...")
system_prompt = """You are an assistant for question-answering tasks.
Use the following pieces of retrieved context to answer the question.
If you don't know the answer, just say that you don't know.
Use three sentences maximum and keep the answer concise."""
context = ""
for i, response in enumerate(responses):
context += f"\n{response}"
user_prompt = f"""Question: {question}
Context: {context}
Answer:"""
response, cost = llm_call(model=llm_model, system_prompt=system_prompt, user_prompt=user_prompt)
answer = response.choices[0].message.content
return answer, cost
def load_wiki_pages(page_titles=["Toronto", "Chicago", "Houston", "Boston", "Atlanta"]):
# Download all wiki documents
for title in page_titles:
response = requests.get(
"https://en.wikipedia.org/w/api.php",
params={
"action": "query",
"format": "json",
"titles": title,
"prop": "extracts",
# 'exintro': True,
"explaintext": True,
},
).json()
page = next(iter(response["query"]["pages"].values()))
wiki_text = page["extract"]
data_path = Path("data")
if not data_path.exists():
Path.mkdir(data_path)
with open(data_path / f"{title}.txt", "w") as fp:
fp.write(wiki_text)
# Load all wiki documents
city_docs = {}
for wiki_title in page_titles:
input_text = open(f"data/{wiki_title}.txt", "r").read()
city_docs[wiki_title] = input_text[:10000]
return city_docs
if __name__ == "__main__":
# establish evadb api cursor
print("⏳ Connect to EvaDB...")
cursor = evadb.connect().cursor()
print("✅ Connected to EvaDB...")
doc_names = ["Toronto", "Chicago", "Houston", "Boston", "Atlanta"]
wiki_docs = load_wiki_pages(page_titles=doc_names)
question = "Which city has the highest population?"
user_task = """We have a database of wikipedia articles about several cities.
We are building an application to answer questions about the cities."""
vector_stores = generate_vector_stores(cursor, wiki_docs)
llm_model = "gpt-35-turbo"
total_cost = 0
while True:
question_cost = 0
# Get question from user
question = str(input("Question (enter 'exit' to exit): "))
if question.lower() == "exit":
break
print("🧠 Generating subquestions...")
|
warnings.filterwarnings("ignore")
if not load_dotenv():
print(
"Could not load .env file or it is empty. Please check if it exists and is readable."
)
exit(1)
def generate_vector_stores(cursor, docs):
"""Generate a vector store for the docs using evadb.
"""
for doc in docs:
print(f"Creating vector store for {doc}...")
cursor.query(f"DROP TABLE IF EXISTS {doc};").df()
cursor.query(f"LOAD DOCUMENT 'data/{doc}.txt' INTO {doc};").df()
evadb_path = os.path.dirname(evadb.__file__)
cursor.query(
f"""CREATE FUNCTION IF NOT EXISTS SentenceFeatureExtractor
IMPL '{evadb_path}/functions/sentence_feature_extractor.py';
""").df()
cursor.query(
f"""CREATE TABLE IF NOT EXISTS {doc}_features AS
SELECT SentenceFeatureExtractor(data), data FROM {doc};"""
).df()
cursor.query(
f"CREATE INDEX IF NOT EXISTS {doc}_index ON {doc}_features (features) USING FAISS;"
).df()
print(f"Successfully created vector store for {doc}.")
def vector_retrieval(cursor, llm_model, question, doc_name):
"""Returns the answer to a factoid question using vector retrieval.
"""
res_batch = cursor.query(
f"""SELECT data FROM {doc_name}_features
ORDER BY Similarity(SentenceFeatureExtractor('{question}'),features)
LIMIT 3;"""
).df()
context_list = []
for i in range(len(res_batch)):
context_list.append(res_batch["data"][i])
context = "\n".join(context_list)
user_prompt = f"""You are an assistant for question-answering tasks.
Use the following pieces of retrieved context to answer the question.
If you don't know the answer, just say that you don't know.
Use three sentences maximum and keep the answer concise.
Question: {question}
Context: {context}
Answer:"""
response, cost = llm_call(model=llm_model, user_prompt=user_prompt)
answer = response.choices[0].message.content
return answer, cost
def summary_retrieval(llm_model, question, doc):
"""Returns the answer to a summarization question over the document using summary retrieval.
"""
# context_length = OPENAI_MODEL_CONTEXT_LENGTH[llm_model]
# total_tokens = get_num_tokens_simple(llm_model, wiki_docs[doc])
user_prompt = f"""Here is some context: {doc}
Use only the provided context to answer the question.
Here is the question: {question}"""
response, cost = llm_call(model=llm_model, user_prompt=user_prompt)
answer = response.choices[0].message.content
return answer, cost
# load max of context_length tokens from the document
def response_aggregator(llm_model, question, responses):
"""Aggregates the responses from the subquestions to generate the final response.
"""
print("-------> ⭐ Aggregating responses...")
system_prompt = """You are an assistant for question-answering tasks.
Use the following pieces of retrieved context to answer the question.
If you don't know the answer, just say that you don't know.
Use three sentences maximum and keep the answer concise."""
context = ""
for i, response in enumerate(responses):
context += f"\n{response}"
user_prompt = f"""Question: {question}
Context: {context}
Answer:"""
response, cost = llm_call(model=llm_model, system_prompt=system_prompt, user_prompt=user_prompt)
answer = response.choices[0].message.content
return answer, cost
def load_wiki_pages(page_titles=["Toronto", "Chicago", "Houston", "Boston", "Atlanta"]):
# Download all wiki documents
for title in page_titles:
response = requests.get(
"https://en.wikipedia.org/w/api.php",
params={
"action": "query",
"format": "json",
"titles": title,
"prop": "extracts",
# 'exintro': True,
"explaintext": True,
},
).json()
page = next(iter(response["query"]["pages"].values()))
wiki_text = page["extract"]
data_path = Path("data")
if not data_path.exists():
Path.mkdir(data_path)
with open(data_path / f"{title}.txt", "w") as fp:
fp.write(wiki_text)
# Load all wiki documents
city_docs = {}
for wiki_title in page_titles:
input_text = open(f"data/{wiki_title}.txt", "r").read()
city_docs[wiki_title] = input_text[:10000]
return city_docs
if __name__ == "__main__":
# establish evadb api cursor
print("⏳ Connect to EvaDB...")
cursor = evadb.connect().cursor()
print("✅ Connected to EvaDB...")
doc_names = ["Toronto", "Chicago", "Houston", "Boston", "Atlanta"]
wiki_docs = load_wiki_pages(page_titles=doc_names)
question = "Which city has the highest population?"
user_task = """We have a database of wikipedia articles about several cities.
We are building an application to answer questions about the cities."""
vector_stores = generate_vector_stores(cursor, wiki_docs)
llm_model = "gpt-35-turbo"
total_cost = 0
while True:
question_cost = 0
# Get question from user
question = str(input("Question (enter 'exit' to exit): "))
if question.lower() == "exit":
break
print("🧠 Generating subquestions...") | subquestions_bundle_list, cost = generate_subquestions(question=question, | 0 | 2023-10-18 16:32:51+00:00 | 4k |
predibase/lorax | server/lorax_server/utils/sources/hub.py | [
{
"identifier": "BaseModelSource",
"path": "server/lorax_server/utils/sources/source.py",
"snippet": "class BaseModelSource:\n def remote_weight_files(self, extension: str = None):\n raise NotImplementedError\n\n def weight_files(self, extension: str = None):\n raise NotImplementedEr... | import time
import os
from datetime import timedelta
from loguru import logger
from pathlib import Path
from typing import Optional, List
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE
from huggingface_hub.utils import (
LocalEntryNotFoundError,
EntryNotFoundError,
RevisionNotFoundError, # Import here to ease try/except in other part of the lib
)
from .source import BaseModelSource, try_to_load_from_cache | 1,689 | and "arguments" not in s.rfilename
and "args" not in s.rfilename
and "training" not in s.rfilename
]
if not filenames:
raise EntryNotFoundError(
f"No {extension} weights found for model {model_id} and revision {revision}.",
None,
)
return filenames
def weight_files(
model_id: str, revision: Optional[str] = None, extension: str = ".safetensors"
) -> List[Path]:
"""Get the local files"""
# Local model
if Path(model_id).exists() and Path(model_id).is_dir():
local_files = list(Path(model_id).glob(f"*{extension}"))
if not local_files:
raise FileNotFoundError(
f"No local weights found in {model_id} with extension {extension}"
)
return local_files
try:
filenames = weight_hub_files(model_id, revision, extension)
except EntryNotFoundError as e:
if extension != ".safetensors":
raise e
# Try to see if there are pytorch weights
pt_filenames = weight_hub_files(model_id, revision, extension=".bin")
# Change pytorch extension to safetensors extension
# It is possible that we have safetensors weights locally even though they are not on the
# hub if we converted weights locally without pushing them
filenames = [
f"{Path(f).stem.lstrip('pytorch_')}.safetensors" for f in pt_filenames
]
if WEIGHTS_CACHE_OVERRIDE is not None:
files = []
for filename in filenames:
p = Path(WEIGHTS_CACHE_OVERRIDE) / filename
if not p.exists():
raise FileNotFoundError(
f"File {p} not found in {WEIGHTS_CACHE_OVERRIDE}."
)
files.append(p)
return files
repo_cache = get_hub_model_local_dir(model_id)
files = []
for filename in filenames:
cache_file = try_to_load_from_cache(
repo_cache, revision=revision, filename=filename
)
if cache_file is None:
raise LocalEntryNotFoundError(
f"File {filename} of model {model_id} not found in "
f"{os.getenv('HUGGINGFACE_HUB_CACHE', 'the local cache')}. "
f"Please run `lorax-server download-weights {model_id}` first."
)
files.append(cache_file)
return files
def download_weights(
filenames: List[str], model_id: str, revision: Optional[str] = None
) -> List[Path]:
"""Download the safetensors files from the hub"""
def download_file(filename, tries=5, backoff: int = 5):
repo_cache = get_hub_model_local_dir(model_id)
local_file = try_to_load_from_cache(repo_cache, revision, filename)
if local_file is not None:
logger.info(f"File {filename} already present in cache.")
return Path(local_file)
for i in range(tries):
try:
logger.info(f"Download file: {filename}")
start_time = time.time()
local_file = hf_hub_download(
filename=filename,
repo_id=model_id,
revision=revision,
local_files_only=False,
)
logger.info(
f"Downloaded {local_file} in {timedelta(seconds=int(time.time() - start_time))}."
)
return Path(local_file)
except Exception as e:
if i + 1 == tries:
raise e
logger.error(e)
logger.info(f"Retrying in {backoff} seconds")
time.sleep(backoff)
logger.info(f"Retry {i + 1}/{tries - 1}")
# We do this instead of using tqdm because we want to parse the logs with the launcher
start_time = time.time()
files = []
for i, filename in enumerate(filenames):
file = download_file(filename)
elapsed = timedelta(seconds=int(time.time() - start_time))
remaining = len(filenames) - (i + 1)
eta = (elapsed / (i + 1)) * remaining if remaining > 0 else 0
logger.info(f"Download: [{i + 1}/{len(filenames)}] -- ETA: {eta}")
files.append(file)
return files
|
WEIGHTS_CACHE_OVERRIDE = os.getenv("WEIGHTS_CACHE_OVERRIDE", None)
def get_hub_model_local_dir(model_id: str) -> Path:
object_id = model_id.replace("/", "--")
repo_cache = Path(HUGGINGFACE_HUB_CACHE) / f"models--{object_id}"
return repo_cache
def weight_hub_files(
model_id: str, revision: Optional[str] = None, extension: str = ".safetensors"
) -> List[str]:
"""Get the weights filenames on the hub"""
api = HfApi()
info = api.model_info(model_id, revision=revision)
filenames = [
s.rfilename
for s in info.siblings
if s.rfilename.endswith(extension)
and len(s.rfilename.split("/")) == 1
and "arguments" not in s.rfilename
and "args" not in s.rfilename
and "training" not in s.rfilename
]
if not filenames:
raise EntryNotFoundError(
f"No {extension} weights found for model {model_id} and revision {revision}.",
None,
)
return filenames
def weight_files(
model_id: str, revision: Optional[str] = None, extension: str = ".safetensors"
) -> List[Path]:
"""Get the local files"""
# Local model
if Path(model_id).exists() and Path(model_id).is_dir():
local_files = list(Path(model_id).glob(f"*{extension}"))
if not local_files:
raise FileNotFoundError(
f"No local weights found in {model_id} with extension {extension}"
)
return local_files
try:
filenames = weight_hub_files(model_id, revision, extension)
except EntryNotFoundError as e:
if extension != ".safetensors":
raise e
# Try to see if there are pytorch weights
pt_filenames = weight_hub_files(model_id, revision, extension=".bin")
# Change pytorch extension to safetensors extension
# It is possible that we have safetensors weights locally even though they are not on the
# hub if we converted weights locally without pushing them
filenames = [
f"{Path(f).stem.lstrip('pytorch_')}.safetensors" for f in pt_filenames
]
if WEIGHTS_CACHE_OVERRIDE is not None:
files = []
for filename in filenames:
p = Path(WEIGHTS_CACHE_OVERRIDE) / filename
if not p.exists():
raise FileNotFoundError(
f"File {p} not found in {WEIGHTS_CACHE_OVERRIDE}."
)
files.append(p)
return files
repo_cache = get_hub_model_local_dir(model_id)
files = []
for filename in filenames:
cache_file = try_to_load_from_cache(
repo_cache, revision=revision, filename=filename
)
if cache_file is None:
raise LocalEntryNotFoundError(
f"File {filename} of model {model_id} not found in "
f"{os.getenv('HUGGINGFACE_HUB_CACHE', 'the local cache')}. "
f"Please run `lorax-server download-weights {model_id}` first."
)
files.append(cache_file)
return files
def download_weights(
filenames: List[str], model_id: str, revision: Optional[str] = None
) -> List[Path]:
"""Download the safetensors files from the hub"""
def download_file(filename, tries=5, backoff: int = 5):
repo_cache = get_hub_model_local_dir(model_id)
local_file = try_to_load_from_cache(repo_cache, revision, filename)
if local_file is not None:
logger.info(f"File {filename} already present in cache.")
return Path(local_file)
for i in range(tries):
try:
logger.info(f"Download file: {filename}")
start_time = time.time()
local_file = hf_hub_download(
filename=filename,
repo_id=model_id,
revision=revision,
local_files_only=False,
)
logger.info(
f"Downloaded {local_file} in {timedelta(seconds=int(time.time() - start_time))}."
)
return Path(local_file)
except Exception as e:
if i + 1 == tries:
raise e
logger.error(e)
logger.info(f"Retrying in {backoff} seconds")
time.sleep(backoff)
logger.info(f"Retry {i + 1}/{tries - 1}")
# We do this instead of using tqdm because we want to parse the logs with the launcher
start_time = time.time()
files = []
for i, filename in enumerate(filenames):
file = download_file(filename)
elapsed = timedelta(seconds=int(time.time() - start_time))
remaining = len(filenames) - (i + 1)
eta = (elapsed / (i + 1)) * remaining if remaining > 0 else 0
logger.info(f"Download: [{i + 1}/{len(filenames)}] -- ETA: {eta}")
files.append(file)
return files
| class HubModelSource(BaseModelSource): | 0 | 2023-10-20 18:19:49+00:00 | 4k |
codefuse-ai/Test-Agent | chat/server/gradio_web_server.py | [
{
"identifier": "SeparatorStyle",
"path": "chat/conversation.py",
"snippet": "class SeparatorStyle(IntEnum):\n \"\"\"Separator styles.\"\"\"\n\n ADD_COLON_SINGLE = auto()\n ADD_COLON_TWO = auto()\n ADD_COLON_SPACE_SINGLE = auto()\n NO_COLON_SINGLE = auto()\n NO_COLON_TWO = auto()\n ... | import argparse
import datetime
import json
import os
import random
import time
import uuid
import gradio as gr
import requests
from collections import defaultdict
from chat.conversation import SeparatorStyle
from chat.constants import (
LOGDIR,
WORKER_API_TIMEOUT,
ErrorCode,
MODERATION_MSG,
CONVERSATION_LIMIT_MSG,
SERVER_ERROR_MSG,
INACTIVE_MSG,
INPUT_CHAR_LEN_LIMIT,
CONVERSATION_TURN_LIMIT,
SESSION_EXPIRATION_TIME,
)
from chat.model.model_adapter import get_conversation_template
from chat.model.model_registry import model_info
from chat.server.api_provider import (
anthropic_api_stream_iter,
openai_api_stream_iter,
palm_api_stream_iter,
init_palm_chat,
)
from chat.utils import (
build_logger,
violates_moderation,
get_window_url_params_js,
parse_gradio_auth_creds,
) | 3,567 | openai_compatible_models_info = json.load(
open(register_openai_compatible_models)
)
models += list(openai_compatible_models_info.keys())
if add_chatgpt:
models += ["gpt-3.5-turbo", "gpt-4"]
if add_claude:
models += ["claude-2", "claude-instant-1"]
if add_palm:
models += ["palm-2"]
models = list(set(models))
priority = {k: f"___{i:02d}" for i, k in enumerate(model_info)}
models.sort(key=lambda x: priority.get(x, x))
logger.info(f"Models: {models}")
return models
def load_demo_single(models, url_params):
selected_model = models[0] if len(models) > 0 else ""
if "model" in url_params:
model = url_params["model"]
if model in models:
selected_model = model
dropdown_update = gr.Dropdown.update(
choices=models, value=selected_model, visible=True
)
state = None
return (
state,
dropdown_update,
gr.Chatbot.update(visible=True),
gr.Textbox.update(visible=True),
gr.Button.update(visible=True),
gr.Row.update(visible=True),
gr.Accordion.update(visible=True),
)
def load_demo(url_params, request: gr.Request):
global models
ip = request.client.host
logger.info(f"load_demo. ip: {ip}. params: {url_params}")
ip_expiration_dict[ip] = time.time() + SESSION_EXPIRATION_TIME
if args.model_list_mode == "reload":
models = get_model_list(
controller_url,
args.register_openai_compatible_models,
args.add_chatgpt,
args.add_claude,
args.add_palm,
)
return load_demo_single(models, url_params)
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
with open(get_conv_log_filename(), "a") as fout:
data = {
"tstamp": round(time.time(), 4),
"type": vote_type,
"model": model_selector,
"state": state.dict(),
"ip": request.client.host,
}
fout.write(json.dumps(data) + "\n")
def upvote_last_response(state, model_selector, request: gr.Request):
logger.info(f"upvote. ip: {request.client.host}")
vote_last_response(state, "upvote", model_selector, request)
return ("",) + (disable_btn,) * 3
def downvote_last_response(state, model_selector, request: gr.Request):
logger.info(f"downvote. ip: {request.client.host}")
vote_last_response(state, "downvote", model_selector, request)
return ("",) + (disable_btn,) * 3
def flag_last_response(state, model_selector, request: gr.Request):
logger.info(f"flag. ip: {request.client.host}")
vote_last_response(state, "flag", model_selector, request)
return ("",) + (disable_btn,) * 3
def regenerate(state, request: gr.Request):
logger.info(f"regenerate. ip: {request.client.host}")
state.conv.update_last_message(None)
return (state, state.to_gradio_chatbot(), "") + (disable_btn,) * 5
def clear_history(request: gr.Request):
logger.info(f"clear_history. ip: {request.client.host}")
state = None
return (state, [], "") + (disable_btn,) * 5
def add_text(state, model_selector, text, request: gr.Request):
ip = request.client.host
logger.info(f"add_text. ip: {ip}. len: {len(text)}")
if state is None:
state = State(model_selector)
if len(text) <= 0:
state.skip_next = True
return (state, state.to_gradio_chatbot(), "") + (no_change_btn,) * 5
if ip_expiration_dict[ip] < time.time():
logger.info(f"inactive. ip: {request.client.host}. text: {text}")
state.skip_next = True
return (state, state.to_gradio_chatbot(), INACTIVE_MSG) + (no_change_btn,) * 5
if enable_moderation:
| """
The gradio demo server for chatting with a single model.
"""
logger = build_logger("gradio_web_server", "gradio_web_server.log")
headers = {"User-Agent": "FastChat Client"}
no_change_btn = gr.Button.update()
enable_btn = gr.Button.update(interactive=True)
disable_btn = gr.Button.update(interactive=False)
controller_url = None
enable_moderation = False
acknowledgment_md = """
**Acknowledgment:** We thank Kaggle, MBZUAI, and AnyScale for their sponsorship.
"""
ip_expiration_dict = defaultdict(lambda: 0)
# Information about custom OpenAI compatible API models.
# JSON file format:
# {
# "vicuna-7b": {
# "model_name": "vicuna-7b-v1.5",
# "api_base": "http://8.8.8.55:5555/v1",
# "api_key": "password"
# },
# }
openai_compatible_models_info = {}
class State:
def __init__(self, model_name):
self.conv = get_conversation_template(model_name)
self.conv_id = uuid.uuid4().hex
self.skip_next = False
self.model_name = model_name
if model_name == "palm-2":
# According to release note, "chat-bison@001" is PaLM 2 for chat.
# https://cloud.google.com/vertex-ai/docs/release-notes#May_10_2023
self.palm_chat = init_palm_chat("chat-bison@001")
def to_gradio_chatbot(self):
return self.conv.to_gradio_chatbot()
def dict(self):
base = self.conv.dict()
base.update(
{
"conv_id": self.conv_id,
"model_name": self.model_name,
}
)
return base
def set_global_vars(controller_url_, enable_moderation_):
global controller_url, enable_moderation
controller_url = controller_url_
enable_moderation = enable_moderation_
def get_conv_log_filename():
t = datetime.datetime.now()
name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
return name
def get_model_list(
controller_url, register_openai_compatible_models, add_chatgpt, add_claude, add_palm
):
if controller_url:
ret = requests.post(controller_url + "/refresh_all_workers")
assert ret.status_code == 200
ret = requests.post(controller_url + "/list_models")
models = ret.json()["models"]
else:
models = []
# Add API providers
if register_openai_compatible_models:
global openai_compatible_models_info
openai_compatible_models_info = json.load(
open(register_openai_compatible_models)
)
models += list(openai_compatible_models_info.keys())
if add_chatgpt:
models += ["gpt-3.5-turbo", "gpt-4"]
if add_claude:
models += ["claude-2", "claude-instant-1"]
if add_palm:
models += ["palm-2"]
models = list(set(models))
priority = {k: f"___{i:02d}" for i, k in enumerate(model_info)}
models.sort(key=lambda x: priority.get(x, x))
logger.info(f"Models: {models}")
return models
def load_demo_single(models, url_params):
selected_model = models[0] if len(models) > 0 else ""
if "model" in url_params:
model = url_params["model"]
if model in models:
selected_model = model
dropdown_update = gr.Dropdown.update(
choices=models, value=selected_model, visible=True
)
state = None
return (
state,
dropdown_update,
gr.Chatbot.update(visible=True),
gr.Textbox.update(visible=True),
gr.Button.update(visible=True),
gr.Row.update(visible=True),
gr.Accordion.update(visible=True),
)
def load_demo(url_params, request: gr.Request):
global models
ip = request.client.host
logger.info(f"load_demo. ip: {ip}. params: {url_params}")
ip_expiration_dict[ip] = time.time() + SESSION_EXPIRATION_TIME
if args.model_list_mode == "reload":
models = get_model_list(
controller_url,
args.register_openai_compatible_models,
args.add_chatgpt,
args.add_claude,
args.add_palm,
)
return load_demo_single(models, url_params)
def vote_last_response(state, vote_type, model_selector, request: gr.Request):
with open(get_conv_log_filename(), "a") as fout:
data = {
"tstamp": round(time.time(), 4),
"type": vote_type,
"model": model_selector,
"state": state.dict(),
"ip": request.client.host,
}
fout.write(json.dumps(data) + "\n")
def upvote_last_response(state, model_selector, request: gr.Request):
logger.info(f"upvote. ip: {request.client.host}")
vote_last_response(state, "upvote", model_selector, request)
return ("",) + (disable_btn,) * 3
def downvote_last_response(state, model_selector, request: gr.Request):
logger.info(f"downvote. ip: {request.client.host}")
vote_last_response(state, "downvote", model_selector, request)
return ("",) + (disable_btn,) * 3
def flag_last_response(state, model_selector, request: gr.Request):
logger.info(f"flag. ip: {request.client.host}")
vote_last_response(state, "flag", model_selector, request)
return ("",) + (disable_btn,) * 3
def regenerate(state, request: gr.Request):
logger.info(f"regenerate. ip: {request.client.host}")
state.conv.update_last_message(None)
return (state, state.to_gradio_chatbot(), "") + (disable_btn,) * 5
def clear_history(request: gr.Request):
logger.info(f"clear_history. ip: {request.client.host}")
state = None
return (state, [], "") + (disable_btn,) * 5
def add_text(state, model_selector, text, request: gr.Request):
ip = request.client.host
logger.info(f"add_text. ip: {ip}. len: {len(text)}")
if state is None:
state = State(model_selector)
if len(text) <= 0:
state.skip_next = True
return (state, state.to_gradio_chatbot(), "") + (no_change_btn,) * 5
if ip_expiration_dict[ip] < time.time():
logger.info(f"inactive. ip: {request.client.host}. text: {text}")
state.skip_next = True
return (state, state.to_gradio_chatbot(), INACTIVE_MSG) + (no_change_btn,) * 5
if enable_moderation: | flagged = violates_moderation(text) | 17 | 2023-10-20 08:56:20+00:00 | 4k |
thuml/iTransformer | model/iInformer.py | [
{
"identifier": "Encoder",
"path": "layers/Transformer_EncDec.py",
"snippet": "class Encoder(nn.Module):\n def __init__(self, attn_layers, conv_layers=None, norm_layer=None):\n super(Encoder, self).__init__()\n self.attn_layers = nn.ModuleList(attn_layers)\n self.conv_layers = nn... | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from layers.Transformer_EncDec import Encoder, EncoderLayer
from layers.SelfAttention_Family import ProbAttention, AttentionLayer
from layers.Embed import DataEmbedding_inverted | 2,602 |
class Model(nn.Module):
"""
Vanilla Transformer
with O(L^2) complexity
Paper link: https://proceedings.neurips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf
"""
def __init__(self, configs):
super(Model, self).__init__()
self.seq_len = configs.seq_len
self.pred_len = configs.pred_len
self.output_attention = configs.output_attention
# Embedding
self.enc_embedding = DataEmbedding_inverted(configs.seq_len, configs.d_model, configs.embed, configs.freq,
configs.dropout)
# Encoder-only architecture
self.encoder = Encoder(
[
|
class Model(nn.Module):
"""
Vanilla Transformer
with O(L^2) complexity
Paper link: https://proceedings.neurips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf
"""
def __init__(self, configs):
super(Model, self).__init__()
self.seq_len = configs.seq_len
self.pred_len = configs.pred_len
self.output_attention = configs.output_attention
# Embedding
self.enc_embedding = DataEmbedding_inverted(configs.seq_len, configs.d_model, configs.embed, configs.freq,
configs.dropout)
# Encoder-only architecture
self.encoder = Encoder(
[ | EncoderLayer( | 1 | 2023-10-19 03:23:15+00:00 | 4k |
kylesargent/ZeroNVS | threestudio/models/prompt_processors/base.py | [
{
"identifier": "BaseObject",
"path": "threestudio/utils/base.py",
"snippet": "class BaseObject(Updateable):\n @dataclass\n class Config:\n pass\n\n cfg: Config # add this to every subclass of BaseObject to enable static type checking\n\n def __init__(\n self, cfg: Optional[Un... | import json
import os
import torch
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
import threestudio
import hashlib
from dataclasses import dataclass, field
from pytorch_lightning.utilities.rank_zero import rank_zero_only
from transformers import AutoTokenizer, BertForMaskedLM
from threestudio.utils.base import BaseObject
from threestudio.utils.misc import barrier, cleanup, get_rank
from threestudio.utils.ops import shifted_cosine_decay, shifted_expotional_decay
from threestudio.utils.typing import * | 1,611 |
def hash_prompt(model: str, prompt: str) -> str:
identifier = f"{model}-{prompt}"
return hashlib.md5(identifier.encode()).hexdigest()
@dataclass
class DirectionConfig:
name: str
prompt: Callable[[str], str]
negative_prompt: Callable[[str], str]
condition: Callable[
[Float[Tensor, "B"], Float[Tensor, "B"], Float[Tensor, "B"]],
Float[Tensor, "B"],
]
@dataclass
class PromptProcessorOutput:
text_embeddings: Float[Tensor, "N Nf"]
uncond_text_embeddings: Float[Tensor, "N Nf"]
text_embeddings_vd: Float[Tensor, "Nv N Nf"]
uncond_text_embeddings_vd: Float[Tensor, "Nv N Nf"]
directions: List[DirectionConfig]
direction2idx: Dict[str, int]
use_perp_neg: bool
perp_neg_f_sb: Tuple[float, float, float]
perp_neg_f_fsb: Tuple[float, float, float]
perp_neg_f_fs: Tuple[float, float, float]
perp_neg_f_sf: Tuple[float, float, float]
def get_text_embeddings(
self,
elevation: Float[Tensor, "B"],
azimuth: Float[Tensor, "B"],
camera_distances: Float[Tensor, "B"],
view_dependent_prompting: bool = True,
) -> Float[Tensor, "BB N Nf"]:
batch_size = elevation.shape[0]
if view_dependent_prompting:
# Get direction
direction_idx = torch.zeros_like(elevation, dtype=torch.long)
for d in self.directions:
direction_idx[
d.condition(elevation, azimuth, camera_distances)
] = self.direction2idx[d.name]
# Get text embeddings
text_embeddings = self.text_embeddings_vd[direction_idx] # type: ignore
uncond_text_embeddings = self.uncond_text_embeddings_vd[direction_idx] # type: ignore
else:
text_embeddings = self.text_embeddings.expand(batch_size, -1, -1) # type: ignore
uncond_text_embeddings = self.uncond_text_embeddings.expand( # type: ignore
batch_size, -1, -1
)
# IMPORTANT: we return (cond, uncond), which is in different order than other implementations!
return torch.cat([text_embeddings, uncond_text_embeddings], dim=0)
def get_text_embeddings_perp_neg(
self,
elevation: Float[Tensor, "B"],
azimuth: Float[Tensor, "B"],
camera_distances: Float[Tensor, "B"],
view_dependent_prompting: bool = True,
) -> Tuple[Float[Tensor, "BBBB N Nf"], Float[Tensor, "B 2"]]:
assert (
view_dependent_prompting
), "Perp-Neg only works with view-dependent prompting"
batch_size = elevation.shape[0]
direction_idx = torch.zeros_like(elevation, dtype=torch.long)
for d in self.directions:
direction_idx[
d.condition(elevation, azimuth, camera_distances)
] = self.direction2idx[d.name]
# 0 - side view
# 1 - front view
# 2 - back view
# 3 - overhead view
pos_text_embeddings = []
neg_text_embeddings = []
neg_guidance_weights = []
uncond_text_embeddings = []
side_emb = self.text_embeddings_vd[0]
front_emb = self.text_embeddings_vd[1]
back_emb = self.text_embeddings_vd[2]
overhead_emb = self.text_embeddings_vd[3]
for idx, ele, azi, dis in zip(
direction_idx, elevation, azimuth, camera_distances
):
azi = shift_azimuth_deg(azi) # to (-180, 180)
uncond_text_embeddings.append(
self.uncond_text_embeddings_vd[idx]
) # should be ""
if idx.item() == 3: # overhead view
pos_text_embeddings.append(overhead_emb) # side view
# dummy
neg_text_embeddings += [
self.uncond_text_embeddings_vd[idx],
self.uncond_text_embeddings_vd[idx],
]
neg_guidance_weights += [0.0, 0.0]
else: # interpolating views
if torch.abs(azi) < 90:
# front-side interpolation
# 0 - complete side, 1 - complete front
r_inter = 1 - torch.abs(azi) / 90
pos_text_embeddings.append(
r_inter * front_emb + (1 - r_inter) * side_emb
)
neg_text_embeddings += [front_emb, side_emb]
neg_guidance_weights += [
|
def hash_prompt(model: str, prompt: str) -> str:
identifier = f"{model}-{prompt}"
return hashlib.md5(identifier.encode()).hexdigest()
@dataclass
class DirectionConfig:
name: str
prompt: Callable[[str], str]
negative_prompt: Callable[[str], str]
condition: Callable[
[Float[Tensor, "B"], Float[Tensor, "B"], Float[Tensor, "B"]],
Float[Tensor, "B"],
]
@dataclass
class PromptProcessorOutput:
text_embeddings: Float[Tensor, "N Nf"]
uncond_text_embeddings: Float[Tensor, "N Nf"]
text_embeddings_vd: Float[Tensor, "Nv N Nf"]
uncond_text_embeddings_vd: Float[Tensor, "Nv N Nf"]
directions: List[DirectionConfig]
direction2idx: Dict[str, int]
use_perp_neg: bool
perp_neg_f_sb: Tuple[float, float, float]
perp_neg_f_fsb: Tuple[float, float, float]
perp_neg_f_fs: Tuple[float, float, float]
perp_neg_f_sf: Tuple[float, float, float]
def get_text_embeddings(
self,
elevation: Float[Tensor, "B"],
azimuth: Float[Tensor, "B"],
camera_distances: Float[Tensor, "B"],
view_dependent_prompting: bool = True,
) -> Float[Tensor, "BB N Nf"]:
batch_size = elevation.shape[0]
if view_dependent_prompting:
# Get direction
direction_idx = torch.zeros_like(elevation, dtype=torch.long)
for d in self.directions:
direction_idx[
d.condition(elevation, azimuth, camera_distances)
] = self.direction2idx[d.name]
# Get text embeddings
text_embeddings = self.text_embeddings_vd[direction_idx] # type: ignore
uncond_text_embeddings = self.uncond_text_embeddings_vd[direction_idx] # type: ignore
else:
text_embeddings = self.text_embeddings.expand(batch_size, -1, -1) # type: ignore
uncond_text_embeddings = self.uncond_text_embeddings.expand( # type: ignore
batch_size, -1, -1
)
# IMPORTANT: we return (cond, uncond), which is in different order than other implementations!
return torch.cat([text_embeddings, uncond_text_embeddings], dim=0)
def get_text_embeddings_perp_neg(
self,
elevation: Float[Tensor, "B"],
azimuth: Float[Tensor, "B"],
camera_distances: Float[Tensor, "B"],
view_dependent_prompting: bool = True,
) -> Tuple[Float[Tensor, "BBBB N Nf"], Float[Tensor, "B 2"]]:
assert (
view_dependent_prompting
), "Perp-Neg only works with view-dependent prompting"
batch_size = elevation.shape[0]
direction_idx = torch.zeros_like(elevation, dtype=torch.long)
for d in self.directions:
direction_idx[
d.condition(elevation, azimuth, camera_distances)
] = self.direction2idx[d.name]
# 0 - side view
# 1 - front view
# 2 - back view
# 3 - overhead view
pos_text_embeddings = []
neg_text_embeddings = []
neg_guidance_weights = []
uncond_text_embeddings = []
side_emb = self.text_embeddings_vd[0]
front_emb = self.text_embeddings_vd[1]
back_emb = self.text_embeddings_vd[2]
overhead_emb = self.text_embeddings_vd[3]
for idx, ele, azi, dis in zip(
direction_idx, elevation, azimuth, camera_distances
):
azi = shift_azimuth_deg(azi) # to (-180, 180)
uncond_text_embeddings.append(
self.uncond_text_embeddings_vd[idx]
) # should be ""
if idx.item() == 3: # overhead view
pos_text_embeddings.append(overhead_emb) # side view
# dummy
neg_text_embeddings += [
self.uncond_text_embeddings_vd[idx],
self.uncond_text_embeddings_vd[idx],
]
neg_guidance_weights += [0.0, 0.0]
else: # interpolating views
if torch.abs(azi) < 90:
# front-side interpolation
# 0 - complete side, 1 - complete front
r_inter = 1 - torch.abs(azi) / 90
pos_text_embeddings.append(
r_inter * front_emb + (1 - r_inter) * side_emb
)
neg_text_embeddings += [front_emb, side_emb]
neg_guidance_weights += [ | -shifted_expotional_decay(*self.perp_neg_f_fs, r_inter), | 5 | 2023-10-24 19:02:44+00:00 | 4k |
princeton-nlp/LLM-Shearing | llmshearing/utils/post_pruning_processing.py | [
{
"identifier": "ComposerMosaicLlama",
"path": "llmshearing/models/composer_llama.py",
"snippet": "class ComposerMosaicLlama(ComposerModel):\n \"\"\" Llama model with the Composer model interface. \"\"\"\n def __init__(self, cfg):\n super().__init__()\n self.model = LlamaModel(cfg)\n... | import glob
import os
import torch
import fire
from llmshearing.models.composer_llama import ComposerMosaicLlama
from llmshearing.utils.utils import load_weights | 1,703 |
def prune_and_save_model(path):
""" prune and save the model after pruning """
outpath = os.path.dirname(path) + f"/pruned-{os.path.basename(path)}"
config_file = os.path.join(os.path.dirname(path), "config.pt")
assert os.path.exists(config_file), f"Config file {config_file} does not exist"
cfg = torch.load(config_file).model
if cfg.l0_module.target_model is not None:
cfg.l0_module.eval_target_model = True # hack
|
def prune_and_save_model(path):
""" prune and save the model after pruning """
outpath = os.path.dirname(path) + f"/pruned-{os.path.basename(path)}"
config_file = os.path.join(os.path.dirname(path), "config.pt")
assert os.path.exists(config_file), f"Config file {config_file} does not exist"
cfg = torch.load(config_file).model
if cfg.l0_module.target_model is not None:
cfg.l0_module.eval_target_model = True # hack
| model = ComposerMosaicLlama(cfg) | 0 | 2023-10-16 12:26:08+00:00 | 4k |
hugoycj/Instant-angelo | models/nerf.py | [
{
"identifier": "BaseModel",
"path": "models/base.py",
"snippet": "class BaseModel(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.rank = get_rank()\n self.setup()\n if self.config.get('weights', None):\n self.... | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import models
from models.base import BaseModel
from models.utils import chunk_batch
from systems.utils import update_module_step
from nerfacc import ContractionType, OccupancyGrid, ray_marching, render_weight_from_density, accumulate_along_rays | 1,891 |
@models.register('nerf')
class NeRFModel(BaseModel):
def setup(self):
self.geometry = models.make(self.config.geometry.name, self.config.geometry)
self.texture = models.make(self.config.texture.name, self.config.texture)
self.register_buffer('scene_aabb', torch.as_tensor([-self.config.radius, -self.config.radius, -self.config.radius, self.config.radius, self.config.radius, self.config.radius], dtype=torch.float32))
if self.config.learned_background:
self.occupancy_grid_res = 256
self.near_plane, self.far_plane = 0.2, 1e4
self.cone_angle = 10**(math.log10(self.far_plane) / self.config.num_samples_per_ray) - 1. # approximate
self.render_step_size = 0.01 # render_step_size = max(distance_to_camera * self.cone_angle, self.render_step_size)
self.contraction_type = ContractionType.UN_BOUNDED_SPHERE
else:
self.occupancy_grid_res = 128
self.near_plane, self.far_plane = None, None
self.cone_angle = 0.0
self.render_step_size = 1.732 * 2 * self.config.radius / self.config.num_samples_per_ray
self.contraction_type = ContractionType.AABB
self.geometry.contraction_type = self.contraction_type
if self.config.grid_prune:
self.occupancy_grid = OccupancyGrid(
roi_aabb=self.scene_aabb,
resolution=self.occupancy_grid_res,
contraction_type=self.contraction_type
)
self.randomized = self.config.randomized
self.background_color = None
def update_step(self, epoch, global_step):
update_module_step(self.geometry, epoch, global_step)
update_module_step(self.texture, epoch, global_step)
def occ_eval_fn(x):
density, _ = self.geometry(x)
# approximate for 1 - torch.exp(-density[...,None] * self.render_step_size) based on taylor series
return density[...,None] * self.render_step_size
if self.training and self.config.grid_prune:
self.occupancy_grid.every_n_step(step=global_step, occ_eval_fn=occ_eval_fn)
def isosurface(self):
mesh = self.geometry.isosurface()
return mesh
def forward_(self, rays):
n_rays = rays.shape[0]
rays_o, rays_d = rays[:, 0:3], rays[:, 3:6] # both (N_rays, 3)
def sigma_fn(t_starts, t_ends, ray_indices):
ray_indices = ray_indices.long()
t_origins = rays_o[ray_indices]
t_dirs = rays_d[ray_indices]
positions = t_origins + t_dirs * (t_starts + t_ends) / 2.
density, _ = self.geometry(positions)
return density[...,None]
def rgb_sigma_fn(t_starts, t_ends, ray_indices):
ray_indices = ray_indices.long()
t_origins = rays_o[ray_indices]
t_dirs = rays_d[ray_indices]
positions = t_origins + t_dirs * (t_starts + t_ends) / 2.
density, feature = self.geometry(positions)
rgb = self.texture(feature, t_dirs)
return rgb, density[...,None]
with torch.no_grad():
ray_indices, t_starts, t_ends = ray_marching(
rays_o, rays_d,
scene_aabb=None if self.config.learned_background else self.scene_aabb,
grid=self.occupancy_grid if self.config.grid_prune else None,
sigma_fn=sigma_fn,
near_plane=self.near_plane, far_plane=self.far_plane,
render_step_size=self.render_step_size,
stratified=self.randomized,
cone_angle=self.cone_angle,
alpha_thre=0.0
)
ray_indices = ray_indices.long()
t_origins = rays_o[ray_indices]
t_dirs = rays_d[ray_indices]
midpoints = (t_starts + t_ends) / 2.
positions = t_origins + t_dirs * midpoints
intervals = t_ends - t_starts
density, feature = self.geometry(positions)
rgb = self.texture(feature, t_dirs)
weights = render_weight_from_density(t_starts, t_ends, density[...,None], ray_indices=ray_indices, n_rays=n_rays)
opacity = accumulate_along_rays(weights, ray_indices, values=None, n_rays=n_rays)
depth = accumulate_along_rays(weights, ray_indices, values=midpoints, n_rays=n_rays)
comp_rgb = accumulate_along_rays(weights, ray_indices, values=rgb, n_rays=n_rays)
comp_rgb = comp_rgb + self.background_color * (1.0 - opacity)
out = {
'comp_rgb': comp_rgb,
'opacity': opacity,
'depth': depth,
'rays_valid': opacity > 0,
'num_samples': torch.as_tensor([len(t_starts)], dtype=torch.int32, device=rays.device)
}
if self.training:
out.update({
'weights': weights.view(-1),
'points': midpoints.view(-1),
'intervals': intervals.view(-1),
'ray_indices': ray_indices.view(-1)
})
return out
def forward(self, rays):
if self.training:
out = self.forward_(rays)
else:
|
@models.register('nerf')
class NeRFModel(BaseModel):
def setup(self):
self.geometry = models.make(self.config.geometry.name, self.config.geometry)
self.texture = models.make(self.config.texture.name, self.config.texture)
self.register_buffer('scene_aabb', torch.as_tensor([-self.config.radius, -self.config.radius, -self.config.radius, self.config.radius, self.config.radius, self.config.radius], dtype=torch.float32))
if self.config.learned_background:
self.occupancy_grid_res = 256
self.near_plane, self.far_plane = 0.2, 1e4
self.cone_angle = 10**(math.log10(self.far_plane) / self.config.num_samples_per_ray) - 1. # approximate
self.render_step_size = 0.01 # render_step_size = max(distance_to_camera * self.cone_angle, self.render_step_size)
self.contraction_type = ContractionType.UN_BOUNDED_SPHERE
else:
self.occupancy_grid_res = 128
self.near_plane, self.far_plane = None, None
self.cone_angle = 0.0
self.render_step_size = 1.732 * 2 * self.config.radius / self.config.num_samples_per_ray
self.contraction_type = ContractionType.AABB
self.geometry.contraction_type = self.contraction_type
if self.config.grid_prune:
self.occupancy_grid = OccupancyGrid(
roi_aabb=self.scene_aabb,
resolution=self.occupancy_grid_res,
contraction_type=self.contraction_type
)
self.randomized = self.config.randomized
self.background_color = None
def update_step(self, epoch, global_step):
update_module_step(self.geometry, epoch, global_step)
update_module_step(self.texture, epoch, global_step)
def occ_eval_fn(x):
density, _ = self.geometry(x)
# approximate for 1 - torch.exp(-density[...,None] * self.render_step_size) based on taylor series
return density[...,None] * self.render_step_size
if self.training and self.config.grid_prune:
self.occupancy_grid.every_n_step(step=global_step, occ_eval_fn=occ_eval_fn)
def isosurface(self):
mesh = self.geometry.isosurface()
return mesh
def forward_(self, rays):
n_rays = rays.shape[0]
rays_o, rays_d = rays[:, 0:3], rays[:, 3:6] # both (N_rays, 3)
def sigma_fn(t_starts, t_ends, ray_indices):
ray_indices = ray_indices.long()
t_origins = rays_o[ray_indices]
t_dirs = rays_d[ray_indices]
positions = t_origins + t_dirs * (t_starts + t_ends) / 2.
density, _ = self.geometry(positions)
return density[...,None]
def rgb_sigma_fn(t_starts, t_ends, ray_indices):
ray_indices = ray_indices.long()
t_origins = rays_o[ray_indices]
t_dirs = rays_d[ray_indices]
positions = t_origins + t_dirs * (t_starts + t_ends) / 2.
density, feature = self.geometry(positions)
rgb = self.texture(feature, t_dirs)
return rgb, density[...,None]
with torch.no_grad():
ray_indices, t_starts, t_ends = ray_marching(
rays_o, rays_d,
scene_aabb=None if self.config.learned_background else self.scene_aabb,
grid=self.occupancy_grid if self.config.grid_prune else None,
sigma_fn=sigma_fn,
near_plane=self.near_plane, far_plane=self.far_plane,
render_step_size=self.render_step_size,
stratified=self.randomized,
cone_angle=self.cone_angle,
alpha_thre=0.0
)
ray_indices = ray_indices.long()
t_origins = rays_o[ray_indices]
t_dirs = rays_d[ray_indices]
midpoints = (t_starts + t_ends) / 2.
positions = t_origins + t_dirs * midpoints
intervals = t_ends - t_starts
density, feature = self.geometry(positions)
rgb = self.texture(feature, t_dirs)
weights = render_weight_from_density(t_starts, t_ends, density[...,None], ray_indices=ray_indices, n_rays=n_rays)
opacity = accumulate_along_rays(weights, ray_indices, values=None, n_rays=n_rays)
depth = accumulate_along_rays(weights, ray_indices, values=midpoints, n_rays=n_rays)
comp_rgb = accumulate_along_rays(weights, ray_indices, values=rgb, n_rays=n_rays)
comp_rgb = comp_rgb + self.background_color * (1.0 - opacity)
out = {
'comp_rgb': comp_rgb,
'opacity': opacity,
'depth': depth,
'rays_valid': opacity > 0,
'num_samples': torch.as_tensor([len(t_starts)], dtype=torch.int32, device=rays.device)
}
if self.training:
out.update({
'weights': weights.view(-1),
'points': midpoints.view(-1),
'intervals': intervals.view(-1),
'ray_indices': ray_indices.view(-1)
})
return out
def forward(self, rays):
if self.training:
out = self.forward_(rays)
else: | out = chunk_batch(self.forward_, self.config.ray_chunk, True, rays) | 1 | 2023-10-22 02:53:17+00:00 | 4k |
HKUDS/GraphGPT | graphgpt/serve/model_worker_graph.py | [
{
"identifier": "WORKER_HEART_BEAT_INTERVAL",
"path": "graphgpt/constants.py",
"snippet": "WORKER_HEART_BEAT_INTERVAL = int(os.getenv(\"FASTCHAT_WORKER_HEART_BEAT_INTERVAL\", 30))"
},
{
"identifier": "build_logger",
"path": "graphgpt/utils.py",
"snippet": "def build_logger(logger_name, l... | import argparse
import asyncio
import json
import time
import threading
import uuid
import requests
import torch
import uvicorn
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.responses import StreamingResponse
from functools import partial
from graphgpt.constants import WORKER_HEART_BEAT_INTERVAL
from graphgpt.utils import (build_logger, server_error_msg,
pretty_print_semaphore)
from graphgpt.model.builder import load_pretrained_model
from graphgpt.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria
from graphgpt.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from transformers import TextIteratorStreamer
from threading import Thread | 3,374 |
GB = 1 << 30
worker_id = str(uuid.uuid4())[:6]
logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
global_counter = 0
model_semaphore = None
def heart_beat_worker(controller):
while True:
time.sleep(WORKER_HEART_BEAT_INTERVAL)
controller.send_heart_beat()
class ModelWorker:
def __init__(self, controller_addr, worker_addr,
worker_id, no_register,
model_path, model_base, model_name,
load_8bit, load_4bit, device):
self.controller_addr = controller_addr
self.worker_addr = worker_addr
self.worker_id = worker_id
if model_path.endswith("/"):
model_path = model_path[:-1]
if model_name is None:
model_paths = model_path.split("/")
if model_paths[-1].startswith('checkpoint-'):
self.model_name = model_paths[-2] + "_" + model_paths[-1]
else:
self.model_name = model_paths[-1]
else:
self.model_name = model_name
self.device = device
logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device)
self.is_multimodal = 'llava' in self.model_name.lower()
if not no_register:
self.register_to_controller()
self.heart_beat_thread = threading.Thread(
target=heart_beat_worker, args=(self,))
self.heart_beat_thread.start()
def register_to_controller(self):
logger.info("Register to controller")
url = self.controller_addr + "/register_worker"
data = {
"worker_name": self.worker_addr,
"check_heart_beat": True,
"worker_status": self.get_status()
}
r = requests.post(url, json=data)
assert r.status_code == 200
def send_heart_beat(self):
logger.info(f"Send heart beat. Models: {[self.model_name]}. "
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
f"global_counter: {global_counter}")
url = self.controller_addr + "/receive_heart_beat"
while True:
try:
ret = requests.post(url, json={
"worker_name": self.worker_addr,
"queue_length": self.get_queue_length()}, timeout=5)
exist = ret.json()["exist"]
break
except requests.exceptions.RequestException as e:
logger.error(f"heart beat error: {e}")
time.sleep(5)
if not exist:
self.register_to_controller()
def get_queue_length(self):
if model_semaphore is None:
return 0
else:
return args.limit_model_concurrency - model_semaphore._value + (len(
model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
def get_status(self):
return {
"model_names": [self.model_name],
"speed": 1,
"queue_length": self.get_queue_length(),
}
@torch.inference_mode()
def generate_stream(self, params):
tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
prompt = params["prompt"]
ori_prompt = prompt
images = params.get("images", None)
num_image_tokens = 0
if images is not None and len(images) > 0 and self.is_multimodal:
if len(images) > 0:
if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
raise ValueError("Number of images does not match number of <image> tokens in prompt")
images = [load_image_from_base64(image) for image in images]
images = process_images(images, image_processor, model.config)
if type(images) is list:
images = [image.to(self.model.device, dtype=torch.float16) for image in images]
else:
images = images.to(self.model.device, dtype=torch.float16)
replace_token = DEFAULT_IMAGE_TOKEN
if getattr(self.model.config, 'mm_use_im_start_end', False):
| """
A model worker executes the model.
"""
GB = 1 << 30
worker_id = str(uuid.uuid4())[:6]
logger = build_logger("model_worker", f"model_worker_{worker_id}.log")
global_counter = 0
model_semaphore = None
def heart_beat_worker(controller):
while True:
time.sleep(WORKER_HEART_BEAT_INTERVAL)
controller.send_heart_beat()
class ModelWorker:
def __init__(self, controller_addr, worker_addr,
worker_id, no_register,
model_path, model_base, model_name,
load_8bit, load_4bit, device):
self.controller_addr = controller_addr
self.worker_addr = worker_addr
self.worker_id = worker_id
if model_path.endswith("/"):
model_path = model_path[:-1]
if model_name is None:
model_paths = model_path.split("/")
if model_paths[-1].startswith('checkpoint-'):
self.model_name = model_paths[-2] + "_" + model_paths[-1]
else:
self.model_name = model_paths[-1]
else:
self.model_name = model_name
self.device = device
logger.info(f"Loading the model {self.model_name} on worker {worker_id} ...")
self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
model_path, model_base, self.model_name, load_8bit, load_4bit, device=self.device)
self.is_multimodal = 'llava' in self.model_name.lower()
if not no_register:
self.register_to_controller()
self.heart_beat_thread = threading.Thread(
target=heart_beat_worker, args=(self,))
self.heart_beat_thread.start()
def register_to_controller(self):
logger.info("Register to controller")
url = self.controller_addr + "/register_worker"
data = {
"worker_name": self.worker_addr,
"check_heart_beat": True,
"worker_status": self.get_status()
}
r = requests.post(url, json=data)
assert r.status_code == 200
def send_heart_beat(self):
logger.info(f"Send heart beat. Models: {[self.model_name]}. "
f"Semaphore: {pretty_print_semaphore(model_semaphore)}. "
f"global_counter: {global_counter}")
url = self.controller_addr + "/receive_heart_beat"
while True:
try:
ret = requests.post(url, json={
"worker_name": self.worker_addr,
"queue_length": self.get_queue_length()}, timeout=5)
exist = ret.json()["exist"]
break
except requests.exceptions.RequestException as e:
logger.error(f"heart beat error: {e}")
time.sleep(5)
if not exist:
self.register_to_controller()
def get_queue_length(self):
if model_semaphore is None:
return 0
else:
return args.limit_model_concurrency - model_semaphore._value + (len(
model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
def get_status(self):
return {
"model_names": [self.model_name],
"speed": 1,
"queue_length": self.get_queue_length(),
}
@torch.inference_mode()
def generate_stream(self, params):
tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
prompt = params["prompt"]
ori_prompt = prompt
images = params.get("images", None)
num_image_tokens = 0
if images is not None and len(images) > 0 and self.is_multimodal:
if len(images) > 0:
if len(images) != prompt.count(DEFAULT_IMAGE_TOKEN):
raise ValueError("Number of images does not match number of <image> tokens in prompt")
images = [load_image_from_base64(image) for image in images]
images = process_images(images, image_processor, model.config)
if type(images) is list:
images = [image.to(self.model.device, dtype=torch.float16) for image in images]
else:
images = images.to(self.model.device, dtype=torch.float16)
replace_token = DEFAULT_IMAGE_TOKEN
if getattr(self.model.config, 'mm_use_im_start_end', False): | replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN | 3 | 2023-10-15 05:13:24+00:00 | 4k |
hkchengrex/Cutie | cutie/model/cutie.py | [
{
"identifier": "AuxComputer",
"path": "cutie/model/aux_modules.py",
"snippet": "class AuxComputer(nn.Module):\n def __init__(self, cfg: DictConfig):\n super().__init__()\n\n use_sensory_aux = cfg.model.aux_loss.sensory.enabled\n self.use_query_aux = cfg.model.aux_loss.query.enab... | from typing import List, Dict
from omegaconf import DictConfig
from cutie.model.modules import *
from cutie.model.big_modules import *
from cutie.model.aux_modules import AuxComputer
from cutie.model.utils.memory_utils import *
from cutie.model.transformer.object_transformer import QueryTransformer
from cutie.model.transformer.object_summarizer import ObjectSummarizer
from cutie.utils.tensor_utils import aggregate
import logging
import torch
import torch.nn as nn | 3,036 |
log = logging.getLogger()
class CUTIE(nn.Module):
def __init__(self, cfg: DictConfig, *, single_object=False):
super().__init__()
model_cfg = cfg.model
self.ms_dims = model_cfg.pixel_encoder.ms_dims
self.key_dim = model_cfg.key_dim
self.value_dim = model_cfg.value_dim
self.sensory_dim = model_cfg.sensory_dim
self.pixel_dim = model_cfg.pixel_dim
self.embed_dim = model_cfg.embed_dim
self.single_object = single_object
log.info(f'Single object: {self.single_object}')
self.pixel_encoder = PixelEncoder(model_cfg)
self.pix_feat_proj = nn.Conv2d(self.ms_dims[0], self.pixel_dim, kernel_size=1)
self.key_proj = KeyProjection(model_cfg)
self.mask_encoder = MaskEncoder(model_cfg, single_object=single_object)
self.mask_decoder = MaskDecoder(model_cfg)
self.pixel_fuser = PixelFeatureFuser(model_cfg, single_object=single_object)
self.object_transformer = QueryTransformer(model_cfg)
self.object_summarizer = ObjectSummarizer(model_cfg)
|
log = logging.getLogger()
class CUTIE(nn.Module):
def __init__(self, cfg: DictConfig, *, single_object=False):
super().__init__()
model_cfg = cfg.model
self.ms_dims = model_cfg.pixel_encoder.ms_dims
self.key_dim = model_cfg.key_dim
self.value_dim = model_cfg.value_dim
self.sensory_dim = model_cfg.sensory_dim
self.pixel_dim = model_cfg.pixel_dim
self.embed_dim = model_cfg.embed_dim
self.single_object = single_object
log.info(f'Single object: {self.single_object}')
self.pixel_encoder = PixelEncoder(model_cfg)
self.pix_feat_proj = nn.Conv2d(self.ms_dims[0], self.pixel_dim, kernel_size=1)
self.key_proj = KeyProjection(model_cfg)
self.mask_encoder = MaskEncoder(model_cfg, single_object=single_object)
self.mask_decoder = MaskDecoder(model_cfg)
self.pixel_fuser = PixelFeatureFuser(model_cfg, single_object=single_object)
self.object_transformer = QueryTransformer(model_cfg)
self.object_summarizer = ObjectSummarizer(model_cfg) | self.aux_computer = AuxComputer(cfg) | 0 | 2023-10-19 17:49:24+00:00 | 4k |
DeepGraphLearning/ULTRA | ultra/util.py | [
{
"identifier": "models",
"path": "ultra/models.py",
"snippet": "class Ultra(nn.Module):\nclass RelNBFNet(BaseNBFNet):\nclass EntityNBFNet(BaseNBFNet):\n def __init__(self, rel_model_cfg, entity_model_cfg):\n def forward(self, data, batch):\n def __init__(self, input_dim, hidden_dims, num_relat... | import os
import sys
import ast
import copy
import time
import logging
import argparse
import yaml
import jinja2
import easydict
import torch
from jinja2 import meta
from torch import distributed as dist
from torch_geometric.data import Data
from torch_geometric.datasets import RelLinkPredDataset, WordNet18RR
from ultra import models, datasets | 2,154 | env = jinja2.Environment()
tree = env.parse(raw)
vars = meta.find_undeclared_variables(tree)
return vars
def load_config(cfg_file, context=None):
with open(cfg_file, "r") as fin:
raw = fin.read()
template = jinja2.Template(raw)
instance = template.render(context)
cfg = yaml.safe_load(instance)
cfg = easydict.EasyDict(cfg)
return cfg
def literal_eval(string):
try:
return ast.literal_eval(string)
except (ValueError, SyntaxError):
return string
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", help="yaml configuration file", required=True)
parser.add_argument("-s", "--seed", help="random seed for PyTorch", type=int, default=1024)
args, unparsed = parser.parse_known_args()
# get dynamic arguments defined in the config file
vars = detect_variables(args.config)
parser = argparse.ArgumentParser()
for var in vars:
parser.add_argument("--%s" % var, required=True)
vars = parser.parse_known_args(unparsed)[0]
vars = {k: literal_eval(v) for k, v in vars._get_kwargs()}
return args, vars
def get_root_logger(file=True):
format = "%(asctime)-10s %(message)s"
datefmt = "%H:%M:%S"
logging.basicConfig(format=format, datefmt=datefmt)
logger = logging.getLogger("")
logger.setLevel(logging.INFO)
if file:
handler = logging.FileHandler("log.txt")
format = logging.Formatter(format, datefmt)
handler.setFormatter(format)
logger.addHandler(handler)
return logger
def get_rank():
if dist.is_initialized():
return dist.get_rank()
if "RANK" in os.environ:
return int(os.environ["RANK"])
return 0
def get_world_size():
if dist.is_initialized():
return dist.get_world_size()
if "WORLD_SIZE" in os.environ:
return int(os.environ["WORLD_SIZE"])
return 1
def synchronize():
if get_world_size() > 1:
dist.barrier()
def get_device(cfg):
if cfg.train.gpus:
device = torch.device(cfg.train.gpus[get_rank()])
else:
device = torch.device("cpu")
return device
def create_working_directory(cfg):
file_name = "working_dir.tmp"
world_size = get_world_size()
if cfg.train.gpus is not None and len(cfg.train.gpus) != world_size:
error_msg = "World size is %d but found %d GPUs in the argument"
if world_size == 1:
error_msg += ". Did you launch with `python -m torch.distributed.launch`?"
raise ValueError(error_msg % (world_size, len(cfg.train.gpus)))
if world_size > 1 and not dist.is_initialized():
dist.init_process_group("nccl", init_method="env://")
working_dir = os.path.join(os.path.expanduser(cfg.output_dir),
cfg.model["class"], cfg.dataset["class"], time.strftime("%Y-%m-%d-%H-%M-%S"))
# synchronize working directory
if get_rank() == 0:
with open(file_name, "w") as fout:
fout.write(working_dir)
os.makedirs(working_dir)
synchronize()
if get_rank() != 0:
with open(file_name, "r") as fin:
working_dir = fin.read()
synchronize()
if get_rank() == 0:
os.remove(file_name)
os.chdir(working_dir)
return working_dir
def build_dataset(cfg):
data_config = copy.deepcopy(cfg.dataset)
cls = data_config.pop("class")
|
logger = logging.getLogger(__file__)
def detect_variables(cfg_file):
with open(cfg_file, "r") as fin:
raw = fin.read()
env = jinja2.Environment()
tree = env.parse(raw)
vars = meta.find_undeclared_variables(tree)
return vars
def load_config(cfg_file, context=None):
with open(cfg_file, "r") as fin:
raw = fin.read()
template = jinja2.Template(raw)
instance = template.render(context)
cfg = yaml.safe_load(instance)
cfg = easydict.EasyDict(cfg)
return cfg
def literal_eval(string):
try:
return ast.literal_eval(string)
except (ValueError, SyntaxError):
return string
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", help="yaml configuration file", required=True)
parser.add_argument("-s", "--seed", help="random seed for PyTorch", type=int, default=1024)
args, unparsed = parser.parse_known_args()
# get dynamic arguments defined in the config file
vars = detect_variables(args.config)
parser = argparse.ArgumentParser()
for var in vars:
parser.add_argument("--%s" % var, required=True)
vars = parser.parse_known_args(unparsed)[0]
vars = {k: literal_eval(v) for k, v in vars._get_kwargs()}
return args, vars
def get_root_logger(file=True):
format = "%(asctime)-10s %(message)s"
datefmt = "%H:%M:%S"
logging.basicConfig(format=format, datefmt=datefmt)
logger = logging.getLogger("")
logger.setLevel(logging.INFO)
if file:
handler = logging.FileHandler("log.txt")
format = logging.Formatter(format, datefmt)
handler.setFormatter(format)
logger.addHandler(handler)
return logger
def get_rank():
if dist.is_initialized():
return dist.get_rank()
if "RANK" in os.environ:
return int(os.environ["RANK"])
return 0
def get_world_size():
if dist.is_initialized():
return dist.get_world_size()
if "WORLD_SIZE" in os.environ:
return int(os.environ["WORLD_SIZE"])
return 1
def synchronize():
if get_world_size() > 1:
dist.barrier()
def get_device(cfg):
if cfg.train.gpus:
device = torch.device(cfg.train.gpus[get_rank()])
else:
device = torch.device("cpu")
return device
def create_working_directory(cfg):
file_name = "working_dir.tmp"
world_size = get_world_size()
if cfg.train.gpus is not None and len(cfg.train.gpus) != world_size:
error_msg = "World size is %d but found %d GPUs in the argument"
if world_size == 1:
error_msg += ". Did you launch with `python -m torch.distributed.launch`?"
raise ValueError(error_msg % (world_size, len(cfg.train.gpus)))
if world_size > 1 and not dist.is_initialized():
dist.init_process_group("nccl", init_method="env://")
working_dir = os.path.join(os.path.expanduser(cfg.output_dir),
cfg.model["class"], cfg.dataset["class"], time.strftime("%Y-%m-%d-%H-%M-%S"))
# synchronize working directory
if get_rank() == 0:
with open(file_name, "w") as fout:
fout.write(working_dir)
os.makedirs(working_dir)
synchronize()
if get_rank() != 0:
with open(file_name, "r") as fin:
working_dir = fin.read()
synchronize()
if get_rank() == 0:
os.remove(file_name)
os.chdir(working_dir)
return working_dir
def build_dataset(cfg):
data_config = copy.deepcopy(cfg.dataset)
cls = data_config.pop("class")
| ds_cls = getattr(datasets, cls) | 1 | 2023-10-23 17:06:10+00:00 | 4k |
ZhengyiLuo/PerpetualHumanoidControl | phc/learning/im_amp.py | [
{
"identifier": "RunningMeanStd",
"path": "phc/utils/running_mean_std.py",
"snippet": "class RunningMeanStd(nn.Module):\n\n def __init__(self,\n insize,\n epsilon=1e-05,\n per_channel=False,\n norm_only=False):\n super(RunningMean... | import glob
import os
import sys
import pdb
import os.path as osp
import time
import numpy as np
import torch
import learning.replay_buffer as replay_buffer
import phc.learning.amp_agent as amp_agent
import joblib
import gc
from phc.utils.running_mean_std import RunningMeanStd
from rl_games.algos_torch import torch_ext
from rl_games.common import a2c_common
from rl_games.common import schedulers
from rl_games.common import vecenv
from isaacgym.torch_utils import *
from datetime import datetime
from torch import optim
from torch import nn
from phc.env.tasks.humanoid_amp_task import HumanoidAMPTask
from phc.utils.flags import flags
from rl_games.common.tr_helpers import unsqueeze_obs
from rl_games.algos_torch.players import rescale_actions
from tensorboardX import SummaryWriter
from uhc.smpllib.smpl_eval import compute_metrics_lite
from tqdm import tqdm | 3,162 |
sys.path.append(os.getcwd())
class IMAmpAgent(amp_agent.AMPAgent):
def __init__(self, base_name, config):
super().__init__(base_name, config)
def get_action(self, obs_dict, is_determenistic=False):
obs = obs_dict["obs"]
if self.has_batch_dimension == False:
obs = unsqueeze_obs(obs)
obs = self._preproc_obs(obs)
input_dict = {
"is_train": False,
"prev_actions": None,
"obs": obs,
"rnn_states": self.states,
}
with torch.no_grad():
res_dict = self.model(input_dict)
mu = res_dict["mus"]
action = res_dict["actions"]
self.states = res_dict["rnn_states"]
if is_determenistic:
current_action = mu
else:
current_action = action
if self.has_batch_dimension == False:
current_action = torch.squeeze(current_action.detach())
if self.clip_actions:
return rescale_actions(
self.actions_low,
self.actions_high,
torch.clamp(current_action, -1.0, 1.0),
)
else:
return current_action
def env_eval_step(self, env, actions):
if not self.is_tensor_obses:
actions = actions.cpu().numpy()
obs, rewards, dones, infos = env.step(actions)
if hasattr(obs, "dtype") and obs.dtype == np.float64:
obs = np.float32(obs)
if self.value_size > 1:
rewards = rewards[0]
if self.is_tensor_obses:
return obs, rewards.to(self.device), dones.to(self.device), infos
else:
if np.isscalar(dones):
rewards = np.expand_dims(np.asarray(rewards), 0)
dones = np.expand_dims(np.asarray(dones), 0)
return (
self.obs_to_torch(obs),
torch.from_numpy(rewards),
torch.from_numpy(dones),
infos,
)
def restore(self, fn):
super().restore(fn)
all_fails = glob.glob(osp.join(self.network_path, f"failed_*"))
if len(all_fails) > 0:
print("------------------------------------------------------ Restoring Termination History ------------------------------------------------------")
failed_pth = sorted(all_fails, key=lambda x: int(x.split("_")[-1].split(".")[0]))[-1]
print(f"loading: {failed_pth}")
termination_history = joblib.load(failed_pth)['termination_history']
humanoid_env = self.vec_env.env.task
res = humanoid_env._motion_lib.update_sampling_prob(termination_history)
if res:
print("Successfully restored termination history")
else:
print("Termination history length does not match")
return
def init_rnn(self):
if self.is_rnn:
rnn_states = self.model.get_default_rnn_state()
self.states = [torch.zeros((s.size()[0], self.vec_env.env.task.num_envs, s.size(
)[2]), dtype=torch.float32).to(self.device) for s in rnn_states]
def update_training_data(self, failed_keys):
humanoid_env = self.vec_env.env.task
joblib.dump({"failed_keys": failed_keys, "termination_history": humanoid_env._motion_lib._termination_history}, osp.join(self.network_path, f"failed_{self.epoch_num:010d}.pkl"))
def eval(self):
print("############################ Evaluation ############################")
|
sys.path.append(os.getcwd())
class IMAmpAgent(amp_agent.AMPAgent):
def __init__(self, base_name, config):
super().__init__(base_name, config)
def get_action(self, obs_dict, is_determenistic=False):
obs = obs_dict["obs"]
if self.has_batch_dimension == False:
obs = unsqueeze_obs(obs)
obs = self._preproc_obs(obs)
input_dict = {
"is_train": False,
"prev_actions": None,
"obs": obs,
"rnn_states": self.states,
}
with torch.no_grad():
res_dict = self.model(input_dict)
mu = res_dict["mus"]
action = res_dict["actions"]
self.states = res_dict["rnn_states"]
if is_determenistic:
current_action = mu
else:
current_action = action
if self.has_batch_dimension == False:
current_action = torch.squeeze(current_action.detach())
if self.clip_actions:
return rescale_actions(
self.actions_low,
self.actions_high,
torch.clamp(current_action, -1.0, 1.0),
)
else:
return current_action
def env_eval_step(self, env, actions):
if not self.is_tensor_obses:
actions = actions.cpu().numpy()
obs, rewards, dones, infos = env.step(actions)
if hasattr(obs, "dtype") and obs.dtype == np.float64:
obs = np.float32(obs)
if self.value_size > 1:
rewards = rewards[0]
if self.is_tensor_obses:
return obs, rewards.to(self.device), dones.to(self.device), infos
else:
if np.isscalar(dones):
rewards = np.expand_dims(np.asarray(rewards), 0)
dones = np.expand_dims(np.asarray(dones), 0)
return (
self.obs_to_torch(obs),
torch.from_numpy(rewards),
torch.from_numpy(dones),
infos,
)
def restore(self, fn):
super().restore(fn)
all_fails = glob.glob(osp.join(self.network_path, f"failed_*"))
if len(all_fails) > 0:
print("------------------------------------------------------ Restoring Termination History ------------------------------------------------------")
failed_pth = sorted(all_fails, key=lambda x: int(x.split("_")[-1].split(".")[0]))[-1]
print(f"loading: {failed_pth}")
termination_history = joblib.load(failed_pth)['termination_history']
humanoid_env = self.vec_env.env.task
res = humanoid_env._motion_lib.update_sampling_prob(termination_history)
if res:
print("Successfully restored termination history")
else:
print("Termination history length does not match")
return
def init_rnn(self):
if self.is_rnn:
rnn_states = self.model.get_default_rnn_state()
self.states = [torch.zeros((s.size()[0], self.vec_env.env.task.num_envs, s.size(
)[2]), dtype=torch.float32).to(self.device) for s in rnn_states]
def update_training_data(self, failed_keys):
humanoid_env = self.vec_env.env.task
joblib.dump({"failed_keys": failed_keys, "termination_history": humanoid_env._motion_lib._termination_history}, osp.join(self.network_path, f"failed_{self.epoch_num:010d}.pkl"))
def eval(self):
print("############################ Evaluation ############################") | if not flags.has_eval: | 2 | 2023-10-15 19:05:47+00:00 | 4k |
laike9m/Python-Type-Challenges | tests/test_challenge.py | [
{
"identifier": "ChallengeKey",
"path": "views/challenge.py",
"snippet": "class ChallengeKey:\n level: Level\n name: ChallengeName\n\n @classmethod\n def from_str(cls, key: str):\n \"\"\"Create a key object from a string like \"basic-foo\".\"\"\"\n level, name = key.split(\"-\"... | from pathlib import Path
from views.challenge import ChallengeKey, ChallengeManager
import pytest | 1,788 |
class TestLoadChallenges:
def test_load_empty_dir(self, tmpdir):
assert ChallengeManager(Path(tmpdir)).challenge_count == 0
def test_defaults(self):
assert ChallengeManager().challenge_count > 0
def test_load_tests_assets(self, assets_dir):
mgr = ChallengeManager(assets_dir / "challenges")
assert mgr.challenge_count > 0
class TestChallengeWithHints:
@pytest.fixture()
def challenge_mgr(self, assets_dir):
return ChallengeManager(assets_dir / "challenges")
def test_misc(self, challenge_mgr):
|
class TestLoadChallenges:
def test_load_empty_dir(self, tmpdir):
assert ChallengeManager(Path(tmpdir)).challenge_count == 0
def test_defaults(self):
assert ChallengeManager().challenge_count > 0
def test_load_tests_assets(self, assets_dir):
mgr = ChallengeManager(assets_dir / "challenges")
assert mgr.challenge_count > 0
class TestChallengeWithHints:
@pytest.fixture()
def challenge_mgr(self, assets_dir):
return ChallengeManager(assets_dir / "challenges")
def test_misc(self, challenge_mgr): | c_foo = challenge_mgr.get_challenge(ChallengeKey.from_str("basic-foo")) | 0 | 2023-10-23 05:11:41+00:00 | 4k |
uni-medical/SAM-Med3D | train.py | [
{
"identifier": "sam_model_registry3D",
"path": "segment_anything/build_sam3D.py",
"snippet": "def build_sam3D_vit_h(checkpoint=None):\ndef build_sam3D_vit_l(checkpoint=None):\ndef build_sam3D_vit_b(checkpoint=None):\ndef build_sam3D_vit_b_ori(checkpoint=None):\ndef _build_sam3D(\n encoder_embed_dim,... | import numpy as np
import random
import datetime
import logging
import matplotlib.pyplot as plt
import os
import torch
import torch.distributed as dist
import torch.nn.functional as F
import torchio as tio
import argparse
import torch.multiprocessing as mp
from tqdm import tqdm
from torch.backends import cudnn
from torch.utils.data.distributed import DistributedSampler
from segment_anything.build_sam3D import sam_model_registry3D
from torch.cuda import amp
from torch.nn.parallel import DistributedDataParallel as DDP
from monai.losses import DiceCELoss
from contextlib import nullcontext
from utils.click_method import get_next_click3D_torch_2
from utils.data_loader import Dataset_Union_ALL, Union_Dataloader
from utils.data_paths import img_datas | 1,960 | # set up environment
join = os.path.join
# %% set up parser
parser = argparse.ArgumentParser()
parser.add_argument('--task_name', type=str, default='union_train')
parser.add_argument('--click_type', type=str, default='random')
parser.add_argument('--multi_click', action='store_true', default=False)
parser.add_argument('--model_type', type=str, default='vit_b_ori')
parser.add_argument('--checkpoint', type=str, default='./work_dir/SAM/sam_vit_b.pth')
parser.add_argument('--device', type=str, default='cuda')
parser.add_argument('--work_dir', type=str, default='./work_dir')
# train
parser.add_argument('--num_workers', type=int, default=24)
parser.add_argument('--gpu_ids', type=int, nargs='+', default=[0,1])
parser.add_argument('--multi_gpu', action='store_true', default=False)
parser.add_argument('--resume', action='store_true', default=False)
# lr_scheduler
parser.add_argument('--lr_scheduler', type=str, default='multisteplr')
parser.add_argument('--step_size', type=list, default=[120, 180])
parser.add_argument('--gamma', type=float, default=0.1)
parser.add_argument('--num_epochs', type=int, default=200)
parser.add_argument('--img_size', type=int, default=128)
parser.add_argument('--batch_size', type=int, default=10)
parser.add_argument('--accumulation_steps', type=int, default=20)
parser.add_argument('--lr', type=float, default=8e-4)
parser.add_argument('--weight_decay', type=float, default=0.1)
parser.add_argument('--port', type=int, default=12361)
args = parser.parse_args()
device = args.device
os.environ["CUDA_VISIBLE_DEVICES"] = ','.join([str(i) for i in args.gpu_ids])
logger = logging.getLogger(__name__)
LOG_OUT_DIR = join(args.work_dir, args.task_name)
click_methods = {
'random': get_next_click3D_torch_2,
}
MODEL_SAVE_PATH = join(args.work_dir, args.task_name)
os.makedirs(MODEL_SAVE_PATH, exist_ok=True)
def build_model(args):
| # set up environment
join = os.path.join
# %% set up parser
parser = argparse.ArgumentParser()
parser.add_argument('--task_name', type=str, default='union_train')
parser.add_argument('--click_type', type=str, default='random')
parser.add_argument('--multi_click', action='store_true', default=False)
parser.add_argument('--model_type', type=str, default='vit_b_ori')
parser.add_argument('--checkpoint', type=str, default='./work_dir/SAM/sam_vit_b.pth')
parser.add_argument('--device', type=str, default='cuda')
parser.add_argument('--work_dir', type=str, default='./work_dir')
# train
parser.add_argument('--num_workers', type=int, default=24)
parser.add_argument('--gpu_ids', type=int, nargs='+', default=[0,1])
parser.add_argument('--multi_gpu', action='store_true', default=False)
parser.add_argument('--resume', action='store_true', default=False)
# lr_scheduler
parser.add_argument('--lr_scheduler', type=str, default='multisteplr')
parser.add_argument('--step_size', type=list, default=[120, 180])
parser.add_argument('--gamma', type=float, default=0.1)
parser.add_argument('--num_epochs', type=int, default=200)
parser.add_argument('--img_size', type=int, default=128)
parser.add_argument('--batch_size', type=int, default=10)
parser.add_argument('--accumulation_steps', type=int, default=20)
parser.add_argument('--lr', type=float, default=8e-4)
parser.add_argument('--weight_decay', type=float, default=0.1)
parser.add_argument('--port', type=int, default=12361)
args = parser.parse_args()
device = args.device
os.environ["CUDA_VISIBLE_DEVICES"] = ','.join([str(i) for i in args.gpu_ids])
logger = logging.getLogger(__name__)
LOG_OUT_DIR = join(args.work_dir, args.task_name)
click_methods = {
'random': get_next_click3D_torch_2,
}
MODEL_SAVE_PATH = join(args.work_dir, args.task_name)
os.makedirs(MODEL_SAVE_PATH, exist_ok=True)
def build_model(args): | sam_model = sam_model_registry3D[args.model_type](checkpoint=None).to(device) | 0 | 2023-10-23 15:41:07+00:00 | 4k |
VikParuchuri/libgen_to_txt | download_and_clean.py | [
{
"identifier": "get_file_path",
"path": "libgen_to_txt/files.py",
"snippet": "def get_file_path(num, client, parent_id):\n files = client.File.list(parent_id=parent_id)\n try:\n sel_file = [f for f in files if get_leading_digits(f.name) == num][0]\n except IndexError:\n return\n ... | import argparse
import multiprocessing
import putiopy
import os
from concurrent.futures import ProcessPoolExecutor
from itertools import repeat
from tqdm import tqdm
from libgen_to_txt.files import get_file_path, download_folder, download_folder_locally, delete_file_locally, \
get_parent_id
from libgen_to_txt.marker.convert import process_folder_marker
from libgen_to_txt.metadata import batch_write_metadata
from libgen_to_txt.naive.convert import process_batch_files_naive
from libgen_to_txt.settings import settings | 1,814 |
def process_single_libgen_chunk(torrent_info, conversion_lock, no_download, no_delete, max_workers=settings.CONVERSION_WORKERS):
num, url = torrent_info
client = putiopy.Client(settings.PUTIO_TOKEN, timeout=15, use_retry=True)
parent_folder_id = get_parent_id(client)
sel_file = get_file_path(num, client, parent_folder_id)
if not sel_file:
sel_file = download_folder(url, num, client, parent_folder_id, no_download)
if not sel_file:
return
stored_path = download_folder_locally(sel_file.name)
files = os.listdir(stored_path)
out_path = os.path.join(settings.BASE_TXT_FOLDER, num)
os.makedirs(out_path, exist_ok=True)
# Only one chunk can be converted at once
with conversion_lock:
match settings.CONVERSION_METHOD:
case "naive":
# PDF -> markdown
process_batch_files_naive(files, stored_path, out_path, max_workers)
# Write metadata
batch_write_metadata(files, out_path, max_workers)
case "marker":
# PDF -> markdown
process_folder_marker(stored_path, out_path, num, max_workers)
case _:
print(f"Unknown conversion method {settings.CONVERSION_METHOD}")
return
# Mark that we have processed this segment of libgen
with open(os.path.join(settings.BASE_PROCESSED_FOLDER, num), "w+") as f:
f.write(sel_file.name)
# Delete files from remote and local
if not no_download:
sel_file.delete()
if not no_delete:
|
def process_single_libgen_chunk(torrent_info, conversion_lock, no_download, no_delete, max_workers=settings.CONVERSION_WORKERS):
num, url = torrent_info
client = putiopy.Client(settings.PUTIO_TOKEN, timeout=15, use_retry=True)
parent_folder_id = get_parent_id(client)
sel_file = get_file_path(num, client, parent_folder_id)
if not sel_file:
sel_file = download_folder(url, num, client, parent_folder_id, no_download)
if not sel_file:
return
stored_path = download_folder_locally(sel_file.name)
files = os.listdir(stored_path)
out_path = os.path.join(settings.BASE_TXT_FOLDER, num)
os.makedirs(out_path, exist_ok=True)
# Only one chunk can be converted at once
with conversion_lock:
match settings.CONVERSION_METHOD:
case "naive":
# PDF -> markdown
process_batch_files_naive(files, stored_path, out_path, max_workers)
# Write metadata
batch_write_metadata(files, out_path, max_workers)
case "marker":
# PDF -> markdown
process_folder_marker(stored_path, out_path, num, max_workers)
case _:
print(f"Unknown conversion method {settings.CONVERSION_METHOD}")
return
# Mark that we have processed this segment of libgen
with open(os.path.join(settings.BASE_PROCESSED_FOLDER, num), "w+") as f:
f.write(sel_file.name)
# Delete files from remote and local
if not no_download:
sel_file.delete()
if not no_delete: | delete_file_locally(sel_file.name) | 3 | 2023-10-16 17:56:36+00:00 | 4k |
NVIDIA/GenerativeAIExamples | RetrievalAugmentedGeneration/examples/developer_rag/chains.py | [
{
"identifier": "LimitRetrievedNodesLength",
"path": "RetrievalAugmentedGeneration/common/utils.py",
"snippet": "class LimitRetrievedNodesLength(BaseNodePostprocessor):\n \"\"\"Llama Index chain filter to limit token lengths.\"\"\"\n\n def _postprocess_nodes(\n self, nodes: List[\"NodeWithS... | import base64
import os
import logging
from pathlib import Path
from typing import Generator
from llama_index import Prompt, download_loader
from llama_index.query_engine import RetrieverQueryEngine
from llama_index.response.schema import StreamingResponse
from llama_index.node_parser import LangchainNodeParser
from RetrievalAugmentedGeneration.common.utils import (
LimitRetrievedNodesLength,
get_config,
get_doc_retriever,
get_llm,
get_text_splitter,
get_vector_index,
is_base64_encoded,
set_service_context,
) | 1,951 | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""LLM Chains for executing Retrival Augmented Generation."""
logger = logging.getLogger(__name__)
def llm_chain(
context: str, question: str, num_tokens: int
) -> Generator[str, None, None]:
"""Execute a simple LLM chain using the components defined above."""
logger.info("Using llm to generate response directly without knowledge base.")
set_service_context()
prompt = get_config().prompts.chat_template.format(
context_str=context, query_str=question
)
logger.info(f"Prompt used for response generation: {prompt}")
response = get_llm().stream_complete(prompt, tokens=num_tokens)
gen_response = (resp.delta for resp in response)
return gen_response
def rag_chain(prompt: str, num_tokens: int) -> Generator[str, None, None]:
"""Execute a Retrieval Augmented Generation chain using the components defined above."""
logger.info("Using rag to generate response from document")
set_service_context()
if get_config().llm.model_engine == "triton-trt-llm":
get_llm().llm.tokens = num_tokens # type: ignore
else:
get_llm().llm.max_tokens = num_tokens
retriever = get_doc_retriever(num_nodes=4)
qa_template = Prompt(get_config().prompts.rag_template)
logger.info(f"Prompt used for response generation: {qa_template}")
query_engine = RetrieverQueryEngine.from_args(
retriever,
text_qa_template=qa_template,
node_postprocessors=[LimitRetrievedNodesLength()],
streaming=True,
)
response = query_engine.query(prompt)
# Properly handle an empty response
if isinstance(response, StreamingResponse):
return response.response_gen
logger.warning("No response generated from LLM, make sure you've ingested document.")
return StreamingResponse(iter(["No response generated from LLM, make sure you have ingested document from the Knowledge Base Tab."])).response_gen # type: ignore
def ingest_docs(data_dir: str, filename: str) -> None:
"""Ingest documents to the VectorDB."""
logger.info(f"Ingesting {filename} in vectorDB")
_, ext = os.path.splitext(filename)
if ext.lower() == ".pdf":
PDFReader = download_loader("PDFReader")
loader = PDFReader()
documents = loader.load_data(file=Path(data_dir))
else:
unstruct_reader = download_loader("UnstructuredReader")
loader = unstruct_reader()
documents = loader.load_data(file=Path(data_dir), split_documents=False)
encoded_filename = filename[:-4]
if not is_base64_encoded(encoded_filename):
encoded_filename = base64.b64encode(encoded_filename.encode("utf-8")).decode(
"utf-8"
)
for document in documents:
document.metadata = {"filename": encoded_filename}
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""LLM Chains for executing Retrival Augmented Generation."""
logger = logging.getLogger(__name__)
def llm_chain(
context: str, question: str, num_tokens: int
) -> Generator[str, None, None]:
"""Execute a simple LLM chain using the components defined above."""
logger.info("Using llm to generate response directly without knowledge base.")
set_service_context()
prompt = get_config().prompts.chat_template.format(
context_str=context, query_str=question
)
logger.info(f"Prompt used for response generation: {prompt}")
response = get_llm().stream_complete(prompt, tokens=num_tokens)
gen_response = (resp.delta for resp in response)
return gen_response
def rag_chain(prompt: str, num_tokens: int) -> Generator[str, None, None]:
"""Execute a Retrieval Augmented Generation chain using the components defined above."""
logger.info("Using rag to generate response from document")
set_service_context()
if get_config().llm.model_engine == "triton-trt-llm":
get_llm().llm.tokens = num_tokens # type: ignore
else:
get_llm().llm.max_tokens = num_tokens
retriever = get_doc_retriever(num_nodes=4)
qa_template = Prompt(get_config().prompts.rag_template)
logger.info(f"Prompt used for response generation: {qa_template}")
query_engine = RetrieverQueryEngine.from_args(
retriever,
text_qa_template=qa_template,
node_postprocessors=[LimitRetrievedNodesLength()],
streaming=True,
)
response = query_engine.query(prompt)
# Properly handle an empty response
if isinstance(response, StreamingResponse):
return response.response_gen
logger.warning("No response generated from LLM, make sure you've ingested document.")
return StreamingResponse(iter(["No response generated from LLM, make sure you have ingested document from the Knowledge Base Tab."])).response_gen # type: ignore
def ingest_docs(data_dir: str, filename: str) -> None:
"""Ingest documents to the VectorDB."""
logger.info(f"Ingesting {filename} in vectorDB")
_, ext = os.path.splitext(filename)
if ext.lower() == ".pdf":
PDFReader = download_loader("PDFReader")
loader = PDFReader()
documents = loader.load_data(file=Path(data_dir))
else:
unstruct_reader = download_loader("UnstructuredReader")
loader = unstruct_reader()
documents = loader.load_data(file=Path(data_dir), split_documents=False)
encoded_filename = filename[:-4]
if not is_base64_encoded(encoded_filename):
encoded_filename = base64.b64encode(encoded_filename.encode("utf-8")).decode(
"utf-8"
)
for document in documents:
document.metadata = {"filename": encoded_filename}
| index = get_vector_index() | 5 | 2023-10-19 13:46:31+00:00 | 4k |
MolecularAI/REINVENT4 | reinvent/runmodes/TL/linkinvent.py | [
{
"identifier": "Learning",
"path": "reinvent/runmodes/TL/learning.py",
"snippet": "class Learning(ABC):\n \"\"\"Trains a given model with new data from SMILES.\"\"\"\n\n def __init__(\n self,\n model: ModelAdapter,\n tb_logdir: str,\n configuration: Configuration,\n ... | import logging
from .learning import Learning
from reinvent.models.linkinvent.dataset.paired_dataset import PairedDataset | 3,182 | """LinkInvent transfer learning
Train a given model with new data. The data comes from a file with SMILES
strings. The file is assumed to be in multi-column format separated by commas
(CSV) or spaces. The SMILES strings are taken from the first two columns.
The two SMILES in each row correspond to two pipe-symbol (|) separated SMILES
fragments (the warheads, 'input') and a single SMILES (linker. 'target',
'output') e.g.
*C#CCO|*CCC#CCCCCCCC(C)C [*]C#CC(O)CCCCCCC[*]
The asterisks (*) are the attachment points to form a complete molecule. The
order of the columns must follow the order in the model (file). Currently,
this means that the warheads/input are in column 1 and the linker/target in
column 2. See (the model is read from the torch pickle file)
>>> import torch
>>> model = torch.load('link_invent_prior.model')
>>> model['vocabulary'].input.vocabulary.tokens()
>>> model['vocabulary'].target.vocabulary.tokens()
"""
from __future__ import annotations
__all__ = ["Linkinvent"]
logger = logging.getLogger(__name__)
| """LinkInvent transfer learning
Train a given model with new data. The data comes from a file with SMILES
strings. The file is assumed to be in multi-column format separated by commas
(CSV) or spaces. The SMILES strings are taken from the first two columns.
The two SMILES in each row correspond to two pipe-symbol (|) separated SMILES
fragments (the warheads, 'input') and a single SMILES (linker. 'target',
'output') e.g.
*C#CCO|*CCC#CCCCCCCC(C)C [*]C#CC(O)CCCCCCC[*]
The asterisks (*) are the attachment points to form a complete molecule. The
order of the columns must follow the order in the model (file). Currently,
this means that the warheads/input are in column 1 and the linker/target in
column 2. See (the model is read from the torch pickle file)
>>> import torch
>>> model = torch.load('link_invent_prior.model')
>>> model['vocabulary'].input.vocabulary.tokens()
>>> model['vocabulary'].target.vocabulary.tokens()
"""
from __future__ import annotations
__all__ = ["Linkinvent"]
logger = logging.getLogger(__name__)
| class Linkinvent(Learning): | 0 | 2023-10-20 06:43:16+00:00 | 4k |
lion-agi/lionagi | lionagi/loaders/chunker.py | [
{
"identifier": "lcall",
"path": "lionagi/utils/call_util.py",
"snippet": "def lcall(\n input_: Any, func_: Callable, flatten: bool = False, \n dropna: bool = False, **kwargs\n ) -> List[Any]:\n \"\"\"\n Applies a function to each element of `input`, after converting it to a list.\n\n ... | from typing import Union, Callable
from lionagi.utils import lcall
from lionagi.schema import DataNode
from lionagi.bridge import langchain_text_splitter, from_langchain, llama_index_node_parser, from_llama_index
from .load_util import ChunkerType, file_to_chunks | 2,973 |
Returns:
List[DataNode]: The list of converted DataNode instances.
"""
for i in range(len(documents)):
if type(documents[i]) == DataNode:
if chunker_type == ChunkerType.LLAMAINDEX:
documents[i] = documents[i].to_llama_index()
elif chunker_type == ChunkerType.LANGCHAIN:
documents[i] = documents[i].to_langchain()
return documents
# Function to chunk text documents
def text_chunker(documents, args, kwargs):
"""
Chunks text documents into smaller pieces.
Parameters:
documents (List[DataNode]): A list of DataNode instances to be chunked.
args (List[Any]): Positional arguments to be passed to the chunking function.
kwargs (dict): Keyword arguments to be passed to the chunking function.
Returns:
List[DataNode]: A list of chunked DataNode instances.
"""
def chunk_node(node):
chunks = file_to_chunks(node.to_dict(), *args, **kwargs)
lcall(chunks, lambda chunk: chunk.pop('node_id'))
chunk_nodes = lcall(chunks, lambda x: DataNode(**x))
return chunk_nodes
nodes = []
for doc in documents:
nodes += chunk_node(doc)
return nodes
def _datanode_parser(nodes, parser):
"""
Parses raw data into DataNode instances using the provided parser function.
Parameters:
nodes (List[Any]): A list of raw data to be parsed.
parser (Callable): A function that parses raw data into DataNode instances.
Returns:
List[DataNode]: A list of parsed DataNode instances.
Raises:
ValueError: If the parser function fails.
"""
try:
nodes = parser(nodes)
except Exception as e:
raise ValueError(f'DataNode parser {parser} failed. Error:{e}')
return nodes
def chunk(documents,
chunker,
chunker_type=ChunkerType.PLAIN,
chunker_args=[],
chunker_kwargs={},
chunking_kwargs={},
documents_convert_func=None,
to_datanode: Union[bool, Callable] = True):
"""
Chunks documents using the specified chunker and chunker type.
Parameters:
documents (List[Any]): A list of documents to be chunked.
chunker (Callable): The chunking function to be used.
chunker_type (ChunkerType): The type of the chunker. Defaults to ChunkerType.PLAIN.
chunker_args (List[Any]): Positional arguments for the chunker function. Defaults to an empty list.
chunker_kwargs (dict): Keyword arguments for the chunker function. Defaults to an empty dict.
chunking_kwargs (dict): Additional keyword arguments for the chunking process. Defaults to an empty dict.
documents_convert_func (Callable): A function to convert documents to a specific format. Defaults to None.
to_datanode (Union[bool, Callable]): Determines whether to convert the result into DataNode instances, or
a callable to convert the result. Defaults to True.
Returns:
List[DataNode]: A list of chunked DataNode instances after applying the chunker.
Raises:
ValueError: If the chunker fails or an unsupported chunker type is provided.
"""
if chunker_type == ChunkerType.PLAIN:
try:
if chunker == 'text_chunker':
chunker = text_chunker
nodes = chunker(documents, chunker_args, chunker_kwargs)
return nodes
except Exception as e:
raise ValueError(f'Reader {chunker} is currently not supported. Error: {e}')
if chunker_type == ChunkerType.LANGCHAIN:
if documents_convert_func:
documents = documents_convert_func(documents, 'langchain')
nodes = langchain_text_splitter(documents, chunker, chunker_args, chunker_kwargs)
if isinstance(to_datanode, bool) and to_datanode is True:
if isinstance(documents, str):
nodes = lcall(nodes, lambda x: DataNode(content=x))
else:
nodes = lcall(nodes, from_langchain)
elif isinstance(to_datanode, Callable):
nodes = _datanode_parser(nodes, to_datanode)
return nodes
elif chunker_type == ChunkerType.LLAMAINDEX:
if documents_convert_func:
documents = documents_convert_func(documents, 'llama_index')
| # use utils, schema and bridge
# Function to convert documents to a specific format based on the chunker type
def datanodes_convert(documents, chunker_type):
"""
Converts a lionagi DataNode documents to a specific format based on the chunker type.
Parameters:
documents (List[DataNode]): A list of DataNode instances to be converted.
chunker_type (ChunkerType): The chunker type to determine the conversion format.
Returns:
List[DataNode]: The list of converted DataNode instances.
"""
for i in range(len(documents)):
if type(documents[i]) == DataNode:
if chunker_type == ChunkerType.LLAMAINDEX:
documents[i] = documents[i].to_llama_index()
elif chunker_type == ChunkerType.LANGCHAIN:
documents[i] = documents[i].to_langchain()
return documents
# Function to chunk text documents
def text_chunker(documents, args, kwargs):
"""
Chunks text documents into smaller pieces.
Parameters:
documents (List[DataNode]): A list of DataNode instances to be chunked.
args (List[Any]): Positional arguments to be passed to the chunking function.
kwargs (dict): Keyword arguments to be passed to the chunking function.
Returns:
List[DataNode]: A list of chunked DataNode instances.
"""
def chunk_node(node):
chunks = file_to_chunks(node.to_dict(), *args, **kwargs)
lcall(chunks, lambda chunk: chunk.pop('node_id'))
chunk_nodes = lcall(chunks, lambda x: DataNode(**x))
return chunk_nodes
nodes = []
for doc in documents:
nodes += chunk_node(doc)
return nodes
def _datanode_parser(nodes, parser):
"""
Parses raw data into DataNode instances using the provided parser function.
Parameters:
nodes (List[Any]): A list of raw data to be parsed.
parser (Callable): A function that parses raw data into DataNode instances.
Returns:
List[DataNode]: A list of parsed DataNode instances.
Raises:
ValueError: If the parser function fails.
"""
try:
nodes = parser(nodes)
except Exception as e:
raise ValueError(f'DataNode parser {parser} failed. Error:{e}')
return nodes
def chunk(documents,
chunker,
chunker_type=ChunkerType.PLAIN,
chunker_args=[],
chunker_kwargs={},
chunking_kwargs={},
documents_convert_func=None,
to_datanode: Union[bool, Callable] = True):
"""
Chunks documents using the specified chunker and chunker type.
Parameters:
documents (List[Any]): A list of documents to be chunked.
chunker (Callable): The chunking function to be used.
chunker_type (ChunkerType): The type of the chunker. Defaults to ChunkerType.PLAIN.
chunker_args (List[Any]): Positional arguments for the chunker function. Defaults to an empty list.
chunker_kwargs (dict): Keyword arguments for the chunker function. Defaults to an empty dict.
chunking_kwargs (dict): Additional keyword arguments for the chunking process. Defaults to an empty dict.
documents_convert_func (Callable): A function to convert documents to a specific format. Defaults to None.
to_datanode (Union[bool, Callable]): Determines whether to convert the result into DataNode instances, or
a callable to convert the result. Defaults to True.
Returns:
List[DataNode]: A list of chunked DataNode instances after applying the chunker.
Raises:
ValueError: If the chunker fails or an unsupported chunker type is provided.
"""
if chunker_type == ChunkerType.PLAIN:
try:
if chunker == 'text_chunker':
chunker = text_chunker
nodes = chunker(documents, chunker_args, chunker_kwargs)
return nodes
except Exception as e:
raise ValueError(f'Reader {chunker} is currently not supported. Error: {e}')
if chunker_type == ChunkerType.LANGCHAIN:
if documents_convert_func:
documents = documents_convert_func(documents, 'langchain')
nodes = langchain_text_splitter(documents, chunker, chunker_args, chunker_kwargs)
if isinstance(to_datanode, bool) and to_datanode is True:
if isinstance(documents, str):
nodes = lcall(nodes, lambda x: DataNode(content=x))
else:
nodes = lcall(nodes, from_langchain)
elif isinstance(to_datanode, Callable):
nodes = _datanode_parser(nodes, to_datanode)
return nodes
elif chunker_type == ChunkerType.LLAMAINDEX:
if documents_convert_func:
documents = documents_convert_func(documents, 'llama_index') | nodes = llama_index_node_parser(documents, chunker, chunker_args, chunker_kwargs, chunking_kwargs) | 5 | 2023-10-17 03:10:02+00:00 | 4k |
ziqipang/LM4VisualEncoding | pointcloud_classification/models/Point_BERT.py | [
{
"identifier": "Group",
"path": "pointcloud_classification/models/dvae.py",
"snippet": "class Group(nn.Module):\n def __init__(self, num_group, group_size):\n super().__init__()\n self.num_group = num_group\n self.group_size = group_size\n # self.knn = KNN(k=self.group_si... | import torch
import torch.nn as nn
import torch.nn.functional as F
import timm
import numpy as np
import random
from pathlib import Path
from timm.models.layers import DropPath, trunc_normal_
from .dvae import Group
from .dvae import DiscreteVAE, Encoder
from .llama import LLaMATransformer
from .build import MODELS
from utils import misc
from utils.checkpoint import get_missing_parameters_message, get_unexpected_parameters_message
from utils.logger import * | 3,370 |
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = Attention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class TransformerEncoder(nn.Module):
""" Transformer Encoder without hierarchical structure
"""
def __init__(self, embed_dim=768, depth=4, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.):
super().__init__()
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate,
drop_path = drop_path_rate[i] if isinstance(drop_path_rate, list) else drop_path_rate
)
for i in range(depth)])
def forward(self, x, pos):
for _, block in enumerate(self.blocks):
x = block(x + pos)
return x
|
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = Attention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class TransformerEncoder(nn.Module):
""" Transformer Encoder without hierarchical structure
"""
def __init__(self, embed_dim=768, depth=4, num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.):
super().__init__()
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate,
drop_path = drop_path_rate[i] if isinstance(drop_path_rate, list) else drop_path_rate
)
for i in range(depth)])
def forward(self, x, pos):
for _, block in enumerate(self.blocks):
x = block(x + pos)
return x
| @MODELS.register_module() | 4 | 2023-10-19 15:40:57+00:00 | 4k |
stanford-oval/WikiChat | benchmark/scripts/automatic_eval.py | [
{
"identifier": "DialogueTurn",
"path": "pipelines/dialog_turn.py",
"snippet": "class DialogueTurn:\n def __init__(\n self,\n agent_utterance: str = None,\n user_utterance: str = None,\n pipeline: str = None,\n engine: str = None,\n generate_engine: str = Non... | from concurrent.futures import ThreadPoolExecutor
from typing import List
from tqdm import tqdm
from scipy.stats import ttest_ind
from pipelines.dialog_turn import DialogueTurn
from llm.llm_generate import llm_generate
from llm.global_variables import get_total_cost
import json
import argparse
import numpy as np
import logging
import sys | 2,596 |
sys.path.insert(0, "./")
logger = logging.getLogger(__name__)
def get_feedback(object_dlg_history: List[DialogueTurn], new_dlg_turn: DialogueTurn):
|
sys.path.insert(0, "./")
logger = logging.getLogger(__name__)
def get_feedback(object_dlg_history: List[DialogueTurn], new_dlg_turn: DialogueTurn): | feedback = llm_generate( | 1 | 2023-10-19 18:17:25+00:00 | 4k |
TonicAI/tvalmetrics | tonic_validate/metrics/answer_consistency_metric.py | [
{
"identifier": "LLMResponse",
"path": "tonic_validate/classes/llm_response.py",
"snippet": "class LLMResponse(BaseModel):\n llm_answer: str\n llm_context_list: list[str]\n benchmark_item: BenchmarkItem"
},
{
"identifier": "Metric",
"path": "tonic_validate/metrics/metric.py",
"s... | import logging
from tonic_validate.classes.llm_response import LLMResponse
from tonic_validate.metrics.metric import Metric
from tonic_validate.utils.metrics_util import (
parse_boolean_response,
parse_bullet_list_response,
)
from tonic_validate.services.openai_service import OpenAIService
from tonic_validate.utils.llm_calls import (
main_points_call,
statement_derived_from_context_call,
) | 1,742 |
logger = logging.getLogger()
class AnswerConsistencyMetric(Metric):
name = "answer_consistency"
def score(self, llm_response: LLMResponse, openai_service: OpenAIService) -> float:
|
logger = logging.getLogger()
class AnswerConsistencyMetric(Metric):
name = "answer_consistency"
def score(self, llm_response: LLMResponse, openai_service: OpenAIService) -> float: | main_points_response = main_points_call(llm_response.llm_answer, openai_service) | 5 | 2023-10-23 21:38:11+00:00 | 4k |
jhejna/cpl | research/datasets/replay_buffer/sampling.py | [
{
"identifier": "utils",
"path": "research/utils/utils.py",
"snippet": "def to_device(batch: Any, device: torch.device) -> Any:\ndef to_tensor(batch: Any) -> Any:\ndef to_np(batch: Any) -> Any:\ndef remove_float64(batch: Any):\ndef unsqueeze(batch: Any, dim: int) -> Any:\ndef squeeze(batch: Any, dim: in... | import copy
import numpy as np
from typing import Callable, Optional, Tuple
from research.utils import utils
from .storage import Storage | 1,743 |
"""
This file defines a number of sampling functions used by the replay buffer.
Each sample function returns tensors of the following shape:
(Batch, Time, dims...)
and requires `storage` and `discount` arguments.
Many of these functions have large blocks of repeated code, but
are implemented separately for readability and performance optimiztaion.
Sequences are sampled as follows:
-stack_length ... -1, 0, 1, 2, ..., seq_length
| stack |idx| seq |
The stack parameter will always be sampled immediately, and is desinged to be used as context
to the network.
Stack will not obey nstep returns. (negative indexing)
Everything is sampled in batches directly from memory (preferred)
If batch_size is set to one, then a squeeze operation will be performed at the very end.
Samples are returned as with shape: (Batch, Time, Dims...)
if seq or stack dims are set to 1, then these parameters are ignored.
"""
def _get_ep_idxs(storage: Storage, batch_size: int = 1, sample_by_timesteps: bool = True, min_length: int = 2):
if batch_size is None or batch_size > 1:
ep_idxs = np.arange(len(storage.lengths))[storage.lengths >= min_length]
if sample_by_timesteps:
# Lower the lengths by the min_length - 1 to give the number of valid sequences.
lengths = storage.lengths[ep_idxs] - (min_length - 1)
p = lengths / lengths.sum()
ep_idxs = np.random.choice(ep_idxs, size=(batch_size,), replace=True, p=p)
else:
ep_idxs = ep_idxs[np.random.randint(0, len(ep_idxs), size=(batch_size,))]
return ep_idxs
else:
# Use a different, much faster sampling scheme for batch_size = 1
assert sample_by_timesteps is False, "Cannot sample by timesteps with batch_size=1, it's too slow!"
ep_idx = np.random.randint(0, len(storage.lengths))
if storage.lengths[ep_idx] < min_length:
return _get_ep_idxs(storage, batch_size, sample_by_timesteps, min_length)
else:
return np.array([ep_idx], np.int64)
def sample(
storage: Storage,
batch_size: int = 1,
sample_by_timesteps: bool = True,
stack: int = 1,
stack_keys: Tuple = (),
discount: float = 0.99,
):
"""
Default sampling for imitation learning.
Returns (obs, action, ... keys) batches.
"""
min_length = 2
ep_idxs = _get_ep_idxs(storage, batch_size, sample_by_timesteps, min_length)
# sample position within the episode randomly
# Note that there is a plus one offset here to account for the difference
# between the obs and action position
offsets = np.random.randint(1, storage.lengths[ep_idxs])
if stack > 1:
assert len(stack_keys) > 1, "Provided stack > 1 but no stack keys"
stack_offsets = np.expand_dims(offsets, axis=-1) + np.arange(-stack + 1, 1)
stack_offsets = np.clip(stack_offsets, 0, None) # Clip to zero as lowest offset = start of episode
stack_idxs = np.expand_dims(storage.starts[ep_idxs], axis=-1) + stack_offsets
idxs = storage.starts[ep_idxs] + offsets
# Sample from the dataset
batch = {}
for k in storage.keys():
sample_idxs = stack_idxs if k in stack_keys else idxs
if k == "obs":
sample_idxs = sample_idxs - 1
if k == "discount":
|
"""
This file defines a number of sampling functions used by the replay buffer.
Each sample function returns tensors of the following shape:
(Batch, Time, dims...)
and requires `storage` and `discount` arguments.
Many of these functions have large blocks of repeated code, but
are implemented separately for readability and performance optimiztaion.
Sequences are sampled as follows:
-stack_length ... -1, 0, 1, 2, ..., seq_length
| stack |idx| seq |
The stack parameter will always be sampled immediately, and is desinged to be used as context
to the network.
Stack will not obey nstep returns. (negative indexing)
Everything is sampled in batches directly from memory (preferred)
If batch_size is set to one, then a squeeze operation will be performed at the very end.
Samples are returned as with shape: (Batch, Time, Dims...)
if seq or stack dims are set to 1, then these parameters are ignored.
"""
def _get_ep_idxs(storage: Storage, batch_size: int = 1, sample_by_timesteps: bool = True, min_length: int = 2):
if batch_size is None or batch_size > 1:
ep_idxs = np.arange(len(storage.lengths))[storage.lengths >= min_length]
if sample_by_timesteps:
# Lower the lengths by the min_length - 1 to give the number of valid sequences.
lengths = storage.lengths[ep_idxs] - (min_length - 1)
p = lengths / lengths.sum()
ep_idxs = np.random.choice(ep_idxs, size=(batch_size,), replace=True, p=p)
else:
ep_idxs = ep_idxs[np.random.randint(0, len(ep_idxs), size=(batch_size,))]
return ep_idxs
else:
# Use a different, much faster sampling scheme for batch_size = 1
assert sample_by_timesteps is False, "Cannot sample by timesteps with batch_size=1, it's too slow!"
ep_idx = np.random.randint(0, len(storage.lengths))
if storage.lengths[ep_idx] < min_length:
return _get_ep_idxs(storage, batch_size, sample_by_timesteps, min_length)
else:
return np.array([ep_idx], np.int64)
def sample(
storage: Storage,
batch_size: int = 1,
sample_by_timesteps: bool = True,
stack: int = 1,
stack_keys: Tuple = (),
discount: float = 0.99,
):
"""
Default sampling for imitation learning.
Returns (obs, action, ... keys) batches.
"""
min_length = 2
ep_idxs = _get_ep_idxs(storage, batch_size, sample_by_timesteps, min_length)
# sample position within the episode randomly
# Note that there is a plus one offset here to account for the difference
# between the obs and action position
offsets = np.random.randint(1, storage.lengths[ep_idxs])
if stack > 1:
assert len(stack_keys) > 1, "Provided stack > 1 but no stack keys"
stack_offsets = np.expand_dims(offsets, axis=-1) + np.arange(-stack + 1, 1)
stack_offsets = np.clip(stack_offsets, 0, None) # Clip to zero as lowest offset = start of episode
stack_idxs = np.expand_dims(storage.starts[ep_idxs], axis=-1) + stack_offsets
idxs = storage.starts[ep_idxs] + offsets
# Sample from the dataset
batch = {}
for k in storage.keys():
sample_idxs = stack_idxs if k in stack_keys else idxs
if k == "obs":
sample_idxs = sample_idxs - 1
if k == "discount": | batch[k] = discount * utils.get_from_batch(storage[k], sample_idxs) | 0 | 2023-10-19 17:25:45+00:00 | 4k |
nbasyl/LLM-FP4 | lm_eval/tasks/triviaqa.py | [
{
"identifier": "Task",
"path": "lm_eval/base.py",
"snippet": "class LM(abc.ABC):\nclass BaseLM(LM):\nclass Task(abc.ABC):\nclass MultipleChoiceTask(Task):\nclass PerplexityTask(Task, abc.ABC):\nclass CacheHook:\nclass CachingLM:\nclass Request:\nclass RequestFactory:\n def __init__(self):\n def l... | import inspect
import string
from lm_eval.base import Task, rf
from lm_eval.metrics import mean | 1,617 | """
TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension
https://arxiv.org/pdf/1705.03551.pdf
TriviaQA is a reading comprehension dataset containing over 650K question-answer-evidence
triples. TriviaQA includes 95K question-answer pairs authored by trivia enthusiasts
and independently gathered evidence documents, six per question on average, that provide
high quality distant supervision for answering the questions.
Homepage: https://nlp.cs.washington.edu/triviaqa/
"""
_CITATION = """
@InProceedings{JoshiTriviaQA2017,
author = {Joshi, Mandar and Choi, Eunsol and Weld, Daniel S. and Zettlemoyer, Luke},
title = {TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension},
booktitle = {Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics},
month = {July},
year = {2017},
address = {Vancouver, Canada},
publisher = {Association for Computational Linguistics},
}
"""
class TriviaQA(Task):
VERSION = 2
DATASET_PATH = "trivia_qa"
DATASET_NAME = "rc.nocontext"
def has_training_docs(self):
return True
def has_validation_docs(self):
return True
def has_test_docs(self):
return False
def training_docs(self):
return self.dataset["train"]
def validation_docs(self):
return self.dataset["validation"]
def test_docs(self):
raise NotImplementedError()
def doc_to_text(self, doc):
return f"Question: {doc['question']}\nAnswer:"
def should_decontaminate(self):
return True
def doc_to_decontamination_query(self, doc):
return doc["question"]
def doc_to_target(self, doc):
return " " + doc["answer"]["value"]
def _remove_prefixes(self, aliases):
# Optimization: Remove any alias that has a strict prefix elsewhere in the list
# we can do this because if the prefix is acceptable by isgreedy, we can stop looking
aliases.sort()
ret = [aliases[0]]
for alias in aliases[1:]:
if not alias.startswith(ret[-1]):
ret.append(alias)
return ret
def construct_requests(self, doc, ctx):
"""Uses RequestFactory to construct Requests and returns an iterable of
Requests which will be sent to the LM.
:param doc:
The document as returned from training_docs, validation_docs, or test_docs.
:param ctx: str
The context string, generated by fewshot_context. This includes the natural
language description, as well as the few shot examples, and the question
part of the document for `doc`.
"""
| """
TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension
https://arxiv.org/pdf/1705.03551.pdf
TriviaQA is a reading comprehension dataset containing over 650K question-answer-evidence
triples. TriviaQA includes 95K question-answer pairs authored by trivia enthusiasts
and independently gathered evidence documents, six per question on average, that provide
high quality distant supervision for answering the questions.
Homepage: https://nlp.cs.washington.edu/triviaqa/
"""
_CITATION = """
@InProceedings{JoshiTriviaQA2017,
author = {Joshi, Mandar and Choi, Eunsol and Weld, Daniel S. and Zettlemoyer, Luke},
title = {TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension},
booktitle = {Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics},
month = {July},
year = {2017},
address = {Vancouver, Canada},
publisher = {Association for Computational Linguistics},
}
"""
class TriviaQA(Task):
VERSION = 2
DATASET_PATH = "trivia_qa"
DATASET_NAME = "rc.nocontext"
def has_training_docs(self):
return True
def has_validation_docs(self):
return True
def has_test_docs(self):
return False
def training_docs(self):
return self.dataset["train"]
def validation_docs(self):
return self.dataset["validation"]
def test_docs(self):
raise NotImplementedError()
def doc_to_text(self, doc):
return f"Question: {doc['question']}\nAnswer:"
def should_decontaminate(self):
return True
def doc_to_decontamination_query(self, doc):
return doc["question"]
def doc_to_target(self, doc):
return " " + doc["answer"]["value"]
def _remove_prefixes(self, aliases):
# Optimization: Remove any alias that has a strict prefix elsewhere in the list
# we can do this because if the prefix is acceptable by isgreedy, we can stop looking
aliases.sort()
ret = [aliases[0]]
for alias in aliases[1:]:
if not alias.startswith(ret[-1]):
ret.append(alias)
return ret
def construct_requests(self, doc, ctx):
"""Uses RequestFactory to construct Requests and returns an iterable of
Requests which will be sent to the LM.
:param doc:
The document as returned from training_docs, validation_docs, or test_docs.
:param ctx: str
The context string, generated by fewshot_context. This includes the natural
language description, as well as the few shot examples, and the question
part of the document for `doc`.
""" | continuation = rf.greedy_until(ctx, {"until": ["\n", ".", ","]}) | 0 | 2023-10-15 06:05:13+00:00 | 4k |
alextamkin/generative-elicitation | run_human_evaluation.py | [
{
"identifier": "FromSavedFileAgent",
"path": "from_saved_file_agent.py",
"snippet": "class FromSavedFileAgent(BaseActiveLearningAgent):\n \"\"\"Agent that loads generated interactions (queries and answers) from a saved file.\"\"\"\n\n def __init__(self, target_specification_file, engine, openai_c... | import glob
import sys
import json
import os
import random
import pandas as pd
from tap import Tap
from from_saved_file_agent import FromSavedFileAgent
from run_model_evaluation import run_problem_instance
from tqdm import tqdm | 3,013 |
task_specific_directives = {
"website_preferences": '\nFor this task, "yes" means the user would like the website, and "no" means the user would not like the website',
"moral_reasoning": '\nFor this task, "yes" means the user would believe it is ethical to steal a loaf of bread, and "no" means the user would believe it is not ethical to steal a loaf of bread',
"email_regex": '\nFor this task, "yes" means the user would find the email address valid, while "no" means the user would find the email address invalid',
}
task_specific_instructions = {
"website_preferences": "asks a user about their preferences for a website",
"moral_reasoning": "asks a user under what conditions they would believe it is ethical to steal a loaf of bread",
"email_regex": "asks a user about their preferences for what makes a valid format for email addresses",
}
def get_saved_interaction_files_for_task(saved_annotations_dir, task):
with open(f"{saved_annotations_dir}/experiment_type_to_prolific_id.json") as f:
experiment_type_to_prolific_id = json.load(f)
files_to_return = {}
for experiment_type in experiment_type_to_prolific_id[task]:
files_to_return[experiment_type] = [
f"{saved_annotations_dir}/{file_id}.json" for file_id in experiment_type_to_prolific_id[task][experiment_type] if os.path.exists(f"{saved_annotations_dir}/{file_id}.json")
]
return files_to_return
def main(args):
if args.no_cache:
openai_cache_file = None
else:
openai_cache_file = f"{args.engine}-cache-seed-{args.seed}.jsonl"
all_test_xs = {
"interaction_time": {},
"interaction_num_turns": {},
"interaction_total_char_length": {},
}
all_test_scores = {
"accuracy": {},
"AUCROC": {},
"correct_prob": {},
"accuracy_relative": {},
"AUCROC_relative": {},
"correct_prob_relative": {}
}
# initialize a dataframe
all_test_results = pd.DataFrame(columns=[
'interaction_time', 'interaction_num_turns', 'interaction_total_char_length',
'accuracy', 'AUCROC', 'correct_prob', 'accuracy_relative', 'AUCROC_relative',
'correct_prob_relative', 'question_mode', 'task', 'engine', 'seed', 'interaction_id',
])
problem_instance_filename = random.choice(glob.glob(f"gpt_prompts/{args.task}/*.json"))
saved_interaction_files_for_task = get_saved_interaction_files_for_task(args.saved_annotations_dir ,args.task)
for question_mode in saved_interaction_files_for_task:
print(question_mode)
for metric in all_test_xs:
all_test_xs[metric][question_mode] = []
for metric in all_test_scores:
all_test_scores[metric][question_mode] = []
for saved_interactions_file in tqdm(saved_interaction_files_for_task[question_mode]):
print(saved_interactions_file)
# filter out preferences that are trivial
if args.filter_trivial_preferences:
with open(saved_interactions_file) as f:
saved_interactions = json.load(f)
all_answers = [sample["label"] for sample in saved_interactions["evaluation_results"]]
if len(set(all_answers)) == 1:
continue
os.makedirs(f"model_human_results/{args.task}", exist_ok=True)
outputs_save_file = open(f"model_human_results/{args.task}/{args.engine}_{args.eval_condition}_{question_mode.replace('/', '_').replace(' ', '_')}_{os.path.split(saved_interactions_file)[-1][:-5]}.txt", "w")
test_xs, test_scores = run_problem_instance(
problem_instance_filename=problem_instance_filename,
engine=args.engine,
openai_cache_file=openai_cache_file,
num_interactions=sys.maxsize,
|
task_specific_directives = {
"website_preferences": '\nFor this task, "yes" means the user would like the website, and "no" means the user would not like the website',
"moral_reasoning": '\nFor this task, "yes" means the user would believe it is ethical to steal a loaf of bread, and "no" means the user would believe it is not ethical to steal a loaf of bread',
"email_regex": '\nFor this task, "yes" means the user would find the email address valid, while "no" means the user would find the email address invalid',
}
task_specific_instructions = {
"website_preferences": "asks a user about their preferences for a website",
"moral_reasoning": "asks a user under what conditions they would believe it is ethical to steal a loaf of bread",
"email_regex": "asks a user about their preferences for what makes a valid format for email addresses",
}
def get_saved_interaction_files_for_task(saved_annotations_dir, task):
with open(f"{saved_annotations_dir}/experiment_type_to_prolific_id.json") as f:
experiment_type_to_prolific_id = json.load(f)
files_to_return = {}
for experiment_type in experiment_type_to_prolific_id[task]:
files_to_return[experiment_type] = [
f"{saved_annotations_dir}/{file_id}.json" for file_id in experiment_type_to_prolific_id[task][experiment_type] if os.path.exists(f"{saved_annotations_dir}/{file_id}.json")
]
return files_to_return
def main(args):
if args.no_cache:
openai_cache_file = None
else:
openai_cache_file = f"{args.engine}-cache-seed-{args.seed}.jsonl"
all_test_xs = {
"interaction_time": {},
"interaction_num_turns": {},
"interaction_total_char_length": {},
}
all_test_scores = {
"accuracy": {},
"AUCROC": {},
"correct_prob": {},
"accuracy_relative": {},
"AUCROC_relative": {},
"correct_prob_relative": {}
}
# initialize a dataframe
all_test_results = pd.DataFrame(columns=[
'interaction_time', 'interaction_num_turns', 'interaction_total_char_length',
'accuracy', 'AUCROC', 'correct_prob', 'accuracy_relative', 'AUCROC_relative',
'correct_prob_relative', 'question_mode', 'task', 'engine', 'seed', 'interaction_id',
])
problem_instance_filename = random.choice(glob.glob(f"gpt_prompts/{args.task}/*.json"))
saved_interaction_files_for_task = get_saved_interaction_files_for_task(args.saved_annotations_dir ,args.task)
for question_mode in saved_interaction_files_for_task:
print(question_mode)
for metric in all_test_xs:
all_test_xs[metric][question_mode] = []
for metric in all_test_scores:
all_test_scores[metric][question_mode] = []
for saved_interactions_file in tqdm(saved_interaction_files_for_task[question_mode]):
print(saved_interactions_file)
# filter out preferences that are trivial
if args.filter_trivial_preferences:
with open(saved_interactions_file) as f:
saved_interactions = json.load(f)
all_answers = [sample["label"] for sample in saved_interactions["evaluation_results"]]
if len(set(all_answers)) == 1:
continue
os.makedirs(f"model_human_results/{args.task}", exist_ok=True)
outputs_save_file = open(f"model_human_results/{args.task}/{args.engine}_{args.eval_condition}_{question_mode.replace('/', '_').replace(' ', '_')}_{os.path.split(saved_interactions_file)[-1][:-5]}.txt", "w")
test_xs, test_scores = run_problem_instance(
problem_instance_filename=problem_instance_filename,
engine=args.engine,
openai_cache_file=openai_cache_file,
num_interactions=sys.maxsize, | agent_class=FromSavedFileAgent, | 0 | 2023-10-16 18:43:47+00:00 | 4k |
bcmi/libcom | libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/openaimodel.py | [
{
"identifier": "checkpoint",
"path": "libcom/painterly_image_harmonization/source/PHDiffusion/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... | from abc import abstractmethod
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.diffusionmodules.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.attention import SpatialTransformer
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.fusion.dual_encoder_fusion import CrossAttentionInteraction
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.util import exists
from omegaconf.listconfig import ListConfig
import math
import torch
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F | 3,221 |
# 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)
|
# 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): | 7 | 2023-10-19 05:08:12+00:00 | 4k |
facebookresearch/motif | rlaif/annotators.py | [
{
"identifier": "BlstatsTransform",
"path": "rlaif/annotators_transforms.py",
"snippet": "class BlstatsTransform:\n def __init__(self, blstats_keys: List[str]):\n self.blstats_keys = blstats_keys\n self.hunger_num_to_str = {\n 0: \"Satiated\", 1: \"\", 2: \"Hungry\", 3: \"Weak\... | from abc import ABC, abstractmethod
from typing import Dict, List, Callable, Optional, Tuple, Sequence
from rlaif.annotators_transforms import BlstatsTransform, MessageTransform
from rlaif.prompts import system_prompts, prompt_templates, goal_strings, regexes, retry_prompts
from rlaif.llms import LocalLanguageModel, AnnotationIdx
import itertools
import numpy as np
import torchvision | 2,345 |
class Annotator(ABC):
def __init__(self, batch_size: int):
self.batch_size = batch_size
@abstractmethod
def __call__(self, batch: Dict[str, np.ndarray], logging_indices: Sequence[int]) -> np.array:
"""General method which takes two sequences and returns whether the second element
is better than the first one, for each batch element,
together with a mask of the valid/invalid elements.
Args:
batch: Dictionary of arrays containing the data for the two sequences (bs, 2, subepisode_length, dims)
logging_indices: a list of indices for logging info about computation for each element
Return:
annotations: int array of shape (bs,) where each element is out of (first, second, tie, invalid)
"""
pass
@property
@abstractmethod
def data_keys(self) -> List[str]:
pass
@property
@abstractmethod
def info_keys(self) -> List[str]:
pass
@property
@abstractmethod
def transform(self) -> Optional[Callable]:
pass
class LanguageModelAnnotator(Annotator):
"""Annotator that annotates based on the output of a language model."""
def __init__(self, batch_size: int, model_name: str,
use_messages: bool, use_blstats: bool,
num_gpus: int = 8, logdir: Optional[str] = None,
prompt_version: str = 'v0',
goal_key: str = '') -> None:
assert use_messages or use_blstats
self.use_messages = use_messages
self.use_blstats = use_blstats
self.blstats_keys = [
'NLE_BL_DEPTH', 'NLE_BL_GOLD', 'NLE_BL_HP',
'NLE_BL_HPMAX', 'NLE_BL_XP', 'NLE_BL_HUNGER'
]
|
class Annotator(ABC):
def __init__(self, batch_size: int):
self.batch_size = batch_size
@abstractmethod
def __call__(self, batch: Dict[str, np.ndarray], logging_indices: Sequence[int]) -> np.array:
"""General method which takes two sequences and returns whether the second element
is better than the first one, for each batch element,
together with a mask of the valid/invalid elements.
Args:
batch: Dictionary of arrays containing the data for the two sequences (bs, 2, subepisode_length, dims)
logging_indices: a list of indices for logging info about computation for each element
Return:
annotations: int array of shape (bs,) where each element is out of (first, second, tie, invalid)
"""
pass
@property
@abstractmethod
def data_keys(self) -> List[str]:
pass
@property
@abstractmethod
def info_keys(self) -> List[str]:
pass
@property
@abstractmethod
def transform(self) -> Optional[Callable]:
pass
class LanguageModelAnnotator(Annotator):
"""Annotator that annotates based on the output of a language model."""
def __init__(self, batch_size: int, model_name: str,
use_messages: bool, use_blstats: bool,
num_gpus: int = 8, logdir: Optional[str] = None,
prompt_version: str = 'v0',
goal_key: str = '') -> None:
assert use_messages or use_blstats
self.use_messages = use_messages
self.use_blstats = use_blstats
self.blstats_keys = [
'NLE_BL_DEPTH', 'NLE_BL_GOLD', 'NLE_BL_HP',
'NLE_BL_HPMAX', 'NLE_BL_XP', 'NLE_BL_HUNGER'
] | self.llm = LocalLanguageModel(system_prompt=system_prompts[prompt_version], | 2 | 2023-10-24 17:45:26+00:00 | 4k |
kyegomez/PALI3 | pali3/main.py | [
{
"identifier": "UL2",
"path": "pali3/ul2.py",
"snippet": "class UL2(nn.Module):\n def __init__(\n self,\n *,\n dim,\n tie_token_emb=False,\n ignore_index=-100,\n pad_value=0,\n cross_attn_tokens_dropout=0.0,\n **kwargs,\n ):\n super()... | import torch
from torch import nn
from pali3.ul2 import UL2, ViTransformerWrapper, Encoder | 2,051 |
class PrependTokens(nn.Module):
"""
# Initialize models
vit_model = ViTModel()
text_embedding = TextEmbedding("bert-base-uncased")
# Initialize PrependVisualTokens
prepend_visual_tokens = PrependVisualTokens(vit_model, text_embedding)
# Process image and text
img = torch.randn(1, 3, 256, 256) # dummy image
text = "This is a sample text"
combined_tokens = prepend_visual_tokens.process(img, text)
"""
def __init__(
self,
vit,
text_embedding,
):
super().__init__()
self.vit = vit
self.text_embedding = text_embedding
def forward(self, x):
visual_tokens = self.vit.process(x)
text_tokens = self.text_embedding.process(x)
combined_tokens = torch.cat((visual_tokens, text_tokens), dim=1)
return combined_tokens
class VitModel:
"""
VitModel is a wrapper around the ViT model from the PyTorch Image Models library.
Args:
image_size (int, optional): Size of the image. Defaults to 256.
patch_size (int, optional): Size of the patch. Defaults to 32.
dim (int, optional): Dimension of the model. Defaults to 512.
depth (int, optional): Depth of the model. Defaults to 6.
heads (int, optional): Number of heads in the model. Defaults to 8.
Raises:
ValueError: If the input image is None.
ValueError: If the input image shape is not [*, 3, image_size, image_size].
Examples:
x = torch.randn(1, 3, 256, 256)
model = VitModel()
out = model.process(x)
print(out)
"""
def __init__(
self, image_size=256, patch_size=32, dim=512, depth=6, heads=8, *args, **kwargs
):
self.image_size = image_size
self.patch_size = patch_size
self.dim = dim
self.depth = depth
self.heads = heads
|
class PrependTokens(nn.Module):
"""
# Initialize models
vit_model = ViTModel()
text_embedding = TextEmbedding("bert-base-uncased")
# Initialize PrependVisualTokens
prepend_visual_tokens = PrependVisualTokens(vit_model, text_embedding)
# Process image and text
img = torch.randn(1, 3, 256, 256) # dummy image
text = "This is a sample text"
combined_tokens = prepend_visual_tokens.process(img, text)
"""
def __init__(
self,
vit,
text_embedding,
):
super().__init__()
self.vit = vit
self.text_embedding = text_embedding
def forward(self, x):
visual_tokens = self.vit.process(x)
text_tokens = self.text_embedding.process(x)
combined_tokens = torch.cat((visual_tokens, text_tokens), dim=1)
return combined_tokens
class VitModel:
"""
VitModel is a wrapper around the ViT model from the PyTorch Image Models library.
Args:
image_size (int, optional): Size of the image. Defaults to 256.
patch_size (int, optional): Size of the patch. Defaults to 32.
dim (int, optional): Dimension of the model. Defaults to 512.
depth (int, optional): Depth of the model. Defaults to 6.
heads (int, optional): Number of heads in the model. Defaults to 8.
Raises:
ValueError: If the input image is None.
ValueError: If the input image shape is not [*, 3, image_size, image_size].
Examples:
x = torch.randn(1, 3, 256, 256)
model = VitModel()
out = model.process(x)
print(out)
"""
def __init__(
self, image_size=256, patch_size=32, dim=512, depth=6, heads=8, *args, **kwargs
):
self.image_size = image_size
self.patch_size = patch_size
self.dim = dim
self.depth = depth
self.heads = heads
| self.vit = ViTransformerWrapper( | 1 | 2023-10-16 15:36:54+00:00 | 4k |
pgorecki/lato | tests/test_application_example_from_readme.py | [
{
"identifier": "Application",
"path": "lato/application.py",
"snippet": "class Application(ApplicationModule):\n dependency_provider_class = SimpleDependencyProvider\n\n def __init__(self, name=__name__, dependency_provider=None, **kwargs):\n super().__init__(name)\n self.dependency... | from uuid import uuid4
from lato import Application, Event, Task, TransactionContext | 1,973 |
class UserService:
def create_user(self, email, password):
...
class EmailService:
def send_welcome_email(self, email):
...
def test_application_example_from_readme():
|
class UserService:
def create_user(self, email, password):
...
class EmailService:
def send_welcome_email(self, email):
...
def test_application_example_from_readme(): | app = Application( | 0 | 2023-10-21 11:33:05+00:00 | 4k |
NVIDIA/trt-llm-rag-windows | app.py | [
{
"identifier": "TrtLlmAPI",
"path": "trt_llama_api.py",
"snippet": "class TrtLlmAPI(CustomLLM):\n model_path: Optional[str] = Field(\n description=\"The path to the trt engine.\"\n )\n temperature: float = Field(description=\"The temperature to use for sampling.\")\n max_new_tokens: ... | import time
import gradio as gr
import argparse
from trt_llama_api import TrtLlmAPI #llama_index does not currently support TRT-LLM. The trt_llama_api.py file defines a llama_index compatible interface for TRT-LLM.
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from llama_index import LangchainEmbedding, ServiceContext
from llama_index.llms.llama_utils import messages_to_prompt, completion_to_prompt
from llama_index import set_global_service_context
from faiss_vector_storage import FaissEmbeddingStorage | 3,532 | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# Create an argument parser
parser = argparse.ArgumentParser(description='NVIDIA Chatbot Parameters')
# Add arguments
parser.add_argument('--trt_engine_path', type=str, required=True,
help="Path to the TensorRT engine.", default="")
parser.add_argument('--trt_engine_name', type=str, required=True,
help="Name of the TensorRT engine.", default="")
parser.add_argument('--tokenizer_dir_path', type=str, required=True,
help="Directory path for the tokenizer.", default="")
parser.add_argument('--embedded_model', type=str,
help="Name or path of the embedded model. Defaults to 'sentence-transformers/all-MiniLM-L6-v2' if "
"not provided.",
default='sentence-transformers/all-MiniLM-L6-v2')
parser.add_argument('--data_dir', type=str, required=False,
help="Directory path for data.", default="./dataset")
parser.add_argument('--verbose', type=bool, required=False,
help="Enable verbose logging.", default=False)
# Parse the arguments
args = parser.parse_args()
# Use the provided arguments
trt_engine_path = args.trt_engine_path
trt_engine_name = args.trt_engine_name
tokenizer_dir_path = args.tokenizer_dir_path
embedded_model = args.embedded_model
data_dir = args.data_dir
verbose = args.verbose
# create trt_llm engine object
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# Create an argument parser
parser = argparse.ArgumentParser(description='NVIDIA Chatbot Parameters')
# Add arguments
parser.add_argument('--trt_engine_path', type=str, required=True,
help="Path to the TensorRT engine.", default="")
parser.add_argument('--trt_engine_name', type=str, required=True,
help="Name of the TensorRT engine.", default="")
parser.add_argument('--tokenizer_dir_path', type=str, required=True,
help="Directory path for the tokenizer.", default="")
parser.add_argument('--embedded_model', type=str,
help="Name or path of the embedded model. Defaults to 'sentence-transformers/all-MiniLM-L6-v2' if "
"not provided.",
default='sentence-transformers/all-MiniLM-L6-v2')
parser.add_argument('--data_dir', type=str, required=False,
help="Directory path for data.", default="./dataset")
parser.add_argument('--verbose', type=bool, required=False,
help="Enable verbose logging.", default=False)
# Parse the arguments
args = parser.parse_args()
# Use the provided arguments
trt_engine_path = args.trt_engine_path
trt_engine_name = args.trt_engine_name
tokenizer_dir_path = args.tokenizer_dir_path
embedded_model = args.embedded_model
data_dir = args.data_dir
verbose = args.verbose
# create trt_llm engine object | llm = TrtLlmAPI( | 0 | 2023-10-18 12:57:53+00:00 | 4k |
instadeepai/flashbax | flashbax/buffers/prioritised_flat_buffer.py | [
{
"identifier": "ExperiencePair",
"path": "flashbax/buffers/flat_buffer.py",
"snippet": "class ExperiencePair(NamedTuple, Generic[Experience]):\n first: Experience\n second: Experience"
},
{
"identifier": "TransitionSample",
"path": "flashbax/buffers/flat_buffer.py",
"snippet": "cl... | import warnings
import jax
from typing import TYPE_CHECKING, Optional
from chex import PRNGKey
from flashbax.buffers.flat_buffer import (
ExperiencePair,
TransitionSample,
validate_flat_buffer_args,
)
from flashbax.buffers.prioritised_trajectory_buffer import (
Indices,
PrioritisedTrajectoryBuffer,
PrioritisedTrajectoryBufferState,
Probabilities,
make_prioritised_trajectory_buffer,
validate_device,
)
from dataclasses import dataclass
from chex import dataclass
from flashbax.utils import add_dim_to_args | 1,917 | # Copyright 2023 InstaDeep Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if TYPE_CHECKING: # https://github.com/python/mypy/issues/6239
else:
@dataclass(frozen=True)
class PrioritisedTransitionSample(TransitionSample):
indices: Indices
priorities: Probabilities
def validate_priority_exponent(priority_exponent: float) -> None:
"""Validates the priority exponent."""
if priority_exponent < 0 or priority_exponent > 1:
raise ValueError(
f"priority_exponent must be in the range [0, 1], but was {priority_exponent}"
)
def make_prioritised_flat_buffer(
max_length: int,
min_length: int,
sample_batch_size: int,
add_sequences: bool = False,
add_batch_size: Optional[int] = None,
priority_exponent: float = 0.6,
device: str = "cpu",
| # Copyright 2023 InstaDeep Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if TYPE_CHECKING: # https://github.com/python/mypy/issues/6239
else:
@dataclass(frozen=True)
class PrioritisedTransitionSample(TransitionSample):
indices: Indices
priorities: Probabilities
def validate_priority_exponent(priority_exponent: float) -> None:
"""Validates the priority exponent."""
if priority_exponent < 0 or priority_exponent > 1:
raise ValueError(
f"priority_exponent must be in the range [0, 1], but was {priority_exponent}"
)
def make_prioritised_flat_buffer(
max_length: int,
min_length: int,
sample_batch_size: int,
add_sequences: bool = False,
add_batch_size: Optional[int] = None,
priority_exponent: float = 0.6,
device: str = "cpu", | ) -> PrioritisedTrajectoryBuffer: | 3 | 2023-10-17 10:57:14+00:00 | 4k |
TheDuckAI/DuckTrack | ducktrack/app.py | [
{
"identifier": "close_obs",
"path": "ducktrack/obs_client.py",
"snippet": "def close_obs(obs_process: subprocess.Popen):\n if obs_process:\n obs_process.terminate()\n try:\n obs_process.wait(timeout=5)\n except subprocess.TimeoutExpired:\n obs_process.kill(... | import os
import sys
from platform import system
from PyQt6.QtCore import QTimer, pyqtSlot
from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog,
QFormLayout, QLabel, QLineEdit, QMenu,
QMessageBox, QPushButton, QSystemTrayIcon,
QTextEdit, QVBoxLayout, QWidget)
from .obs_client import close_obs, is_obs_running, open_obs
from .playback import Player, get_latest_recording
from .recorder import Recorder
from .util import get_recordings_dir, open_file | 3,316 |
class TitleDescriptionDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Recording Details")
layout = QVBoxLayout(self)
self.form_layout = QFormLayout()
self.title_label = QLabel("Title:")
self.title_input = QLineEdit(self)
self.form_layout.addRow(self.title_label, self.title_input)
self.description_label = QLabel("Description:")
self.description_input = QTextEdit(self)
self.form_layout.addRow(self.description_label, self.description_input)
layout.addLayout(self.form_layout)
self.submit_button = QPushButton("Save", self)
self.submit_button.clicked.connect(self.accept)
layout.addWidget(self.submit_button)
def get_values(self):
return self.title_input.text(), self.description_input.toPlainText()
class MainInterface(QWidget):
def __init__(self, app: QApplication):
super().__init__()
self.tray = QSystemTrayIcon(QIcon(resource_path("assets/duck.png")))
self.tray.show()
self.app = app
self.init_tray()
self.init_window()
if not is_obs_running():
self.obs_process = open_obs()
def init_window(self):
self.setWindowTitle("DuckTrack")
layout = QVBoxLayout(self)
self.toggle_record_button = QPushButton("Start Recording", self)
self.toggle_record_button.clicked.connect(self.toggle_record)
layout.addWidget(self.toggle_record_button)
self.toggle_pause_button = QPushButton("Pause Recording", self)
self.toggle_pause_button.clicked.connect(self.toggle_pause)
self.toggle_pause_button.setEnabled(False)
layout.addWidget(self.toggle_pause_button)
self.show_recordings_button = QPushButton("Show Recordings", self)
|
class TitleDescriptionDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Recording Details")
layout = QVBoxLayout(self)
self.form_layout = QFormLayout()
self.title_label = QLabel("Title:")
self.title_input = QLineEdit(self)
self.form_layout.addRow(self.title_label, self.title_input)
self.description_label = QLabel("Description:")
self.description_input = QTextEdit(self)
self.form_layout.addRow(self.description_label, self.description_input)
layout.addLayout(self.form_layout)
self.submit_button = QPushButton("Save", self)
self.submit_button.clicked.connect(self.accept)
layout.addWidget(self.submit_button)
def get_values(self):
return self.title_input.text(), self.description_input.toPlainText()
class MainInterface(QWidget):
def __init__(self, app: QApplication):
super().__init__()
self.tray = QSystemTrayIcon(QIcon(resource_path("assets/duck.png")))
self.tray.show()
self.app = app
self.init_tray()
self.init_window()
if not is_obs_running():
self.obs_process = open_obs()
def init_window(self):
self.setWindowTitle("DuckTrack")
layout = QVBoxLayout(self)
self.toggle_record_button = QPushButton("Start Recording", self)
self.toggle_record_button.clicked.connect(self.toggle_record)
layout.addWidget(self.toggle_record_button)
self.toggle_pause_button = QPushButton("Pause Recording", self)
self.toggle_pause_button.clicked.connect(self.toggle_pause)
self.toggle_pause_button.setEnabled(False)
layout.addWidget(self.toggle_pause_button)
self.show_recordings_button = QPushButton("Show Recordings", self) | self.show_recordings_button.clicked.connect(lambda: open_file(get_recordings_dir())) | 6 | 2023-10-18 19:34:19+00:00 | 4k |
e4s2023/E4S2023 | swap_face_fine/Blender/model_center/blener.py | [
{
"identifier": "Referencer",
"path": "swap_face_fine/Blender/model_center/referencer.py",
"snippet": "class Referencer(nn.Module):\n def __init__(self, args):\n super(Referencer, self).__init__()\n self.args = args\n if args.small_FPN:\n self.FPN = SmallFPN()\n ... | import torch
import torch.nn as nn
from .referencer import Referencer
from .res_u_net import ResUNet | 1,705 |
class Blender(nn.Module):
def __init__(self, args):
super(Blender, self).__init__()
self.referencer = Referencer(args)
|
class Blender(nn.Module):
def __init__(self, args):
super(Blender, self).__init__()
self.referencer = Referencer(args) | self.unet = ResUNet(args) | 1 | 2023-10-15 12:15:01+00:00 | 4k |
riverscn/epghub | epg/plugin/weibo_cctv9.py | [
{
"identifier": "search",
"path": "epg/plugin/__weibo_search.py",
"snippet": "def search(keyword: str, page: int = 1) -> list:\n \"\"\"\n Search weibo by keyword.\n\n Args:\n keyword (str): The keyword to search.\n page (int): The page number to search.\n\n Returns:\n ... | from .__weibo_search import search as weibo_search
from .__weibo_search import headers
from datetime import date, datetime, timedelta
from epg.model import Channel, Program
import re
import requests
import json | 1,739 |
keyword = "#每日央视纪录片精选#"
def update_programs(programs: list[Program], programs_new: list[Program]) -> int:
"""
Update programs with new programs.
Args:
programs (list[Program]): The programs to update.
programs_new (list[Program]): The new programs.
Returns:
int: The number of programs updated.
"""
num_updated_programs = 0
for program_new in programs_new:
for program in programs:
if program_new.start_time - program.start_time < timedelta(minutes=5):
program.title = program_new.title
num_updated_programs += 1
break
return num_updated_programs
|
keyword = "#每日央视纪录片精选#"
def update_programs(programs: list[Program], programs_new: list[Program]) -> int:
"""
Update programs with new programs.
Args:
programs (list[Program]): The programs to update.
programs_new (list[Program]): The new programs.
Returns:
int: The number of programs updated.
"""
num_updated_programs = 0
for program_new in programs_new:
for program in programs:
if program_new.start_time - program.start_time < timedelta(minutes=5):
program.title = program_new.title
num_updated_programs += 1
break
return num_updated_programs
| def update(channel: Channel, date: date) -> int: | 2 | 2023-10-20 04:35:12+00:00 | 4k |
Aggify/aggify | tests/test_aggify.py | [
{
"identifier": "Aggify",
"path": "aggify/aggify.py",
"snippet": "def last_out_stage_check(method: AggifyType) -> AggifyType:\n def decorator(*args, **kwargs):\n def __init__(self, base_model: Type[Document]):\n def __iter__(self):\n def project(self, **kwargs: QueryParams) -> \"Aggify\":\n ... | import pytest
from mongoengine import Document, IntField, StringField
from aggify import Aggify, Cond, F, Q
from aggify.exceptions import (
AggifyValueError,
AnnotationError,
OutStageError,
InvalidArgument,
InvalidField,
InvalidOperator,
AlreadyExistsField,
InvalidEmbeddedField,
MongoIndexError,
InvalidProjection,
InvalidAnnotateExpression,
) | 2,565 |
class BaseModel(Document):
# Define your fields here
name = StringField(max_length=100)
age = IntField()
meta = {"allow_inheritance": True, "abstract": True}
# This defines a base document model for MongoDB using MongoEngine, with 'name' and 'age' fields.
# The 'allow_inheritance' and 'abstract' options ensure it's used as a base class for other documents.
class TestAggify:
def test__getitem__zero(self):
aggify = Aggify(BaseModel)
assert aggify[0]
def test__getitem__slice(self):
aggify = Aggify(BaseModel)
thing = aggify[0:10]
assert isinstance(thing, Aggify)
assert thing.pipelines[-1]["$limit"] == 10
assert thing.pipelines[-2]["$skip"] == 0
def test__getitem__value_error(self):
with pytest.raises(AggifyValueError) as err:
Aggify(BaseModel)["hello"] # type: ignore # noqa
assert "str" in err.__str__(), "wrong type was not detected"
def test_filtering_and_projection(self):
aggify = Aggify(BaseModel)
aggify.filter(age__gte=30).project(name=1, age=1)
assert len(aggify.pipelines) == 2
assert aggify.pipelines[1]["$project"] == {"name": 1, "age": 1}
assert list(aggify.base_model._fields.keys()) == ["name", "age", "id"]
def test_filtering_and_projection_with_deleting_id(self):
aggify = Aggify(BaseModel)
aggify.filter(age__gte=30).project(name=1, age=1, id=0)
assert len(aggify.pipelines) == 2
assert aggify.pipelines[1]["$project"] == {"_id": 0, "name": 1, "age": 1}
assert list(aggify.base_model._fields.keys()) == ["name", "age"]
def test_filtering_and_ordering(self):
aggify = Aggify(BaseModel)
aggify.filter(age__gte=30).order_by("-age")
assert len(aggify.pipelines) == 2
assert aggify.pipelines[1]["$sort"] == {"age": -1}
# Test multiple filters and complex conditions
def test_multiple_filters_and_conditions(self):
aggify = Aggify(BaseModel)
age = F("age") * 2
|
class BaseModel(Document):
# Define your fields here
name = StringField(max_length=100)
age = IntField()
meta = {"allow_inheritance": True, "abstract": True}
# This defines a base document model for MongoDB using MongoEngine, with 'name' and 'age' fields.
# The 'allow_inheritance' and 'abstract' options ensure it's used as a base class for other documents.
class TestAggify:
def test__getitem__zero(self):
aggify = Aggify(BaseModel)
assert aggify[0]
def test__getitem__slice(self):
aggify = Aggify(BaseModel)
thing = aggify[0:10]
assert isinstance(thing, Aggify)
assert thing.pipelines[-1]["$limit"] == 10
assert thing.pipelines[-2]["$skip"] == 0
def test__getitem__value_error(self):
with pytest.raises(AggifyValueError) as err:
Aggify(BaseModel)["hello"] # type: ignore # noqa
assert "str" in err.__str__(), "wrong type was not detected"
def test_filtering_and_projection(self):
aggify = Aggify(BaseModel)
aggify.filter(age__gte=30).project(name=1, age=1)
assert len(aggify.pipelines) == 2
assert aggify.pipelines[1]["$project"] == {"name": 1, "age": 1}
assert list(aggify.base_model._fields.keys()) == ["name", "age", "id"]
def test_filtering_and_projection_with_deleting_id(self):
aggify = Aggify(BaseModel)
aggify.filter(age__gte=30).project(name=1, age=1, id=0)
assert len(aggify.pipelines) == 2
assert aggify.pipelines[1]["$project"] == {"_id": 0, "name": 1, "age": 1}
assert list(aggify.base_model._fields.keys()) == ["name", "age"]
def test_filtering_and_ordering(self):
aggify = Aggify(BaseModel)
aggify.filter(age__gte=30).order_by("-age")
assert len(aggify.pipelines) == 2
assert aggify.pipelines[1]["$sort"] == {"age": -1}
# Test multiple filters and complex conditions
def test_multiple_filters_and_conditions(self):
aggify = Aggify(BaseModel)
age = F("age") * 2 | aggify.filter(Q(name="John") | Q(name="Alice")).project( | 0 | 2023-10-22 07:53:28+00:00 | 4k |
sotopia-lab/sotopia | lmlib/serve/lm_inference.py | [
{
"identifier": "SeparatorStyle",
"path": "lmlib/utils/conversation.py",
"snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n TWO = auto()\n DOLLY = auto()\n OASST_PYTHIA = auto()\n BAIZE = auto()\n def get_prompt(self) -> str:\n def append_message(self, ... | import abc
import os
import os.path as osp
import warnings
import torch
import pdb
from typing import Any, Dict, List, Optional, Tuple, Union
from logzero import logger
from peft import PeftModel, set_peft_model_state_dict
from transformers import LlamaForCausalLM # type: ignore[attr-defined]
from transformers import LlamaTokenizer # type: ignore[attr-defined]
from lmlib.utils.conversation import (
SeparatorStyle,
compute_skip_echo_len,
conv_templates,
get_default_conv_template,
)
from lmlib.utils.data_utils import load_json
from lmlib.model_tools import (
load_and_cache_large_model,
load_and_cache_model,
)
from argparse import Namespace
from peft import get_peft_model
from transformers.trainer_utils import get_last_checkpoint | 2,307 | out = model(
input_ids=torch.as_tensor([input_ids], device=device),
use_cache=True,
encoder_outputs=encoder_outputs,
decoder_input_ids=torch.as_tensor(
[[token]], device=device
),
past_key_values=past_key_values,
)
logits = out.logits
past_key_values = out.past_key_values
else:
out = model(
input_ids=torch.as_tensor([[token]], device=device),
use_cache=True,
past_key_values=past_key_values,
)
logits = out.logits
past_key_values = out.past_key_values
last_token_logits = logits[0][-1]
if device == "mps":
# Switch to CPU by avoiding some bugs in mps backend.
last_token_logits = last_token_logits.float().to("cpu")
if temperature < 1e-4:
token = int(torch.argmax(last_token_logits))
else:
probs = torch.softmax(last_token_logits / temperature, dim=-1)
token = int(torch.multinomial(probs, num_samples=1))
output_ids.append(token)
if token in stop_token_ids:
stopped = True
else:
stopped = False
if i % stream_interval == 0 or i == max_new_tokens - 1 or stopped:
output = tokenizer.decode(output_ids, skip_special_tokens=True)
if stop_str:
pos = output.rfind(stop_str, l_prompt)
if pos != -1:
output = output[:pos]
stopped = True
yield output
if stopped:
break
del past_key_values
class ChatIO(abc.ABC):
@abc.abstractmethod
def prompt_for_input(self, role: str) -> str:
"""Prompt for input from a role."""
@abc.abstractmethod
def prompt_for_output(self, role: str) -> None:
"""Prompt for output from a role."""
@abc.abstractmethod
def stream_output(self, output_stream: Any, skip_echo_len: int) -> str:
"""Stream output."""
def chat_loop(
args: Any,
model_path: str,
cache_dir: str,
device: str,
num_gpus: str,
max_gpu_memory: str,
load_8bit: bool,
conv_template: Optional[str],
temperature: float,
max_new_tokens: int,
chatio: ChatIO,
debug: bool,
) -> None:
# Model
int8 = args.load_8bit
lora_path = args.lora_weight_path
model, tokenizer = load_gen_model(
model_path,
cache_dir,
large_model=int8,
device="cuda:0",
lora_path=lora_path,
)
is_chatglm = False # "chatglm" in str(type(model)).lower()
# Chat
if conv_template:
conv = conv_templates[conv_template].copy()
else:
conv = get_default_conv_template("vicuna_character").copy()
# import pdb; pdb.set_trace()
def chat() -> None:
while True:
try:
inp = chatio.prompt_for_input(conv.roles[0])
except EOFError:
inp = ""
if not inp:
print("exit...")
break
# import pdb; pdb.set_trace()
conv.append_message(conv.roles[0], inp)
conv.append_message(conv.roles[1], "")
# if is_chatglm:
# prompt = conv.messages[conv.offset :]
# generate_stream_func = chatglm_generate_stream
# else:
generate_stream_func = generate_stream
prompt = conv.get_prompt()
| """Inference for FastChat models."""
# try:
# from transformers import (
# AutoModel,
# AutoModelForCausalLM,
# AutoModelForSeq2SeqLM,
# LlamaForCausalLM,
# LlamaTokenizer,
# )
# except ImportError:
# from transformers import (
# AutoModelForCausalLM,
# LLaMATokenizer,
# LLamaForCausalLM,
# AutoModel,
# AutoModelForSeq2SeqLM,
# )
# from lmlib.serve.compression import compress_module
# from lmlib.serve.monkey_patch_non_inplace import (
# replace_llama_attn_with_non_inplace_operations,
# )
# from lmlib.serve.serve_chatglm import chatglm_generate_stream
def get_gpu_memory(max_gpus: Union[int, None] = None) -> list[float]:
gpu_memory = []
num_gpus = (
torch.cuda.device_count()
if max_gpus is None
else min(max_gpus, torch.cuda.device_count())
)
for gpu_id in range(num_gpus):
with torch.cuda.device(gpu_id):
device = torch.cuda.current_device()
gpu_properties = torch.cuda.get_device_properties(device)
total_memory = gpu_properties.total_memory / (1024**3) # type: ignore
allocated_memory = torch.cuda.memory_allocated() / (1024**3)
available_memory = total_memory - allocated_memory
gpu_memory.append(available_memory)
return gpu_memory
def load_gen_model(
gen_model_name: str,
cache_dir: str,
large_model: bool = False,
device: str = "cuda",
lora_path: Union[str, None] = None,
margs: Dict[str, Any] = {},
) -> Any:
if large_model:
gen_model = load_and_cache_large_model(
gen_model_name, cache_dir=cache_dir, device=device
)
else:
# margs = {"revision": "float16", "torch_dtype": torch.float16, "low_cpu_mem_usage": True}
gen_model = load_and_cache_model(
gen_model_name, cache_dir=cache_dir, margs=margs
)
gen_model = gen_model.to(device)
if lora_path is not None:
logger.info(f"load lora from {lora_path}")
lora_config_json = load_json(
osp.join(lora_path, "adapter_config.json")
)
lora_config = Namespace(**lora_config_json)
gen_model = get_peft_model(gen_model, lora_config)
ckpt_path = get_last_checkpoint(lora_path)
if ckpt_path is None:
gen_model = PeftModel.from_pretrained(
gen_model,
lora_path,
torch_dtype=torch.float16,
)
else:
checkpoint_name = os.path.join(ckpt_path, "pytorch_model.bin")
adapter_weigths = torch.load(checkpoint_name)
set_peft_model_state_dict(gen_model, adapter_weigths)
gen_tokenizer = LlamaTokenizer.from_pretrained(
gen_model_name, cache_dir=cache_dir
)
# use the vicuna version of special tokens
gen_tokenizer.add_special_tokens(
{
"bos_token": "<s>",
"eos_token": "</s>",
"unk_token": "<unk>",
"pad_token": "<unk>",
}
)
return gen_model, gen_tokenizer
@torch.inference_mode()
def generate_stream(
model: Any,
tokenizer: Any,
params: Any,
device: str,
context_len: int = 2048,
stream_interval: int = 2,
) -> Any:
prompt = params["prompt"]
l_prompt = len(prompt)
temperature = float(params.get("temperature", 1.0))
max_new_tokens = int(params.get("max_new_tokens", 256))
stop_str = params.get("stop", None)
stop_token_ids = params.get("stop_ids", [tokenizer.eos_token_id])
input_ids = tokenizer(prompt).input_ids
output_ids = list(input_ids)
max_src_len = context_len - max_new_tokens - 8
input_ids = input_ids[-max_src_len:]
token = 0
for i in range(max_new_tokens):
if i == 0:
if model.config.is_encoder_decoder:
encoder_outputs = model.encoder(
input_ids=torch.as_tensor([input_ids], device=device)
)
out = model(
torch.as_tensor([input_ids], device=device),
decoder_input_ids=torch.as_tensor(
[[model.generation_config.decoder_start_token_id]],
device=device,
),
encoder_outputs=encoder_outputs,
use_cache=True,
)
logits = out.logits
past_key_values = out.past_key_values
else:
out = model(
torch.as_tensor([input_ids], device=device), use_cache=True
)
logits = out.logits
past_key_values = out.past_key_values
else:
if model.config.is_encoder_decoder:
out = model(
input_ids=torch.as_tensor([input_ids], device=device),
use_cache=True,
encoder_outputs=encoder_outputs,
decoder_input_ids=torch.as_tensor(
[[token]], device=device
),
past_key_values=past_key_values,
)
logits = out.logits
past_key_values = out.past_key_values
else:
out = model(
input_ids=torch.as_tensor([[token]], device=device),
use_cache=True,
past_key_values=past_key_values,
)
logits = out.logits
past_key_values = out.past_key_values
last_token_logits = logits[0][-1]
if device == "mps":
# Switch to CPU by avoiding some bugs in mps backend.
last_token_logits = last_token_logits.float().to("cpu")
if temperature < 1e-4:
token = int(torch.argmax(last_token_logits))
else:
probs = torch.softmax(last_token_logits / temperature, dim=-1)
token = int(torch.multinomial(probs, num_samples=1))
output_ids.append(token)
if token in stop_token_ids:
stopped = True
else:
stopped = False
if i % stream_interval == 0 or i == max_new_tokens - 1 or stopped:
output = tokenizer.decode(output_ids, skip_special_tokens=True)
if stop_str:
pos = output.rfind(stop_str, l_prompt)
if pos != -1:
output = output[:pos]
stopped = True
yield output
if stopped:
break
del past_key_values
class ChatIO(abc.ABC):
@abc.abstractmethod
def prompt_for_input(self, role: str) -> str:
"""Prompt for input from a role."""
@abc.abstractmethod
def prompt_for_output(self, role: str) -> None:
"""Prompt for output from a role."""
@abc.abstractmethod
def stream_output(self, output_stream: Any, skip_echo_len: int) -> str:
"""Stream output."""
def chat_loop(
args: Any,
model_path: str,
cache_dir: str,
device: str,
num_gpus: str,
max_gpu_memory: str,
load_8bit: bool,
conv_template: Optional[str],
temperature: float,
max_new_tokens: int,
chatio: ChatIO,
debug: bool,
) -> None:
# Model
int8 = args.load_8bit
lora_path = args.lora_weight_path
model, tokenizer = load_gen_model(
model_path,
cache_dir,
large_model=int8,
device="cuda:0",
lora_path=lora_path,
)
is_chatglm = False # "chatglm" in str(type(model)).lower()
# Chat
if conv_template:
conv = conv_templates[conv_template].copy()
else:
conv = get_default_conv_template("vicuna_character").copy()
# import pdb; pdb.set_trace()
def chat() -> None:
while True:
try:
inp = chatio.prompt_for_input(conv.roles[0])
except EOFError:
inp = ""
if not inp:
print("exit...")
break
# import pdb; pdb.set_trace()
conv.append_message(conv.roles[0], inp)
conv.append_message(conv.roles[1], "")
# if is_chatglm:
# prompt = conv.messages[conv.offset :]
# generate_stream_func = chatglm_generate_stream
# else:
generate_stream_func = generate_stream
prompt = conv.get_prompt()
| skip_echo_len = compute_skip_echo_len(conv, prompt) | 0 | 2023-10-23 19:47:26+00:00 | 4k |
Zai-Kun/reverse-engineered-chatgpt | re_gpt/async_chatgpt.py | [
{
"identifier": "BackendError",
"path": "re_gpt/errors.py",
"snippet": "class BackendError(Exception):\n def __init__(self, error_code):\n self.error_code = error_code\n self.message = (\n f\"An error occurred on the backend. Error code: {self.error_code}\"\n )\n ... | import asyncio
import ctypes
import inspect
import json
import uuid
from typing import AsyncGenerator, Callable, Optional
from curl_cffi.requests import AsyncSession
from .errors import (
BackendError,
InvalidSessionToken,
RetryError,
TokenNotProvided,
UnexpectedResponseError,
InvalidModelName,
)
from .utils import async_get_binary_path, get_model_slug | 2,643 | payload (dict): Payload containing message information.
Yields:
bytes: Chunk of data received as a response.
"""
response_queue = asyncio.Queue()
async def perform_request():
def content_callback(chunk):
response_queue.put_nowait(chunk)
url = CHATGPT_API.format("conversation")
await self.chatgpt.session.post(
url=url,
headers=self.chatgpt.build_request_headers(),
json=payload,
content_callback=content_callback,
)
await response_queue.put(None)
asyncio.create_task(perform_request())
while True:
chunk = await response_queue.get()
if chunk is None:
break
yield chunk
async def build_message_payload(self, user_input: str) -> dict:
"""
Build a payload for sending a user message.
Returns:
dict: Payload containing message information.
"""
if self.conversation_id and (self.parent_id is None or self.model is None):
await self.fetch_chat() # it will automatically fetch the chat and set the parent id
payload = {
"conversation_mode": {"conversation_mode": {"kind": "primary_assistant"}},
"conversation_id": self.conversation_id,
"action": "next",
"arkose_token": await self.arkose_token_generator()
if self.chatgpt.generate_arkose_token
or MODELS[self.model]["needs_arkose_token"]
else None,
"force_paragen": False,
"history_and_training_disabled": False,
"messages": [
{
"author": {"role": "user"},
"content": {"content_type": "text", "parts": [user_input]},
"id": str(uuid.uuid4()),
"metadata": {},
}
],
"model": MODELS[self.model]["slug"],
"parent_message_id": str(uuid.uuid4())
if not self.parent_id
else self.parent_id,
}
return payload
async def build_message_continuation_payload(self) -> dict:
"""
Build a payload for continuing ChatGPT's cut off response.
Returns:
dict: Payload containing message information for continuation.
"""
payload = {
"conversation_mode": {"conversation_mode": {"kind": "primary_assistant"}},
"action": "continue",
"arkose_token": await self.arkose_token_generator()
if self.chatgpt.generate_arkose_token
or MODELS[self.model]["needs_arkose_token"]
else None,
"conversation_id": self.conversation_id,
"force_paragen": False,
"history_and_training_disabled": False,
"model": MODELS[self.model]["slug"],
"parent_message_id": self.parent_id,
"timezone_offset_min": -300,
}
return payload
async def arkose_token_generator(self) -> str:
"""
Generate an Arkose token.
Returns:
str: Arkose token.
"""
if not self.chatgpt.tried_downloading_binary:
self.chatgpt.binary_path = await async_get_binary_path(self.chatgpt.session)
if self.chatgpt.binary_path:
self.chatgpt.arkose = ctypes.CDLL(self.chatgpt.binary_path)
self.chatgpt.arkose.GetToken.restype = ctypes.c_char_p
self.chatgpt.tried_downloading_binary = True
if self.chatgpt.binary_path:
try:
result = self.chatgpt.arkose.GetToken()
return ctypes.string_at(result).decode("utf-8")
except:
pass
for _ in range(5):
response = await self.chatgpt.session.get(BACKUP_ARKOSE_TOKEN_GENERATOR)
if response.text == "null":
raise BackendError(error_code=505)
try:
return response.json()["token"]
except:
await asyncio.sleep(0.7)
|
# Constants
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
CHATGPT_API = "https://chat.openai.com/backend-api/{}"
BACKUP_ARKOSE_TOKEN_GENERATOR = "https://arkose-token-generator.zaieem.repl.co/token"
MODELS = {
"gpt-4": {"slug": "gpt-4", "needs_arkose_token": True},
"gpt-3.5": {"slug": "text-davinci-002-render-sha", "needs_arkose_token": False},
}
class AsyncConversation:
def __init__(self, chatgpt, conversation_id=None, model=None):
self.chatgpt = chatgpt
self.conversation_id = conversation_id
self.parent_id = None
self.model = model
async def fetch_chat(self) -> dict:
"""
Fetches the chat of the conversation from the API.
Returns:
dict: The JSON response from the API containing the chat if the conversation_id is not none, else returns an empty dict.
Raises:
UnexpectedResponseError: If the response is not a valid JSON object or if the response json is not in the expected format
"""
if not self.conversation_id:
return {}
url = CHATGPT_API.format(f"conversation/{self.conversation_id}")
response = await self.chatgpt.session.get(
url=url, headers=self.chatgpt.build_request_headers()
)
error = None
try:
chat = response.json()
self.parent_id = list(chat.get("mapping", {}))[-1]
model_slug = get_model_slug(chat)
self.model = [
key for key, value in MODELS.items() if value["slug"] == model_slug
][0]
except Exception as e:
error = e
if error is not None:
raise UnexpectedResponseError(error, response.text)
return chat
async def chat(self, user_input: str) -> AsyncGenerator[dict, None]:
"""
As the name implies, chat with ChatGPT.
Args:
user_input (str): The user's input message.
Yields:
dict: A dictionary representing assistant responses.
Returns:
AsyncGenerator[dict, None]: An asynchronous generator object that yields assistant responses.
Raises:
UnexpectedResponseError: If the response is not a valid JSON object or if the response json is not in the expected format
"""
payload = await self.build_message_payload(user_input)
server_response = (
"" # To store what the server returned for debugging in case of an error
)
error = None
try:
full_message = None
while True:
response = self.send_message(payload=payload)
async for chunk in response:
decoded_chunk = chunk.decode()
server_response += decoded_chunk
for line in decoded_chunk.splitlines():
if not line.startswith("data: "):
continue
raw_json_data = line[6:]
if not (decoded_json := self.decode_raw_json(raw_json_data)):
continue
if (
"message" in decoded_json
and decoded_json["message"]["author"]["role"] == "assistant"
):
processed_response = self.filter_response(decoded_json)
if full_message:
prev_resp_len = len(
full_message["message"]["content"]["parts"][0]
)
processed_response["content"] = processed_response[
"content"
][prev_resp_len::]
yield processed_response
full_message = decoded_json
self.conversation_id = full_message["conversation_id"]
self.parent_id = full_message["message"]["id"]
if (
full_message["message"]["metadata"]["finish_details"]["type"]
== "max_tokens"
):
payload = await self.build_message_continuation_payload()
else:
break
except Exception as e:
error = e
# raising the error outside the 'except' block to prevent the 'During handling of the above exception, another exception occurred' error
if error is not None:
raise UnexpectedResponseError(error, server_response)
async def send_message(self, payload: dict) -> AsyncGenerator[bytes, None]:
"""
Send a message payload to the server and receive the response.
Args:
payload (dict): Payload containing message information.
Yields:
bytes: Chunk of data received as a response.
"""
response_queue = asyncio.Queue()
async def perform_request():
def content_callback(chunk):
response_queue.put_nowait(chunk)
url = CHATGPT_API.format("conversation")
await self.chatgpt.session.post(
url=url,
headers=self.chatgpt.build_request_headers(),
json=payload,
content_callback=content_callback,
)
await response_queue.put(None)
asyncio.create_task(perform_request())
while True:
chunk = await response_queue.get()
if chunk is None:
break
yield chunk
async def build_message_payload(self, user_input: str) -> dict:
"""
Build a payload for sending a user message.
Returns:
dict: Payload containing message information.
"""
if self.conversation_id and (self.parent_id is None or self.model is None):
await self.fetch_chat() # it will automatically fetch the chat and set the parent id
payload = {
"conversation_mode": {"conversation_mode": {"kind": "primary_assistant"}},
"conversation_id": self.conversation_id,
"action": "next",
"arkose_token": await self.arkose_token_generator()
if self.chatgpt.generate_arkose_token
or MODELS[self.model]["needs_arkose_token"]
else None,
"force_paragen": False,
"history_and_training_disabled": False,
"messages": [
{
"author": {"role": "user"},
"content": {"content_type": "text", "parts": [user_input]},
"id": str(uuid.uuid4()),
"metadata": {},
}
],
"model": MODELS[self.model]["slug"],
"parent_message_id": str(uuid.uuid4())
if not self.parent_id
else self.parent_id,
}
return payload
async def build_message_continuation_payload(self) -> dict:
"""
Build a payload for continuing ChatGPT's cut off response.
Returns:
dict: Payload containing message information for continuation.
"""
payload = {
"conversation_mode": {"conversation_mode": {"kind": "primary_assistant"}},
"action": "continue",
"arkose_token": await self.arkose_token_generator()
if self.chatgpt.generate_arkose_token
or MODELS[self.model]["needs_arkose_token"]
else None,
"conversation_id": self.conversation_id,
"force_paragen": False,
"history_and_training_disabled": False,
"model": MODELS[self.model]["slug"],
"parent_message_id": self.parent_id,
"timezone_offset_min": -300,
}
return payload
async def arkose_token_generator(self) -> str:
"""
Generate an Arkose token.
Returns:
str: Arkose token.
"""
if not self.chatgpt.tried_downloading_binary:
self.chatgpt.binary_path = await async_get_binary_path(self.chatgpt.session)
if self.chatgpt.binary_path:
self.chatgpt.arkose = ctypes.CDLL(self.chatgpt.binary_path)
self.chatgpt.arkose.GetToken.restype = ctypes.c_char_p
self.chatgpt.tried_downloading_binary = True
if self.chatgpt.binary_path:
try:
result = self.chatgpt.arkose.GetToken()
return ctypes.string_at(result).decode("utf-8")
except:
pass
for _ in range(5):
response = await self.chatgpt.session.get(BACKUP_ARKOSE_TOKEN_GENERATOR)
if response.text == "null":
raise BackendError(error_code=505)
try:
return response.json()["token"]
except:
await asyncio.sleep(0.7)
| raise RetryError(website=BACKUP_ARKOSE_TOKEN_GENERATOR) | 2 | 2023-10-17 08:34:04+00:00 | 4k |
qualabs/video-headline | utils/cloudfront.py | [
{
"identifier": "cloudfront_deleted",
"path": "video/signals.py",
"snippet": ""
},
{
"identifier": "Configuration",
"path": "configuration/models.py",
"snippet": "class Configuration(SingletonModel):\n slack_notifications_url = models.URLField(blank=True, null=True)\n cloud_front_c... | import boto3
from botocore.exceptions import ClientError
from celery import shared_task
from django.utils import timezone
from video.signals import cloudfront_deleted
from configuration.models import Configuration
from organization.models import AWSAccount
from video.models import LiveVideo
from organization.models import Channel
from video.models import LiveVideo | 2,395 | # skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
def update_distribution(organization, dist_id, status = False):
"""
If Organization is deleted the associated AWS CloudFront distribution
should be previously deleted too.
Steps:
- retrieve distribution config
- find & update 'Enabled' field value to disable distribution
- send updated configuration
See docs on [1]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.get_distribution_config
[2]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.update_distribution
"""
cloudfront = get_cloudfront_client(organization.aws_account)
try:
# GetDistributionConfig
cf_config = cloudfront.get_distribution_config(Id=dist_id)
cf_config_etag = cf_config['ETag']
# update 'Enabled' field to False
cf_config['DistributionConfig']['Enabled'] = status
return cloudfront.update_distribution(
Id=dist_id, IfMatch=cf_config_etag, DistributionConfig=cf_config['DistributionConfig']
)
except ClientError as ex:
# skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
def update_distribution_status(organization, dist_id, status = False):
"""
If Organization is deleted the associated AWS CloudFront distribution
should be previously deleted too.
Steps:
- retrieve distribution config
- find & update 'Enabled' field value to disable distribution
- send updated configuration
See docs on [1]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.get_distribution_config
[2]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.update_distribution
"""
cloudfront = get_cloudfront_client(organization.aws_account)
try:
# GetDistributionConfig
cf_config = cloudfront.get_distribution_config(Id=dist_id)
cf_config_etag = cf_config['ETag']
# update 'Enabled' field to False
cf_config['DistributionConfig']['Enabled'] = status
return cloudfront.update_distribution(
Id=dist_id, IfMatch=cf_config_etag, DistributionConfig=cf_config['DistributionConfig']
)
except ClientError as ex:
# skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
def update_distribution_geoblocking(dist_id, type, location, organization):
cloudfront = get_cloudfront_client(organization.aws_account)
try:
# GetDistributionConfig
cf_config = cloudfront.get_distribution_config(Id=dist_id)
cf_config_etag = cf_config['ETag']
# Geoblocking
cf_config = cf_config['DistributionConfig']
cf_config['Restrictions']['GeoRestriction']['RestrictionType'] = type
# Local import to avoid recursive import
if type == LiveVideo.GeoType.NONE:
location = []
cf_config['Restrictions']['GeoRestriction']['Quantity'] = len(location)
cf_config['Restrictions']['GeoRestriction']['Items'] = location
# upload new configuration
return cloudfront.update_distribution(
Id=dist_id, IfMatch=cf_config_etag, DistributionConfig=cf_config
)
except ClientError as ex:
# skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
@shared_task
def delete_distributions():
"""
Extract & mark for delete disabled CloudFront distributions.
See docs on https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.list_distributions
"""
video_dist_used = list(Channel.objects.all().values_list('cf_id', flat=True))
live_dist_used = list(LiveVideo.objects.all().values_list('cf_id', flat=True))
dist_used = video_dist_used + live_dist_used
|
def get_cloudfront_client(aws_account):
if aws_account:
cloudfront = boto3.client('cloudfront', aws_access_key_id=aws_account.access_key,
aws_secret_access_key=aws_account.secret_access_key,
region_name=aws_account.region)
else:
cloudfront = boto3.client('cloudfront')
return cloudfront
def create_distribution(settings, organization, channel):
"""
Generate CloudFront distribution, use global default profile configuration.
Replace conf settings, supplied values (keys):
-id: origin id
-domain: S3 bucker domain
-target: origin Id
-caller: operation unique id
minimum set of target keys (from base node) in profile JSON config file:
"Origins": { "Items": [{
"Id": origin id,
"DomainName": S3 bucker domain
}]
}
"DefaultCacheBehavior": {
"TargetOriginId": origin Id,
}
"CallerReference": operation unique id"
See docs on [1]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.create_distribution
[2]: >> default profile configuration on /configuration/cloud_front_configuration.sample
"""
global_config = Configuration.get_solo()
conf_cont = global_config.cloud_front_configuration
# get Origins/Items path, update & replace values
origin_conf = conf_cont['Origins']['Items'][0]
origin_conf['Id'] = settings['id']
origin_conf['DomainName'] = settings['domain']
conf_cont['Origins']['Items'] = [origin_conf]
# get & update TargetOriginId path
conf_cont['DefaultCacheBehavior']['TargetOriginId'] = settings['target']
# get & update CallerReference path
conf_cont['CallerReference'] = settings['caller']
# assign a path if specified
if settings.get('path'):
origin_conf['OriginPath'] = settings['path']
# change TTL of distribution if specified
if settings.get('maxTTL') and settings.get('defaultTTL'):
conf_cont['DefaultCacheBehavior']['DefaultTTL'] = settings['defaultTTL']
conf_cont['DefaultCacheBehavior']['MaxTTL'] = settings['maxTTL']
# Tags
tags = {
'Items': [{
'Key': 'vh:org-id',
'Value': str(organization.id),
},{
'Key': 'vh:channel-id',
'Value': str(channel.id),
}]
}
DistributionConfigWithTags = {
'DistributionConfig': conf_cont,
'Tags': tags
}
# create distribution
cloudfront = get_cloudfront_client(organization.aws_account)
new_dist = cloudfront.create_distribution_with_tags(DistributionConfigWithTags=DistributionConfigWithTags)
# recover & return new CloudFront distribution Id & DomainName
return {
'cf_id': new_dist['Distribution']['Id'],
'cf_domain': new_dist['Distribution']['DomainName']
}
def tag_distribution(organization, dist_id, tags):
"""
tags = [(key, value), ... , (key, value)]
"""
cloudfront = get_cloudfront_client(organization.aws_account)
try:
dist_arn = cloudfront.get_distribution(Id=dist_id)['Distribution']['ARN']
cloudfront.tag_resource(Resource=dist_arn, Tags={'Items': [{'Key': k, 'Value': v} for k, v in tags]})
except ClientError as ex:
# skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
def update_distribution(organization, dist_id, status = False):
"""
If Organization is deleted the associated AWS CloudFront distribution
should be previously deleted too.
Steps:
- retrieve distribution config
- find & update 'Enabled' field value to disable distribution
- send updated configuration
See docs on [1]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.get_distribution_config
[2]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.update_distribution
"""
cloudfront = get_cloudfront_client(organization.aws_account)
try:
# GetDistributionConfig
cf_config = cloudfront.get_distribution_config(Id=dist_id)
cf_config_etag = cf_config['ETag']
# update 'Enabled' field to False
cf_config['DistributionConfig']['Enabled'] = status
return cloudfront.update_distribution(
Id=dist_id, IfMatch=cf_config_etag, DistributionConfig=cf_config['DistributionConfig']
)
except ClientError as ex:
# skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
def update_distribution_status(organization, dist_id, status = False):
"""
If Organization is deleted the associated AWS CloudFront distribution
should be previously deleted too.
Steps:
- retrieve distribution config
- find & update 'Enabled' field value to disable distribution
- send updated configuration
See docs on [1]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.get_distribution_config
[2]: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.update_distribution
"""
cloudfront = get_cloudfront_client(organization.aws_account)
try:
# GetDistributionConfig
cf_config = cloudfront.get_distribution_config(Id=dist_id)
cf_config_etag = cf_config['ETag']
# update 'Enabled' field to False
cf_config['DistributionConfig']['Enabled'] = status
return cloudfront.update_distribution(
Id=dist_id, IfMatch=cf_config_etag, DistributionConfig=cf_config['DistributionConfig']
)
except ClientError as ex:
# skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
def update_distribution_geoblocking(dist_id, type, location, organization):
cloudfront = get_cloudfront_client(organization.aws_account)
try:
# GetDistributionConfig
cf_config = cloudfront.get_distribution_config(Id=dist_id)
cf_config_etag = cf_config['ETag']
# Geoblocking
cf_config = cf_config['DistributionConfig']
cf_config['Restrictions']['GeoRestriction']['RestrictionType'] = type
# Local import to avoid recursive import
if type == LiveVideo.GeoType.NONE:
location = []
cf_config['Restrictions']['GeoRestriction']['Quantity'] = len(location)
cf_config['Restrictions']['GeoRestriction']['Items'] = location
# upload new configuration
return cloudfront.update_distribution(
Id=dist_id, IfMatch=cf_config_etag, DistributionConfig=cf_config
)
except ClientError as ex:
# skip operation on distribution not exists operation
if ex.response['Error']['Code'] == 'NoSuchDistribution':
pass
else:
raise ex
@shared_task
def delete_distributions():
"""
Extract & mark for delete disabled CloudFront distributions.
See docs on https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.list_distributions
"""
video_dist_used = list(Channel.objects.all().values_list('cf_id', flat=True))
live_dist_used = list(LiveVideo.objects.all().values_list('cf_id', flat=True))
dist_used = video_dist_used + live_dist_used | for account in AWSAccount.objects.all(): | 2 | 2023-10-17 19:44:32+00:00 | 4k |
Qualcomm-AI-research/geometric-algebra-transformer | tests/gatr/interface/test_translation.py | [
{
"identifier": "embed_oriented_plane",
"path": "gatr/interface/plane.py",
"snippet": "def embed_oriented_plane(\n normal: torch.Tensor, position: Optional[torch.Tensor] = None\n) -> torch.Tensor:\n \"\"\"Embeds an (oriented plane) in the PGA.\n\n Following L. Dorst, the plane is represent as P... | import pytest
import torch
from gatr.interface import (
embed_oriented_plane,
embed_point,
embed_pseudoscalar,
embed_scalar,
embed_translation,
extract_oriented_plane,
extract_point,
extract_point_embedding_reg,
extract_pseudoscalar,
extract_scalar,
extract_translation,
)
from gatr.primitives import geometric_product, reverse
from tests.helpers import BATCH_DIMS, TOLERANCES | 3,574 | # Copyright (c) 2023 Qualcomm Technologies, Inc.
# All rights reserved.
@pytest.mark.parametrize("batch_dims", BATCH_DIMS)
def test_translation_embedding_consistency(batch_dims):
"""Tests whether translation embeddings into multivectors are cycle consistent."""
translations = torch.randn(*batch_dims, 3)
multivectors = embed_translation(translations)
translations_reencoded = extract_translation(multivectors)
| # Copyright (c) 2023 Qualcomm Technologies, Inc.
# All rights reserved.
@pytest.mark.parametrize("batch_dims", BATCH_DIMS)
def test_translation_embedding_consistency(batch_dims):
"""Tests whether translation embeddings into multivectors are cycle consistent."""
translations = torch.randn(*batch_dims, 3)
multivectors = embed_translation(translations)
translations_reencoded = extract_translation(multivectors) | torch.testing.assert_close(translations, translations_reencoded, **TOLERANCES) | 14 | 2023-10-23 15:58:36+00:00 | 4k |
StanislavPetrovV/Wolfenstein-3D-Clone | game_objects/npc.py | [
{
"identifier": "GameObject",
"path": "game_objects/game_object.py",
"snippet": "class GameObject:\n def __init__(self, level_map, tex_id, x, z):\n self.eng = level_map.eng\n self.app = self.eng.app\n self.tex_id = tex_id\n #\n self.pos = glm.vec3(x + H_WALL_SIZE, 0... | from settings import *
from game_objects.game_object import GameObject
from game_objects.item import Item
import random | 1,613 | #
self.animate()
# set current texture
self.tex_id = self.state_tex_id + self.frame
def get_damage(self):
self.health -= WEAPON_SETTINGS[self.player.weapon_id]['damage']
self.is_hurt = True
#
if not self.is_player_spotted:
self.is_player_spotted = True
def attack(self):
if not self.is_player_spotted:
return False
if glm.length(self.player.position.xz - self.pos.xz) > self.attack_dist:
return False
dir_to_player = glm.normalize(self.player.position - self.pos)
#
if self.eng.ray_casting.run(start_pos=self.pos, direction=dir_to_player):
self.set_state(state='attack')
if self.app.sound_trigger:
self.play(self.sound.enemy_attack[self.npc_id])
if random.random() < self.hit_probability:
self.player.health -= self.damage
#
self.play(self.sound.player_hurt)
return True
def get_path_to_player(self):
if not self.is_player_spotted:
return None
self.path_to_player = self.eng.path_finder.find(
start_pos=self.tile_pos,
end_pos=self.player.tile_pos
)
def move_to_player(self):
if not self.path_to_player:
return None
# set state
self.set_state(state='walk')
# step to player
dir_vec = glm.normalize(glm.vec2(self.path_to_player) + H_WALL_SIZE - self.pos.xz)
delta_vec = dir_vec * self.speed * self.app.delta_time
# collisions
if not self.is_collide(dx=delta_vec[0]):
self.pos.x += delta_vec[0]
if not self.is_collide(dz=delta_vec[1]):
self.pos.z += delta_vec[1]
# open door
door_map = self.level_map.door_map
if self.tile_pos in door_map:
door = door_map[self.tile_pos]
if door.is_closed and not door.is_moving:
door.is_moving = True
#
self.play(self.sound.open_door)
# translate
self.m_model = self.get_model_matrix()
def is_collide(self, dx=0, dz=0):
int_pos = (
int(self.pos.x + dx + (self.size if dx > 0 else -self.size if dx < 0 else 0)),
int(self.pos.z + dz + (self.size if dz > 0 else -self.size if dz < 0 else 0))
)
return (int_pos in self.level_map.wall_map or
int_pos in (self.level_map.npc_map.keys() - {self.tile_pos}))
def update_tile_position(self):
self.tile_pos = int(self.pos.x), int(self.pos.z)
def ray_to_player(self):
if self.is_player_spotted:
return None
dir_to_player = glm.normalize(self.player.position - self.pos)
#
if self.eng.ray_casting.run(start_pos=self.pos, direction=dir_to_player):
self.is_player_spotted = True
#
self.play(self.sound.spotted[self.npc_id])
def set_state(self, state):
self.num_frames = NPC_SETTINGS[self.npc_id]['num_frames'][state]
self.state_tex_id = NPC_SETTINGS[self.npc_id]['state_tex_id'][state]
self.frame %= self.num_frames
def animate(self):
if not (self.is_animate and self.app.anim_trigger):
return None
self.anim_counter += 1
#
if self.anim_counter == self.anim_periods:
self.anim_counter = 0
self.frame = (self.frame + 1) % self.num_frames
#
if self.is_hurt:
self.is_hurt = False
#
elif not self.is_alive and self.frame == self.num_frames - 1:
self.is_animate = False
#
self.to_drop_item()
#
self.play(self.eng.sound.death[self.npc_id])
def to_drop_item(self):
if self.drop_item is not None:
|
class NPC(GameObject):
def __init__(self, level_map, tex_id, x, z):
super().__init__(level_map, tex_id, x, z)
self.level_map = level_map
self.player = self.eng.player
self.npc_id = tex_id
#
self.scale = NPC_SETTINGS[self.npc_id]['scale']
self.speed = NPC_SETTINGS[self.npc_id]['speed']
self.size = NPC_SETTINGS[self.npc_id]['size']
self.attack_dist = NPC_SETTINGS[self.npc_id]['attack_dist']
self.health = NPC_SETTINGS[self.npc_id]['health']
self.damage = NPC_SETTINGS[self.npc_id]['damage']
self.hit_probability = NPC_SETTINGS[self.npc_id]['hit_probability']
self.drop_item = NPC_SETTINGS[self.npc_id]['drop_item']
#
self.anim_periods = NPC_SETTINGS[self.npc_id]['anim_periods']
self.anim_counter = 0
self.frame = 0
self.is_animate = True
# current state: walk, attack, hurt, death
self.num_frames, self.state_tex_id = None, None
self.set_state(state='walk')
#
self.tile_pos: Tuple[int, int] = None
#
self.is_player_spotted: bool = False
self.path_to_player: Tuple[int, int] = None
#
self.is_alive = True
self.is_hurt = False
#
self.play = self.eng.sound.play
self.sound = self.eng.sound
#
self.m_model = self.get_model_matrix()
self.update_tile_position()
def update(self):
if self.is_hurt:
self.set_state(state='hurt')
#
elif self.health > 0:
self.update_tile_position()
self.ray_to_player()
self.get_path_to_player()
#
if not self.attack():
self.move_to_player()
else:
self.is_alive = False
self.set_state('death')
#
self.animate()
# set current texture
self.tex_id = self.state_tex_id + self.frame
def get_damage(self):
self.health -= WEAPON_SETTINGS[self.player.weapon_id]['damage']
self.is_hurt = True
#
if not self.is_player_spotted:
self.is_player_spotted = True
def attack(self):
if not self.is_player_spotted:
return False
if glm.length(self.player.position.xz - self.pos.xz) > self.attack_dist:
return False
dir_to_player = glm.normalize(self.player.position - self.pos)
#
if self.eng.ray_casting.run(start_pos=self.pos, direction=dir_to_player):
self.set_state(state='attack')
if self.app.sound_trigger:
self.play(self.sound.enemy_attack[self.npc_id])
if random.random() < self.hit_probability:
self.player.health -= self.damage
#
self.play(self.sound.player_hurt)
return True
def get_path_to_player(self):
if not self.is_player_spotted:
return None
self.path_to_player = self.eng.path_finder.find(
start_pos=self.tile_pos,
end_pos=self.player.tile_pos
)
def move_to_player(self):
if not self.path_to_player:
return None
# set state
self.set_state(state='walk')
# step to player
dir_vec = glm.normalize(glm.vec2(self.path_to_player) + H_WALL_SIZE - self.pos.xz)
delta_vec = dir_vec * self.speed * self.app.delta_time
# collisions
if not self.is_collide(dx=delta_vec[0]):
self.pos.x += delta_vec[0]
if not self.is_collide(dz=delta_vec[1]):
self.pos.z += delta_vec[1]
# open door
door_map = self.level_map.door_map
if self.tile_pos in door_map:
door = door_map[self.tile_pos]
if door.is_closed and not door.is_moving:
door.is_moving = True
#
self.play(self.sound.open_door)
# translate
self.m_model = self.get_model_matrix()
def is_collide(self, dx=0, dz=0):
int_pos = (
int(self.pos.x + dx + (self.size if dx > 0 else -self.size if dx < 0 else 0)),
int(self.pos.z + dz + (self.size if dz > 0 else -self.size if dz < 0 else 0))
)
return (int_pos in self.level_map.wall_map or
int_pos in (self.level_map.npc_map.keys() - {self.tile_pos}))
def update_tile_position(self):
self.tile_pos = int(self.pos.x), int(self.pos.z)
def ray_to_player(self):
if self.is_player_spotted:
return None
dir_to_player = glm.normalize(self.player.position - self.pos)
#
if self.eng.ray_casting.run(start_pos=self.pos, direction=dir_to_player):
self.is_player_spotted = True
#
self.play(self.sound.spotted[self.npc_id])
def set_state(self, state):
self.num_frames = NPC_SETTINGS[self.npc_id]['num_frames'][state]
self.state_tex_id = NPC_SETTINGS[self.npc_id]['state_tex_id'][state]
self.frame %= self.num_frames
def animate(self):
if not (self.is_animate and self.app.anim_trigger):
return None
self.anim_counter += 1
#
if self.anim_counter == self.anim_periods:
self.anim_counter = 0
self.frame = (self.frame + 1) % self.num_frames
#
if self.is_hurt:
self.is_hurt = False
#
elif not self.is_alive and self.frame == self.num_frames - 1:
self.is_animate = False
#
self.to_drop_item()
#
self.play(self.eng.sound.death[self.npc_id])
def to_drop_item(self):
if self.drop_item is not None: | self.level_map.item_map[self.tile_pos] = Item( | 1 | 2023-10-22 08:41:55+00:00 | 4k |
tomguluson92/cloth2tex | renderer/cloth_renderer.py | [
{
"identifier": "PerspectiveCamera",
"path": "renderer/landmark_renderer.py",
"snippet": "class PerspectiveCamera(nn.Module):\n\n FOCAL_LENGTH = 50*128\n\n def __init__(self, rotation=None, translation=None,\n focal_length_x=None, focal_length_y=None,\n batch_size=1... | import datetime
import os
import cv2
import torch
import numpy as np
import matplotlib.pyplot as plt
import pytorch3d
import torchvision.transforms as transforms
import random
from PIL import Image
from pytorch3d.structures import Meshes
from pytorch3d.renderer.mesh import Textures
from pytorch3d.renderer import (
look_at_view_transform,
BlendParams,
OrthographicCameras,
FoVOrthographicCameras,
FoVPerspectiveCameras,
PointLights,
AmbientLights,
DirectionalLights,
Materials,
RasterizationSettings,
MeshRenderer,
MeshRendererWithFragments,
MeshRasterizer,
SoftPhongShader,
HardPhongShader,
SoftSilhouetteShader,
SoftPhongShader,
TexturesVertex,
TexturesUV
)
from pytorch3d.io import load_obj, load_objs_as_meshes, save_obj
from pytorch3d.transforms import RotateAxisAngle, Rotate, axis_angle_to_matrix
from renderer.landmark_renderer import PerspectiveCamera, OrthogonalCamera | 1,758 | # coding: UTF-8
"""
clothrenderer
"""
# Data structures and functions for rendering
DEG_TO_RAD = np.pi / 180
class ClothRenderer(object):
def __init__(self, objfile, resolution=512, focal_distance=1.6, scale_factor=1):
self.device = torch.device("cuda:0")
self.img_size = resolution
self.render_size = resolution
self.renderer, self.renderer_silhouette = self.__get_renderer(self.render_size, focal_distance)
print("[Cloth2Tex]", objfile)
obj_filename = os.path.join(objfile)
verts, faces, aux = load_obj(
obj_filename,
device=self.device,
load_textures=True)
self.faces = faces.verts_idx
self.verts = verts
self.aux = aux
self.verts = self.normalize_vertex(verts.clone()) * scale_factor
self.center = verts.mean(0)
self.scale = max((verts - self.center).abs().max(0)[0])
| # coding: UTF-8
"""
clothrenderer
"""
# Data structures and functions for rendering
DEG_TO_RAD = np.pi / 180
class ClothRenderer(object):
def __init__(self, objfile, resolution=512, focal_distance=1.6, scale_factor=1):
self.device = torch.device("cuda:0")
self.img_size = resolution
self.render_size = resolution
self.renderer, self.renderer_silhouette = self.__get_renderer(self.render_size, focal_distance)
print("[Cloth2Tex]", objfile)
obj_filename = os.path.join(objfile)
verts, faces, aux = load_obj(
obj_filename,
device=self.device,
load_textures=True)
self.faces = faces.verts_idx
self.verts = verts
self.aux = aux
self.verts = self.normalize_vertex(verts.clone()) * scale_factor
self.center = verts.mean(0)
self.scale = max((verts - self.center).abs().max(0)[0]) | self.landmark_cam = OrthogonalCamera(rotation=self.cameras.R.cuda(), translation=self.cameras.T.cuda()).to(self.device) | 1 | 2023-10-17 11:30:53+00:00 | 4k |
amazon-science/cceval | eval.py | [
{
"identifier": "compute_metric_stmt",
"path": "eval_metric.py",
"snippet": "def compute_metric_stmt(args):\n with open(f\"{args.output_dir}/prediction.jsonl\", \"r\") as f_pred:\n samples = []\n for l in f_pred.readlines():\n samples.append(json.loads(l))\n\n examples = {... | import argparse
import json
import logging
import os
import numpy as np
import torch
import custom_generate
from accelerate import Accelerator
from accelerate.utils import set_seed
from datasets import load_dataset
from torch.utils.data import DataLoader, SequentialSampler
from tqdm import tqdm
from transformers import (
AutoTokenizer,
AutoModelForCausalLM
)
from eval_metric import compute_metric_stmt
from eval_utils import compute_mean_logp | 3,574 | crossfile_context,
truncation=True,
max_length=args.cfc_seq_length
)
features = {"input_ids": [], "attention_mask": []}
tokenizer.truncation_side = "left"
for idx, prompt in enumerate(examples["prompt"]):
allowed_prompt_length = max_prompt_length - len(crossfile_features["input_ids"][idx])
prompt_feats = tokenizer(
[prompt],
truncation=True,
max_length=allowed_prompt_length
)
for k, v in prompt_feats.items():
features[k].append(crossfile_features[k][idx] + prompt_feats[k][0])
# pad to max_seq_length
tokenizer.padding_side = "left"
features = tokenizer.pad(features, padding="max_length", max_length=args.max_seq_length - args.gen_length)
features["index"] = examples["index"]
return features
if args.model_type in ["codelm", "seq2seqlm"]:
tokenized_datasets = raw_datasets.map(
prepare_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on dataset",
)
elif args.model_type == "codelm_cfc":
tokenized_datasets = raw_datasets.map(
prepare_features_cfc,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on dataset",
)
else:
raise NotImplementedError("prepare feature functions not implemented for new model type")
return tokenized_datasets, index2taskid
def model_inference(tokenized_datasets, index2taskid, tokenizer):
if args.dtype == 'fp16':
dtype = torch.float16
elif args.dtype == 'fp32':
dtype = torch.float32
elif args.dtype == 'bf16':
dtype = torch.bfloat16
elif args.dtype == 'int8':
dtype = torch.int8
else:
assert False, f'{args.dtype=} not implemented'
if args.model_type in ["codelm", "codelm_cfc"]:
model = AutoModelForCausalLM.from_pretrained(
args.model_name_or_path,
torch_dtype=dtype,
trust_remote_code=True,
revision="main"
)
else:
raise ValueError("Unknown model type")
total_samples_cnt = len(tokenized_datasets)
logger.info(f"total samples: {total_samples_cnt}")
data_sampler = SequentialSampler(tokenized_datasets)
dataloader = DataLoader(
tokenized_datasets,
sampler=data_sampler,
collate_fn=custom_data_collator,
batch_size=args.batch_size
)
model = accelerator.prepare_model(model)
dataloader = accelerator.prepare_data_loader(dataloader)
if not os.path.isdir(args.output_dir):
os.mkdir(args.output_dir)
tokenizer.pad_token = tokenizer.eos_token if tokenizer.eos_token else tokenizer.bos_token
prompt_length = args.max_seq_length - args.gen_length
@torch.no_grad()
def generate_completions(batch):
output_dict = custom_generate.generate(
accelerator.unwrap_model(model),
input_ids=batch["input_ids"],
attention_mask=batch["attention_mask"],
max_length=args.max_seq_length,
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
do_sample=args.do_sample,
num_beams=args.num_beams,
num_return_sequences=1,
pad_token_id=tokenizer.pad_token_id,
return_dict_in_generate=True,
output_scores=True
)
batch_task_id = batch["index"]
batch_pred = accelerator.pad_across_processes(
output_dict.sequences, dim=1, pad_index=tokenizer.pad_token_id
)
scores = torch.stack(output_dict.scores, dim=1)
batch_scores = accelerator.pad_across_processes(
scores, dim=1, pad_index=tokenizer.pad_token_id
)
# batch_scores.shape = (batch_size x num_gpus x num_return_sequences, max_length)
batch_task_id, batch_pred, batch_scores = accelerator.gather((batch_task_id, batch_pred, batch_scores))
batch_pred = batch_pred[:, prompt_length:]
generated_texts = tokenizer.batch_decode(batch_pred, skip_special_tokens=True)
| # Copyright Amazon.com, Inc. or its affiliates. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
COMMENT_SYMBOL = {
"python": "#",
"java": "//",
"csharp": "//",
"typescript": "//"
}
def custom_data_collator(features):
first = features[0]
batch = {}
for k, v in first.items():
if v is not None and not isinstance(v, str):
if isinstance(v, torch.Tensor):
batch[k] = torch.stack([f[k] for f in features])
elif isinstance(v, np.ndarray):
batch[k] = torch.tensor(np.stack([f[k] for f in features]))
else:
batch[k] = torch.tensor([f[k] for f in features])
if v is not None and isinstance(v, str):
batch[k] = [f[k] for f in features]
return batch
def build_datasets(args, tokenizer):
# Initialize the model and tokenizer
# when generating, we will use the logits of right-most token to predict the next token
# so the padding should be on the left
tokenizer.padding_side = "left"
tokenizer.pad_token = tokenizer.eos_token if tokenizer.eos_token else tokenizer.bos_token
# load the files into Dataset
raw_datasets = load_dataset("json", data_files=args.prompt_file, cache_dir=args.cache_dir)
raw_datasets = raw_datasets["train"]
raw_datasets = raw_datasets.map(lambda example, idx: {'index': idx, **example}, with_indices=True)
index2taskid = {idx: md["task_id"] for idx, md in zip(raw_datasets["index"], raw_datasets["metadata"])}
column_names = raw_datasets.column_names
# Prompt composition
def prepare_features(examples):
tokenizer.truncation_side = "left"
tokenized_inputs = tokenizer(
examples["prompt"],
padding="max_length",
truncation=True,
max_length=args.max_seq_length - args.gen_length
)
features = {k: t for k, t in tokenized_inputs.items()}
features["index"] = examples["index"]
return features
def prepare_features_cfc(examples):
max_prompt_length = args.max_seq_length - args.gen_length
use_key = "list"
crossfile_context = []
if use_key == "text":
crossfile_context = [ex["text"] for ex in examples["crossfile_context"]]
else:
ls_sym = COMMENT_SYMBOL[args.language]
num_chunk_inc_prompt = []
augmented_prompt = 0
for cfc_chunks in examples["crossfile_context"]:
cfc_chunks = cfc_chunks["list"] # a list of dict
cfc_text = ""
if cfc_chunks:
# at least 1 relevant cfc_chunk found
init_cfc_text = f"{ls_sym} Here are some relevant code fragments from other files of the repo:\n\n"
cfc_length = len(tokenizer.tokenize(init_cfc_text))
num_chunk_inc = 0
for cfc_idx, cfc_chunk in enumerate(cfc_chunks):
if cfc_chunk["score"] > args.min_cfc_score:
add_text = f"{ls_sym} the below code fragment is found in {cfc_chunk['filename']}" + "\n"
cfc_lines = cfc_chunk["retrieved_chunk"].split('\n')
add_text += "\n".join([f"{ls_sym} {cl}" for cl in cfc_lines if cl]) + "\n\n"
# check if adding chunk exceeds max length budget for CFC
add_text_len = len(tokenizer.tokenize(add_text))
if cfc_length + add_text_len <= args.cfc_seq_length:
cfc_text += add_text
cfc_length += add_text_len
num_chunk_inc += 1
else:
break
num_chunk_inc_prompt.append(num_chunk_inc)
if num_chunk_inc > 0:
cfc_text = init_cfc_text + cfc_text
augmented_prompt += 1
crossfile_context.append(cfc_text)
logger.info(
f"{augmented_prompt} out of {len(examples['crossfile_context'])} prompts are augmented with cross-file context.")
tokenizer.truncation_side = "right"
crossfile_features = tokenizer(
crossfile_context,
truncation=True,
max_length=args.cfc_seq_length
)
features = {"input_ids": [], "attention_mask": []}
tokenizer.truncation_side = "left"
for idx, prompt in enumerate(examples["prompt"]):
allowed_prompt_length = max_prompt_length - len(crossfile_features["input_ids"][idx])
prompt_feats = tokenizer(
[prompt],
truncation=True,
max_length=allowed_prompt_length
)
for k, v in prompt_feats.items():
features[k].append(crossfile_features[k][idx] + prompt_feats[k][0])
# pad to max_seq_length
tokenizer.padding_side = "left"
features = tokenizer.pad(features, padding="max_length", max_length=args.max_seq_length - args.gen_length)
features["index"] = examples["index"]
return features
if args.model_type in ["codelm", "seq2seqlm"]:
tokenized_datasets = raw_datasets.map(
prepare_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on dataset",
)
elif args.model_type == "codelm_cfc":
tokenized_datasets = raw_datasets.map(
prepare_features_cfc,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on dataset",
)
else:
raise NotImplementedError("prepare feature functions not implemented for new model type")
return tokenized_datasets, index2taskid
def model_inference(tokenized_datasets, index2taskid, tokenizer):
if args.dtype == 'fp16':
dtype = torch.float16
elif args.dtype == 'fp32':
dtype = torch.float32
elif args.dtype == 'bf16':
dtype = torch.bfloat16
elif args.dtype == 'int8':
dtype = torch.int8
else:
assert False, f'{args.dtype=} not implemented'
if args.model_type in ["codelm", "codelm_cfc"]:
model = AutoModelForCausalLM.from_pretrained(
args.model_name_or_path,
torch_dtype=dtype,
trust_remote_code=True,
revision="main"
)
else:
raise ValueError("Unknown model type")
total_samples_cnt = len(tokenized_datasets)
logger.info(f"total samples: {total_samples_cnt}")
data_sampler = SequentialSampler(tokenized_datasets)
dataloader = DataLoader(
tokenized_datasets,
sampler=data_sampler,
collate_fn=custom_data_collator,
batch_size=args.batch_size
)
model = accelerator.prepare_model(model)
dataloader = accelerator.prepare_data_loader(dataloader)
if not os.path.isdir(args.output_dir):
os.mkdir(args.output_dir)
tokenizer.pad_token = tokenizer.eos_token if tokenizer.eos_token else tokenizer.bos_token
prompt_length = args.max_seq_length - args.gen_length
@torch.no_grad()
def generate_completions(batch):
output_dict = custom_generate.generate(
accelerator.unwrap_model(model),
input_ids=batch["input_ids"],
attention_mask=batch["attention_mask"],
max_length=args.max_seq_length,
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
do_sample=args.do_sample,
num_beams=args.num_beams,
num_return_sequences=1,
pad_token_id=tokenizer.pad_token_id,
return_dict_in_generate=True,
output_scores=True
)
batch_task_id = batch["index"]
batch_pred = accelerator.pad_across_processes(
output_dict.sequences, dim=1, pad_index=tokenizer.pad_token_id
)
scores = torch.stack(output_dict.scores, dim=1)
batch_scores = accelerator.pad_across_processes(
scores, dim=1, pad_index=tokenizer.pad_token_id
)
# batch_scores.shape = (batch_size x num_gpus x num_return_sequences, max_length)
batch_task_id, batch_pred, batch_scores = accelerator.gather((batch_task_id, batch_pred, batch_scores))
batch_pred = batch_pred[:, prompt_length:]
generated_texts = tokenizer.batch_decode(batch_pred, skip_special_tokens=True)
| mean_logp = compute_mean_logp(batch_scores, batch_pred, tokenizer.pad_token_id) | 1 | 2023-10-16 04:23:03+00:00 | 4k |
uukuguy/multi_loras | multi_loras/dare.py | [
{
"identifier": "DeltaWeights",
"path": "multi_loras/delta_weights.py",
"snippet": "class DeltaWeights:\n \"\"\"\n Functions to compute the delta weights between two models \n \"\"\"\n\n def __init__(\n self,\n base_model: nn.Module = None,\n tuned_model: nn.Module = Non... | from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer
from .delta_weights import DeltaWeights, copy_params_to_model
import torch
import torch.nn as nn | 2,118 | # DARE (Drop And REscale)
# Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch
# https://arxiv.org/abs/2311.03099
def drop_and_rescale_tensor(
input_tensor: torch.Tensor, mask_rate: float, use_rescale: bool, mask_strategy: str
):
"""
mask the input with mask rate
:param input_tensor: Tensor, input tensor
:param mask_rate: float, mask rate
:param use_rescale: boolean, whether to rescale the input by 1 / (1 - mask_rate)
:param mask_strategy: str, mask strategy, can be "random" and "magnitude"
:return:
"""
assert (
0.0 <= mask_rate <= 1.0
), f"wrong range of mask_rate {mask_rate}, should be [0.0, 1.0]!"
if mask_strategy == "random":
mask = torch.bernoulli(
torch.full_like(input=input_tensor.float(), fill_value=mask_rate)
).to(input_tensor.device)
masked_input_tensor = input_tensor * (1 - mask)
else:
assert (
mask_strategy == "magnitude"
), f"wrong setting for mask_strategy {mask_strategy}!"
original_shape = input_tensor.shape
input_tensor = input_tensor.flatten()
num_mask_params = int(len(input_tensor) * mask_rate)
# Tensor, shape (1, ),
# find the num_mask_params-th smallest magnitude element of all the parameters in the model
kth_values, _ = input_tensor.abs().kthvalue(
k=num_mask_params, dim=0, keepdim=True
)
# Tensor, shape (num_total_params, ),
# where True is for parameters that we want to perform mask
mask = input_tensor.abs() <= kth_values
masked_input_tensor = input_tensor * (~mask)
masked_input_tensor = masked_input_tensor.reshape(original_shape)
if use_rescale and mask_rate != 1.0:
masked_input_tensor = torch.div(input=masked_input_tensor, other=1 - mask_rate)
return masked_input_tensor
def drop_and_rescale_model(
tuned_model: nn.Module,
base_model: nn.Module,
exclude_param_names_regex: list = None,
weight_mask_rate: float = 0.85,
use_weight_rescale: bool = True,
mask_strategy: str = "random",
scaling_coefficient: float = 1.0,
):
"""
mask model weights
:param tuned_model: nn.Module, the tuned model
:param base_model: nn.Module, the base model
:param exclude_param_names_regex: list, regular expression of names of parameters that need to be excluded
:param weight_mask_rate: float, weight mask rate
:param use_weight_rescale: boolean, whether to rescale the weight by 1 / (1 - weight_mask_rate)
:param mask_strategy: str, mask strategy, can be "random" and "magnitude"
:return:
"""
# get weights that need to be masked
delta_weights = DeltaWeights(
base_model=base_model,
tuned_model=tuned_model,
exclude_param_names_regex=exclude_param_names_regex,
)
model_param_dict = delta_weights.params_dict
with torch.no_grad():
dare_params_dict = {}
for param_name, param_value in tqdm(model_param_dict.items(), ncols=0):
dare_params_dict[param_name] = drop_and_rescale_tensor(
input_tensor=param_value,
mask_rate=weight_mask_rate,
use_rescale=use_weight_rescale,
mask_strategy=mask_strategy,
)
new_delta_weights = DeltaWeights(params_dict=dare_params_dict)
# combine with parameters of the merged model based on scaling coefficient
dare_model_weights = new_delta_weights.combine_with_pretrained_model(
base_model=base_model, scaling_coefficient=scaling_coefficient
)
return dare_model_weights
def do_dare(args):
"""
This function is used to do drop and rescale for the tuned model
"""
print(f"Loading base model from {args.base_model_name_or_path} ...")
base_model = AutoModelForCausalLM.from_pretrained(
args.base_model_name_or_path, device_map=args.device_map, trust_remote_code=True
).half()
print(f"Loading tuned model from {args.tuned_model_name_or_path} ...")
tuned_model = AutoModelForCausalLM.from_pretrained(
args.tuned_model_name_or_path,
device_map=args.device_map,
trust_remote_code=True,
).half()
tokenizer = AutoTokenizer.from_pretrained(args.tuned_model_name_or_path, trust_remote_code=True)
dare_kwargs = {
"weight_mask_rate": args.dare_weight_mask_rate,
"use_weight_rescale": args.dare_use_weight_rescale,
"mask_strategy": args.dare_mask_strategy,
"scaling_coefficient": args.dare_scaling_coefficient,
}
print(
f"Do drop and rescale with {dare_kwargs=} with {args.tuned_model_name_or_path} ..."
)
model_weights = drop_and_rescale_model(
tuned_model=tuned_model,
base_model=base_model,
**dare_kwargs,
)
| #!/usr/bon/env python
"""
This script is used to do drop and rescale for the tuned model
"""
default_dare_kwargs = {
"weight_mask_rate": 0.85,
"use_weight_rescale": True,
"mask_strategy": "random",
"scaling_coefficient": 1.0,
}
# DARE (Drop And REscale)
# Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch
# https://arxiv.org/abs/2311.03099
def drop_and_rescale_tensor(
input_tensor: torch.Tensor, mask_rate: float, use_rescale: bool, mask_strategy: str
):
"""
mask the input with mask rate
:param input_tensor: Tensor, input tensor
:param mask_rate: float, mask rate
:param use_rescale: boolean, whether to rescale the input by 1 / (1 - mask_rate)
:param mask_strategy: str, mask strategy, can be "random" and "magnitude"
:return:
"""
assert (
0.0 <= mask_rate <= 1.0
), f"wrong range of mask_rate {mask_rate}, should be [0.0, 1.0]!"
if mask_strategy == "random":
mask = torch.bernoulli(
torch.full_like(input=input_tensor.float(), fill_value=mask_rate)
).to(input_tensor.device)
masked_input_tensor = input_tensor * (1 - mask)
else:
assert (
mask_strategy == "magnitude"
), f"wrong setting for mask_strategy {mask_strategy}!"
original_shape = input_tensor.shape
input_tensor = input_tensor.flatten()
num_mask_params = int(len(input_tensor) * mask_rate)
# Tensor, shape (1, ),
# find the num_mask_params-th smallest magnitude element of all the parameters in the model
kth_values, _ = input_tensor.abs().kthvalue(
k=num_mask_params, dim=0, keepdim=True
)
# Tensor, shape (num_total_params, ),
# where True is for parameters that we want to perform mask
mask = input_tensor.abs() <= kth_values
masked_input_tensor = input_tensor * (~mask)
masked_input_tensor = masked_input_tensor.reshape(original_shape)
if use_rescale and mask_rate != 1.0:
masked_input_tensor = torch.div(input=masked_input_tensor, other=1 - mask_rate)
return masked_input_tensor
def drop_and_rescale_model(
tuned_model: nn.Module,
base_model: nn.Module,
exclude_param_names_regex: list = None,
weight_mask_rate: float = 0.85,
use_weight_rescale: bool = True,
mask_strategy: str = "random",
scaling_coefficient: float = 1.0,
):
"""
mask model weights
:param tuned_model: nn.Module, the tuned model
:param base_model: nn.Module, the base model
:param exclude_param_names_regex: list, regular expression of names of parameters that need to be excluded
:param weight_mask_rate: float, weight mask rate
:param use_weight_rescale: boolean, whether to rescale the weight by 1 / (1 - weight_mask_rate)
:param mask_strategy: str, mask strategy, can be "random" and "magnitude"
:return:
"""
# get weights that need to be masked
delta_weights = DeltaWeights(
base_model=base_model,
tuned_model=tuned_model,
exclude_param_names_regex=exclude_param_names_regex,
)
model_param_dict = delta_weights.params_dict
with torch.no_grad():
dare_params_dict = {}
for param_name, param_value in tqdm(model_param_dict.items(), ncols=0):
dare_params_dict[param_name] = drop_and_rescale_tensor(
input_tensor=param_value,
mask_rate=weight_mask_rate,
use_rescale=use_weight_rescale,
mask_strategy=mask_strategy,
)
new_delta_weights = DeltaWeights(params_dict=dare_params_dict)
# combine with parameters of the merged model based on scaling coefficient
dare_model_weights = new_delta_weights.combine_with_pretrained_model(
base_model=base_model, scaling_coefficient=scaling_coefficient
)
return dare_model_weights
def do_dare(args):
"""
This function is used to do drop and rescale for the tuned model
"""
print(f"Loading base model from {args.base_model_name_or_path} ...")
base_model = AutoModelForCausalLM.from_pretrained(
args.base_model_name_or_path, device_map=args.device_map, trust_remote_code=True
).half()
print(f"Loading tuned model from {args.tuned_model_name_or_path} ...")
tuned_model = AutoModelForCausalLM.from_pretrained(
args.tuned_model_name_or_path,
device_map=args.device_map,
trust_remote_code=True,
).half()
tokenizer = AutoTokenizer.from_pretrained(args.tuned_model_name_or_path, trust_remote_code=True)
dare_kwargs = {
"weight_mask_rate": args.dare_weight_mask_rate,
"use_weight_rescale": args.dare_use_weight_rescale,
"mask_strategy": args.dare_mask_strategy,
"scaling_coefficient": args.dare_scaling_coefficient,
}
print(
f"Do drop and rescale with {dare_kwargs=} with {args.tuned_model_name_or_path} ..."
)
model_weights = drop_and_rescale_model(
tuned_model=tuned_model,
base_model=base_model,
**dare_kwargs,
) | copy_params_to_model(model_weights, base_model) | 1 | 2023-10-16 02:39:47+00:00 | 4k |
aws/res | tasks/build.py | [
{
"identifier": "BuildTool",
"path": "tasks/tools/build_tool.py",
"snippet": "class BuildTool:\n \"\"\"\n IDEA Project Build Tool\n Handles building of individual projects under <PROJECT_ROOT>/source/idea/*\n\n Works based on standard idea directory structure:\n <PROJECT_ROOT>/\n + sou... | import tasks.idea as idea
import os
import shutil
from tasks.tools.build_tool import BuildTool
from tasks.apispec import (
cluster_manager as apispec_cluster_manager,
virtual_desktop_controller as apispec_virtual_desktop_controller
)
from invoke import task, Context | 3,258 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
# and limitations under the License.
@task
def data_model(c):
"""
build data-model
"""
BuildTool(c, 'idea-data-model').build()
@task
def sdk(c):
# type: (Context) -> None
"""
build sdk
"""
BuildTool(c, 'idea-sdk').build()
@task
def administrator(c):
# type: (Context) -> None
"""
build administrator
"""
BuildTool(c, 'idea-administrator').build()
@task
def cluster_manager(c):
# type: (Context) -> None
"""
build cluster manager
"""
tool = BuildTool(c, 'idea-cluster-manager')
tool.build()
apispec_cluster_manager(c, output_file=os.path.join(tool.output_dir, 'resources', 'api', 'openapi.yml'))
def dcv_connection_gateway(c):
# type: (Context) -> None
"""
build dcv connection gateway
"""
tool = BuildTool(c, 'idea-dcv-connection-gateway')
output_dir = tool.output_dir
shutil.rmtree(output_dir, ignore_errors=True)
os.makedirs(output_dir, exist_ok=True)
shutil.copytree(idea.props.dcv_connection_gateway_dir, os.path.join(tool.output_dir, 'static_resources'))
@task
def virtual_desktop_controller(c):
# type: (Context) -> None
"""
build virtual desktop controller
"""
tool = BuildTool(c, 'idea-virtual-desktop-controller')
tool.build()
| # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
# and limitations under the License.
@task
def data_model(c):
"""
build data-model
"""
BuildTool(c, 'idea-data-model').build()
@task
def sdk(c):
# type: (Context) -> None
"""
build sdk
"""
BuildTool(c, 'idea-sdk').build()
@task
def administrator(c):
# type: (Context) -> None
"""
build administrator
"""
BuildTool(c, 'idea-administrator').build()
@task
def cluster_manager(c):
# type: (Context) -> None
"""
build cluster manager
"""
tool = BuildTool(c, 'idea-cluster-manager')
tool.build()
apispec_cluster_manager(c, output_file=os.path.join(tool.output_dir, 'resources', 'api', 'openapi.yml'))
def dcv_connection_gateway(c):
# type: (Context) -> None
"""
build dcv connection gateway
"""
tool = BuildTool(c, 'idea-dcv-connection-gateway')
output_dir = tool.output_dir
shutil.rmtree(output_dir, ignore_errors=True)
os.makedirs(output_dir, exist_ok=True)
shutil.copytree(idea.props.dcv_connection_gateway_dir, os.path.join(tool.output_dir, 'static_resources'))
@task
def virtual_desktop_controller(c):
# type: (Context) -> None
"""
build virtual desktop controller
"""
tool = BuildTool(c, 'idea-virtual-desktop-controller')
tool.build() | apispec_virtual_desktop_controller(c, output_file=os.path.join(tool.output_dir, 'resources', 'api', 'openapi.yml')) | 0 | 2023-10-20 17:11:30+00:00 | 4k |
cvlab-yonsei/ACLS | tools/train.py | [
{
"identifier": "Trainer",
"path": "calibrate/engine/trainer.py",
"snippet": "class Trainer:\n def __init__(self, cfg: DictConfig) -> None:\n self.cfg = cfg\n self.work_dir = self.cfg.work_dir\n self.device = torch.device(self.cfg.device)\n self.build_data_loader()\n ... | import os
import sys
import logging
import hydra
from omegaconf import DictConfig, OmegaConf
from omegaconf.omegaconf import open_dict
from calibrate.engine import Trainer
from calibrate.utils import set_random_seed | 2,739 |
logger = logging.getLogger(__name__)
TRAINERS = {
"cv": Trainer
}
@hydra.main(config_path="../configs", config_name="defaults")
def main(cfg: DictConfig):
logger.info("Launch command : ")
logger.info(" ".join(sys.argv))
with open_dict(cfg):
cfg.work_dir = os.getcwd()
logger.info("\n" + OmegaConf.to_yaml(cfg))
|
logger = logging.getLogger(__name__)
TRAINERS = {
"cv": Trainer
}
@hydra.main(config_path="../configs", config_name="defaults")
def main(cfg: DictConfig):
logger.info("Launch command : ")
logger.info(" ".join(sys.argv))
with open_dict(cfg):
cfg.work_dir = os.getcwd()
logger.info("\n" + OmegaConf.to_yaml(cfg))
| set_random_seed( | 1 | 2023-10-23 09:55:13+00:00 | 4k |
myshell-ai/AIlice | ailice/core/AProcessor.py | [
{
"identifier": "config",
"path": "ailice/common/AConfig.py",
"snippet": "class AConfig():\n def __init__(self):\n def Initialize(self, needOpenaiGPTKey = False):\n def Load(self, configFile: str) -> dict:\n def Store(self, configFile: str):"
},
{
"identifier": "llmPool",
"path":... | import time
from functools import partial
from ailice.common.AConfig import config
from ailice.core.llm.ALLMPool import llmPool
from ailice.common.APrompts import promptsManager
from ailice.common.ARemoteAccessors import clientPool
from ailice.core.AConversation import AConversations
from ailice.core.AInterpreter import AInterpreter | 1,666 |
class AProcessor():
def __init__(self, name, modelID, promptName, outputCB, collection = None):
self.name = name
self.modelID = modelID
|
class AProcessor():
def __init__(self, name, modelID, promptName, outputCB, collection = None):
self.name = name
self.modelID = modelID | self.llm = llmPool.GetModel(modelID) | 1 | 2023-10-16 01:51:14+00:00 | 4k |
Agora-X/Bing-Chat-API | src/bing_chat/chathub.py | [
{
"identifier": "DELIMITER",
"path": "src/bing_chat/constants.py",
"snippet": "DELIMITER = \"\\x1e\""
},
{
"identifier": "HEADERS",
"path": "src/bing_chat/constants.py",
"snippet": "HEADERS = {\n \"accept\": \"application/json\",\n \"accept-language\": \"en-US;q=0.9\",\n \"accep... | import asyncio
import json
import os
import ssl
import sys
import aiohttp
import certifi
import httpx
import urllib.parse
from time import time
from typing import Generator
from typing import List
from typing import Union
from BingImageCreator import ImageGenAsync
from .constants import DELIMITER
from .constants import HEADERS
from .constants import HEADERS_INIT_CONVER
from .conversation import Conversation
from .conversation_style import CONVERSATION_STYLE_TYPE
from .request import ChatHubRequest
from .utilities import append_identifier
from .utilities import get_ran_hex
from .utilities import guess_locale | 3,459 |
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations(certifi.where())
class ChatHub:
def __init__(
self,
|
ssl_context = ssl.create_default_context()
ssl_context.load_verify_locations(certifi.where())
class ChatHub:
def __init__(
self, | conversation: Conversation, | 3 | 2023-10-19 19:17:05+00:00 | 4k |
city96/ComfyUI_ExtraModels | PixArt/models/PixArt.py | [
{
"identifier": "auto_grad_checkpoint",
"path": "PixArt/models/utils.py",
"snippet": "def _ntuple(n):\n def parse(x):\ndef set_grad_checkpoint(model, use_fp32_attention=False, gc_step=1):\n def set_attr(module):\ndef auto_grad_checkpoint(module, *args, **kwargs):\ndef checkpoint_sequential(functio... | import math
import torch
import torch.nn as nn
import os
import numpy as np
from timm.models.layers import DropPath
from timm.models.vision_transformer import PatchEmbed, Mlp
from .utils import auto_grad_checkpoint, to_2tuple
from .PixArt_blocks import t2i_modulate, CaptionEmbedder, WindowAttention, MultiHeadCrossAttention, T2IFinalLayer, TimestepEmbedder, LabelEmbedder, FinalLayer | 3,572 | # 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.
# --------------------------------------------------------
# References:
# GLIDE: https://github.com/openai/glide-text2im
# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py
# --------------------------------------------------------
class PixArtBlock(nn.Module):
"""
A PixArt block with adaptive layer norm (adaLN-single) conditioning.
"""
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, drop_path=0., window_size=0, input_size=None, use_rel_pos=False, **block_kwargs):
super().__init__()
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
| # 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.
# --------------------------------------------------------
# References:
# GLIDE: https://github.com/openai/glide-text2im
# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py
# --------------------------------------------------------
class PixArtBlock(nn.Module):
"""
A PixArt block with adaptive layer norm (adaLN-single) conditioning.
"""
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, drop_path=0., window_size=0, input_size=None, use_rel_pos=False, **block_kwargs):
super().__init__()
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) | self.attn = WindowAttention(hidden_size, num_heads=num_heads, qkv_bias=True, | 3 | 2023-10-20 21:19:44+00:00 | 4k |
aszc-dev/ComfyUI-CoreMLSuite | coreml_suite/models.py | [
{
"identifier": "get_model_config",
"path": "coreml_suite/config.py",
"snippet": "def get_model_config(model_version: ModelVersion):\n unet_config = convert_config(config_map[model_version])\n config = supported_models_base.BASE(unet_config)\n config.latent_format = latent_format_map[model_vers... | import numpy as np
import torch
from comfy import model_base
from comfy.model_management import get_torch_device
from comfy.model_patcher import ModelPatcher
from coreml_suite.config import get_model_config, ModelVersion
from coreml_suite.controlnet import extract_residual_kwargs, chunk_control
from coreml_suite.latents import chunk_batch, merge_chunks
from coreml_suite.lcm.utils import is_lcm
from coreml_suite.logger import logger | 1,666 |
class CoreMLModelWrapper:
def __init__(self, coreml_model):
self.coreml_model = coreml_model
self.dtype = torch.float16
def __call__(self, x, t, context, control, transformer_options=None, **kwargs):
inputs = CoreMLInputs(x, t, context, control, **kwargs)
input_list = inputs.chunks(self.expected_inputs)
chunked_out = [
self.get_torch_outputs(
self.coreml_model(**input_kwargs.coreml_kwargs(self.expected_inputs)),
x.device,
)
for input_kwargs in input_list
]
merged_out = merge_chunks(chunked_out, x.shape)
return merged_out
@staticmethod
def get_torch_outputs(model_output, device):
return torch.from_numpy(model_output["noise_pred"]).to(device)
@property
def expected_inputs(self):
return self.coreml_model.expected_inputs
@property
def is_lcm(self):
return is_lcm(self.coreml_model)
@property
def is_sdxl_base(self):
return is_sdxl_base(self.coreml_model)
@property
def is_sdxl_refiner(self):
return is_sdxl_refiner(self.coreml_model)
@property
def config(self):
if self.is_sdxl_base:
return get_model_config(ModelVersion.SDXL)
if self.is_sdxl_refiner:
return get_model_config(ModelVersion.SDXL_REFINER)
return get_model_config(ModelVersion.SD15)
class CoreMLModelWrapperLCM(CoreMLModelWrapper):
def __init__(self, coreml_model):
super().__init__(coreml_model)
self.config = None
class CoreMLInputs:
def __init__(self, x, t, context, control, **kwargs):
self.x = x
self.t = t
self.context = context
self.control = control
self.time_ids = kwargs.get("time_ids")
self.text_embeds = kwargs.get("text_embeds")
self.ts_cond = kwargs.get("timestep_cond")
def coreml_kwargs(self, expected_inputs):
sample = self.x.cpu().numpy().astype(np.float16)
context = self.context.cpu().numpy().astype(np.float16)
context = context.transpose(0, 2, 1)[:, :, None, :]
t = self.t.cpu().numpy().astype(np.float16)
model_input_kwargs = {
"sample": sample,
"encoder_hidden_states": context,
"timestep": t,
}
residual_kwargs = extract_residual_kwargs(expected_inputs, self.control)
model_input_kwargs |= residual_kwargs
# LCM
if self.ts_cond is not None:
model_input_kwargs["timestep_cond"] = (
self.ts_cond.cpu().numpy().astype(np.float16)
)
# SDXL
if "text_embeds" in expected_inputs:
model_input_kwargs["text_embeds"] = (
self.text_embeds.cpu().numpy().astype(np.float16)
)
if "time_ids" in expected_inputs:
model_input_kwargs["time_ids"] = (
self.time_ids.cpu().numpy().astype(np.float16)
)
return model_input_kwargs
def chunks(self, expected_inputs):
sample_shape = expected_inputs["sample"]["shape"]
timestep_shape = expected_inputs["timestep"]["shape"]
hidden_shape = expected_inputs["encoder_hidden_states"]["shape"]
context_shape = (hidden_shape[0], hidden_shape[3], hidden_shape[1])
chunked_x = chunk_batch(self.x, sample_shape)
ts = list(torch.full((len(chunked_x), timestep_shape[0]), self.t[0]))
chunked_context = chunk_batch(self.context, context_shape)
chunked_control = [None] * len(chunked_x)
if self.control is not None:
|
class CoreMLModelWrapper:
def __init__(self, coreml_model):
self.coreml_model = coreml_model
self.dtype = torch.float16
def __call__(self, x, t, context, control, transformer_options=None, **kwargs):
inputs = CoreMLInputs(x, t, context, control, **kwargs)
input_list = inputs.chunks(self.expected_inputs)
chunked_out = [
self.get_torch_outputs(
self.coreml_model(**input_kwargs.coreml_kwargs(self.expected_inputs)),
x.device,
)
for input_kwargs in input_list
]
merged_out = merge_chunks(chunked_out, x.shape)
return merged_out
@staticmethod
def get_torch_outputs(model_output, device):
return torch.from_numpy(model_output["noise_pred"]).to(device)
@property
def expected_inputs(self):
return self.coreml_model.expected_inputs
@property
def is_lcm(self):
return is_lcm(self.coreml_model)
@property
def is_sdxl_base(self):
return is_sdxl_base(self.coreml_model)
@property
def is_sdxl_refiner(self):
return is_sdxl_refiner(self.coreml_model)
@property
def config(self):
if self.is_sdxl_base:
return get_model_config(ModelVersion.SDXL)
if self.is_sdxl_refiner:
return get_model_config(ModelVersion.SDXL_REFINER)
return get_model_config(ModelVersion.SD15)
class CoreMLModelWrapperLCM(CoreMLModelWrapper):
def __init__(self, coreml_model):
super().__init__(coreml_model)
self.config = None
class CoreMLInputs:
def __init__(self, x, t, context, control, **kwargs):
self.x = x
self.t = t
self.context = context
self.control = control
self.time_ids = kwargs.get("time_ids")
self.text_embeds = kwargs.get("text_embeds")
self.ts_cond = kwargs.get("timestep_cond")
def coreml_kwargs(self, expected_inputs):
sample = self.x.cpu().numpy().astype(np.float16)
context = self.context.cpu().numpy().astype(np.float16)
context = context.transpose(0, 2, 1)[:, :, None, :]
t = self.t.cpu().numpy().astype(np.float16)
model_input_kwargs = {
"sample": sample,
"encoder_hidden_states": context,
"timestep": t,
}
residual_kwargs = extract_residual_kwargs(expected_inputs, self.control)
model_input_kwargs |= residual_kwargs
# LCM
if self.ts_cond is not None:
model_input_kwargs["timestep_cond"] = (
self.ts_cond.cpu().numpy().astype(np.float16)
)
# SDXL
if "text_embeds" in expected_inputs:
model_input_kwargs["text_embeds"] = (
self.text_embeds.cpu().numpy().astype(np.float16)
)
if "time_ids" in expected_inputs:
model_input_kwargs["time_ids"] = (
self.time_ids.cpu().numpy().astype(np.float16)
)
return model_input_kwargs
def chunks(self, expected_inputs):
sample_shape = expected_inputs["sample"]["shape"]
timestep_shape = expected_inputs["timestep"]["shape"]
hidden_shape = expected_inputs["encoder_hidden_states"]["shape"]
context_shape = (hidden_shape[0], hidden_shape[3], hidden_shape[1])
chunked_x = chunk_batch(self.x, sample_shape)
ts = list(torch.full((len(chunked_x), timestep_shape[0]), self.t[0]))
chunked_context = chunk_batch(self.context, context_shape)
chunked_control = [None] * len(chunked_x)
if self.control is not None: | chunked_control = chunk_control(self.control, sample_shape[0]) | 3 | 2023-10-23 13:08:00+00:00 | 4k |
aikunyi/FreTS | exp/exp_main.py | [
{
"identifier": "data_provider",
"path": "data_provider/data_factory.py",
"snippet": "def data_provider(args, flag):\n Data = data_dict[args.data]\n timeenc = 0 if args.embed != 'timeF' else 1\n train_only = args.train_only\n\n if flag == 'test':\n shuffle_flag = False\n drop_l... | from data_provider.data_factory import data_provider
from exp.exp_basic import Exp_Basic
from models import DLinear, NLinear, FreTS
from utils.tools import EarlyStopping, adjust_learning_rate, visual, test_params_flop
from utils.metrics import metric
from torch import optim
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import os
import time
import warnings
import matplotlib.pyplot as plt
import numpy as np | 2,036 |
warnings.filterwarnings('ignore')
class Exp_Main(Exp_Basic):
def __init__(self, args):
super(Exp_Main, self).__init__(args)
def _build_model(self):
model_dict = {
'DLinear': DLinear,
|
warnings.filterwarnings('ignore')
class Exp_Main(Exp_Basic):
def __init__(self, args):
super(Exp_Main, self).__init__(args)
def _build_model(self):
model_dict = {
'DLinear': DLinear, | 'NLinear': NLinear, | 3 | 2023-10-23 13:15:14+00:00 | 4k |
amitfin/oref_alert | custom_components/oref_alert/binary_sensor.py | [
{
"identifier": "expand_areas_and_groups",
"path": "custom_components/oref_alert/area_utils.py",
"snippet": "def expand_areas_and_groups(areas_and_groups: list[str]) -> list[str]:\n \"\"\"Expand groups (if exists) to areas.\"\"\"\n areas = []\n for area_or_group in areas_and_groups:\n if... | from typing import Any
from collections.abc import Mapping
from homeassistant.components import binary_sensor
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .area_utils import expand_areas_and_groups
from .const import (
DOMAIN,
DATA_COORDINATOR,
TITLE,
CONF_AREAS,
CONF_ALERT_MAX_AGE,
CONF_OFF_ICON,
CONF_ON_ICON,
CONF_SENSORS,
ALL_AREAS_ID_SUFFIX,
ALL_AREAS_NAME_SUFFIX,
ATTR_COUNTRY_ACTIVE_ALERTS,
ATTR_COUNTRY_ALERTS,
ATTR_SELECTED_AREAS_ACTIVE_ALERTS,
ATTR_SELECTED_AREAS_ALERTS,
DEFAULT_OFF_ICON,
DEFAULT_ON_ICON,
OREF_ALERT_UNIQUE_ID,
)
from .coordinator import OrefAlertCoordinatorData, OrefAlertDataUpdateCoordinator | 2,580 | """Support for representing daily schedule as binary sensors."""
from __future__ import annotations
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize config entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]
async_add_entities(
[
AlertSensor(name, config_entry, coordinator)
for name in [None] + list(config_entry.options.get(CONF_SENSORS, {}).keys())
]
+ [AlertSensorAllAreas(config_entry, coordinator)]
)
class AlertSensorBase(
CoordinatorEntity[OrefAlertDataUpdateCoordinator], binary_sensor.BinarySensorEntity
):
"""Representation of the alert sensor base."""
_attr_has_entity_name = True
_attr_device_class = binary_sensor.BinarySensorDeviceClass.SAFETY
_entity_component_unrecorded_attributes = frozenset(
{
ATTR_COUNTRY_ACTIVE_ALERTS,
ATTR_COUNTRY_ALERTS,
ATTR_SELECTED_AREAS_ACTIVE_ALERTS,
ATTR_SELECTED_AREAS_ALERTS,
CONF_AREAS,
CONF_ALERT_MAX_AGE,
}
)
def __init__(
self,
config_entry: ConfigEntry,
coordinator: OrefAlertDataUpdateCoordinator,
) -> None:
"""Initialize object with defaults."""
super().__init__(coordinator)
self._config_entry = config_entry
self._on_icon = self._config_entry.options.get(CONF_ON_ICON, DEFAULT_ON_ICON)
self._off_icon = self._config_entry.options.get(CONF_OFF_ICON, DEFAULT_OFF_ICON)
self._data: OrefAlertCoordinatorData = coordinator.data
@callback
def _handle_coordinator_update(self) -> None:
"""Take the data from the coordinator."""
self._data = self.coordinator.data
super()._handle_coordinator_update()
@property
def icon(self):
"""Return the sensor icon."""
return self._on_icon if self.is_on else self._off_icon
class AlertSensor(AlertSensorBase):
"""Representation of the alert sensor."""
def __init__(
self,
name: str | None,
config_entry: ConfigEntry,
coordinator: OrefAlertDataUpdateCoordinator,
) -> None:
"""Initialize object with defaults."""
super().__init__(config_entry, coordinator)
if not name:
| """Support for representing daily schedule as binary sensors."""
from __future__ import annotations
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Initialize config entry."""
coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]
async_add_entities(
[
AlertSensor(name, config_entry, coordinator)
for name in [None] + list(config_entry.options.get(CONF_SENSORS, {}).keys())
]
+ [AlertSensorAllAreas(config_entry, coordinator)]
)
class AlertSensorBase(
CoordinatorEntity[OrefAlertDataUpdateCoordinator], binary_sensor.BinarySensorEntity
):
"""Representation of the alert sensor base."""
_attr_has_entity_name = True
_attr_device_class = binary_sensor.BinarySensorDeviceClass.SAFETY
_entity_component_unrecorded_attributes = frozenset(
{
ATTR_COUNTRY_ACTIVE_ALERTS,
ATTR_COUNTRY_ALERTS,
ATTR_SELECTED_AREAS_ACTIVE_ALERTS,
ATTR_SELECTED_AREAS_ALERTS,
CONF_AREAS,
CONF_ALERT_MAX_AGE,
}
)
def __init__(
self,
config_entry: ConfigEntry,
coordinator: OrefAlertDataUpdateCoordinator,
) -> None:
"""Initialize object with defaults."""
super().__init__(coordinator)
self._config_entry = config_entry
self._on_icon = self._config_entry.options.get(CONF_ON_ICON, DEFAULT_ON_ICON)
self._off_icon = self._config_entry.options.get(CONF_OFF_ICON, DEFAULT_OFF_ICON)
self._data: OrefAlertCoordinatorData = coordinator.data
@callback
def _handle_coordinator_update(self) -> None:
"""Take the data from the coordinator."""
self._data = self.coordinator.data
super()._handle_coordinator_update()
@property
def icon(self):
"""Return the sensor icon."""
return self._on_icon if self.is_on else self._off_icon
class AlertSensor(AlertSensorBase):
"""Representation of the alert sensor."""
def __init__(
self,
name: str | None,
config_entry: ConfigEntry,
coordinator: OrefAlertDataUpdateCoordinator,
) -> None:
"""Initialize object with defaults."""
super().__init__(config_entry, coordinator)
if not name: | self._attr_name = TITLE | 3 | 2023-10-18 11:16:41+00:00 | 4k |
apple/ml-nvas3d | demo/generate_demo_data.py | [
{
"identifier": "render_ir_parallel_room_idx",
"path": "soundspaces_nvas3d/utils/ss_utils.py",
"snippet": "def render_ir_parallel_room_idx(room: str,\n source_idx_list: T.List[int],\n receiver_idx_list: T.List[int],\n ... | import os
import json
import random
import argparse
import subprocess
import typing as T
import torch
import torchaudio
from soundspaces_nvas3d.utils.ss_utils import render_ir_parallel_room_idx, create_scene
from soundspaces_nvas3d.utils.aihabitat_utils import load_room_grid
from soundspaces_nvas3d.utils.audio_utils import wiener_deconv_list
from nvas3d.utils.audio_utils import clip_two
from nvas3d.utils.utils import normalize
from nvas3d.utils.generate_dataset_utils import load_ir_source_receiver, save_audio_list, compute_reverb | 2,813 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
def generate_rir(
args: argparse.Namespace,
room: str,
source_idx_list: T.List[int],
receiver_idx_list: T.List[int]
):
"""
Generates and saves Room Impulse Response (RIR) data for pairs of source_idx_list and receiver_idx_list.
Args:
- args: Parsed command line arguments for dirname and grid distance.
- room: Name of the room.
- source_idx_list: List of source indices.
- receiver_idx_list: List of receiver indices.
"""
ir_dir = f'data/{args.dataset_dir}/temp/ir/grid_{str(args.grid_distance).replace(".", "_")}'
filename_ir = f'{ir_dir}/{room}/ir'
os.makedirs(filename_ir, exist_ok=True)
| #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2023 Apple Inc. All Rights Reserved.
#
def generate_rir(
args: argparse.Namespace,
room: str,
source_idx_list: T.List[int],
receiver_idx_list: T.List[int]
):
"""
Generates and saves Room Impulse Response (RIR) data for pairs of source_idx_list and receiver_idx_list.
Args:
- args: Parsed command line arguments for dirname and grid distance.
- room: Name of the room.
- source_idx_list: List of source indices.
- receiver_idx_list: List of receiver indices.
"""
ir_dir = f'data/{args.dataset_dir}/temp/ir/grid_{str(args.grid_distance).replace(".", "_")}'
filename_ir = f'{ir_dir}/{room}/ir'
os.makedirs(filename_ir, exist_ok=True) | render_ir_parallel_room_idx(room, source_idx_list, receiver_idx_list, filename_ir, args.grid_distance) | 0 | 2023-10-19 05:35:54+00:00 | 4k |
virevolai/logos-shift-client | logos_shift_client/logos_shift.py | [
{
"identifier": "BohitaClient",
"path": "logos_shift_client/bohita.py",
"snippet": "class BohitaClient:\n def __init__(self, api_key: str):\n if api_key is None:\n logging.warning(\n \"No API KEY provided. No data will be sent to Bohita and automatic routing will not ... | import asyncio
import logging
import threading
import time
import uuid
from pathlib import Path
from collections import deque
from typing import Optional, Union
from tenacity import retry, wait_fixed
from .bohita import BohitaClient
from .router import APIRouter | 2,308 |
logger = logging.getLogger(__name__)
MAX_ENTRIES = 10
CHECK_SECONDS = 5
class SingletonMeta(type):
_instances = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class BufferManager(metaclass=SingletonMeta):
"""
A singleton class responsible for managing data buffers and sending data to a remote server.
Attributes:
bohita_client: An instance of BohitaClient used to send data to the remote server.
check_seconds: The interval in seconds between checks to send data from the buffers.
filepath: The file path for local data storage. If None, data is not stored locally.
buffers: A list of data buffers.
thread: The thread responsible for sending data from the buffers.
"""
_instance = None
lock = threading.Lock()
def __init__(
self,
|
logger = logging.getLogger(__name__)
MAX_ENTRIES = 10
CHECK_SECONDS = 5
class SingletonMeta(type):
_instances = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class BufferManager(metaclass=SingletonMeta):
"""
A singleton class responsible for managing data buffers and sending data to a remote server.
Attributes:
bohita_client: An instance of BohitaClient used to send data to the remote server.
check_seconds: The interval in seconds between checks to send data from the buffers.
filepath: The file path for local data storage. If None, data is not stored locally.
buffers: A list of data buffers.
thread: The thread responsible for sending data from the buffers.
"""
_instance = None
lock = threading.Lock()
def __init__(
self, | bohita_client: BohitaClient, | 0 | 2023-10-20 00:00:38+00:00 | 4k |
kwonathan/language-models-trajectory-generators | env.py | [
{
"identifier": "Robot",
"path": "robot.py",
"snippet": "class Robot:\n\n def __init__(self, args):\n\n if args.robot == \"sawyer\":\n self.base_start_position = config.base_start_position_sawyer\n self.base_start_orientation_q = p.getQuaternionFromEuler(config.base_start... | import pybullet as p
import numpy as np
import pybullet_data
import time
import config
from robot import Robot
from config import OK, PROGRESS, FAIL, ENDC
from config import CAPTURE_IMAGES, ADD_BOUNDING_CUBES, ADD_TRAJECTORY_POINTS, EXECUTE_TRAJECTORY, OPEN_GRIPPER, CLOSE_GRIPPER, TASK_COMPLETED, RESET_ENVIRONMENT | 3,151 |
class Environment:
def __init__(self, args):
self.mode = args.mode
def load(self):
p.resetDebugVisualizerCamera(config.camera_distance, config.camera_yaw, config.camera_pitch, config.camera_target_position)
object_start_position = config.object_start_position
object_start_orientation_q = p.getQuaternionFromEuler(config.object_start_orientation_e)
object_model = p.loadURDF("ycb_assets/002_master_chef_can.urdf", object_start_position, object_start_orientation_q, useFixedBase=False, globalScaling=config.global_scaling)
if self.mode == "default":
p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0)
p.configureDebugVisualizer(p.COV_ENABLE_SHADOWS, 0)
def update(self):
p.stepSimulation()
time.sleep(config.control_dt)
def run_simulation_environment(args, env_connection, logger):
# Environment set-up
logger.info(PROGRESS + "Setting up environment..." + ENDC)
physics_client = p.connect(p.GUI)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
p.setGravity(0, 0, -9.81)
plane = p.loadURDF("plane.urdf")
env = Environment(args)
env.load()
robot = Robot(args)
robot.move(env, robot.ee_start_position, robot.ee_start_orientation_e, gripper_open=True, is_trajectory=False)
|
class Environment:
def __init__(self, args):
self.mode = args.mode
def load(self):
p.resetDebugVisualizerCamera(config.camera_distance, config.camera_yaw, config.camera_pitch, config.camera_target_position)
object_start_position = config.object_start_position
object_start_orientation_q = p.getQuaternionFromEuler(config.object_start_orientation_e)
object_model = p.loadURDF("ycb_assets/002_master_chef_can.urdf", object_start_position, object_start_orientation_q, useFixedBase=False, globalScaling=config.global_scaling)
if self.mode == "default":
p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0)
p.configureDebugVisualizer(p.COV_ENABLE_SHADOWS, 0)
def update(self):
p.stepSimulation()
time.sleep(config.control_dt)
def run_simulation_environment(args, env_connection, logger):
# Environment set-up
logger.info(PROGRESS + "Setting up environment..." + ENDC)
physics_client = p.connect(p.GUI)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
p.setGravity(0, 0, -9.81)
plane = p.loadURDF("plane.urdf")
env = Environment(args)
env.load()
robot = Robot(args)
robot.move(env, robot.ee_start_position, robot.ee_start_orientation_e, gripper_open=True, is_trajectory=False)
| env_connection_message = OK + "Finished setting up environment!" + ENDC | 1 | 2023-10-18 16:38:09+00:00 | 4k |
kvablack/susie | susie/model.py | [
{
"identifier": "sampling",
"path": "susie/sampling.py",
"snippet": "def q_sample(x_0, log_snr, noise):\ndef model_predict(state, x, y, prompt_embeds, t, use_ema=True):\ndef sample_step(\n rng,\n state,\n x,\n y,\n prompt_embeds,\n uncond_y,\n uncond_prompt_embeds,\n t,\n t_ne... | import os
import time
import einops as eo
import jax
import jax.numpy as jnp
import ml_collections
import numpy as np
import orbax.checkpoint
import wandb
from functools import partial
from typing import Any, Callable, List, Optional, Tuple
from absl import logging
from diffusers.models import FlaxAutoencoderKL, FlaxUNet2DConditionModel
from flax.core.frozen_dict import FrozenDict
from flax.training.train_state import TrainState
from jax.lax import with_sharding_constraint as wsc
from transformers import CLIPTokenizer, FlaxCLIPTextModel
from susie import sampling, scheduling
from susie.jax_utils import replicate | 2,490 | scale, lambda: latents / vae.config.scaling_factor, lambda: latents
)
sample = vae.apply({"params": vae_params}, latents, method=vae.decode)
sample = eo.rearrange(sample, "(n x) h w c -> n h w (x c)", n=batch_size)
return sample
return partial(vae_encode, vae_params), partial(vae_decode, vae_params)
def load_text_encoder(
path: str,
) -> Tuple[
Callable[[List[str]], np.ndarray],
Callable[[np.ndarray], List[str]],
Callable[[jax.Array], jax.Array],
]:
if ":" in path:
path, revision = path.split(":")
else:
revision = None
text_encoder = FlaxCLIPTextModel.from_pretrained(
path, subfolder="text_encoder", revision=revision
)
tokenizer = CLIPTokenizer.from_pretrained(
path, subfolder="tokenizer", revision=revision
)
def tokenize(s: List[str]) -> np.ndarray:
return tokenizer(s, padding="max_length", return_tensors="np").input_ids
untokenize = partial(tokenizer.batch_decode, skip_special_tokens=True)
@jax.jit
def text_encode(params, prompt_ids):
return text_encoder(prompt_ids, params=params)[0]
return tokenize, untokenize, partial(text_encode, text_encoder.params)
def load_pretrained_unet(
path: str, in_channels: int
) -> Tuple[FlaxUNet2DConditionModel, dict]:
model_def, params = FlaxUNet2DConditionModel.from_pretrained(
path, dtype=np.float32, subfolder="unet"
)
# same issue, they commit the params to the CPU, which totally messes stuff
# up downstream...
params = jax.device_get(params)
# add extra parameters to conv_in if necessary
old_conv_in = params["conv_in"]["kernel"]
h, w, cin, cout = old_conv_in.shape
logging.info(f"Adding {in_channels - cin} channels to conv_in")
params["conv_in"]["kernel"] = np.zeros(
(h, w, in_channels, cout), dtype=old_conv_in.dtype
)
params["conv_in"]["kernel"][:, :, :cin, :] = old_conv_in
# monkey-patch __call__ to use channels-last
model_def.__call__ = lambda self, sample, *args, **kwargs: eo.rearrange(
FlaxUNet2DConditionModel.__call__(
self, eo.rearrange(sample, "b h w c -> b c h w"), *args, **kwargs
).sample,
"b c h w -> b h w c",
)
return model_def, params
def create_sample_fn(
path: str,
wandb_run_name: Optional[str] = None,
num_timesteps: int = 50,
prompt_w: float = 7.5,
context_w: float = 2.5,
eta: float = 0.0,
pretrained_path: str = "runwayml/stable-diffusion-v1-5:flax",
) -> Callable[[np.ndarray, str], np.ndarray]:
if (
os.path.exists(path)
and os.path.isdir(path)
and "checkpoint" in os.listdir(path)
):
# this is an orbax checkpoint
assert wandb_run_name is not None
# load config from wandb
api = wandb.Api()
run = api.run(wandb_run_name)
config = ml_collections.ConfigDict(run.config)
# load params
params = orbax.checkpoint.PyTreeCheckpointer().restore(path, item=None)
assert "params_ema" not in params
# load model
model_def = create_model_def(config.model)
else:
# assume this is in HuggingFace format
model_def, params = load_pretrained_unet(path, in_channels=8)
# hardcode scheduling config to be "scaled_linear" (used by Stable Diffusion)
config = {"scheduling": {"noise_schedule": "scaled_linear"}}
state = EmaTrainState(
step=0,
apply_fn=model_def.apply,
params=None,
params_ema=params,
tx=None,
opt_state=None,
)
del params
# load encoders
vae_encode, vae_decode = load_vae(pretrained_path)
tokenize, untokenize, text_encode = load_text_encoder(pretrained_path)
uncond_prompt_embed = text_encode(tokenize([""])) # (1, 77, 768)
log_snr_fn = scheduling.create_log_snr_fn(config["scheduling"])
|
class EmaTrainState(TrainState):
params_ema: FrozenDict[str, Any]
@partial(jax.jit, donate_argnums=0)
def apply_ema_decay(self, ema_decay):
params_ema = jax.tree_map(
lambda p_ema, p: p_ema * ema_decay + p * (1.0 - ema_decay),
self.params_ema,
self.params,
)
return self.replace(params_ema=params_ema)
def create_model_def(config: dict) -> FlaxUNet2DConditionModel:
model, unused_kwargs = FlaxUNet2DConditionModel.from_config(
dict(config), return_unused_kwargs=True
)
if unused_kwargs:
logging.warning(f"FlaxUNet2DConditionModel unused kwargs: {unused_kwargs}")
# monkey-patch __call__ to use channels-last
model.__call__ = lambda self, sample, *args, **kwargs: eo.rearrange(
FlaxUNet2DConditionModel.__call__(
self, eo.rearrange(sample, "b h w c -> b c h w"), *args, **kwargs
).sample,
"b c h w -> b h w c",
)
return model
def load_vae(
path: str,
) -> Tuple[
Callable[[jax.Array, jax.Array, bool], jax.Array],
Callable[[jax.Array, bool], jax.Array],
]:
if ":" in path:
path, revision = path.split(":")
else:
revision = None
vae, vae_params = FlaxAutoencoderKL.from_pretrained(
path, subfolder="vae", revision=revision
)
# monkey-patch encode to use channels-last (it returns a FlaxDiagonalGaussianDistribution object, which is already
# channels-last)
vae.encode = lambda self, sample, *args, **kwargs: FlaxAutoencoderKL.encode(
self, eo.rearrange(sample, "b h w c -> b c h w"), *args, **kwargs
).latent_dist
# monkey-patch decode to use channels-last (it already accepts channels-last input)
vae.decode = lambda self, latents, *args, **kwargs: eo.rearrange(
FlaxAutoencoderKL.decode(self, latents, *args, **kwargs).sample,
"b c h w -> b h w c",
)
# HuggingFace places vae_params committed onto the CPU -_-
# this one took me awhile to figure out...
vae_params = jax.device_get(vae_params)
@jax.jit
def vae_encode(vae_params, key, sample, scale=False):
# handle the case where `sample` is multiple images stacked
batch_size = sample.shape[0]
sample = eo.rearrange(sample, "n h w (x c) -> (n x) h w c", c=3)
latents = vae.apply({"params": vae_params}, sample, method=vae.encode).sample(
key
)
latents = eo.rearrange(latents, "(n x) h w c -> n h w (x c)", n=batch_size)
latents = jax.lax.cond(
scale, lambda: latents * vae.config.scaling_factor, lambda: latents
)
return latents
@jax.jit
def vae_decode(vae_params, latents, scale=True):
# handle the case where `latents` is multiple images stacked
batch_size = latents.shape[0]
latents = eo.rearrange(
latents, "n h w (x c) -> (n x) h w c", c=vae.config.latent_channels
)
latents = jax.lax.cond(
scale, lambda: latents / vae.config.scaling_factor, lambda: latents
)
sample = vae.apply({"params": vae_params}, latents, method=vae.decode)
sample = eo.rearrange(sample, "(n x) h w c -> n h w (x c)", n=batch_size)
return sample
return partial(vae_encode, vae_params), partial(vae_decode, vae_params)
def load_text_encoder(
path: str,
) -> Tuple[
Callable[[List[str]], np.ndarray],
Callable[[np.ndarray], List[str]],
Callable[[jax.Array], jax.Array],
]:
if ":" in path:
path, revision = path.split(":")
else:
revision = None
text_encoder = FlaxCLIPTextModel.from_pretrained(
path, subfolder="text_encoder", revision=revision
)
tokenizer = CLIPTokenizer.from_pretrained(
path, subfolder="tokenizer", revision=revision
)
def tokenize(s: List[str]) -> np.ndarray:
return tokenizer(s, padding="max_length", return_tensors="np").input_ids
untokenize = partial(tokenizer.batch_decode, skip_special_tokens=True)
@jax.jit
def text_encode(params, prompt_ids):
return text_encoder(prompt_ids, params=params)[0]
return tokenize, untokenize, partial(text_encode, text_encoder.params)
def load_pretrained_unet(
path: str, in_channels: int
) -> Tuple[FlaxUNet2DConditionModel, dict]:
model_def, params = FlaxUNet2DConditionModel.from_pretrained(
path, dtype=np.float32, subfolder="unet"
)
# same issue, they commit the params to the CPU, which totally messes stuff
# up downstream...
params = jax.device_get(params)
# add extra parameters to conv_in if necessary
old_conv_in = params["conv_in"]["kernel"]
h, w, cin, cout = old_conv_in.shape
logging.info(f"Adding {in_channels - cin} channels to conv_in")
params["conv_in"]["kernel"] = np.zeros(
(h, w, in_channels, cout), dtype=old_conv_in.dtype
)
params["conv_in"]["kernel"][:, :, :cin, :] = old_conv_in
# monkey-patch __call__ to use channels-last
model_def.__call__ = lambda self, sample, *args, **kwargs: eo.rearrange(
FlaxUNet2DConditionModel.__call__(
self, eo.rearrange(sample, "b h w c -> b c h w"), *args, **kwargs
).sample,
"b c h w -> b h w c",
)
return model_def, params
def create_sample_fn(
path: str,
wandb_run_name: Optional[str] = None,
num_timesteps: int = 50,
prompt_w: float = 7.5,
context_w: float = 2.5,
eta: float = 0.0,
pretrained_path: str = "runwayml/stable-diffusion-v1-5:flax",
) -> Callable[[np.ndarray, str], np.ndarray]:
if (
os.path.exists(path)
and os.path.isdir(path)
and "checkpoint" in os.listdir(path)
):
# this is an orbax checkpoint
assert wandb_run_name is not None
# load config from wandb
api = wandb.Api()
run = api.run(wandb_run_name)
config = ml_collections.ConfigDict(run.config)
# load params
params = orbax.checkpoint.PyTreeCheckpointer().restore(path, item=None)
assert "params_ema" not in params
# load model
model_def = create_model_def(config.model)
else:
# assume this is in HuggingFace format
model_def, params = load_pretrained_unet(path, in_channels=8)
# hardcode scheduling config to be "scaled_linear" (used by Stable Diffusion)
config = {"scheduling": {"noise_schedule": "scaled_linear"}}
state = EmaTrainState(
step=0,
apply_fn=model_def.apply,
params=None,
params_ema=params,
tx=None,
opt_state=None,
)
del params
# load encoders
vae_encode, vae_decode = load_vae(pretrained_path)
tokenize, untokenize, text_encode = load_text_encoder(pretrained_path)
uncond_prompt_embed = text_encode(tokenize([""])) # (1, 77, 768)
log_snr_fn = scheduling.create_log_snr_fn(config["scheduling"]) | sample_loop = partial(sampling.sample_loop, log_snr_fn=log_snr_fn) | 0 | 2023-10-17 05:05:57+00:00 | 4k |
skywalker023/fantom | eval_fantom.py | [
{
"identifier": "GPT3BaseAgent",
"path": "agents/gpt.py",
"snippet": "class GPT3BaseAgent():\n def __init__(self, kwargs: dict):\n openai.api_key = os.getenv('OPENAI_API_KEY')\n self.args = SimpleNamespace(**kwargs)\n self._set_default_args()\n\n def _set_default_args(self):\n... | import os
import json
import argparse
import random
import evaluate
import torch
import pandas as pd
import colorful as cf
import task.dataset_loader as loader
from pathlib import Path
from collections import Counter
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
from agents.gpt import GPT3BaseAgent, ConversationalGPTBaseAgent
from agents.huggingface import FlanT5Agent, FlanUL2Agent, MistralAIAgent, ZephyrAgent
from agents.together_ai import TogetherAIAgent | 2,586 |
tqdm.pandas()
cf.use_true_colors()
cf.use_style('monokai')
PROJECT_HOME = Path(__file__).parent.resolve()
DATA_DIR = 'data'
DATA_DIR_PATH = os.path.join(PROJECT_HOME, DATA_DIR)
EVAL_DIR_PATH = os.path.join(DATA_DIR_PATH, 'results')
RANDOM_SEED = 99
random.seed(RANDOM_SEED)
class FantomDataset(Dataset):
def __init__(self, texts, args):
self.texts = texts
def __len__(self):
return len(self.texts)
def __getitem__(self, index):
text = self.texts[index]
return text
class FantomEvalAgent():
def __init__(self, args):
self.args = args
self.prompt_header = "This is a theory-of-mind test. Please answer the question regarding facts or beliefs, based on the following in-person conversation between individuals who have just met.\n\n"
self.output_filename_suffix = '_{}_input_{}_cot-{}.json'.format(self.args.conversation_input_type, self.args.model, self.args.use_cot)
self.load_fantom()
self.setup_fantom()
self.model = self.load_model()
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.embedder = SentenceTransformer('sentence-transformers/all-roberta-large-v1').to(self.device)
def load_fantom(self):
self.fantom_df = loader.load()
def respond(self, prompt):
response = self.model.interact(prompt)
return response
def load_model(self):
if self.args.model.startswith("text-"):
model = GPT3BaseAgent({'engine': self.args.model, 'temperature': 0, 'top_p': 0.95, 'frequency_penalty': 0.0, 'presence_penalty': 0.0})
elif self.args.model.startswith("gpt-"):
model = ConversationalGPTBaseAgent({'model': self.args.model, 'temperature': 0, 'top_p': 0.95, 'frequency_penalty': 0.0, 'presence_penalty': 0.0})
elif self.args.model.startswith('flan-t5'):
model = FlanT5Agent(self.args)
elif self.args.model.startswith('flan-ul2'):
model = FlanUL2Agent(self.args)
elif self.args.model.endswith('-tg'):
|
tqdm.pandas()
cf.use_true_colors()
cf.use_style('monokai')
PROJECT_HOME = Path(__file__).parent.resolve()
DATA_DIR = 'data'
DATA_DIR_PATH = os.path.join(PROJECT_HOME, DATA_DIR)
EVAL_DIR_PATH = os.path.join(DATA_DIR_PATH, 'results')
RANDOM_SEED = 99
random.seed(RANDOM_SEED)
class FantomDataset(Dataset):
def __init__(self, texts, args):
self.texts = texts
def __len__(self):
return len(self.texts)
def __getitem__(self, index):
text = self.texts[index]
return text
class FantomEvalAgent():
def __init__(self, args):
self.args = args
self.prompt_header = "This is a theory-of-mind test. Please answer the question regarding facts or beliefs, based on the following in-person conversation between individuals who have just met.\n\n"
self.output_filename_suffix = '_{}_input_{}_cot-{}.json'.format(self.args.conversation_input_type, self.args.model, self.args.use_cot)
self.load_fantom()
self.setup_fantom()
self.model = self.load_model()
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.embedder = SentenceTransformer('sentence-transformers/all-roberta-large-v1').to(self.device)
def load_fantom(self):
self.fantom_df = loader.load()
def respond(self, prompt):
response = self.model.interact(prompt)
return response
def load_model(self):
if self.args.model.startswith("text-"):
model = GPT3BaseAgent({'engine': self.args.model, 'temperature': 0, 'top_p': 0.95, 'frequency_penalty': 0.0, 'presence_penalty': 0.0})
elif self.args.model.startswith("gpt-"):
model = ConversationalGPTBaseAgent({'model': self.args.model, 'temperature': 0, 'top_p': 0.95, 'frequency_penalty': 0.0, 'presence_penalty': 0.0})
elif self.args.model.startswith('flan-t5'):
model = FlanT5Agent(self.args)
elif self.args.model.startswith('flan-ul2'):
model = FlanUL2Agent(self.args)
elif self.args.model.endswith('-tg'): | model = TogetherAIAgent(self.args.__dict__) | 6 | 2023-10-21 22:49:56+00:00 | 4k |
turingmotors/openlenda | yolox/models/darknet.py | [
{
"identifier": "BaseConv",
"path": "yolox/models/network_blocks.py",
"snippet": "class BaseConv(nn.Module):\n \"\"\"A Conv2d -> Batchnorm -> silu/leaky relu block\"\"\"\n\n def __init__(\n self, in_channels, out_channels, ksize, stride, groups=1, bias=False, act=\"silu\"\n ):\n s... | from torch import nn
from .network_blocks import BaseConv, CSPLayer, DWConv, Focus, ResLayer, SPPBottleneck | 1,738 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) Megvii Inc. All rights reserved.
class Darknet(nn.Module):
# number of blocks from dark2 to dark5.
depth2blocks = {21: [1, 2, 2, 1], 53: [2, 8, 8, 4]}
def __init__(
self,
depth,
in_channels=3,
stem_out_channels=32,
out_features=("dark3", "dark4", "dark5"),
):
"""
Args:
depth (int): depth of darknet used in model, usually use [21, 53] for this param.
in_channels (int): number of input channels, for example, use 3 for RGB image.
stem_out_channels (int): number of output channels of darknet stem.
It decides channels of darknet layer2 to layer5.
out_features (Tuple[str]): desired output layer name.
"""
super().__init__()
assert out_features, "please provide output features of Darknet"
self.out_features = out_features
self.stem = nn.Sequential(
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) Megvii Inc. All rights reserved.
class Darknet(nn.Module):
# number of blocks from dark2 to dark5.
depth2blocks = {21: [1, 2, 2, 1], 53: [2, 8, 8, 4]}
def __init__(
self,
depth,
in_channels=3,
stem_out_channels=32,
out_features=("dark3", "dark4", "dark5"),
):
"""
Args:
depth (int): depth of darknet used in model, usually use [21, 53] for this param.
in_channels (int): number of input channels, for example, use 3 for RGB image.
stem_out_channels (int): number of output channels of darknet stem.
It decides channels of darknet layer2 to layer5.
out_features (Tuple[str]): desired output layer name.
"""
super().__init__()
assert out_features, "please provide output features of Darknet"
self.out_features = out_features
self.stem = nn.Sequential( | BaseConv(in_channels, stem_out_channels, ksize=3, stride=1, act="lrelu"), | 0 | 2023-10-20 08:12:26+00:00 | 4k |
tiejundong/FlexPose | FlexPose/preprocess/aug_pseudo_apo.py | [
{
"identifier": "delmkdir",
"path": "FlexPose/utils/common.py",
"snippet": "def delmkdir(path, remove_old=True):\n isexist = os.path.exists(path)\n if not isexist:\n os.makedirs(path)\n if isexist == True and remove_old:\n shutil.rmtree(path)\n os.makedirs(path)"
},
{
... | import os
import shutil
import sys
import argparse
import numpy as np
import scipy.spatial
import random
import pickle
import pyrosetta
from ray.util.multiprocessing import Pool
from einops import rearrange
from pyrosetta import rosetta
from pyrosetta.rosetta import core
from modeller import environ
from modeller.scripts import complete_pdb
from FlexPose.utils.common import delmkdir
from FlexPose.utils.pdbbind_preprocess import read_mol_from_pdbbind, get_true_posi | 2,120 | tf.push_back(core.pack.task.operation.RestrictToRepacking())
restrict_to_focus = core.pack.task.operation.OperateOnResidueSubset(core.pack.task.operation.PreventRepackingRLT(),
res_selector,
True) # True indicates flipping the selection
tf.push_back(restrict_to_focus)
# pyrosetta.toolbox.generate_resfile.generate_resfile_from_pose(original_pose, f'{sub_MC_path}/protein_resfile',
# pack=True, design=False, input_sc=False)
# tf.push_back(core.pack.task.operation.ReadResfile(f'{sub_MC_path}/protein_resfile'))
# print(tf.create_task_and_apply_taskoperations(pose))
# test tf
# packer = pyrosetta.rosetta.protocols.minimization_packing.PackRotamersMover()
# packer = pyrosetta.rosetta.protocols.minimization_packing.MinPackMover()
# packer.task_factory(tf)
# packer.apply(pose)
# get FastRelax
mm = core.kinematics.MoveMap()
mm.set_jump(False)
for i in range(1, pose.size()+1):
if i in res_list:
mm.set_chi(i, True)
mm.set_bb(i, flexbb)
else:
mm.set_chi(i, False)
mm.set_bb(i, False)
# mmf = core.select.movemap.MoveMapFactory()
# mmf.all_bb(False)
# mmf.all_bondangles(False)
# mmf.all_bondlengths(False)
# mmf.all_branches(False)
# mmf.all_chi(False)
# mmf.all_jumps(False)
# mmf.all_nu(False)
# mmf.set_cartesian(False)
# mmf.add_bb_action(core.select.movemap.move_map_action.mm_enable, pocket_selector)
# mmf.add_chi_action(core.select.movemap.move_map_action.mm_enable, pocket_selector)
# mm = mmf.create_movemap_from_pose(pose)
fr = pyrosetta.rosetta.protocols.relax.FastRelax()
# fr.max_iter(100)
fr.constrain_relax_to_start_coords(False)
fr.set_movemap_disables_packing_of_fixed_chi_positions(True)
fr.set_task_factory(tf)
fr.set_movemap(mm)
# fr.set_movemap_factory(mmf)
fr.cartesian(False)
fr.set_scorefxn(core.scoring.ScoreFunctionFactory.create_score_function('ref2015_cart'))
fr.min_type('dfpmin_armijo_nonmonotone') # For non-Cartesian scorefunctions, use "dfpmin_armijo_nonmonotone", else lbfgs_armijo_nonmonotone
return fr
def get_torsion(pose):
bb_torsion = []
sc_torsion = []
for i in range(1, pose.size() + 1):
try:
res = pose.residue(i)
assert res.name3() in ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE',
'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']
phi_psi = [pose.phi(i), pose.psi(i)]
chi = [c for c in res.chi()]
bb_torsion.append(phi_psi)
sc_torsion.append(chi)
except:
bb_torsion.append([None])
sc_torsion.append([None])
return {'bb_torsion': bb_torsion, 'sc_torsion': sc_torsion}
def try_gen_pose(task, pose):
try:
task.apply(pose)
return True
except:
return False
def run_single_pdbbind(tup_in):
pdbbind_path, apobind_path, MC_path, pdb_id, n_rand_pert, n_fixbb_repack, n_flexbb_repack, rand_pert_range = tup_in
sub_pdbbind_path = f'{pdbbind_path}/{pdb_id}'
sub_apobind_path = f'{apobind_path}/{pdb_id}'
sub_MC_path = f'{MC_path}/{pdb_id}'
delmkdir(sub_MC_path)
####################################################################################################################
# repaire protein
####################################################################################################################
env_ = environ()
env_.libs.topology.read(file='$(LIB)/top_heav.lib')
env_.libs.parameters.read(file='$(LIB)/par.lib')
pdb_m = complete_pdb(env_, f'{sub_pdbbind_path}/{pdb_id}_protein.pdb')
pdb_m.write(f'{sub_MC_path}/protein_modeller.pdb')
os.system(f'grep HETATM {sub_pdbbind_path}/{pdb_id}_protein.pdb >> {sub_MC_path}/protein_modeller.pdb') # add ion
os.system(f'grep -v END {sub_MC_path}/protein_modeller.pdb > {sub_MC_path}/protein_repaired.pdb')
if os.path.exists(f'{sub_apobind_path}/{pdb_id}_apo_added.pdb'):
have_apo = True
else:
have_apo = False
if have_apo:
pdb_m = complete_pdb(env_, f'{sub_apobind_path}/{pdb_id}_apo_added.pdb')
pdb_m.write(f'{sub_MC_path}/protein_modeller.pdb')
os.system(f'grep -v END {sub_MC_path}/protein_modeller.pdb > {sub_MC_path}/protein_repaired_apo.pdb')
####################################################################################################################
# init rosetta
####################################################################################################################
# check https://new.rosettacommons.org/docs/latest/full-options-list for opts
# -ex3 -ex4 -ex1aro -ex2aro
opts = '-ex1 true -packing:ex1:level 1 -ex2 true -packing:ex2:level 1 -extrachi_cutoff 0 -ignore_unrecognized_res true -relax:default_repeats 3'
pyrosetta.distributed.init(opts)
original_pose = pyrosetta.io.pose_from_pdb(f'{sub_MC_path}/protein_repaired.pdb')
original_pose.dump_pdb(f'{sub_MC_path}/origin.pdb')
if have_apo:
apo_pose = pyrosetta.io.pose_from_pdb(f'{sub_MC_path}/protein_repaired_apo.pdb')
# select local res
ligand_mol = read_mol_from_pdbbind(pdbbind_path, pdb_id)
| sys.path.append('/'.join(os.path.abspath(__file__).split('/')[:-2]))
def random_sc(pose, res_list=None, pert=180):
# random chi
if isinstance(res_list, type(None)):
res_list = range(1, pose.size() + 1)
for i in res_list:
res = pose.residue(i)
for chino, chi in enumerate(res.chi(), start=1):
res.set_chi(chino, chi + random.uniform(-pert, pert))
def get_FastRelax(pose, res_list=None, flexbb=True):
if isinstance(res_list, type(None)):
res_list = range(1, pose.size() + 1)
res_selector = core.select.residue_selector.ResidueIndexSelector(','.join([str(i) for i in res_list]))
# get TaskFactory
tf = core.pack.task.TaskFactory()
tf.push_back(core.pack.task.operation.InitializeFromCommandline())
# tf.push_back(core.pack.task.operation.IncludeCurrent())
tf.push_back(core.pack.task.operation.NoRepackDisulfides())
tf.push_back(core.pack.task.operation.RestrictToRepacking())
restrict_to_focus = core.pack.task.operation.OperateOnResidueSubset(core.pack.task.operation.PreventRepackingRLT(),
res_selector,
True) # True indicates flipping the selection
tf.push_back(restrict_to_focus)
# pyrosetta.toolbox.generate_resfile.generate_resfile_from_pose(original_pose, f'{sub_MC_path}/protein_resfile',
# pack=True, design=False, input_sc=False)
# tf.push_back(core.pack.task.operation.ReadResfile(f'{sub_MC_path}/protein_resfile'))
# print(tf.create_task_and_apply_taskoperations(pose))
# test tf
# packer = pyrosetta.rosetta.protocols.minimization_packing.PackRotamersMover()
# packer = pyrosetta.rosetta.protocols.minimization_packing.MinPackMover()
# packer.task_factory(tf)
# packer.apply(pose)
# get FastRelax
mm = core.kinematics.MoveMap()
mm.set_jump(False)
for i in range(1, pose.size()+1):
if i in res_list:
mm.set_chi(i, True)
mm.set_bb(i, flexbb)
else:
mm.set_chi(i, False)
mm.set_bb(i, False)
# mmf = core.select.movemap.MoveMapFactory()
# mmf.all_bb(False)
# mmf.all_bondangles(False)
# mmf.all_bondlengths(False)
# mmf.all_branches(False)
# mmf.all_chi(False)
# mmf.all_jumps(False)
# mmf.all_nu(False)
# mmf.set_cartesian(False)
# mmf.add_bb_action(core.select.movemap.move_map_action.mm_enable, pocket_selector)
# mmf.add_chi_action(core.select.movemap.move_map_action.mm_enable, pocket_selector)
# mm = mmf.create_movemap_from_pose(pose)
fr = pyrosetta.rosetta.protocols.relax.FastRelax()
# fr.max_iter(100)
fr.constrain_relax_to_start_coords(False)
fr.set_movemap_disables_packing_of_fixed_chi_positions(True)
fr.set_task_factory(tf)
fr.set_movemap(mm)
# fr.set_movemap_factory(mmf)
fr.cartesian(False)
fr.set_scorefxn(core.scoring.ScoreFunctionFactory.create_score_function('ref2015_cart'))
fr.min_type('dfpmin_armijo_nonmonotone') # For non-Cartesian scorefunctions, use "dfpmin_armijo_nonmonotone", else lbfgs_armijo_nonmonotone
return fr
def get_torsion(pose):
bb_torsion = []
sc_torsion = []
for i in range(1, pose.size() + 1):
try:
res = pose.residue(i)
assert res.name3() in ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE',
'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']
phi_psi = [pose.phi(i), pose.psi(i)]
chi = [c for c in res.chi()]
bb_torsion.append(phi_psi)
sc_torsion.append(chi)
except:
bb_torsion.append([None])
sc_torsion.append([None])
return {'bb_torsion': bb_torsion, 'sc_torsion': sc_torsion}
def try_gen_pose(task, pose):
try:
task.apply(pose)
return True
except:
return False
def run_single_pdbbind(tup_in):
pdbbind_path, apobind_path, MC_path, pdb_id, n_rand_pert, n_fixbb_repack, n_flexbb_repack, rand_pert_range = tup_in
sub_pdbbind_path = f'{pdbbind_path}/{pdb_id}'
sub_apobind_path = f'{apobind_path}/{pdb_id}'
sub_MC_path = f'{MC_path}/{pdb_id}'
delmkdir(sub_MC_path)
####################################################################################################################
# repaire protein
####################################################################################################################
env_ = environ()
env_.libs.topology.read(file='$(LIB)/top_heav.lib')
env_.libs.parameters.read(file='$(LIB)/par.lib')
pdb_m = complete_pdb(env_, f'{sub_pdbbind_path}/{pdb_id}_protein.pdb')
pdb_m.write(f'{sub_MC_path}/protein_modeller.pdb')
os.system(f'grep HETATM {sub_pdbbind_path}/{pdb_id}_protein.pdb >> {sub_MC_path}/protein_modeller.pdb') # add ion
os.system(f'grep -v END {sub_MC_path}/protein_modeller.pdb > {sub_MC_path}/protein_repaired.pdb')
if os.path.exists(f'{sub_apobind_path}/{pdb_id}_apo_added.pdb'):
have_apo = True
else:
have_apo = False
if have_apo:
pdb_m = complete_pdb(env_, f'{sub_apobind_path}/{pdb_id}_apo_added.pdb')
pdb_m.write(f'{sub_MC_path}/protein_modeller.pdb')
os.system(f'grep -v END {sub_MC_path}/protein_modeller.pdb > {sub_MC_path}/protein_repaired_apo.pdb')
####################################################################################################################
# init rosetta
####################################################################################################################
# check https://new.rosettacommons.org/docs/latest/full-options-list for opts
# -ex3 -ex4 -ex1aro -ex2aro
opts = '-ex1 true -packing:ex1:level 1 -ex2 true -packing:ex2:level 1 -extrachi_cutoff 0 -ignore_unrecognized_res true -relax:default_repeats 3'
pyrosetta.distributed.init(opts)
original_pose = pyrosetta.io.pose_from_pdb(f'{sub_MC_path}/protein_repaired.pdb')
original_pose.dump_pdb(f'{sub_MC_path}/origin.pdb')
if have_apo:
apo_pose = pyrosetta.io.pose_from_pdb(f'{sub_MC_path}/protein_repaired_apo.pdb')
# select local res
ligand_mol = read_mol_from_pdbbind(pdbbind_path, pdb_id) | ligand_coor = get_true_posi(ligand_mol) | 2 | 2023-10-19 22:03:51+00:00 | 4k |
openvpi/SingingVocoders | train.py | [
{
"identifier": "read_full_config",
"path": "utils/config_utils.py",
"snippet": "def read_full_config(config_path: pathlib.Path) -> dict:\n config_path = config_path.resolve()\n config_path_str = config_path.as_posix()\n if config_path in loaded_config_files:\n return loaded_config_files... | import importlib
import logging
import os
import pathlib
import sys
import click
import lightning.pytorch as pl
import torch.utils.data
import yaml
from lightning.pytorch.loggers import TensorBoardLogger
from utils.config_utils import read_full_config, print_config
from utils.training_utils import (
DsModelCheckpoint, DsTQDMProgressBar,
get_latest_checkpoint_path, get_strategy
) | 2,764 |
torch.multiprocessing.set_sharing_strategy(os.getenv('TORCH_SHARE_STRATEGY', 'file_system'))
log_format = '%(asctime)s %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format=log_format, datefmt='%m/%d %I:%M:%S %p')
@click.command(help='')
@click.option('--config', required=True, metavar='FILE', help='Path to the configuration file')
@click.option('--exp_name', required=True, metavar='EXP', help='Name of the experiment')
@click.option('--work_dir', required=False, metavar='DIR', help='Directory to save the experiment')
def train(config, exp_name, work_dir):
config = pathlib.Path(config)
config = read_full_config(config)
print_config(config)
if work_dir is None:
work_dir = pathlib.Path(__file__).parent / 'experiments'
else:
work_dir = pathlib.Path(work_dir)
work_dir = work_dir / exp_name
assert not work_dir.exists() or work_dir.is_dir(), f'Path \'{work_dir}\' is not a directory.'
work_dir.mkdir(parents=True, exist_ok=True)
with open(work_dir / 'config.yaml', 'w', encoding='utf8') as f:
yaml.safe_dump(config, f)
config.update({'work_dir':str(work_dir)})
if not config['nccl_p2p']:
print("Disabling NCCL P2P")
os.environ['NCCL_P2P_DISABLE'] = '1'
pl.seed_everything(config['seed'], workers=True)
assert config['task_cls'] != ''
pkg = ".".join(config["task_cls"].split(".")[:-1])
cls_name = config["task_cls"].split(".")[-1]
task_cls = getattr(importlib.import_module(pkg), cls_name)
# assert issubclass(task_cls, training.BaseTask), f'Task class {task_cls} is not a subclass of {training.BaseTask}.'
task = task_cls(config=config)
# work_dir = pathlib.Path(config['work_dir'])
trainer = pl.Trainer(
accelerator=config['pl_trainer_accelerator'],
devices=config['pl_trainer_devices'],
num_nodes=config['pl_trainer_num_nodes'],
strategy=get_strategy(config['pl_trainer_strategy']),
precision=config['pl_trainer_precision'],
callbacks=[
DsModelCheckpoint(
dirpath=work_dir,
filename='model_ckpt_steps_{step}',
auto_insert_metric_name=False,
monitor='step',
mode='max',
save_last=False,
# every_n_train_steps=config['val_check_interval'],
save_top_k=config['num_ckpt_keep'],
permanent_ckpt_start=config['permanent_ckpt_start'],
permanent_ckpt_interval=config['permanent_ckpt_interval'],
verbose=True
),
# LearningRateMonitor(logging_interval='step'),
DsTQDMProgressBar(),
],
logger=TensorBoardLogger(
save_dir=str(work_dir),
name='lightning_logs',
version='lastest'
),
# gradient_clip_val=config['clip_grad_norm'],
val_check_interval=config['val_check_interval'] ,#* config['accumulate_grad_batches'],
# so this is global_steps
check_val_every_n_epoch=None,
log_every_n_steps=1,
max_steps=config['max_updates'],
use_distributed_sampler=True,
num_sanity_val_steps=config['num_sanity_val_steps'],
# accumulate_grad_batches=config['accumulate_grad_batches']
)
|
torch.multiprocessing.set_sharing_strategy(os.getenv('TORCH_SHARE_STRATEGY', 'file_system'))
log_format = '%(asctime)s %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
format=log_format, datefmt='%m/%d %I:%M:%S %p')
@click.command(help='')
@click.option('--config', required=True, metavar='FILE', help='Path to the configuration file')
@click.option('--exp_name', required=True, metavar='EXP', help='Name of the experiment')
@click.option('--work_dir', required=False, metavar='DIR', help='Directory to save the experiment')
def train(config, exp_name, work_dir):
config = pathlib.Path(config)
config = read_full_config(config)
print_config(config)
if work_dir is None:
work_dir = pathlib.Path(__file__).parent / 'experiments'
else:
work_dir = pathlib.Path(work_dir)
work_dir = work_dir / exp_name
assert not work_dir.exists() or work_dir.is_dir(), f'Path \'{work_dir}\' is not a directory.'
work_dir.mkdir(parents=True, exist_ok=True)
with open(work_dir / 'config.yaml', 'w', encoding='utf8') as f:
yaml.safe_dump(config, f)
config.update({'work_dir':str(work_dir)})
if not config['nccl_p2p']:
print("Disabling NCCL P2P")
os.environ['NCCL_P2P_DISABLE'] = '1'
pl.seed_everything(config['seed'], workers=True)
assert config['task_cls'] != ''
pkg = ".".join(config["task_cls"].split(".")[:-1])
cls_name = config["task_cls"].split(".")[-1]
task_cls = getattr(importlib.import_module(pkg), cls_name)
# assert issubclass(task_cls, training.BaseTask), f'Task class {task_cls} is not a subclass of {training.BaseTask}.'
task = task_cls(config=config)
# work_dir = pathlib.Path(config['work_dir'])
trainer = pl.Trainer(
accelerator=config['pl_trainer_accelerator'],
devices=config['pl_trainer_devices'],
num_nodes=config['pl_trainer_num_nodes'],
strategy=get_strategy(config['pl_trainer_strategy']),
precision=config['pl_trainer_precision'],
callbacks=[
DsModelCheckpoint(
dirpath=work_dir,
filename='model_ckpt_steps_{step}',
auto_insert_metric_name=False,
monitor='step',
mode='max',
save_last=False,
# every_n_train_steps=config['val_check_interval'],
save_top_k=config['num_ckpt_keep'],
permanent_ckpt_start=config['permanent_ckpt_start'],
permanent_ckpt_interval=config['permanent_ckpt_interval'],
verbose=True
),
# LearningRateMonitor(logging_interval='step'),
DsTQDMProgressBar(),
],
logger=TensorBoardLogger(
save_dir=str(work_dir),
name='lightning_logs',
version='lastest'
),
# gradient_clip_val=config['clip_grad_norm'],
val_check_interval=config['val_check_interval'] ,#* config['accumulate_grad_batches'],
# so this is global_steps
check_val_every_n_epoch=None,
log_every_n_steps=1,
max_steps=config['max_updates'],
use_distributed_sampler=True,
num_sanity_val_steps=config['num_sanity_val_steps'],
# accumulate_grad_batches=config['accumulate_grad_batches']
) | trainer.fit(task, ckpt_path=get_latest_checkpoint_path(work_dir)) | 4 | 2023-10-17 13:45:09+00:00 | 4k |
RobertCsordas/moe | models/transformer_language_model.py | [
{
"identifier": "LoggingLayer",
"path": "layers/logging_layer.py",
"snippet": "class LoggingLayer:\n def __init__(self) -> None:\n super().__init__()\n self._logs = {}\n self._log_counts = {}\n self._custom_reductions = {}\n\n def custom_reduction(self, name: str, reduc... | import torch
import torch.nn
import torch.nn.functional as F
import framework
import math
from typing import Optional, Tuple, Any, List
from layers import LoggingLayer
from layers.transformer.multi_head_attention import AttentionMask
from layers.transformer.transformer import Transformer | 2,064 | self.shared_layers = all([la is layers[0] for la in layers])
if embedding_size is None:
self.embedding_adapter = lambda x: x
else:
self.embedding_adapter = torch.nn.Linear(embedding_size, state_size)
self.dropout = torch.nn.Dropout(dropout)
self.layers = torch.nn.ModuleList(layers)
self.output_adapter = lambda x: x
self.n_prev_states = n_prev_states
self.n_prev_states_test = n_prev_states_test or n_prev_states
self.same_length_eval = same_length_eval
self.embedding_scale = math.sqrt(state_size)
self.p_drop_layer = p_drop_layer
self.use_last_state = use_last_state
self.same_length = same_length
self.iter = 0
self.output_mode = output_mode
assert self.output_mode in {"normal", "sum", "geometric", "sigmoid"}
if self.output_mode in {"geometric", "sigmoid"}:
self.output_gate = torch.nn.Linear(state_size, 1)
self.adaptive = bool(adaptive_cutoffs)
out_proj_size = (embedding_size or state_size) if tied_embedding else state_size
if self.adaptive:
self.output = framework.layers.CustomAdaptiveLogSoftmaxWithLoss(
out_proj_size, voc_size, adaptive_cutoffs, div_value=1,
tied_to=self.embedding if tied_embedding else None)
else:
self.output = torch.nn.Linear(out_proj_size, voc_size)
if norm_before_output or self.output_mode in {"sum", "sigmoid"}:
self.out_norm = torch.nn.LayerNorm(state_size)
else:
self.out_norm = lambda x: x
if tied_embedding:
if not self.adaptive:
self.output.weight = self.embedding.weight
if embedding_size is not None:
self.output_adapter = torch.nn.Linear(state_size, embedding_size)
@staticmethod
def generate_history_mask(sz: int, device: torch.device) -> torch.Tensor:
return torch.tril(torch.ones(sz, sz, dtype=torch.bool, device=device), diagonal=-1)
def gen_output(self, x: torch.Tensor, target: Optional[torch.Tensor]) -> torch.Tensor:
net = self.out_norm(x)
net = self.output_adapter(net)
net = self.dropout(net)
if self.adaptive:
net = self.output(net.transpose(0, 1), target)
else:
net = self.output(net.transpose(0, 1))
return net
def accumulate_output(self, features: List[torch.Tensor]) -> torch.Tensor:
if self.output_mode == "sum":
return sum(features)
elif self.output_mode in {"geometric", "sigmoid"}:
# Must cast it to float16, otherwise pytorch will crash after a few hundred iterations with an
# incomprehensible error in the gradient scaler
gates = torch.sigmoid(torch.cat([self.output_gate(f).float() for f in features], -1))
if self.output_mode == "geometric":
ngates = torch.cumprod(1.0 - gates, -1)
scores = torch.cat([gates[..., 0:1], gates[..., 1:] * ngates[..., :-1]], -1)
else:
scores = gates
if self.iter % 100 == 0 and self.training:
self.log("output_gate_mean", framework.visualize.plot.Barplot(scores.flatten(end_dim=-2).mean(0)))
# return sum(f * scores[..., i: i+1] for i, f in enumerate(features))
f = scores.unsqueeze(-2) @ torch.stack(features, -2)
return f.squeeze(-2)
else:
assert False, "Invalid output mode"
def forward(self, x: torch.Tensor, target: Optional[torch.Tensor], state) -> Tuple[torch.Tensor, Any]:
causality_mask = Transformer.generate_square_subsequent_mask(x.shape[0], x.device)
net = self.dropout(self.embedding(x.T.long()))
net = self.embedding_adapter(net)
net = net * self.embedding_scale
new_state = []
features = [net]
n_prev_states = self.n_prev_states if self.training else self.n_prev_states_test
same_length = self.same_length or ((not self.training) and self.same_length_eval)
if same_length and state is not None:
causality_mask = [self.generate_history_mask(x.shape[0], x.device)] + \
[torch.zeros_like(causality_mask)] * (len(state[0]) - 1) + [causality_mask]
causality_mask = torch.cat(causality_mask, -1)
plot_cossim = (self.iter % 100 == 0 and self.training)
for li, l in enumerate(self.layers):
if n_prev_states > 0:
if li == 0:
# Pos offset should be constant for all layers
pos_offset = sum(s.shape[1] for s in state[0]) if state is not None else 0
# Concatenate the new state with the previous states
li_r = 0 if self.use_last_state else li
s = (state[li_r] + [net]) if state is not None else [net]
attend_to = torch.cat(s, 1)
if not self.use_last_state:
s[-1] = s[-1].detach()
new_state.append(s[-n_prev_states:])
else:
pos_offset = None
attend_to = None
|
class TransformerLanguageModel(LoggingLayer, torch.nn.Module):
def __init__(self, voc_size: int, embedding_size: Optional[int], state_size: int, dropout: float,
tied_embedding: bool, layers: List[torch.nn.Module], n_prev_states: int,
n_prev_states_test: Optional[int] = None, adaptive_cutoffs: List[int] = [],
same_length_eval: bool = True, norm_before_output: bool = False,
p_drop_layer: float = 0.0, use_last_state: bool = False, same_length: bool = False,
output_mode: str = "normal"):
super().__init__()
self.embedding = torch.nn.Embedding(voc_size, embedding_size or state_size)
# with torch.no_grad():
# self.embedding.weight.uniform_(-0.1, 0.1)
torch.nn.init.xavier_uniform_(self.embedding.weight)
self.shared_layers = all([la is layers[0] for la in layers])
if embedding_size is None:
self.embedding_adapter = lambda x: x
else:
self.embedding_adapter = torch.nn.Linear(embedding_size, state_size)
self.dropout = torch.nn.Dropout(dropout)
self.layers = torch.nn.ModuleList(layers)
self.output_adapter = lambda x: x
self.n_prev_states = n_prev_states
self.n_prev_states_test = n_prev_states_test or n_prev_states
self.same_length_eval = same_length_eval
self.embedding_scale = math.sqrt(state_size)
self.p_drop_layer = p_drop_layer
self.use_last_state = use_last_state
self.same_length = same_length
self.iter = 0
self.output_mode = output_mode
assert self.output_mode in {"normal", "sum", "geometric", "sigmoid"}
if self.output_mode in {"geometric", "sigmoid"}:
self.output_gate = torch.nn.Linear(state_size, 1)
self.adaptive = bool(adaptive_cutoffs)
out_proj_size = (embedding_size or state_size) if tied_embedding else state_size
if self.adaptive:
self.output = framework.layers.CustomAdaptiveLogSoftmaxWithLoss(
out_proj_size, voc_size, adaptive_cutoffs, div_value=1,
tied_to=self.embedding if tied_embedding else None)
else:
self.output = torch.nn.Linear(out_proj_size, voc_size)
if norm_before_output or self.output_mode in {"sum", "sigmoid"}:
self.out_norm = torch.nn.LayerNorm(state_size)
else:
self.out_norm = lambda x: x
if tied_embedding:
if not self.adaptive:
self.output.weight = self.embedding.weight
if embedding_size is not None:
self.output_adapter = torch.nn.Linear(state_size, embedding_size)
@staticmethod
def generate_history_mask(sz: int, device: torch.device) -> torch.Tensor:
return torch.tril(torch.ones(sz, sz, dtype=torch.bool, device=device), diagonal=-1)
def gen_output(self, x: torch.Tensor, target: Optional[torch.Tensor]) -> torch.Tensor:
net = self.out_norm(x)
net = self.output_adapter(net)
net = self.dropout(net)
if self.adaptive:
net = self.output(net.transpose(0, 1), target)
else:
net = self.output(net.transpose(0, 1))
return net
def accumulate_output(self, features: List[torch.Tensor]) -> torch.Tensor:
if self.output_mode == "sum":
return sum(features)
elif self.output_mode in {"geometric", "sigmoid"}:
# Must cast it to float16, otherwise pytorch will crash after a few hundred iterations with an
# incomprehensible error in the gradient scaler
gates = torch.sigmoid(torch.cat([self.output_gate(f).float() for f in features], -1))
if self.output_mode == "geometric":
ngates = torch.cumprod(1.0 - gates, -1)
scores = torch.cat([gates[..., 0:1], gates[..., 1:] * ngates[..., :-1]], -1)
else:
scores = gates
if self.iter % 100 == 0 and self.training:
self.log("output_gate_mean", framework.visualize.plot.Barplot(scores.flatten(end_dim=-2).mean(0)))
# return sum(f * scores[..., i: i+1] for i, f in enumerate(features))
f = scores.unsqueeze(-2) @ torch.stack(features, -2)
return f.squeeze(-2)
else:
assert False, "Invalid output mode"
def forward(self, x: torch.Tensor, target: Optional[torch.Tensor], state) -> Tuple[torch.Tensor, Any]:
causality_mask = Transformer.generate_square_subsequent_mask(x.shape[0], x.device)
net = self.dropout(self.embedding(x.T.long()))
net = self.embedding_adapter(net)
net = net * self.embedding_scale
new_state = []
features = [net]
n_prev_states = self.n_prev_states if self.training else self.n_prev_states_test
same_length = self.same_length or ((not self.training) and self.same_length_eval)
if same_length and state is not None:
causality_mask = [self.generate_history_mask(x.shape[0], x.device)] + \
[torch.zeros_like(causality_mask)] * (len(state[0]) - 1) + [causality_mask]
causality_mask = torch.cat(causality_mask, -1)
plot_cossim = (self.iter % 100 == 0 and self.training)
for li, l in enumerate(self.layers):
if n_prev_states > 0:
if li == 0:
# Pos offset should be constant for all layers
pos_offset = sum(s.shape[1] for s in state[0]) if state is not None else 0
# Concatenate the new state with the previous states
li_r = 0 if self.use_last_state else li
s = (state[li_r] + [net]) if state is not None else [net]
attend_to = torch.cat(s, 1)
if not self.use_last_state:
s[-1] = s[-1].detach()
new_state.append(s[-n_prev_states:])
else:
pos_offset = None
attend_to = None
| net_o = l(net, mask=AttentionMask(None, causality_mask), attend_to=attend_to, | 1 | 2023-10-16 11:26:45+00:00 | 4k |
yk/llmvm | parsing.py | [
{
"identifier": "Arg",
"path": "interface.py",
"snippet": "class Arg(pydantic.BaseModel):\n vtype: str\n value: str"
},
{
"identifier": "Load",
"path": "interface.py",
"snippet": "class Load(Expr):\n kind: str = \"load\"\n vtype: str\n ptr: str"
},
{
"identifier": ... | import re
from loguru import logger
from interface import Arg, Load, Icmp, Srem, Add, Mul, Call, Assign, Store, Branch, BranchCond, Return, Program, to_vtype, GetElementPtr, Copy, Switch, AllocArray, Alloc | 2,119 | def parse_arg(arg):
logger.debug(f"parse_arg({arg})")
if m := re.match(r"ptr noundef (\S+)", arg):
return Arg(vtype="str", value=m.group(1))
if m := re.match(r"i32 noundef (\S+)", arg):
return Arg(vtype="i32", value=m.group(1))
raise NotImplementedError(arg)
def parse_call(expr):
logger.debug(f"parse_call({expr})")
if m := re.match(r"\s*call \w+(?: \(.*\))? @(\w+)\((.*)\)", expr):
name, args = m.groups()
args = args.split(", ")
args = [parse_arg(arg) for arg in args if arg]
return Call(name=name, args=args)
return None
def parse_expr(expr):
if m := re.match(r"alloca \[(\d+) x (\S+)\]", expr):
size, vtype = m.groups()
return AllocArray(vtype=vtype, size=int(size))
if m := re.match(r"alloca (\S+),", expr):
vtype = m.group(1)
return Alloc(vtype=vtype)
if m := re.match(r"sext \S+ (\S+) to \S+", expr):
return Copy(ptr=m.group(1))
if m := re.match(r"load (\w+), ptr (%\d+),", expr):
return Load(vtype=m.group(1), ptr=m.group(2))
if m := re.match(r"icmp (eq|ne|sgt|sge|slt|sle) (\w+) (\S+), (\S+)", expr):
op, vtype, lhs, rhs = m.groups()
return Icmp(vtype=vtype, op=op, lhs=lhs, rhs=rhs)
if m := re.match(r"srem (\w+) (\S+), (\S+)", expr):
vtype, lhs, rhs = m.groups()
return Srem(vtype=vtype, lhs=lhs, rhs=rhs)
if m := re.match(r"add nsw (\w+) (\S+), (\S+)", expr):
vtype, lhs, rhs = m.groups()
return Add(vtype=vtype, lhs=lhs, rhs=rhs)
if m := re.match(r"mul nsw (\w+) (\S+), (\S+)", expr):
vtype, lhs, rhs = m.groups()
return Mul(vtype=vtype, lhs=lhs, rhs=rhs)
if call := parse_call(expr):
if call is not None:
logger.debug(f"found call {call}")
return call
if m := re.match(r"getelementptr inbounds \[\d+ x (\S+)\], ptr (\S+), i32 0, i32 (\S+)", expr):
vtype, ptr, idx = m.groups()
return GetElementPtr(vtype=vtype, ptr=ptr, idx=idx)
raise NotImplementedError(expr)
def parse_switch(in_f):
cases = {}
for line in _line_stripper(in_f):
if re.fullmatch(r"\s+\]", line):
break
if m := re.match(r"\s+i32 (\S+), label %(\d+)", line):
value, label = m.groups()
cases[value] = label
continue
raise NotImplementedError(line)
else:
raise ValueError("Expected ']' in switch")
return cases
def parse_instructions(in_f):
instructions = []
labels = {}
for line in _line_stripper(in_f):
if re.fullmatch(r"\}", line):
break
if m := re.match(r"(\d+):", line):
label = m.group(1)
labels[label] = len(instructions)
continue
if m := re.fullmatch(r"\s+(%\d+) = (.*)", line): # register assignment
reg, expr = m.groups()
expr = parse_expr(expr)
if expr is not None:
instructions.append(Assign(reg=reg, expr=expr))
continue
if m := re.match(r"\s+store (\w+) (\S+), ptr (\S+),", line):
vtype, value, ptr = m.groups()
instructions.append(Store(vtype=vtype, value=value, ptr=ptr))
continue
if m := re.match(r"\s+br label %(\d+)", line):
label = m.group(1)
instructions.append(Branch(label=label))
continue
if m := re.match(r"\s+br i1 (%\d+), label %(\d+), label %(\d+)", line):
cond_reg, label_true, label_false = m.groups()
instructions.append(BranchCond(cond_reg=cond_reg, label_true=label_true, label_false=label_false))
continue
if m := re.match(r"\s+ret (\S+) (\S+)", line):
vtype, value = m.groups()
instructions.append(Return(vtype=vtype, value=value))
continue
if call := parse_call(line):
if call is not None:
logger.debug(f"found call {call}")
instructions.append(call)
continue
if m := re.match(r"\s+switch \S+ (\S+), label %(\d+) \[", line):
ptr, default_label = m.groups()
cases = parse_switch(in_f)
instructions.append(Switch(ptr=ptr, default_label=default_label, cases=cases))
continue
raise NotImplementedError(line)
return instructions, labels
def parse_program(in_f):
constants = {}
for line in _line_stripper(in_f):
if m := re.match(r'(@\.str(?:\.\d+)?) .* c"([^"]+)\\00",', line):
name, value = m.groups()
value = value.replace(r"\0A", "\n")
|
def _line_stripper(in_f):
for line in in_f:
line = line.rstrip()
if not line:
continue
yield line
def parse_arg(arg):
logger.debug(f"parse_arg({arg})")
if m := re.match(r"ptr noundef (\S+)", arg):
return Arg(vtype="str", value=m.group(1))
if m := re.match(r"i32 noundef (\S+)", arg):
return Arg(vtype="i32", value=m.group(1))
raise NotImplementedError(arg)
def parse_call(expr):
logger.debug(f"parse_call({expr})")
if m := re.match(r"\s*call \w+(?: \(.*\))? @(\w+)\((.*)\)", expr):
name, args = m.groups()
args = args.split(", ")
args = [parse_arg(arg) for arg in args if arg]
return Call(name=name, args=args)
return None
def parse_expr(expr):
if m := re.match(r"alloca \[(\d+) x (\S+)\]", expr):
size, vtype = m.groups()
return AllocArray(vtype=vtype, size=int(size))
if m := re.match(r"alloca (\S+),", expr):
vtype = m.group(1)
return Alloc(vtype=vtype)
if m := re.match(r"sext \S+ (\S+) to \S+", expr):
return Copy(ptr=m.group(1))
if m := re.match(r"load (\w+), ptr (%\d+),", expr):
return Load(vtype=m.group(1), ptr=m.group(2))
if m := re.match(r"icmp (eq|ne|sgt|sge|slt|sle) (\w+) (\S+), (\S+)", expr):
op, vtype, lhs, rhs = m.groups()
return Icmp(vtype=vtype, op=op, lhs=lhs, rhs=rhs)
if m := re.match(r"srem (\w+) (\S+), (\S+)", expr):
vtype, lhs, rhs = m.groups()
return Srem(vtype=vtype, lhs=lhs, rhs=rhs)
if m := re.match(r"add nsw (\w+) (\S+), (\S+)", expr):
vtype, lhs, rhs = m.groups()
return Add(vtype=vtype, lhs=lhs, rhs=rhs)
if m := re.match(r"mul nsw (\w+) (\S+), (\S+)", expr):
vtype, lhs, rhs = m.groups()
return Mul(vtype=vtype, lhs=lhs, rhs=rhs)
if call := parse_call(expr):
if call is not None:
logger.debug(f"found call {call}")
return call
if m := re.match(r"getelementptr inbounds \[\d+ x (\S+)\], ptr (\S+), i32 0, i32 (\S+)", expr):
vtype, ptr, idx = m.groups()
return GetElementPtr(vtype=vtype, ptr=ptr, idx=idx)
raise NotImplementedError(expr)
def parse_switch(in_f):
cases = {}
for line in _line_stripper(in_f):
if re.fullmatch(r"\s+\]", line):
break
if m := re.match(r"\s+i32 (\S+), label %(\d+)", line):
value, label = m.groups()
cases[value] = label
continue
raise NotImplementedError(line)
else:
raise ValueError("Expected ']' in switch")
return cases
def parse_instructions(in_f):
instructions = []
labels = {}
for line in _line_stripper(in_f):
if re.fullmatch(r"\}", line):
break
if m := re.match(r"(\d+):", line):
label = m.group(1)
labels[label] = len(instructions)
continue
if m := re.fullmatch(r"\s+(%\d+) = (.*)", line): # register assignment
reg, expr = m.groups()
expr = parse_expr(expr)
if expr is not None:
instructions.append(Assign(reg=reg, expr=expr))
continue
if m := re.match(r"\s+store (\w+) (\S+), ptr (\S+),", line):
vtype, value, ptr = m.groups()
instructions.append(Store(vtype=vtype, value=value, ptr=ptr))
continue
if m := re.match(r"\s+br label %(\d+)", line):
label = m.group(1)
instructions.append(Branch(label=label))
continue
if m := re.match(r"\s+br i1 (%\d+), label %(\d+), label %(\d+)", line):
cond_reg, label_true, label_false = m.groups()
instructions.append(BranchCond(cond_reg=cond_reg, label_true=label_true, label_false=label_false))
continue
if m := re.match(r"\s+ret (\S+) (\S+)", line):
vtype, value = m.groups()
instructions.append(Return(vtype=vtype, value=value))
continue
if call := parse_call(line):
if call is not None:
logger.debug(f"found call {call}")
instructions.append(call)
continue
if m := re.match(r"\s+switch \S+ (\S+), label %(\d+) \[", line):
ptr, default_label = m.groups()
cases = parse_switch(in_f)
instructions.append(Switch(ptr=ptr, default_label=default_label, cases=cases))
continue
raise NotImplementedError(line)
return instructions, labels
def parse_program(in_f):
constants = {}
for line in _line_stripper(in_f):
if m := re.match(r'(@\.str(?:\.\d+)?) .* c"([^"]+)\\00",', line):
name, value = m.groups()
value = value.replace(r"\0A", "\n") | constants[name] = to_vtype(value=value, vtype="str") | 13 | 2023-10-23 21:29:14+00:00 | 4k |
w-e-w/sd-webui-nudenet-nsfw-censor | scripts/nudenet_nsfw_censor_scripts/post_processing_script.py | [
{
"identifier": "pil_nude_detector",
"path": "scripts/nudenet_nsfw_censor_scripts/pil_nude_detector.py",
"snippet": "def draw_ellipse(draw, left_expanded, top_expanded, right_expanded, down_expanded, *args, **kwargs):\ndef draw_rectangle(draw, left_expanded, top_expanded, right_expanded, down_expanded, ... | from scripts.nudenet_nsfw_censor_scripts.pil_nude_detector import pil_nude_detector, mask_shapes_func_dict
from scripts.nudenet_nsfw_censor_scripts.censor_image_filters import apply_filter, filter_dict
from modules import shared, images, scripts_postprocessing
from PIL import Image, ImageFilter
from math import sqrt
from modules.ui_components import InputAccordion
import gradio as gr | 2,843 | mask_brush_color.change(
fn=update_mask_brush_color,
inputs=[mask_brush_color],
outputs=[input_mask]
)
def get_current_image(image):
# ToDo if possible make this a client side operation
if image:
return gr.Image.update(image)
dummy_component = gr.Label(visible=False)
create_canvas.click(
fn=get_current_image,
_js='getCurrentExtraSourceImg',
inputs=[dummy_component],
outputs=[input_mask],
postprocess=False,
)
def update_opt_ui(_filter_type, _mask_shape, _override_settings, _enable_nudenet):
filter_opt_enable_list = filter_opt_ui_show_dict[_filter_type]
mask_shape_opt_show_list = mask_shape_opt_ui_show_dict[_mask_shape]
# blur_radius, blur_strength_curve, pixelation_factor, fill_color, mask_blend_radius, mask_blend_radius_variable_blur, rectangle_round_radius, nms_threshold
return (
gr.Dropdown.update(visible=_override_settings), # filter_type
gr.Dropdown.update(visible=_override_settings), # mask_shape
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[0]), # blur_radius
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[1]), # blur_strength_curve
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[2]), # pixelation_factor
gr.ColorPicker.update(visible=_override_settings and filter_opt_enable_list[3]), # fill_color
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[4] and mask_shape_opt_show_list[0]), # mask_blend_radius
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[5] and mask_shape_opt_show_list[0]), # mask_blend_radius_variable_blur
gr.Number().update(visible=_override_settings and mask_shape_opt_show_list[1]), # rectangle_round_radius
gr.Slider.update(visible=_override_settings and mask_shape_opt_show_list[2] and _enable_nudenet), # nms_threshold
)
for element in [override_settings, filter_type, mask_shape, enable_nudenet]:
element.change(update_opt_ui, inputs=[filter_type, mask_shape, override_settings, enable_nudenet], outputs=[filter_type, mask_shape, blur_radius, blur_strength_curve, pixelation_factor, fill_color, mask_blend_radius, mask_blend_radius_variable_blur, rectangle_round_radius, nms_threshold])
controls = {
'enable': enable,
'enable_nudenet': enable_nudenet,
'override_settings': override_settings,
'save_mask': save_mask,
'filter_type': filter_type,
'blur_radius': blur_radius,
'pixelation_factor': pixelation_factor,
'fill_color': fill_color,
'mask_shape': mask_shape,
'blur_strength_curve': blur_strength_curve,
'mask_blend_radius': mask_blend_radius,
'mask_blend_radius_variable_blur': mask_blend_radius_variable_blur,
'rectangle_round_radius': rectangle_round_radius,
'nms_threshold': nms_threshold,
'input_mask': input_mask,
'mask_source': mask_source,
}
return controls
def process(self, pp: scripts_postprocessing.PostprocessedImage, **args):
if not args['enable']:
return
censor_mask = None
if args['input_mask']:
if 'Upload mask' in args['mask_source']:
censor_mask = args['input_mask']['image'].convert('L').resize(pp.image.size)
if 'Draw mask' in args['mask_source']:
censor_mask = Image.new('L', pp.image.size, 0) if censor_mask is None else censor_mask
draw_mask = args['input_mask']['mask'].convert('L').resize(pp.image.size)
censor_mask.paste(draw_mask, draw_mask)
if args['enable_nudenet']:
if args['override_settings']:
nms_threshold = args['nms_threshold']
mask_shape = args['mask_shape']
rectangle_round_radius = args['rectangle_round_radius']
else:
nms_threshold = shared.opts.nudenet_nsfw_censor_nms_threshold
mask_shape = shared.opts.nudenet_nsfw_censor_mask_shape
rectangle_round_radius = shared.opts.nudenet_nsfw_censor_rectangle_round_radius
if pil_nude_detector.thresholds is None:
pil_nude_detector.refresh_label_configs()
nudenet_mask = pil_nude_detector.get_censor_mask(pp.image, nms_threshold, mask_shape, rectangle_round_radius, pil_nude_detector.thresholds, pil_nude_detector.expand_horizontal, pil_nude_detector.expand_vertical)
if nudenet_mask is not None:
nudenet_mask = nudenet_mask.convert('L')
if nudenet_mask and censor_mask:
censor_mask.paste(nudenet_mask, nudenet_mask)
else:
censor_mask = nudenet_mask
if censor_mask:
scale_factor = sqrt((pp.image.size[0] ** 2 + pp.image.size[1] ** 2) / 524288)
save_mask = args['save_mask']
if args['override_settings']:
filter_type = args['filter_type']
mask_blend_radius = args['mask_blend_radius_variable_blur'] if filter_type == 'Variable blur' else args['mask_blend_radius']
filter_settings = {
'blur_radius': args['blur_radius'],
'blur_strength_curve': args['blur_strength_curve'],
'color': args['fill_color'],
'pixelation_factor': args['pixelation_factor'],
}
else:
filter_type = shared.opts.nudenet_nsfw_censor_extras_filter_type
mask_blend_radius = shared.opts.nudenet_nsfw_censor_mask_blend_radius_variable_blur if filter_type == 'Variable blur' else shared.opts.nudenet_nsfw_censor_mask_blend_radius
filter_settings = {
'blur_radius': shared.opts.nudenet_nsfw_censor_blur_radius * scale_factor,
'blur_strength_curve': shared.opts.nudenet_nsfw_censor_blur_strength_curve,
'color': shared.opts.nudenet_nsfw_censor_fill_color,
'pixelation_factor': shared.opts.nudenet_nsfw_censor_pixelation_factor,
}
censor_mask = censor_mask.filter(ImageFilter.GaussianBlur(mask_blend_radius * scale_factor))
if filter_type:
|
if hasattr(scripts_postprocessing.ScriptPostprocessing, 'process_firstpass'): # webui >= 1.7
else:
InputAccordion = None
filter_opt_ui_show_dict = {
# [blur_radius, blur_strength_curve, pixelation_factor, fill_color, mask_blend_radius, mask_blend_radius_variable_blur]
'Variable blur': [True, True, False, False, False, True],
'Gaussian Blur': [True, False, False, False, True, False],
'Pixelate': [False, False, True, False, True, False],
'Fill color': [False, False, False, True, True, False],
'Detect only': [False, False, False, False, True, False],
}
mask_shape_opt_ui_show_dict = {
# [(mask_blend_radius, mask_blend_radius_variable_blur), rectangle_round_radius, nms_threshold]
'Ellipse': [True, False, True],
'Rectangle': [True, False, True],
'Rounded rectangle': [True, True, True],
'Entire image': [False, False, False]
}
class ScriptPostprocessingNudenetCensor(scripts_postprocessing.ScriptPostprocessing):
name = 'NudeNet NSFW censor'
order = 100000
def ui(self):
with (
InputAccordion(False, label="NSFW Censor", elem_id='nudenet_nsfw_censor_extras') if InputAccordion
else gr.Accordion('NSFW Censor', open=False, elem_id='nudenet_nsfw_censor_extras')
as enable
):
with gr.Row():
if not InputAccordion:
enable = gr.Checkbox(False, label='Enable', elem_id='nudenet_nsfw_censor_extras-visible-checkbox')
enable_nudenet = gr.Checkbox(True, label='NudeNet Auto-detect')
save_mask = gr.Checkbox(False, label='Save mask')
override_settings = gr.Checkbox(False, label='Override filter configs')
with gr.Row():
filter_type = gr.Dropdown(value='Variable blur', label='Censor filter', choices=list(filter_dict), visible=False)
mask_shape = gr.Dropdown(value='Ellipse', choices=list(mask_shapes_func_dict), label='Mask shape', visible=False)
with gr.Row():
blur_radius = gr.Slider(0, 100, 10, label='Blur radius', visible=False) # Variable blur Gaussian Blur
blur_strength_curve = gr.Slider(0, 6, 3, label='Blur strength curve', visible=False) # Variable blur
pixelation_factor = gr.Slider(1, 10, 5, label='Pixelation factor', visible=False) # Pixelate
fill_color = gr.ColorPicker(value='#000000', label='fill color', visible=False) # Fill color
mask_blend_radius = gr.Slider(0, 100, 0, label='Mask blend radius', visible=False) # except Variable blur
mask_blend_radius_variable_blur = gr.Slider(0, 100, 10, label='Variable blur mask blend radius', visible=False) # Variable blur
nms_threshold = gr.Slider(0, 1, 1, label='NMS threshold', visible=False) # NMS threshold
rectangle_round_radius = gr.Number(value=0.5, label='Rectangle round radius', visible=False) # Rounded rectangle
with gr.Row():
create_canvas = gr.Button('Create canvas')
mask_source = gr.CheckboxGroup(['Draw mask', 'Upload mask'], value=['Draw mask'], label="Canvas mask source")
mask_brush_color = gr.ColorPicker('#000000', label='Brush color', info='visual only, use when brush color is hard to see')
with gr.Row():
input_mask = gr.Image(
label="Censor mask",
show_label=False,
elem_id="nsfw_censor_mask",
source="upload",
interactive=True,
type="pil",
tool="sketch",
image_mode="RGBA",
brush_color='#000000'
)
def update_mask_brush_color(color):
return gr.Image.update(brush_color=color)
mask_brush_color.change(
fn=update_mask_brush_color,
inputs=[mask_brush_color],
outputs=[input_mask]
)
def get_current_image(image):
# ToDo if possible make this a client side operation
if image:
return gr.Image.update(image)
dummy_component = gr.Label(visible=False)
create_canvas.click(
fn=get_current_image,
_js='getCurrentExtraSourceImg',
inputs=[dummy_component],
outputs=[input_mask],
postprocess=False,
)
def update_opt_ui(_filter_type, _mask_shape, _override_settings, _enable_nudenet):
filter_opt_enable_list = filter_opt_ui_show_dict[_filter_type]
mask_shape_opt_show_list = mask_shape_opt_ui_show_dict[_mask_shape]
# blur_radius, blur_strength_curve, pixelation_factor, fill_color, mask_blend_radius, mask_blend_radius_variable_blur, rectangle_round_radius, nms_threshold
return (
gr.Dropdown.update(visible=_override_settings), # filter_type
gr.Dropdown.update(visible=_override_settings), # mask_shape
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[0]), # blur_radius
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[1]), # blur_strength_curve
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[2]), # pixelation_factor
gr.ColorPicker.update(visible=_override_settings and filter_opt_enable_list[3]), # fill_color
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[4] and mask_shape_opt_show_list[0]), # mask_blend_radius
gr.Slider.update(visible=_override_settings and filter_opt_enable_list[5] and mask_shape_opt_show_list[0]), # mask_blend_radius_variable_blur
gr.Number().update(visible=_override_settings and mask_shape_opt_show_list[1]), # rectangle_round_radius
gr.Slider.update(visible=_override_settings and mask_shape_opt_show_list[2] and _enable_nudenet), # nms_threshold
)
for element in [override_settings, filter_type, mask_shape, enable_nudenet]:
element.change(update_opt_ui, inputs=[filter_type, mask_shape, override_settings, enable_nudenet], outputs=[filter_type, mask_shape, blur_radius, blur_strength_curve, pixelation_factor, fill_color, mask_blend_radius, mask_blend_radius_variable_blur, rectangle_round_radius, nms_threshold])
controls = {
'enable': enable,
'enable_nudenet': enable_nudenet,
'override_settings': override_settings,
'save_mask': save_mask,
'filter_type': filter_type,
'blur_radius': blur_radius,
'pixelation_factor': pixelation_factor,
'fill_color': fill_color,
'mask_shape': mask_shape,
'blur_strength_curve': blur_strength_curve,
'mask_blend_radius': mask_blend_radius,
'mask_blend_radius_variable_blur': mask_blend_radius_variable_blur,
'rectangle_round_radius': rectangle_round_radius,
'nms_threshold': nms_threshold,
'input_mask': input_mask,
'mask_source': mask_source,
}
return controls
def process(self, pp: scripts_postprocessing.PostprocessedImage, **args):
if not args['enable']:
return
censor_mask = None
if args['input_mask']:
if 'Upload mask' in args['mask_source']:
censor_mask = args['input_mask']['image'].convert('L').resize(pp.image.size)
if 'Draw mask' in args['mask_source']:
censor_mask = Image.new('L', pp.image.size, 0) if censor_mask is None else censor_mask
draw_mask = args['input_mask']['mask'].convert('L').resize(pp.image.size)
censor_mask.paste(draw_mask, draw_mask)
if args['enable_nudenet']:
if args['override_settings']:
nms_threshold = args['nms_threshold']
mask_shape = args['mask_shape']
rectangle_round_radius = args['rectangle_round_radius']
else:
nms_threshold = shared.opts.nudenet_nsfw_censor_nms_threshold
mask_shape = shared.opts.nudenet_nsfw_censor_mask_shape
rectangle_round_radius = shared.opts.nudenet_nsfw_censor_rectangle_round_radius
if pil_nude_detector.thresholds is None:
pil_nude_detector.refresh_label_configs()
nudenet_mask = pil_nude_detector.get_censor_mask(pp.image, nms_threshold, mask_shape, rectangle_round_radius, pil_nude_detector.thresholds, pil_nude_detector.expand_horizontal, pil_nude_detector.expand_vertical)
if nudenet_mask is not None:
nudenet_mask = nudenet_mask.convert('L')
if nudenet_mask and censor_mask:
censor_mask.paste(nudenet_mask, nudenet_mask)
else:
censor_mask = nudenet_mask
if censor_mask:
scale_factor = sqrt((pp.image.size[0] ** 2 + pp.image.size[1] ** 2) / 524288)
save_mask = args['save_mask']
if args['override_settings']:
filter_type = args['filter_type']
mask_blend_radius = args['mask_blend_radius_variable_blur'] if filter_type == 'Variable blur' else args['mask_blend_radius']
filter_settings = {
'blur_radius': args['blur_radius'],
'blur_strength_curve': args['blur_strength_curve'],
'color': args['fill_color'],
'pixelation_factor': args['pixelation_factor'],
}
else:
filter_type = shared.opts.nudenet_nsfw_censor_extras_filter_type
mask_blend_radius = shared.opts.nudenet_nsfw_censor_mask_blend_radius_variable_blur if filter_type == 'Variable blur' else shared.opts.nudenet_nsfw_censor_mask_blend_radius
filter_settings = {
'blur_radius': shared.opts.nudenet_nsfw_censor_blur_radius * scale_factor,
'blur_strength_curve': shared.opts.nudenet_nsfw_censor_blur_strength_curve,
'color': shared.opts.nudenet_nsfw_censor_fill_color,
'pixelation_factor': shared.opts.nudenet_nsfw_censor_pixelation_factor,
}
censor_mask = censor_mask.filter(ImageFilter.GaussianBlur(mask_blend_radius * scale_factor))
if filter_type: | pp.image = apply_filter(pp.image, censor_mask, filter_type, **filter_settings) | 1 | 2023-10-16 16:44:07+00:00 | 4k |
enkeejunior1/Diffusion-Pullback | src/models/guided_diffusion/unet.py | [
{
"identifier": "convert_module_to_f16",
"path": "src/models/guided_diffusion/fp16_util.py",
"snippet": "def convert_module_to_f16(l):\n \"\"\"\n Convert primitive modules to float16.\n \"\"\"\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):\n l.weight.data = l.weight.data.half(... | from abc import abstractmethod
from einops import rearrange, reduce, repeat, einsum
from .fp16_util import convert_module_to_f16, convert_module_to_f32
from .nn import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
import math
import time
import torchvision.utils as tvu
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F | 3,468 | )
self.input_blocks.append(TimestepEmbedSequential(*layers))
self._feature_size += ch
input_block_chans.append(ch)
if level != len(channel_mult) - 1:
out_ch = ch
self.input_blocks.append(
TimestepEmbedSequential(
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=out_ch,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
down=True,
)
if resblock_updown
else Downsample(
ch, conv_resample, dims=dims, out_channels=out_ch
)
)
)
ch = out_ch
input_block_chans.append(ch)
ds *= 2
self._feature_size += ch
self.middle_block = TimestepEmbedSequential(
ResBlock(
ch,
time_embed_dim,
dropout,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
),
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
),
ResBlock(
ch,
time_embed_dim,
dropout,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
),
)
self._feature_size += ch
self.output_blocks = nn.ModuleList([])
for level, mult in list(enumerate(channel_mult))[::-1]:
for i in range(num_res_blocks + 1):
ich = input_block_chans.pop()
layers = [
ResBlock(
ch + ich,
time_embed_dim,
dropout,
out_channels=int(model_channels * mult),
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = int(model_channels * mult)
if ds in attention_resolutions:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads_upsample,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
)
)
if level and i == num_res_blocks:
out_ch = ch
layers.append(
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=out_ch,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
up=True,
)
if resblock_updown
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
)
ds //= 2
self.output_blocks.append(TimestepEmbedSequential(*layers))
self._feature_size += ch
self.out = nn.Sequential(
normalization(ch),
nn.SiLU(),
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
)
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.
"""
|
class AttentionPool2d(nn.Module):
"""
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
"""
def __init__(
self,
spacial_dim: int,
embed_dim: int,
num_heads_channels: int,
output_dim: int = None,
):
super().__init__()
self.positional_embedding = nn.Parameter(
th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
)
self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
self.num_heads = embed_dim // num_heads_channels
self.attention = QKVAttention(self.num_heads)
def forward(self, x):
b, c, *_spatial = x.shape
x = x.reshape(b, c, -1) # NC(HW)
x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
x = self.qkv_proj(x)
x = self.attention(x)
x = self.c_proj(x)
return x[:, :, 0]
class TimestepBlock(nn.Module):
"""
Any module where forward() takes timestep embeddings as a second argument.
"""
@abstractmethod
def forward(self, x, emb):
"""
Apply the module to `x` given `emb` timestep embeddings.
"""
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
else:
x = layer(x)
return x
class Upsample(nn.Module):
"""
An upsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
upsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2, out_channels=None):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.dims = dims
if use_conv:
self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
def forward(self, x):
assert x.shape[1] == self.channels
if self.dims == 3:
x = F.interpolate(
x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
)
else:
x = F.interpolate(x, scale_factor=2, mode="nearest")
if self.use_conv:
x = self.conv(x)
return x
class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2, out_channels=None):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.dims = dims
stride = 2 if dims != 3 else (1, 2, 2)
if use_conv:
self.op = conv_nd(
dims, self.channels, self.out_channels, 3, stride=stride, padding=1
)
else:
assert self.channels == self.out_channels
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
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)
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,
):
super().__init__()
if num_heads_upsample == -1:
num_heads_upsample = num_heads
self.image_size = image_size
self.in_channels = in_channels
self.model_channels = model_channels
self.out_channels = out_channels
self.num_res_blocks = num_res_blocks
self.attention_resolutions = attention_resolutions
self.dropout = dropout
self.channel_mult = channel_mult
self.conv_resample = conv_resample
self.num_classes = num_classes
self.use_checkpoint = use_checkpoint
self.dtype = th.float32
self.num_heads = num_heads
self.num_head_channels = num_head_channels
self.num_heads_upsample = num_heads_upsample
time_embed_dim = model_channels * 4
self.time_embed = nn.Sequential(
linear(model_channels, time_embed_dim),
nn.SiLU(),
linear(time_embed_dim, time_embed_dim),
)
if self.num_classes is not None:
self.label_emb = nn.Embedding(num_classes, time_embed_dim)
ch = input_ch = int(channel_mult[0] * model_channels)
self.input_blocks = nn.ModuleList(
[TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
)
self._feature_size = ch
input_block_chans = [ch]
ds = 1
for level, mult in enumerate(channel_mult):
for _ in range(num_res_blocks):
layers = [
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=int(mult * model_channels),
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = int(mult * model_channels)
if ds in attention_resolutions:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
)
)
self.input_blocks.append(TimestepEmbedSequential(*layers))
self._feature_size += ch
input_block_chans.append(ch)
if level != len(channel_mult) - 1:
out_ch = ch
self.input_blocks.append(
TimestepEmbedSequential(
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=out_ch,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
down=True,
)
if resblock_updown
else Downsample(
ch, conv_resample, dims=dims, out_channels=out_ch
)
)
)
ch = out_ch
input_block_chans.append(ch)
ds *= 2
self._feature_size += ch
self.middle_block = TimestepEmbedSequential(
ResBlock(
ch,
time_embed_dim,
dropout,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
),
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
),
ResBlock(
ch,
time_embed_dim,
dropout,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
),
)
self._feature_size += ch
self.output_blocks = nn.ModuleList([])
for level, mult in list(enumerate(channel_mult))[::-1]:
for i in range(num_res_blocks + 1):
ich = input_block_chans.pop()
layers = [
ResBlock(
ch + ich,
time_embed_dim,
dropout,
out_channels=int(model_channels * mult),
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
)
]
ch = int(model_channels * mult)
if ds in attention_resolutions:
layers.append(
AttentionBlock(
ch,
use_checkpoint=use_checkpoint,
num_heads=num_heads_upsample,
num_head_channels=num_head_channels,
use_new_attention_order=use_new_attention_order,
)
)
if level and i == num_res_blocks:
out_ch = ch
layers.append(
ResBlock(
ch,
time_embed_dim,
dropout,
out_channels=out_ch,
dims=dims,
use_checkpoint=use_checkpoint,
use_scale_shift_norm=use_scale_shift_norm,
up=True,
)
if resblock_updown
else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
)
ds //= 2
self.output_blocks.append(TimestepEmbedSequential(*layers))
self._feature_size += ch
self.out = nn.Sequential(
normalization(ch),
nn.SiLU(),
zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
)
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) | 1 | 2023-10-21 04:08:44+00:00 | 4k |
NVIDIA-Omniverse/IsaacSim-Automator | src/python/deployer.py | [
{
"identifier": "colorize_error",
"path": "src/python/utils.py",
"snippet": "def colorize_error(text):\n return click.style(text, fg=\"bright_red\", italic=True)"
},
{
"identifier": "colorize_info",
"path": "src/python/utils.py",
"snippet": "def colorize_info(text):\n return click.... | import json
import os
import re
import shlex
import sys
import click
from pathlib import Path
from src.python.utils import (
colorize_error,
colorize_info,
colorize_prompt,
colorize_result,
read_meta,
shell_command,
)
from src.python.debug import debug_break # noqa
from src.python.ngc import check_ngc_access | 2,107 | self.params["debug"],
)
def recreate_command_line(self, separator=" \\\n"):
"""
Recreate command line
"""
command_line = sys.argv[0]
for k, v in self.input_params.items():
k = k.replace("_", "-")
if isinstance(v, bool):
if v:
command_line += separator + "--" + k
else:
not_prefix = "--no-"
if k in ["from-image"]:
not_prefix = "--not-"
command_line += separator + not_prefix + k
else:
command_line += separator + "--" + k + " "
if isinstance(v, str):
command_line += "'" + shlex.quote(v) + "'"
else:
command_line += str(v)
return command_line
def ask_existing_behavior(self):
"""
Ask what to do if deployment already exists
"""
deployment_name = self.params["deployment_name"]
existing = self.params["existing"]
self.existing_behavior = existing
if existing == "ask" and os.path.isfile(
f"{self.config['state_dir']}/{deployment_name}/.tfvars"
):
self.existing_behavior = click.prompt(
text=colorize_prompt(
"* Deploymemnt exists, what would you like to do? See --help for details."
),
type=click.Choice(["repair", "modify", "replace", "run_ansible"]),
default="replace",
)
if (
self.existing_behavior == "repair"
or self.existing_behavior == "run_ansible"
):
# restore params from meta file
r = self.read_meta()
self.params = r["params"]
click.echo(
colorize_info(
f"* Repairing existing deployment \"{self.params['deployment_name']}\"..."
)
)
# update meta info (with new value for existing_behavior)
self.save_meta()
# destroy existing deployment``
if self.existing_behavior == "replace":
debug = self.params["debug"]
click.echo(colorize_info("* Deleting existing deployment..."))
shell_command(
command=f'{self.config["app_dir"]}/destroy "{deployment_name}" --yes'
+ f' {"--debug" if debug else ""}',
verbose=debug,
)
# update meta info if deployment was destroyed
self.save_meta()
def validate_ngc_api_key(self, image, restricted_image=False):
"""
Check if NGC API key allows to log in and has access to appropriate NGC image
@param image: NGC image to check access to
@param restricted_image: If image is restricted to specific org/team?
"""
debug = self.params["debug"]
ngc_api_key = self.params["ngc_api_key"]
ngc_api_key_check = self.params["ngc_api_key_check"]
# extract org and team from the image path
r = re.findall(
"^nvcr\\.io/([a-z0-9\\-_]+)/([a-z0-9\\-_]+/)?[a-z0-9\\-_]+:[a-z0-9\\-_.]+$",
image,
)
ngc_org, ngc_team = r[0]
ngc_team = ngc_team.rstrip("/")
if ngc_org == "nvidia":
click.echo(
colorize_info(
"* Access to docker image can't be checked for NVIDIA org. But you'll be fine. Fingers crossed."
)
)
return
if debug:
click.echo(colorize_info(f'* Will check access to NGC Org: "{ngc_org}"'))
click.echo(colorize_info(f'* Will check access to NGC Team: "{ngc_team}"'))
if ngc_api_key_check and ngc_api_key != "none":
click.echo(colorize_info("* Validating NGC API key... "))
| # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
class Deployer:
def __init__(self, params, config):
self.tf_outputs = {}
self.params = params
self.config = config
self.existing_behavior = None
# save original params so we can recreate command line
self.input_params = params.copy()
# convert "in_china"
self.params["in_china"] = {"yes": True, "no": False, "auto": False}[
self.params["in_china"]
]
# create state directory if it doesn't exist
os.makedirs(self.config["state_dir"], exist_ok=True)
# print complete command line
if self.params["debug"]:
click.echo(colorize_info("* Command:\n" + self.recreate_command_line()))
def __del__(self):
# update meta info
self.save_meta()
def save_meta(self):
"""
Save command parameters in json file, just in case
"""
meta_file = (
f"{self.config['state_dir']}/{self.params['deployment_name']}/meta.json"
)
data = {
"command": self.recreate_command_line(separator=" "),
"input_params": self.input_params,
"params": self.params,
"config": self.config,
}
Path(meta_file).parent.mkdir(parents=True, exist_ok=True)
Path(meta_file).write_text(json.dumps(data, indent=4))
if self.params["debug"]:
click.echo(colorize_info(f"* Meta info saved to '{meta_file}'"))
def read_meta(self):
return read_meta(
self.params["deployment_name"],
self.params["debug"],
)
def recreate_command_line(self, separator=" \\\n"):
"""
Recreate command line
"""
command_line = sys.argv[0]
for k, v in self.input_params.items():
k = k.replace("_", "-")
if isinstance(v, bool):
if v:
command_line += separator + "--" + k
else:
not_prefix = "--no-"
if k in ["from-image"]:
not_prefix = "--not-"
command_line += separator + not_prefix + k
else:
command_line += separator + "--" + k + " "
if isinstance(v, str):
command_line += "'" + shlex.quote(v) + "'"
else:
command_line += str(v)
return command_line
def ask_existing_behavior(self):
"""
Ask what to do if deployment already exists
"""
deployment_name = self.params["deployment_name"]
existing = self.params["existing"]
self.existing_behavior = existing
if existing == "ask" and os.path.isfile(
f"{self.config['state_dir']}/{deployment_name}/.tfvars"
):
self.existing_behavior = click.prompt(
text=colorize_prompt(
"* Deploymemnt exists, what would you like to do? See --help for details."
),
type=click.Choice(["repair", "modify", "replace", "run_ansible"]),
default="replace",
)
if (
self.existing_behavior == "repair"
or self.existing_behavior == "run_ansible"
):
# restore params from meta file
r = self.read_meta()
self.params = r["params"]
click.echo(
colorize_info(
f"* Repairing existing deployment \"{self.params['deployment_name']}\"..."
)
)
# update meta info (with new value for existing_behavior)
self.save_meta()
# destroy existing deployment``
if self.existing_behavior == "replace":
debug = self.params["debug"]
click.echo(colorize_info("* Deleting existing deployment..."))
shell_command(
command=f'{self.config["app_dir"]}/destroy "{deployment_name}" --yes'
+ f' {"--debug" if debug else ""}',
verbose=debug,
)
# update meta info if deployment was destroyed
self.save_meta()
def validate_ngc_api_key(self, image, restricted_image=False):
"""
Check if NGC API key allows to log in and has access to appropriate NGC image
@param image: NGC image to check access to
@param restricted_image: If image is restricted to specific org/team?
"""
debug = self.params["debug"]
ngc_api_key = self.params["ngc_api_key"]
ngc_api_key_check = self.params["ngc_api_key_check"]
# extract org and team from the image path
r = re.findall(
"^nvcr\\.io/([a-z0-9\\-_]+)/([a-z0-9\\-_]+/)?[a-z0-9\\-_]+:[a-z0-9\\-_.]+$",
image,
)
ngc_org, ngc_team = r[0]
ngc_team = ngc_team.rstrip("/")
if ngc_org == "nvidia":
click.echo(
colorize_info(
"* Access to docker image can't be checked for NVIDIA org. But you'll be fine. Fingers crossed."
)
)
return
if debug:
click.echo(colorize_info(f'* Will check access to NGC Org: "{ngc_org}"'))
click.echo(colorize_info(f'* Will check access to NGC Team: "{ngc_team}"'))
if ngc_api_key_check and ngc_api_key != "none":
click.echo(colorize_info("* Validating NGC API key... ")) | r = check_ngc_access( | 7 | 2023-10-18 17:25:44+00:00 | 4k |
blackgold3/SemanticBoost | mdm/sample.py | [
{
"identifier": "recover_from_ric",
"path": "mdm/dataset/recover_joints.py",
"snippet": "def recover_from_ric(data, joints_num):\n if isinstance(data, np.ndarray):\n data = torch.from_numpy(data).float()\n dtype = \"numpy\"\n else:\n data = data.float()\n dtype = \"tens... | from argparse import Namespace
from mdm.dataset.recover_joints import recover_from_ric
from mdm.model.cfg_sampler import ClassifierFreeSampleModel
from mdm.model_util import create_model_and_diffusion, load_model_wo_clip, create_trt_model
from mdm.dataset.recover_smr import *
from mdm.double_take import double_take
import torch
import os
import numpy as np
import json | 2,862 |
class Predictor(object):
def __init__(self, **kargs):
self.path = kargs["path"]
self.handshake_size = 20
self.blend_size = 10
self.speedup = kargs.get("speedup", 1)
args = Namespace()
with open(self.path["config"], 'r') as f:
params1 = json.load(f)
for key, value in params1.items():
setattr(args, key, value)
args.quantization = False
mode = kargs.get("mode", "camd")
if mode != "mdm" and (not os.path.exists(self.path[f"{mode}1"]) or not os.path.exists(self.path[f"{mode}2"])):
self.speedup = 0
if mode == "camd":
args.arch = "llama_decoder_static"
args.encode_full = 2
args.txt_tokens = 1
args.model_path = self.path["camd"]
args.rep = "smr"
args.conv_bias = False
args.conv_norm = "rmsnorm"
args.conv_activate = "silu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
elif mode == "camd-augment":
args.arch = "llama_decoder_static"
args.encode_full = 2
args.txt_tokens = 1
args.model_path = self.path["camd-augment"]
args.rep = "smr"
args.conv_bias = False
args.conv_norm = "rmsnorm"
args.conv_activate = "silu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
elif mode == "mdm":
args.arch = "trans_enc"
args.encode_full = 0
args.txt_tokens = 0
args.model_path = self.path["mdm"]
args.rep = "t2m"
elif mode == "ncamd":
args.arch = "llama_decoder_rope"
args.encode_full = 2
args.txt_tokens = 2
args.model_path = self.path["ncamd"]
args.rep = "smr"
args.conv_bias = True
args.conv_norm = "layernorm"
args.conv_activate = "relu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
elif mode == "ncamd-augment":
args.arch = "llama_decoder_rope"
args.encode_full = 2
args.txt_tokens = 2
args.model_path = self.path["ncamd-augment"]
args.rep = "smr"
args.conv_bias = True
args.conv_norm = "layernorm"
args.conv_activate = "relu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
self.skip_steps = kargs.get("skip_steps", 0)
self.device = kargs.get("device", "cpu")
self.length = kargs.get("length", "120")
self.args = args
self.rep = args.rep
self.num_frames = args.num_frames
self.condition = kargs.get("condition", "text")
if self.condition == "uncond":
self.args.guidance_param = 0
if self.rep == "t2m":
extension = ""
elif self.rep == "smr":
extension = "_smr"
self.mean = torch.from_numpy(np.load(os.path.join(self.path["dataset_dir"], 'Mean{}.npy'.format(extension)))).to(self.device)
self.std = torch.from_numpy(np.load(os.path.join(self.path["dataset_dir"], 'Std{}.npy'.format(extension)))).to(self.device)
if not args.quantization:
print(f"Loading checkpoints from...")
self.model, self.diffusion = create_model_and_diffusion(args, args.control_signal, self.path)
state_dict = torch.load(self.args.model_path, map_location='cpu')
if mode == "mdm":
load_model_wo_clip(self.model, state_dict)
else:
load_model_wo_clip(self.model, state_dict["ema"])
if self.args.guidance_param != 1 and not self.args.unconstrained:
|
class Predictor(object):
def __init__(self, **kargs):
self.path = kargs["path"]
self.handshake_size = 20
self.blend_size = 10
self.speedup = kargs.get("speedup", 1)
args = Namespace()
with open(self.path["config"], 'r') as f:
params1 = json.load(f)
for key, value in params1.items():
setattr(args, key, value)
args.quantization = False
mode = kargs.get("mode", "camd")
if mode != "mdm" and (not os.path.exists(self.path[f"{mode}1"]) or not os.path.exists(self.path[f"{mode}2"])):
self.speedup = 0
if mode == "camd":
args.arch = "llama_decoder_static"
args.encode_full = 2
args.txt_tokens = 1
args.model_path = self.path["camd"]
args.rep = "smr"
args.conv_bias = False
args.conv_norm = "rmsnorm"
args.conv_activate = "silu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
elif mode == "camd-augment":
args.arch = "llama_decoder_static"
args.encode_full = 2
args.txt_tokens = 1
args.model_path = self.path["camd-augment"]
args.rep = "smr"
args.conv_bias = False
args.conv_norm = "rmsnorm"
args.conv_activate = "silu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
elif mode == "mdm":
args.arch = "trans_enc"
args.encode_full = 0
args.txt_tokens = 0
args.model_path = self.path["mdm"]
args.rep = "t2m"
elif mode == "ncamd":
args.arch = "llama_decoder_rope"
args.encode_full = 2
args.txt_tokens = 2
args.model_path = self.path["ncamd"]
args.rep = "smr"
args.conv_bias = True
args.conv_norm = "layernorm"
args.conv_activate = "relu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
elif mode == "ncamd-augment":
args.arch = "llama_decoder_rope"
args.encode_full = 2
args.txt_tokens = 2
args.model_path = self.path["ncamd-augment"]
args.rep = "smr"
args.conv_bias = True
args.conv_norm = "layernorm"
args.conv_activate = "relu"
args.trans_activate = "swiglu"
args.quantization = self.speedup == 1
self.skip_steps = kargs.get("skip_steps", 0)
self.device = kargs.get("device", "cpu")
self.length = kargs.get("length", "120")
self.args = args
self.rep = args.rep
self.num_frames = args.num_frames
self.condition = kargs.get("condition", "text")
if self.condition == "uncond":
self.args.guidance_param = 0
if self.rep == "t2m":
extension = ""
elif self.rep == "smr":
extension = "_smr"
self.mean = torch.from_numpy(np.load(os.path.join(self.path["dataset_dir"], 'Mean{}.npy'.format(extension)))).to(self.device)
self.std = torch.from_numpy(np.load(os.path.join(self.path["dataset_dir"], 'Std{}.npy'.format(extension)))).to(self.device)
if not args.quantization:
print(f"Loading checkpoints from...")
self.model, self.diffusion = create_model_and_diffusion(args, args.control_signal, self.path)
state_dict = torch.load(self.args.model_path, map_location='cpu')
if mode == "mdm":
load_model_wo_clip(self.model, state_dict)
else:
load_model_wo_clip(self.model, state_dict["ema"])
if self.args.guidance_param != 1 and not self.args.unconstrained: | self.model = ClassifierFreeSampleModel(self.model) # wrapping model with the classifier-free sampler | 1 | 2023-10-20 14:53:26+00:00 | 4k |
justchenhao/SILI_CD | datasets/base_dataset.py | [
{
"identifier": "get_transforms",
"path": "datasets/transforms.py",
"snippet": "def get_transforms(norm=False, img_size=256):\n basic_transform = []\n basic_transform.append(T.ToTensor()) # ndarray转为 torch.FloatTensor, 范围[0,1]\n if norm:\n basic_transform.append(T.Normalize(mean=[0.5, 0... | import os
import numpy as np
import torch
from typing import Dict, Sequence, Tuple, Optional, Union
from PIL import Image
from torch.utils import data
from datasets.transforms import get_transforms, get_mask_transforms
from datasets.transforms import get_seg_augs
from misc.imutils import pil_rescale, pil_resize
from misc.imutils import pil_rescale, pil_resize
from misc.torchutils import visualize_tensors | 2,067 | list_folder_name: str = 'list',
scale_ratios: Union[int, list] = 1):
super(ImageDataset, self).__init__()
self.root_dir = root_dir
self.split = split # train | train_aug | val
self.list_path = os.path.join(self.root_dir, list_folder_name, self.split+'.txt')
self.img_name_list = load_img_name_list(self.list_path)
if isinstance(img_folder_name, list) or isinstance(img_folder_name, tuple):
# 此处为了兼容存在多个img_folder,内部文件共名字的情况,比如img_folder_name=['A','B']
self.img_folder_with_name_list = [img_folder_name_+'/'+name
for name in self.img_name_list
for img_folder_name_ in img_folder_name]
elif isinstance(img_folder_name, str):
self.img_folder_with_name_list = [img_folder_name+'/'+name
for name in self.img_name_list]
else:
raise NotImplementedError
self.A_size = len(self.img_folder_with_name_list) # get the size of dataset A
self.img_folder_name = img_folder_name
self.img_size = img_size
self.norm = norm
self.basic_transforms = get_transforms(norm=norm, img_size=img_size)
self.scale_ratios = scale_ratios
def __getitem__(self, index):
folder_with_name = self.img_folder_with_name_list[index % self.A_size]
img_folder_name = folder_with_name.split('/')[0]
name = folder_with_name.split('/')[-1]
A_path = os.path.join(self.root_dir, img_folder_name, name)
img = np.asarray(Image.open(A_path).convert('RGB'))
scales = self.scale_ratios
if isinstance(scales, list):
scale = scales[torch.randint(len(scales), (1,)).item()]
else:
scale = scales
if scale != 1:
h, w = img.shape[:2]
img = pil_rescale(img, scale=scale, order=3)
img = pil_resize(img, size=[h, w], order=3)
if self.basic_transforms is not None:
img = self.basic_transforms(img)
return {'A': img, 'name': name}
def __len__(self):
"""Return the total number of images in the dataset."""
return self.A_size
class SegDataset(ImageDataset):
'''
transforms: 表示同时对image 和 mask 做变换;
'''
def __init__(self,
root_dir: str,
split: str = 'train',
img_size: int = 256,
norm: bool = False,
img_folder_name: Union[str, list, tuple] = 'A',
label_transform: str = 'norm',
label_folder_name: str = 'label',
scale_ratios: Union[int, list] = 1):
super(SegDataset, self).__init__(root_dir, split=split,
img_size=img_size,
norm=norm,
img_folder_name=img_folder_name,
scale_ratios=scale_ratios)
self.basic_mask_transforms = get_mask_transforms(img_size=img_size)
self.label_folder_name = label_folder_name
self.label_transform = label_transform
def __getitem__(self, index):
# name = self.img_name_list[index]
# A_path = os.path.join(self.root_dir, self.img_folder_name, name)
folder_with_name = self.img_folder_with_name_list[index % self.A_size]
img_folder_name = folder_with_name.split('/')[0]
name = folder_with_name.split('/')[-1]
A_path = os.path.join(self.root_dir, img_folder_name, name)
img = np.asarray(Image.open(A_path).convert('RGB'))
scales = self.scale_ratios
if isinstance(scales, list):
scale = scales[torch.randint(len(scales), (1,)).item()]
else:
scale = scales
if scale != 1:
h, w = img.shape[:2]
img = pil_rescale(img, scale=scale, order=3)
img = pil_resize(img, size=[h, w], order=3)
L_path = os.path.join(self.root_dir, self.label_folder_name, name)
mask = np.array(Image.open(L_path), dtype=np.uint8)
# 二分类中,前景标注为255
if self.label_transform == 'norm':
mask = mask // 255
elif self.label_transform == 'ignore0_sub1':
mask = mask - 1
# 原来label==0的部分变为255,自动被ignore
if self.basic_transforms is not None:
img = self.basic_transforms(img)
if self.basic_mask_transforms is not None:
mask = self.basic_mask_transforms(mask)
return {'A': img, 'mask': mask, 'name': name}
if __name__ == '__main__':
is_train = True
root_dir = r'G:/tmp_data/inria_cut256/'
img_folder_name = ['A']
split = 'train'
label_transform = 'norm'
dataset = SegDataset(root_dir=root_dir, split=split,
img_folder_name=img_folder_name,
label_transform=label_transform)
print(f'dataset len is {len(dataset)}')
|
"""
some basic data loader
for example:
Image loader, Segmentation loader,
data root
├─A
├─label
└─list
"""
def load_img_name_list(dataset_path):
img_name_list = np.loadtxt(dataset_path, dtype=str)
if img_name_list.ndim == 2:
return img_name_list[:, 0]
return img_name_list
class ImageDataset(data.Dataset):
"""list dataloder"""
def __init__(self, root_dir: str,
split: str = 'train',
img_size: int = 256,
norm: bool = False,
img_folder_name: Union[str, list, tuple] = 'A',
list_folder_name: str = 'list',
scale_ratios: Union[int, list] = 1):
super(ImageDataset, self).__init__()
self.root_dir = root_dir
self.split = split # train | train_aug | val
self.list_path = os.path.join(self.root_dir, list_folder_name, self.split+'.txt')
self.img_name_list = load_img_name_list(self.list_path)
if isinstance(img_folder_name, list) or isinstance(img_folder_name, tuple):
# 此处为了兼容存在多个img_folder,内部文件共名字的情况,比如img_folder_name=['A','B']
self.img_folder_with_name_list = [img_folder_name_+'/'+name
for name in self.img_name_list
for img_folder_name_ in img_folder_name]
elif isinstance(img_folder_name, str):
self.img_folder_with_name_list = [img_folder_name+'/'+name
for name in self.img_name_list]
else:
raise NotImplementedError
self.A_size = len(self.img_folder_with_name_list) # get the size of dataset A
self.img_folder_name = img_folder_name
self.img_size = img_size
self.norm = norm
self.basic_transforms = get_transforms(norm=norm, img_size=img_size)
self.scale_ratios = scale_ratios
def __getitem__(self, index):
folder_with_name = self.img_folder_with_name_list[index % self.A_size]
img_folder_name = folder_with_name.split('/')[0]
name = folder_with_name.split('/')[-1]
A_path = os.path.join(self.root_dir, img_folder_name, name)
img = np.asarray(Image.open(A_path).convert('RGB'))
scales = self.scale_ratios
if isinstance(scales, list):
scale = scales[torch.randint(len(scales), (1,)).item()]
else:
scale = scales
if scale != 1:
h, w = img.shape[:2]
img = pil_rescale(img, scale=scale, order=3)
img = pil_resize(img, size=[h, w], order=3)
if self.basic_transforms is not None:
img = self.basic_transforms(img)
return {'A': img, 'name': name}
def __len__(self):
"""Return the total number of images in the dataset."""
return self.A_size
class SegDataset(ImageDataset):
'''
transforms: 表示同时对image 和 mask 做变换;
'''
def __init__(self,
root_dir: str,
split: str = 'train',
img_size: int = 256,
norm: bool = False,
img_folder_name: Union[str, list, tuple] = 'A',
label_transform: str = 'norm',
label_folder_name: str = 'label',
scale_ratios: Union[int, list] = 1):
super(SegDataset, self).__init__(root_dir, split=split,
img_size=img_size,
norm=norm,
img_folder_name=img_folder_name,
scale_ratios=scale_ratios)
self.basic_mask_transforms = get_mask_transforms(img_size=img_size)
self.label_folder_name = label_folder_name
self.label_transform = label_transform
def __getitem__(self, index):
# name = self.img_name_list[index]
# A_path = os.path.join(self.root_dir, self.img_folder_name, name)
folder_with_name = self.img_folder_with_name_list[index % self.A_size]
img_folder_name = folder_with_name.split('/')[0]
name = folder_with_name.split('/')[-1]
A_path = os.path.join(self.root_dir, img_folder_name, name)
img = np.asarray(Image.open(A_path).convert('RGB'))
scales = self.scale_ratios
if isinstance(scales, list):
scale = scales[torch.randint(len(scales), (1,)).item()]
else:
scale = scales
if scale != 1:
h, w = img.shape[:2]
img = pil_rescale(img, scale=scale, order=3)
img = pil_resize(img, size=[h, w], order=3)
L_path = os.path.join(self.root_dir, self.label_folder_name, name)
mask = np.array(Image.open(L_path), dtype=np.uint8)
# 二分类中,前景标注为255
if self.label_transform == 'norm':
mask = mask // 255
elif self.label_transform == 'ignore0_sub1':
mask = mask - 1
# 原来label==0的部分变为255,自动被ignore
if self.basic_transforms is not None:
img = self.basic_transforms(img)
if self.basic_mask_transforms is not None:
mask = self.basic_mask_transforms(mask)
return {'A': img, 'mask': mask, 'name': name}
if __name__ == '__main__':
is_train = True
root_dir = r'G:/tmp_data/inria_cut256/'
img_folder_name = ['A']
split = 'train'
label_transform = 'norm'
dataset = SegDataset(root_dir=root_dir, split=split,
img_folder_name=img_folder_name,
label_transform=label_transform)
print(f'dataset len is {len(dataset)}') | augs = get_seg_augs(imgz_size=256) | 2 | 2023-10-21 09:09:57+00:00 | 4k |
pythonlessons/FinRock | finrock/trading_env.py | [
{
"identifier": "State",
"path": "finrock/state.py",
"snippet": "class State:\n def __init__(\n self, \n timestamp: str, \n open: float, \n high: float, \n low: float, \n close: float, \n volume: float=0.0,\n indi... | import typing
import numpy as np
from .state import State, Observations
from .data_feeder import PdDataFeeder
from .reward import simpleReward | 2,050 |
class TradingEnv:
def __init__(
self,
data_feeder: PdDataFeeder,
output_transformer: typing.Callable = None,
initial_balance: float = 1000.0,
max_episode_steps: int = None,
window_size: int = 50,
reward_function: typing.Callable = simpleReward,
metrics: typing.List[typing.Callable] = []
) -> None:
self._data_feeder = data_feeder
self._output_transformer = output_transformer
self._initial_balance = initial_balance
self._max_episode_steps = max_episode_steps if max_episode_steps is not None else len(data_feeder)
self._window_size = window_size
self._reward_function = reward_function
self._metrics = metrics
self._observations = Observations(window_size=window_size)
self._observation_space = np.zeros(self.reset()[0].shape)
self.action_space = 3
@property
def observation_space(self):
return self._observation_space
|
class TradingEnv:
def __init__(
self,
data_feeder: PdDataFeeder,
output_transformer: typing.Callable = None,
initial_balance: float = 1000.0,
max_episode_steps: int = None,
window_size: int = 50,
reward_function: typing.Callable = simpleReward,
metrics: typing.List[typing.Callable] = []
) -> None:
self._data_feeder = data_feeder
self._output_transformer = output_transformer
self._initial_balance = initial_balance
self._max_episode_steps = max_episode_steps if max_episode_steps is not None else len(data_feeder)
self._window_size = window_size
self._reward_function = reward_function
self._metrics = metrics
self._observations = Observations(window_size=window_size)
self._observation_space = np.zeros(self.reset()[0].shape)
self.action_space = 3
@property
def observation_space(self):
return self._observation_space
| def _get_obs(self, index: int, balance: float=None) -> State: | 0 | 2023-10-23 07:44:54+00:00 | 4k |
hitlic/deepepochs | examples/10-multi-optimizers.py | [
{
"identifier": "Trainer",
"path": "deepepochs/trainer.py",
"snippet": "class Trainer(TrainerBase):\r\n def train_step(self,\r\n batch_x:[torch.Tensor, List[torch.Tensor]],\r\n batch_y:[torch.Tensor, List[torch.Tensor]],\r\n **step_args\r\n ... | import torch
from torch import nn
from torch.nn import functional as F
from torchvision.datasets import MNIST
from torchvision import transforms
from torch.utils.data import DataLoader, random_split
from deepepochs import Trainer, Optimizer | 1,703 | """
使用多个优化器
"""
data_dir = './datasets'
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
mnist_full = MNIST(data_dir, train=True, transform=transform, download=True)
train_ds, val_ds = random_split(mnist_full, [55000, 5000])
test_ds = MNIST(data_dir, train=False, transform=transform, download=True)
train_dl = DataLoader(train_ds, batch_size=32)
val_dl = DataLoader(val_ds, batch_size=32)
test_dl = DataLoader(test_ds, batch_size=32)
channels, width, height = (1, 28, 28)
model = nn.Sequential(
nn.Flatten(),
nn.Linear(channels * width * height, 64),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(64, 64),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(64, 10)
)
# 定义多个优化器,实际使用中每个优化器应针对不同的模型组成部分
# 注意:大多数情况下不需要多个优化器,而是为模型参数分组,每个组使用不同的学习率
opt1 = torch.optim.Adam(model.parameters(), lr=2e-4)
opt2 = torch.optim.Adam(model.parameters(), lr=2e-4)
opts = [opt1, opt2] # 第一种方式
| """
使用多个优化器
"""
data_dir = './datasets'
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
mnist_full = MNIST(data_dir, train=True, transform=transform, download=True)
train_ds, val_ds = random_split(mnist_full, [55000, 5000])
test_ds = MNIST(data_dir, train=False, transform=transform, download=True)
train_dl = DataLoader(train_ds, batch_size=32)
val_dl = DataLoader(val_ds, batch_size=32)
test_dl = DataLoader(test_ds, batch_size=32)
channels, width, height = (1, 28, 28)
model = nn.Sequential(
nn.Flatten(),
nn.Linear(channels * width * height, 64),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(64, 64),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(64, 10)
)
# 定义多个优化器,实际使用中每个优化器应针对不同的模型组成部分
# 注意:大多数情况下不需要多个优化器,而是为模型参数分组,每个组使用不同的学习率
opt1 = torch.optim.Adam(model.parameters(), lr=2e-4)
opt2 = torch.optim.Adam(model.parameters(), lr=2e-4)
opts = [opt1, opt2] # 第一种方式 | opts = [Optimizer(opt1), Optimizer(opt2)] # 第二种方式,这种方式可为每个优化器指定高度器 | 1 | 2023-10-19 05:41:48+00:00 | 4k |
yukara-ikemiya/minimal-sqvae | models/sqvae.py | [
{
"identifier": "Encoder",
"path": "models/encdec.py",
"snippet": "class Encoder(nn.Module):\n def __init__(self, in_ch, width, depth, num_down, stride, **kwargs):\n super().__init__()\n\n blocks = []\n for ii in range(num_down):\n # Down-sampling\n down = n... | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .encdec import Encoder, Decoder
from .stochastic_quantizer import SQuantizer | 2,202 | """
Copyright (C) 2023 Yukara Ikemiya
"""
class SQVAE(nn.Module):
def __init__(self, kwargs_encdec: dict, kwargs_quantizer: dict):
super().__init__()
assert (kwargs_encdec['width'] == kwargs_quantizer['dim_dict'])
self.encoder = Encoder(**kwargs_encdec)
| """
Copyright (C) 2023 Yukara Ikemiya
"""
class SQVAE(nn.Module):
def __init__(self, kwargs_encdec: dict, kwargs_quantizer: dict):
super().__init__()
assert (kwargs_encdec['width'] == kwargs_quantizer['dim_dict'])
self.encoder = Encoder(**kwargs_encdec) | self.decoder = Decoder(**kwargs_encdec) | 1 | 2023-10-15 14:48:55+00:00 | 4k |
colour-science/colour-visuals | colour_visuals/planckian_locus.py | [
{
"identifier": "DEFAULT_FLOAT_DTYPE_WGPU",
"path": "colour_visuals/common.py",
"snippet": "DEFAULT_FLOAT_DTYPE_WGPU = np.float32"
},
{
"identifier": "append_channel",
"path": "colour_visuals/common.py",
"snippet": "def append_channel(a: ArrayLike, value: float = 1) -> NDArray:\n \"\"... | import numpy as np
import pygfx as gfx
from colour.hints import (
ArrayLike,
Literal,
Sequence,
cast,
)
from colour.plotting import (
CONSTANTS_COLOUR_STYLE,
LABELS_PLANCKIAN_LOCUS_DEFAULT,
lines_planckian_locus,
)
from colour.utilities import (
as_int_scalar,
optional,
)
from colour_visuals.common import (
DEFAULT_FLOAT_DTYPE_WGPU,
append_channel,
as_contiguous_array,
)
from colour_visuals.visual import (
MixinPropertyColour,
MixinPropertyMethod,
MixinPropertyOpacity,
MixinPropertyThickness,
Visual,
visual_property,
) | 3,181 | colour: ArrayLike | None = None,
opacity: float = 1,
thickness: float = 1,
):
super().__init__()
self._planckian_locus = None
self._iso_temperature_lines = []
self._texts = []
self._labels = None
self._mireds = False
with self.block_update():
self.method = method
self.labels = labels
self.mireds = mireds
self.colour = colour
self.opacity = opacity
self.thickness = thickness
self.update()
@visual_property
def labels(
self,
) -> Sequence | None:
"""
Getter and setter property for the labels.
Parameters
----------
value
Value to set the labels with.
Returns
-------
:class:`str`
Labels.
"""
return self._labels
@labels.setter
def labels(self, value: Sequence | None):
"""Setter for the **self.labels** property."""
self._labels = cast(
Sequence,
optional(
value,
LABELS_PLANCKIAN_LOCUS_DEFAULT[
"Mireds" if self._mireds else "Default"
],
),
)
@visual_property
def mireds(
self,
) -> bool:
"""
Getter and setter property for the mireds state.
Parameters
----------
value
Value to set the mireds state with.
Returns
-------
:class:`bool`
Mireds state.
"""
return self._mireds
@mireds.setter
def mireds(self, value: bool):
"""Setter for the **self.mireds** property."""
self._mireds = value
def update(self):
"""Update the visual."""
if self._is_update_blocked:
return
self.clear()
lines_pl, lines_l = lines_planckian_locus(
self._labels,
self._mireds,
method=self._method,
)
# Planckian Locus
positions = np.concatenate(
[lines_pl["position"][:-1], lines_pl["position"][1:]], axis=1
).reshape([-1, 2])
positions = np.hstack(
[
positions,
np.full((positions.shape[0], 1), 0, DEFAULT_FLOAT_DTYPE_WGPU),
]
)
if self._colour is None:
colour_sl = np.concatenate(
[lines_pl["colour"][:-1], lines_pl["colour"][1:]], axis=1
).reshape([-1, 3])
else:
colour_sl = np.tile(self._colour, (positions.shape[0], 1))
self._planckian_locus = gfx.Line(
gfx.Geometry(
positions=as_contiguous_array(positions),
colors=as_contiguous_array(
| # !/usr/bin/env python
"""
Planckian Locus Visuals
=======================
Defines the *Planckian Locus* visuals:
- :class:`colour_visuals.VisualPlanckianLocus`
"""
from __future__ import annotations
__author__ = "Colour Developers"
__copyright__ = "Copyright 2023 Colour Developers"
__license__ = "BSD-3-Clause - https://opensource.org/licenses/BSD-3-Clause"
__maintainer__ = "Colour Developers"
__email__ = "colour-developers@colour-science.org"
__status__ = "Production"
__all__ = [
"VisualPlanckianLocus",
]
class VisualPlanckianLocus(
MixinPropertyColour,
MixinPropertyMethod,
MixinPropertyOpacity,
MixinPropertyThickness,
Visual,
):
"""
Create a *Planckian Locus* visual.
Parameters
----------
method
*Planckian Locus* method.
labels
Array of labels used to customise which iso-temperature lines will be
drawn along the *Planckian Locus*. Passing an empty array will result
in no iso-temperature lines being drawn.
mireds
Whether to use micro reciprocal degrees for the iso-temperature lines.
colour
Colour of the visual, if *None*, the colour is computed from the visual
geometry.
opacity
Opacity of the visual.
thickness
Thickness of the visual lines.
Attributes
----------
- :attr:`~colour_visuals.VisualPlanckianLocus.method`
- :attr:`~colour_visuals.VisualPlanckianLocus.labels`
- :attr:`~colour_visuals.VisualPlanckianLocus.mireds`
- :attr:`~colour_visuals.VisualPlanckianLocus.colour`
- :attr:`~colour_visuals.VisualPlanckianLocus.opacity`
- :attr:`~colour_visuals.VisualPlanckianLocus.thickness`
Methods
-------
- :meth:`~colour_visuals.VisualPlanckianLocus.__init__`
- :meth:`~colour_visuals.VisualPlanckianLocus.update`
Examples
--------
>>> import os
>>> from colour.utilities import suppress_stdout
>>> from wgpu.gui.auto import WgpuCanvas
>>> with suppress_stdout():
... canvas = WgpuCanvas(size=(960, 540))
... scene = gfx.Scene()
... scene.add(
... gfx.Background(
... None, gfx.BackgroundMaterial(np.array([0.18, 0.18, 0.18]))
... )
... )
... visual = VisualPlanckianLocus()
... camera = gfx.PerspectiveCamera(50, 16 / 9)
... camera.show_object(visual, up=np.array([0, 0, 1]), scale=1.25)
... scene.add(visual)
... if os.environ.get("CI") is None:
... gfx.show(scene, camera=camera, canvas=canvas)
...
.. image:: ../_static/Plotting_VisualPlanckianLocus.png
:align: center
:alt: visual-planckian-locus
"""
def __init__(
self,
method: Literal["CIE 1931", "CIE 1960 UCS", "CIE 1976 UCS"]
| str = "CIE 1931",
labels: Sequence | None = None,
mireds: bool = False,
colour: ArrayLike | None = None,
opacity: float = 1,
thickness: float = 1,
):
super().__init__()
self._planckian_locus = None
self._iso_temperature_lines = []
self._texts = []
self._labels = None
self._mireds = False
with self.block_update():
self.method = method
self.labels = labels
self.mireds = mireds
self.colour = colour
self.opacity = opacity
self.thickness = thickness
self.update()
@visual_property
def labels(
self,
) -> Sequence | None:
"""
Getter and setter property for the labels.
Parameters
----------
value
Value to set the labels with.
Returns
-------
:class:`str`
Labels.
"""
return self._labels
@labels.setter
def labels(self, value: Sequence | None):
"""Setter for the **self.labels** property."""
self._labels = cast(
Sequence,
optional(
value,
LABELS_PLANCKIAN_LOCUS_DEFAULT[
"Mireds" if self._mireds else "Default"
],
),
)
@visual_property
def mireds(
self,
) -> bool:
"""
Getter and setter property for the mireds state.
Parameters
----------
value
Value to set the mireds state with.
Returns
-------
:class:`bool`
Mireds state.
"""
return self._mireds
@mireds.setter
def mireds(self, value: bool):
"""Setter for the **self.mireds** property."""
self._mireds = value
def update(self):
"""Update the visual."""
if self._is_update_blocked:
return
self.clear()
lines_pl, lines_l = lines_planckian_locus(
self._labels,
self._mireds,
method=self._method,
)
# Planckian Locus
positions = np.concatenate(
[lines_pl["position"][:-1], lines_pl["position"][1:]], axis=1
).reshape([-1, 2])
positions = np.hstack(
[
positions,
np.full((positions.shape[0], 1), 0, DEFAULT_FLOAT_DTYPE_WGPU),
]
)
if self._colour is None:
colour_sl = np.concatenate(
[lines_pl["colour"][:-1], lines_pl["colour"][1:]], axis=1
).reshape([-1, 3])
else:
colour_sl = np.tile(self._colour, (positions.shape[0], 1))
self._planckian_locus = gfx.Line(
gfx.Geometry(
positions=as_contiguous_array(positions),
colors=as_contiguous_array( | append_channel(colour_sl, self._opacity) | 1 | 2023-10-15 04:30:47+00:00 | 4k |
JiahuiLei/NAP | core/models/utils/occnet_utils/utils/voxels.py | [
{
"identifier": "check_mesh_contains",
"path": "core/models/utils/occnet_utils/utils/libmesh/inside_mesh.py",
"snippet": "def check_mesh_contains(mesh, points, hash_resolution=512):\n intersector = MeshIntersector(mesh, hash_resolution)\n contains = intersector.query(points)\n return contains"
... | import numpy as np
import trimesh
from scipy import ndimage
from skimage.measure import block_reduce
from .libvoxelize.voxelize import voxelize_mesh_
from .libmesh import check_mesh_contains
from .common import make_3d_grid | 2,850 | v_idx[f1_l_x, f1_l_y, f1_l_z + 1],
v_idx[f1_l_x, f1_l_y + 1, f1_l_z + 1],
v_idx[f1_l_x, f1_l_y + 1, f1_l_z],
], axis=1)
faces_1_r = np.stack([
v_idx[f1_r_x, f1_r_y, f1_r_z],
v_idx[f1_r_x, f1_r_y + 1, f1_r_z],
v_idx[f1_r_x, f1_r_y + 1, f1_r_z + 1],
v_idx[f1_r_x, f1_r_y, f1_r_z + 1],
], axis=1)
faces_2_l = np.stack([
v_idx[f2_l_x, f2_l_y, f2_l_z],
v_idx[f2_l_x + 1, f2_l_y, f2_l_z],
v_idx[f2_l_x + 1, f2_l_y, f2_l_z + 1],
v_idx[f2_l_x, f2_l_y, f2_l_z + 1],
], axis=1)
faces_2_r = np.stack([
v_idx[f2_r_x, f2_r_y, f2_r_z],
v_idx[f2_r_x, f2_r_y, f2_r_z + 1],
v_idx[f2_r_x + 1, f2_r_y, f2_r_z + 1],
v_idx[f2_r_x + 1, f2_r_y, f2_r_z],
], axis=1)
faces_3_l = np.stack([
v_idx[f3_l_x, f3_l_y, f3_l_z],
v_idx[f3_l_x, f3_l_y + 1, f3_l_z],
v_idx[f3_l_x + 1, f3_l_y + 1, f3_l_z],
v_idx[f3_l_x + 1, f3_l_y, f3_l_z],
], axis=1)
faces_3_r = np.stack([
v_idx[f3_r_x, f3_r_y, f3_r_z],
v_idx[f3_r_x + 1, f3_r_y, f3_r_z],
v_idx[f3_r_x + 1, f3_r_y + 1, f3_r_z],
v_idx[f3_r_x, f3_r_y + 1, f3_r_z],
], axis=1)
faces = np.concatenate([
faces_1_l, faces_1_r,
faces_2_l, faces_2_r,
faces_3_l, faces_3_r,
], axis=0)
vertices = self.loc + self.scale * vertices
mesh = trimesh.Trimesh(vertices, faces, process=False)
return mesh
@property
def resolution(self):
assert (self.data.shape[0] == self.data.shape[1] == self.data.shape[2])
return self.data.shape[0]
def contains(self, points):
nx = self.resolution
# Rescale bounding box to [-0.5, 0.5]^3
points = (points - self.loc) / self.scale
# Discretize points to [0, nx-1]^3
points_i = ((points + 0.5) * nx).astype(np.int32)
# i1, i2, i3 have sizes (batch_size, T)
i1, i2, i3 = points_i[..., 0], points_i[..., 1], points_i[..., 2]
# Only use indices inside bounding box
mask = (
(i1 >= 0) & (i2 >= 0) & (i3 >= 0)
& (nx > i1) & (nx > i2) & (nx > i3)
)
# Prevent out of bounds error
i1 = i1[mask]
i2 = i2[mask]
i3 = i3[mask]
# Compute values, default value outside box is 0
occ = np.zeros(points.shape[:-1], dtype=np.bool)
occ[mask] = self.data[i1, i2, i3]
return occ
def voxelize_ray(mesh, resolution):
occ_surface = voxelize_surface(mesh, resolution)
# TODO: use surface voxels here?
occ_interior = voxelize_interior(mesh, resolution)
occ = (occ_interior | occ_surface)
return occ
def voxelize_fill(mesh, resolution):
bounds = mesh.bounds
if (np.abs(bounds) >= 0.5).any():
raise ValueError('voxelize fill is only supported if mesh is inside [-0.5, 0.5]^3/')
occ = voxelize_surface(mesh, resolution)
occ = ndimage.morphology.binary_fill_holes(occ)
return occ
def voxelize_surface(mesh, resolution):
vertices = mesh.vertices
faces = mesh.faces
vertices = (vertices + 0.5) * resolution
face_loc = vertices[faces]
occ = np.full((resolution,) * 3, 0, dtype=np.int32)
face_loc = face_loc.astype(np.float32)
voxelize_mesh_(occ, face_loc)
occ = (occ != 0)
return occ
def voxelize_interior(mesh, resolution):
shape = (resolution,) * 3
bb_min = (0.5,) * 3
bb_max = (resolution - 0.5,) * 3
# Create points. Add noise to break symmetry
|
class VoxelGrid:
def __init__(self, data, loc=(0., 0., 0.), scale=1):
assert (data.shape[0] == data.shape[1] == data.shape[2])
data = np.asarray(data, dtype=np.bool)
loc = np.asarray(loc)
self.data = data
self.loc = loc
self.scale = scale
@classmethod
def from_mesh(cls, mesh, resolution, loc=None, scale=None, method='ray'):
bounds = mesh.bounds
# Default location is center
if loc is None:
loc = (bounds[0] + bounds[1]) / 2
# Default scale, scales the mesh to [-0.45, 0.45]^3
if scale is None:
scale = (bounds[1] - bounds[0]).max() / 0.9
loc = np.asarray(loc)
scale = float(scale)
# Transform mesh
mesh = mesh.copy()
mesh.apply_translation(-loc)
mesh.apply_scale(1 / scale)
# Apply method
if method == 'ray':
voxel_data = voxelize_ray(mesh, resolution)
elif method == 'fill':
voxel_data = voxelize_fill(mesh, resolution)
voxels = cls(voxel_data, loc, scale)
return voxels
def down_sample(self, factor=2):
if not (self.resolution % factor) == 0:
raise ValueError('Resolution must be divisible by factor.')
new_data = block_reduce(self.data, (factor,) * 3, np.max)
return VoxelGrid(new_data, self.loc, self.scale)
def to_mesh(self):
# Shorthand
occ = self.data
# Shape of voxel grid
nx, ny, nz = occ.shape
# Shape of corresponding occupancy grid
grid_shape = (nx + 1, ny + 1, nz + 1)
# Convert values to occupancies
occ = np.pad(occ, 1, 'constant')
# Determine if face present
f1_r = (occ[:-1, 1:-1, 1:-1] & ~occ[1:, 1:-1, 1:-1])
f2_r = (occ[1:-1, :-1, 1:-1] & ~occ[1:-1, 1:, 1:-1])
f3_r = (occ[1:-1, 1:-1, :-1] & ~occ[1:-1, 1:-1, 1:])
f1_l = (~occ[:-1, 1:-1, 1:-1] & occ[1:, 1:-1, 1:-1])
f2_l = (~occ[1:-1, :-1, 1:-1] & occ[1:-1, 1:, 1:-1])
f3_l = (~occ[1:-1, 1:-1, :-1] & occ[1:-1, 1:-1, 1:])
f1 = f1_r | f1_l
f2 = f2_r | f2_l
f3 = f3_r | f3_l
assert (f1.shape == (nx + 1, ny, nz))
assert (f2.shape == (nx, ny + 1, nz))
assert (f3.shape == (nx, ny, nz + 1))
# Determine if vertex present
v = np.full(grid_shape, False)
v[:, :-1, :-1] |= f1
v[:, :-1, 1:] |= f1
v[:, 1:, :-1] |= f1
v[:, 1:, 1:] |= f1
v[:-1, :, :-1] |= f2
v[:-1, :, 1:] |= f2
v[1:, :, :-1] |= f2
v[1:, :, 1:] |= f2
v[:-1, :-1, :] |= f3
v[:-1, 1:, :] |= f3
v[1:, :-1, :] |= f3
v[1:, 1:, :] |= f3
# Calculate indices for vertices
n_vertices = v.sum()
v_idx = np.full(grid_shape, -1)
v_idx[v] = np.arange(n_vertices)
# Vertices
v_x, v_y, v_z = np.where(v)
v_x = v_x / nx - 0.5
v_y = v_y / ny - 0.5
v_z = v_z / nz - 0.5
vertices = np.stack([v_x, v_y, v_z], axis=1)
# Face indices
f1_l_x, f1_l_y, f1_l_z = np.where(f1_l)
f2_l_x, f2_l_y, f2_l_z = np.where(f2_l)
f3_l_x, f3_l_y, f3_l_z = np.where(f3_l)
f1_r_x, f1_r_y, f1_r_z = np.where(f1_r)
f2_r_x, f2_r_y, f2_r_z = np.where(f2_r)
f3_r_x, f3_r_y, f3_r_z = np.where(f3_r)
faces_1_l = np.stack([
v_idx[f1_l_x, f1_l_y, f1_l_z],
v_idx[f1_l_x, f1_l_y, f1_l_z + 1],
v_idx[f1_l_x, f1_l_y + 1, f1_l_z + 1],
v_idx[f1_l_x, f1_l_y + 1, f1_l_z],
], axis=1)
faces_1_r = np.stack([
v_idx[f1_r_x, f1_r_y, f1_r_z],
v_idx[f1_r_x, f1_r_y + 1, f1_r_z],
v_idx[f1_r_x, f1_r_y + 1, f1_r_z + 1],
v_idx[f1_r_x, f1_r_y, f1_r_z + 1],
], axis=1)
faces_2_l = np.stack([
v_idx[f2_l_x, f2_l_y, f2_l_z],
v_idx[f2_l_x + 1, f2_l_y, f2_l_z],
v_idx[f2_l_x + 1, f2_l_y, f2_l_z + 1],
v_idx[f2_l_x, f2_l_y, f2_l_z + 1],
], axis=1)
faces_2_r = np.stack([
v_idx[f2_r_x, f2_r_y, f2_r_z],
v_idx[f2_r_x, f2_r_y, f2_r_z + 1],
v_idx[f2_r_x + 1, f2_r_y, f2_r_z + 1],
v_idx[f2_r_x + 1, f2_r_y, f2_r_z],
], axis=1)
faces_3_l = np.stack([
v_idx[f3_l_x, f3_l_y, f3_l_z],
v_idx[f3_l_x, f3_l_y + 1, f3_l_z],
v_idx[f3_l_x + 1, f3_l_y + 1, f3_l_z],
v_idx[f3_l_x + 1, f3_l_y, f3_l_z],
], axis=1)
faces_3_r = np.stack([
v_idx[f3_r_x, f3_r_y, f3_r_z],
v_idx[f3_r_x + 1, f3_r_y, f3_r_z],
v_idx[f3_r_x + 1, f3_r_y + 1, f3_r_z],
v_idx[f3_r_x, f3_r_y + 1, f3_r_z],
], axis=1)
faces = np.concatenate([
faces_1_l, faces_1_r,
faces_2_l, faces_2_r,
faces_3_l, faces_3_r,
], axis=0)
vertices = self.loc + self.scale * vertices
mesh = trimesh.Trimesh(vertices, faces, process=False)
return mesh
@property
def resolution(self):
assert (self.data.shape[0] == self.data.shape[1] == self.data.shape[2])
return self.data.shape[0]
def contains(self, points):
nx = self.resolution
# Rescale bounding box to [-0.5, 0.5]^3
points = (points - self.loc) / self.scale
# Discretize points to [0, nx-1]^3
points_i = ((points + 0.5) * nx).astype(np.int32)
# i1, i2, i3 have sizes (batch_size, T)
i1, i2, i3 = points_i[..., 0], points_i[..., 1], points_i[..., 2]
# Only use indices inside bounding box
mask = (
(i1 >= 0) & (i2 >= 0) & (i3 >= 0)
& (nx > i1) & (nx > i2) & (nx > i3)
)
# Prevent out of bounds error
i1 = i1[mask]
i2 = i2[mask]
i3 = i3[mask]
# Compute values, default value outside box is 0
occ = np.zeros(points.shape[:-1], dtype=np.bool)
occ[mask] = self.data[i1, i2, i3]
return occ
def voxelize_ray(mesh, resolution):
occ_surface = voxelize_surface(mesh, resolution)
# TODO: use surface voxels here?
occ_interior = voxelize_interior(mesh, resolution)
occ = (occ_interior | occ_surface)
return occ
def voxelize_fill(mesh, resolution):
bounds = mesh.bounds
if (np.abs(bounds) >= 0.5).any():
raise ValueError('voxelize fill is only supported if mesh is inside [-0.5, 0.5]^3/')
occ = voxelize_surface(mesh, resolution)
occ = ndimage.morphology.binary_fill_holes(occ)
return occ
def voxelize_surface(mesh, resolution):
vertices = mesh.vertices
faces = mesh.faces
vertices = (vertices + 0.5) * resolution
face_loc = vertices[faces]
occ = np.full((resolution,) * 3, 0, dtype=np.int32)
face_loc = face_loc.astype(np.float32)
voxelize_mesh_(occ, face_loc)
occ = (occ != 0)
return occ
def voxelize_interior(mesh, resolution):
shape = (resolution,) * 3
bb_min = (0.5,) * 3
bb_max = (resolution - 0.5,) * 3
# Create points. Add noise to break symmetry | points = make_3d_grid(bb_min, bb_max, shape=shape).numpy() | 1 | 2023-10-22 03:46:35+00:00 | 4k |
Th3Tr1ckst3r/GReverse | greverse.py | [
{
"identifier": "requestData",
"path": "utils/imageSearch.py",
"snippet": "def requestData(image_input, max_results=10, titles_to_urls=None):\n client = vision_v1.ImageAnnotatorClient()\n if image_input.startswith('http') or image_input.startswith('https'):\n response = requests.get(image_i... | import sys
import argparse
from utils.imageSearch import requestData as imageSearch
from utils.querySearch import requestData as querySearch
from utils.dataUtils import *
from api_creds.creds import googleCreds | 1,654 | """
GReverse - A tool for OSINT(Open Source Intelligence) gathering & facial recognition via Google Custom Search & Google Vision API's.
Created by Adrian Tarver(Th3Tr1ckst3r) @ https://github.com/Th3Tr1ckst3r/
////////////////////////////////////////////////////////////////////////////////////////
IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
By downloading, copying, installing, or using the software you agree to this license.
If you do not agree to this license, do not download, install,
copy, or use the software.
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow here:
https://raw.githubusercontent.com/Th3Tr1ckst3r/GReverse/main/LICENSE
"""
| """
GReverse - A tool for OSINT(Open Source Intelligence) gathering & facial recognition via Google Custom Search & Google Vision API's.
Created by Adrian Tarver(Th3Tr1ckst3r) @ https://github.com/Th3Tr1ckst3r/
////////////////////////////////////////////////////////////////////////////////////////
IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
By downloading, copying, installing, or using the software you agree to this license.
If you do not agree to this license, do not download, install,
copy, or use the software.
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow here:
https://raw.githubusercontent.com/Th3Tr1ckst3r/GReverse/main/LICENSE
""" | from utils.imageSearch import requestData as imageSearch | 0 | 2023-10-20 03:48:16+00:00 | 4k |
yongliang-wu/ExploreCfg | open_flamingo/src/factory.py | [
{
"identifier": "Flamingo",
"path": "open_flamingo/src/flamingo.py",
"snippet": "class Flamingo(nn.Module):\n def __init__(\n self,\n vision_encoder: nn.Module,\n lang_encoder: nn.Module,\n eoc_token_id: int,\n media_token_id: int,\n vis_dim: int,\n cr... | from transformers import AutoModelForCausalLM, AutoTokenizer
from typing import Literal, Optional
from .flamingo import Flamingo
from .flamingo_lm import FlamingoLMMixin
from .utils import extend_instance
from open_clip import transformer
from torch.nn import functional as F
import open_clip
import torch | 3,579 |
def LNormforward(self, x: torch.Tensor):
#x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
transformer.LayerNormFp32.forward = LNormforward
def create_model_and_transforms(
clip_vision_encoder_path: str,
clip_vision_encoder_pretrained: str,
lang_encoder_path: str,
tokenizer_path: str,
cross_attn_every_n_layers: int = 1,
use_local_files: bool = False,
decoder_layers_attr_name: Optional[str] = None,
inference: bool = False,
precision: Literal["fp16","fp32"] = "fp32",
device: str = "cpu",
checkpoint_path: Optional[str] = None,
**flamingo_kwargs,
):
"""
Initialize a Flamingo model from a pretrained vision encoder and language encoder.
Appends special tokens to the tokenizer and freezes backbones.
Args:
clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32")
clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "laion2b_s32b_b79k")
lang_encoder_path (str): path to pretrained language encoder
tokenizer_path (str): path to pretrained tokenizer
cross_attn_every_n_layers (int, optional): determines how often to add a cross-attention layer. Defaults to 1.
use_local_files (bool, optional): whether to use local files. Defaults to False.
decoder_layers_attr_name (str, optional): name of the decoder layers attribute. Defaults to None.
inference (bool, optional): whether to use inference mode. Defaults to True.
precision (str, optional): precision to use. Defaults to "fp16".
device (str, optional): device to use. Defaults to "cuda".
checkpoint_path (str, optional): path to flamingo checkpoint. Defaults to None.
Returns:
Flamingo: Flamingo model from pretrained vision and language encoders
Image processor: Pipeline to preprocess input images
Tokenizer: A tokenizer for the language model
"""
vision_encoder, _, image_processor = open_clip.create_model_and_transforms(
clip_vision_encoder_path, pretrained=clip_vision_encoder_pretrained,
precision=precision, device=device
)
# set the vision encoder to output the visual features
vision_encoder.visual.output_tokens = True
text_tokenizer = AutoTokenizer.from_pretrained(
tokenizer_path, local_files_only=use_local_files
)
# add Flamingo special tokens to the tokenizer
text_tokenizer.add_special_tokens(
{"additional_special_tokens": ["<|endofchunk|>", "<image>"]}
)
if text_tokenizer.pad_token is None:
# Issue: GPT models don't have a pad token, which we use to
# modify labels for the loss.
text_tokenizer.add_special_tokens({"pad_token": "<PAD>"})
dtype = torch.float16 if precision == "fp16" else torch.float32
lang_encoder = AutoModelForCausalLM.from_pretrained(
lang_encoder_path, local_files_only=use_local_files,
torch_dtype=dtype, # DO NOT EVER USE device_map HERE IT WILL CAUSE HORROR
).to(device)
|
def LNormforward(self, x: torch.Tensor):
#x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
transformer.LayerNormFp32.forward = LNormforward
def create_model_and_transforms(
clip_vision_encoder_path: str,
clip_vision_encoder_pretrained: str,
lang_encoder_path: str,
tokenizer_path: str,
cross_attn_every_n_layers: int = 1,
use_local_files: bool = False,
decoder_layers_attr_name: Optional[str] = None,
inference: bool = False,
precision: Literal["fp16","fp32"] = "fp32",
device: str = "cpu",
checkpoint_path: Optional[str] = None,
**flamingo_kwargs,
):
"""
Initialize a Flamingo model from a pretrained vision encoder and language encoder.
Appends special tokens to the tokenizer and freezes backbones.
Args:
clip_vision_encoder_path (str): path to pretrained clip model (e.g. "ViT-B-32")
clip_vision_encoder_pretrained (str): name of pretraining dataset for clip model (e.g. "laion2b_s32b_b79k")
lang_encoder_path (str): path to pretrained language encoder
tokenizer_path (str): path to pretrained tokenizer
cross_attn_every_n_layers (int, optional): determines how often to add a cross-attention layer. Defaults to 1.
use_local_files (bool, optional): whether to use local files. Defaults to False.
decoder_layers_attr_name (str, optional): name of the decoder layers attribute. Defaults to None.
inference (bool, optional): whether to use inference mode. Defaults to True.
precision (str, optional): precision to use. Defaults to "fp16".
device (str, optional): device to use. Defaults to "cuda".
checkpoint_path (str, optional): path to flamingo checkpoint. Defaults to None.
Returns:
Flamingo: Flamingo model from pretrained vision and language encoders
Image processor: Pipeline to preprocess input images
Tokenizer: A tokenizer for the language model
"""
vision_encoder, _, image_processor = open_clip.create_model_and_transforms(
clip_vision_encoder_path, pretrained=clip_vision_encoder_pretrained,
precision=precision, device=device
)
# set the vision encoder to output the visual features
vision_encoder.visual.output_tokens = True
text_tokenizer = AutoTokenizer.from_pretrained(
tokenizer_path, local_files_only=use_local_files
)
# add Flamingo special tokens to the tokenizer
text_tokenizer.add_special_tokens(
{"additional_special_tokens": ["<|endofchunk|>", "<image>"]}
)
if text_tokenizer.pad_token is None:
# Issue: GPT models don't have a pad token, which we use to
# modify labels for the loss.
text_tokenizer.add_special_tokens({"pad_token": "<PAD>"})
dtype = torch.float16 if precision == "fp16" else torch.float32
lang_encoder = AutoModelForCausalLM.from_pretrained(
lang_encoder_path, local_files_only=use_local_files,
torch_dtype=dtype, # DO NOT EVER USE device_map HERE IT WILL CAUSE HORROR
).to(device) | extend_instance(lang_encoder, FlamingoLMMixin) | 1 | 2023-10-18 02:38:00+00:00 | 4k |
mimo-x/Code-Review-GPT-Gitlab | app/gitlab_webhook.py | [
{
"identifier": "WEBHOOK_VERIFY_TOKEN",
"path": "config/config.py",
"snippet": ""
},
{
"identifier": "review_code",
"path": "service/chat_review.py",
"snippet": "@retry(stop_max_attempt_number=3, wait_fixed=2000)\ndef review_code(project_id, project_commit_id, merge_id, context):\n re... | import json
import threading
from os import abort
from flask import Blueprint, request, jsonify
from config.config import WEBHOOK_VERIFY_TOKEN
from service.chat_review import review_code, review_code_for_mr, review_code_for_add_commit
from utils.logger import log
from app.gitlab_utils import get_commit_list, get_merge_request_id, get_commit_change_file
from utils.dingding import send_dingtalk_message_by_sign | 2,757 |
git = Blueprint('git', __name__)
@git.route('/api')
def question():
return 'hello world'
@git.route('/webhook', methods=['GET', 'POST'])
def webhook():
if request.method == 'GET':
# 获取gitlab的webhook的token
verify_token = request.headers.get('X-Gitlab-Token')
# gitlab的webhook的token验证
|
git = Blueprint('git', __name__)
@git.route('/api')
def question():
return 'hello world'
@git.route('/webhook', methods=['GET', 'POST'])
def webhook():
if request.method == 'GET':
# 获取gitlab的webhook的token
verify_token = request.headers.get('X-Gitlab-Token')
# gitlab的webhook的token验证 | if verify_token == WEBHOOK_VERIFY_TOKEN: | 0 | 2023-10-19 14:10:10+00:00 | 4k |
vorausrobotik/voraus-ad-dataset | tests/test_normalizing_flow.py | [
{
"identifier": "Configuration",
"path": "configuration.py",
"snippet": "class Configuration(BaseModel):\n \"\"\"Describes the configuration parameters.\"\"\"\n\n seed: int\n epochs: int\n batchsize: int\n n_hidden_layers: int = Field(alias=\"nHiddenLayers\")\n n_coupling_blocks: int =... | from typing import List
from configuration import Configuration
from normalizing_flow import InternalNetwork, NormalizingFlow, get_loss, get_loss_per_sample
import pytest
import torch | 2,602 | """Contains tests for the normalizing flow module."""
@pytest.mark.parametrize(
("z_tensor", "jacobian", "expected_loss"),
(
([[0, 1, 2, 3], [2, 3, 4, 5]], [[1, 3], [1, 3]], 8.0),
([[1, 2, 3, 0], [4, 3, 2, 5]], [[1, 3], [1, 3]], 8.0),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [1, 3]], 10.8750),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [3, 1]], 10.8750),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[0, 2], [3, 5]], 10.75),
),
)
def test_get_loss(z_tensor: List[float], jacobian: List[float], expected_loss: float) -> None:
loss = get_loss(torch.Tensor(z_tensor), torch.Tensor(jacobian))
assert loss.item() == pytest.approx(expected_loss, abs=1e-3)
@pytest.mark.parametrize(
("z_tensor", "jacobian", "expected_loss"),
(
([[0, 1, 2, 3], [2, 3, 4, 5]], [[3, 4], [1, 3]], [[4, 23], [6, 24]]),
([[1, 2, 3, 0], [4, 3, 2, 5]], [[1, 3], [1, 3]], [[6, 24], [6, 24]]),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [1, 3]], [[19.5, 22], [19.5, 22]]),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [3, 1]], [[19.5, 22], [17.5, 24]]),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[0, 2], [3, 5]], [[20.5, 23], [17.5, 20]]),
),
)
def test_get_loss_per_sample(z_tensor: List[float], jacobian: List[float], expected_loss: List[float]) -> None:
loss = get_loss_per_sample(torch.Tensor(z_tensor), torch.Tensor(jacobian))
for sample_i in range(len(z_tensor)):
assert loss[sample_i].detach() == pytest.approx(expected_loss[sample_i], abs=1e-3)
def test_internal_network() -> None:
| """Contains tests for the normalizing flow module."""
@pytest.mark.parametrize(
("z_tensor", "jacobian", "expected_loss"),
(
([[0, 1, 2, 3], [2, 3, 4, 5]], [[1, 3], [1, 3]], 8.0),
([[1, 2, 3, 0], [4, 3, 2, 5]], [[1, 3], [1, 3]], 8.0),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [1, 3]], 10.8750),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [3, 1]], 10.8750),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[0, 2], [3, 5]], 10.75),
),
)
def test_get_loss(z_tensor: List[float], jacobian: List[float], expected_loss: float) -> None:
loss = get_loss(torch.Tensor(z_tensor), torch.Tensor(jacobian))
assert loss.item() == pytest.approx(expected_loss, abs=1e-3)
@pytest.mark.parametrize(
("z_tensor", "jacobian", "expected_loss"),
(
([[0, 1, 2, 3], [2, 3, 4, 5]], [[3, 4], [1, 3]], [[4, 23], [6, 24]]),
([[1, 2, 3, 0], [4, 3, 2, 5]], [[1, 3], [1, 3]], [[6, 24], [6, 24]]),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [1, 3]], [[19.5, 22], [19.5, 22]]),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [3, 1]], [[19.5, 22], [17.5, 24]]),
([[6, 0, 1, 2], [7, 0, 0, 1]], [[0, 2], [3, 5]], [[20.5, 23], [17.5, 20]]),
),
)
def test_get_loss_per_sample(z_tensor: List[float], jacobian: List[float], expected_loss: List[float]) -> None:
loss = get_loss_per_sample(torch.Tensor(z_tensor), torch.Tensor(jacobian))
for sample_i in range(len(z_tensor)):
assert loss[sample_i].detach() == pytest.approx(expected_loss[sample_i], abs=1e-3)
def test_internal_network() -> None: | internal_network_factory = InternalNetwork.setup( | 1 | 2023-10-18 15:09:24+00:00 | 4k |
invictus717/UniDG | domainbed/algorithms.py | [
{
"identifier": "networks",
"path": "domainbed/networks.py",
"snippet": "def remove_batch_norm_from_resnet(model):\n def __init__(self):\n def forward(self, x):\n def __init__(self):\n def forward(self, x):\n def __init__(self, n_inputs, n_outputs, hparams):\n def forward(self, x):\n ... | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from domainbed import networks
from domainbed.lib.misc import random_pairs_of_minibatches
from domainbed.optimizers import get_optimizer
from domainbed.networks import URFeaturizer
from domainbed.lib import misc
from domainbed.algorithms import Algorithm | 1,944 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
ALGORITHMS = [
'ERM',
'IRM',
'GroupDRO',
'Mixup',
'MLDG',
'CORAL',
'MMD',
'DANN',
'CDANN',
'MTL',
'SagNet',
'ARM',
'VREx',
'RSC',
'SD',
'MIRO'
]
def get_algorithm_class(algorithm_name):
"""Return the algorithm class with the given name."""
if algorithm_name not in globals():
raise NotImplementedError("Algorithm not found: {}".format(algorithm_name))
return globals()[algorithm_name]
class Algorithm(torch.nn.Module):
"""
A subclass of Algorithm implements a domain generalization algorithm.
Subclasses should implement the following:
- update()
- predict()
"""
def __init__(self, input_shape, num_classes, num_domains, hparams):
super(Algorithm, self).__init__()
self.hparams = hparams
def update(self, minibatches, unlabeled=None):
"""
Perform one update step, given a list of (x, y) tuples for all
environments.
Admits an optional list of unlabeled minibatches from the test domains,
when task is domain_adaptation.
"""
raise NotImplementedError
def predict(self, x):
raise NotImplementedError
class ERM(Algorithm):
"""
Empirical Risk Minimization (ERM)
"""
def __init__(self, input_shape, num_classes, num_domains, hparams):
super(ERM, self).__init__(input_shape, num_classes, num_domains,
hparams)
| # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
ALGORITHMS = [
'ERM',
'IRM',
'GroupDRO',
'Mixup',
'MLDG',
'CORAL',
'MMD',
'DANN',
'CDANN',
'MTL',
'SagNet',
'ARM',
'VREx',
'RSC',
'SD',
'MIRO'
]
def get_algorithm_class(algorithm_name):
"""Return the algorithm class with the given name."""
if algorithm_name not in globals():
raise NotImplementedError("Algorithm not found: {}".format(algorithm_name))
return globals()[algorithm_name]
class Algorithm(torch.nn.Module):
"""
A subclass of Algorithm implements a domain generalization algorithm.
Subclasses should implement the following:
- update()
- predict()
"""
def __init__(self, input_shape, num_classes, num_domains, hparams):
super(Algorithm, self).__init__()
self.hparams = hparams
def update(self, minibatches, unlabeled=None):
"""
Perform one update step, given a list of (x, y) tuples for all
environments.
Admits an optional list of unlabeled minibatches from the test domains,
when task is domain_adaptation.
"""
raise NotImplementedError
def predict(self, x):
raise NotImplementedError
class ERM(Algorithm):
"""
Empirical Risk Minimization (ERM)
"""
def __init__(self, input_shape, num_classes, num_domains, hparams):
super(ERM, self).__init__(input_shape, num_classes, num_domains,
hparams) | self.featurizer = networks.Featurizer(input_shape, self.hparams) | 0 | 2023-10-15 14:26:12+00:00 | 4k |
AI-Application-and-Integration-Lab/DGUA_FAS | util/evaluate.py | [
{
"identifier": "AverageMeter",
"path": "util/utils.py",
"snippet": "class AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n ... | from util.utils import AverageMeter, accuracy
from util.statistic import get_EER_states, get_HTER_at_thr, calculate, calculate_threshold
from sklearn.metrics import roc_auc_score
from torch.autograd import Variable
from torch.nn import functional as F
import torch
import torch.nn as nn
import numpy as np | 1,771 |
def eval(valid_dataloader, model):
criterion = nn.CrossEntropyLoss()
valid_losses = AverageMeter()
valid_top1 = AverageMeter()
prob_dict = {}
label_dict = {}
model.eval()
output_dict_tmp = {}
target_dict_tmp = {}
with torch.no_grad():
for iter, (input, target, videoID) in enumerate(valid_dataloader):
input = Variable(input).cuda()
target = Variable(torch.from_numpy(np.array(target)).long()).cuda()
cls_out = model(input)
prob = F.softmax(cls_out, dim=1).cpu().data.numpy()[:, 1]
label = target.cpu().data.numpy()
videoID = videoID.cpu().data.numpy()
for i in range(len(prob)):
if(videoID[i] in prob_dict.keys()):
prob_dict[videoID[i]].append(prob[i])
label_dict[videoID[i]].append(label[i])
output_dict_tmp[videoID[i]].append(cls_out[i].view(1, 3))
target_dict_tmp[videoID[i]].append(target[i].view(1))
else:
prob_dict[videoID[i]] = []
label_dict[videoID[i]] = []
prob_dict[videoID[i]].append(prob[i])
label_dict[videoID[i]].append(label[i])
output_dict_tmp[videoID[i]] = []
target_dict_tmp[videoID[i]] = []
output_dict_tmp[videoID[i]].append(cls_out[i].view(1, 3))
target_dict_tmp[videoID[i]].append(target[i].view(1))
prob_list = []
label_list = []
na = []
for key in prob_dict.keys():
avg_single_video_prob = sum(prob_dict[key]) / len(prob_dict[key])
avg_single_video_label = sum(label_dict[key]) / len(label_dict[key])
prob_list = np.append(prob_list, avg_single_video_prob)
label_list = np.append(label_list, avg_single_video_label)
# compute loss and acc for every video
avg_single_video_output = sum(output_dict_tmp[key]) / len(output_dict_tmp[key])
avg_single_video_target = (sum(target_dict_tmp[key]) / len(target_dict_tmp[key])).long()
loss = criterion(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0))
acc_valid = accuracy(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0), topk=(1,))
# loss = criterion(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0))
# acc_valid = accuracy(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0), topk=(1,))
valid_losses.update(loss.item())
valid_top1.update(acc_valid[0])
if avg_single_video_label == 2:
na += [avg_single_video_prob]
label_list = np.where(np.array(label_list) == 1, np.ones_like(label_list), np.zeros_like(label_list))
auc_score = roc_auc_score(label_list, prob_list)
cur_EER_valid, threshold, _, _ = get_EER_states(prob_list, label_list)
|
def eval(valid_dataloader, model):
criterion = nn.CrossEntropyLoss()
valid_losses = AverageMeter()
valid_top1 = AverageMeter()
prob_dict = {}
label_dict = {}
model.eval()
output_dict_tmp = {}
target_dict_tmp = {}
with torch.no_grad():
for iter, (input, target, videoID) in enumerate(valid_dataloader):
input = Variable(input).cuda()
target = Variable(torch.from_numpy(np.array(target)).long()).cuda()
cls_out = model(input)
prob = F.softmax(cls_out, dim=1).cpu().data.numpy()[:, 1]
label = target.cpu().data.numpy()
videoID = videoID.cpu().data.numpy()
for i in range(len(prob)):
if(videoID[i] in prob_dict.keys()):
prob_dict[videoID[i]].append(prob[i])
label_dict[videoID[i]].append(label[i])
output_dict_tmp[videoID[i]].append(cls_out[i].view(1, 3))
target_dict_tmp[videoID[i]].append(target[i].view(1))
else:
prob_dict[videoID[i]] = []
label_dict[videoID[i]] = []
prob_dict[videoID[i]].append(prob[i])
label_dict[videoID[i]].append(label[i])
output_dict_tmp[videoID[i]] = []
target_dict_tmp[videoID[i]] = []
output_dict_tmp[videoID[i]].append(cls_out[i].view(1, 3))
target_dict_tmp[videoID[i]].append(target[i].view(1))
prob_list = []
label_list = []
na = []
for key in prob_dict.keys():
avg_single_video_prob = sum(prob_dict[key]) / len(prob_dict[key])
avg_single_video_label = sum(label_dict[key]) / len(label_dict[key])
prob_list = np.append(prob_list, avg_single_video_prob)
label_list = np.append(label_list, avg_single_video_label)
# compute loss and acc for every video
avg_single_video_output = sum(output_dict_tmp[key]) / len(output_dict_tmp[key])
avg_single_video_target = (sum(target_dict_tmp[key]) / len(target_dict_tmp[key])).long()
loss = criterion(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0))
acc_valid = accuracy(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0), topk=(1,))
# loss = criterion(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0))
# acc_valid = accuracy(avg_single_video_output, torch.where(avg_single_video_target == 1, 1, 0), topk=(1,))
valid_losses.update(loss.item())
valid_top1.update(acc_valid[0])
if avg_single_video_label == 2:
na += [avg_single_video_prob]
label_list = np.where(np.array(label_list) == 1, np.ones_like(label_list), np.zeros_like(label_list))
auc_score = roc_auc_score(label_list, prob_list)
cur_EER_valid, threshold, _, _ = get_EER_states(prob_list, label_list) | ACC_threshold = calculate_threshold(prob_list, label_list, threshold) | 5 | 2023-10-17 15:35:33+00:00 | 4k |
jianlanluo/SAQ | vqn/vqiql.py | [
{
"identifier": "FullyConnectedNetwork",
"path": "vqn/model.py",
"snippet": "class FullyConnectedNetwork(nn.Module):\n output_dim: int\n arch: str = '256-256'\n orthogonal_init: bool = False\n\n @nn.compact\n def __call__(self, input_tensor):\n x = input_tensor\n hidden_size... | import copy
import collections
import distrax
import jax
import jax.numpy as jnp
import numpy as np
import optax
import flax
from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple, Union
from functools import partial
from gym.utils import seeding
from jax import random
from flax import linen as nn
from flax.core import frozen_dict
from flax.core.frozen_dict import FrozenDict
from flax.training.train_state import TrainState
from tqdm import tqdm
from .model import FullyConnectedNetwork, StateActionEnsemble, StateValue
from .jax_utils import next_rng, JaxRNG, collect_jax_metrics, wrap_function_with_rng | 2,839 | def squared_euclidean_distance(a, b, b2=None, precision=None):
if b2 is None:
b2 = jnp.sum(b.T**2, axis=0, keepdims=True)
a2 = jnp.sum(a**2, axis=1, keepdims=True)
ab = jnp.matmul(a, b.T, precision=precision)
d = a2 - 2 * ab + b2
return d
def entropy_loss_fn(affinity, loss_type="softmax", temperature=1.0):
"""Calculates the entropy loss."""
flat_affinity = affinity.reshape(-1, affinity.shape[-1])
flat_affinity /= temperature
probs = jax.nn.softmax(flat_affinity, axis=-1)
log_probs = jax.nn.log_softmax(flat_affinity + 1e-5, axis=-1)
if loss_type == "softmax":
target_probs = probs
elif loss_type == "argmax":
codes = jnp.argmax(flat_affinity, axis=-1)
onehots = jax.nn.one_hot(
codes, flat_affinity.shape[-1], dtype=flat_affinity.dtype
)
onehots = probs - jax.lax.stop_gradient(probs - onehots)
target_probs = onehots
else:
raise ValueError("Entropy loss {} not supported".format(loss_type))
avg_probs = jnp.mean(target_probs, axis=0)
avg_entropy = -jnp.sum(avg_probs * jnp.log(avg_probs + 1e-5))
sample_entropy = -jnp.mean(jnp.sum(target_probs * log_probs, axis=-1))
loss = sample_entropy - avg_entropy
return loss
class VectorQuantizer(nn.Module):
"""Basic vector quantizer."""
codebook_size: int
commitment_cost: float
quantization_cost: float
entropy_loss_ratio: float = 0.0
entropy_loss_type: str = "softmax"
entropy_temperature: float = 1.0
@nn.compact
def __call__(self, x, train=False):
codebook = self.param(
"codebook",
jax.nn.initializers.variance_scaling(
scale=1.0, mode="fan_in", distribution="uniform"
),
(self.codebook_size, x.shape[-1]),
)
codebook = jnp.asarray(codebook, dtype=jnp.float32)
distances = jnp.reshape(
squared_euclidean_distance(x, codebook),
x.shape[:-1] + (self.codebook_size,),
)
encoding_indices = jnp.argmin(distances, axis=-1)
encodings = jax.nn.one_hot(encoding_indices, self.codebook_size, dtype=jnp.float32)
quantized = self.quantize(encodings)
result_dict = dict(
quantized=quantized,
encoding_indices=encoding_indices,
)
if train:
e_latent_loss = jnp.mean(
(jax.lax.stop_gradient(quantized) - x) ** 2
) * self.commitment_cost
q_latent_loss = jnp.mean(
(quantized - jax.lax.stop_gradient(x)) ** 2
) * self.quantization_cost
entropy_loss = 0.0
if self.entropy_loss_ratio != 0:
entropy_loss = (
entropy_loss_fn(
-distances,
loss_type=self.entropy_loss_type,
temperature=self.entropy_temperature,
)
* self.entropy_loss_ratio
)
e_latent_loss = jnp.asarray(e_latent_loss, jnp.float32)
q_latent_loss = jnp.asarray(q_latent_loss, jnp.float32)
entropy_loss = jnp.asarray(entropy_loss, jnp.float32)
loss = e_latent_loss + q_latent_loss + entropy_loss
result_dict.update(dict(
loss=loss,
e_latent_loss=e_latent_loss,
q_latent_loss=q_latent_loss,
entropy_loss=entropy_loss,
))
quantized = x + jax.lax.stop_gradient(quantized - x)
return quantized, result_dict
def quantize(self, z):
codebook = jnp.asarray(self.variables["params"]["codebook"], dtype=jnp.float32)
return jnp.dot(z, codebook)
def get_codebook(self):
return jnp.asarray(self.variables["params"]["codebook"], dtype=jnp.float32)
def decode_ids(self, ids):
codebook = self.variables["params"]["codebook"]
return jnp.take(codebook, ids, axis=0)
class ActionVQVAE(nn.Module):
observation_dim: int
action_dim: int
embedding_dim: int
codebook_size: int
commitment_cost: float = 1.0
quantization_cost: float = 1.0
entropy_loss_ratio: float = 0.0
entropy_loss_type: str = "softmax"
entropy_temperature: float = 1.0
arch: str = '256-256'
action_only_quantization: bool = False
reconstruction_loss_type: str = 'l2'
def setup(self):
| """Implementations of algorithms for continuous control."""
Batch = collections.namedtuple(
'Batch',
['observations', 'actions', 'rewards', 'masks', 'next_observations'])
def default_init(scale: Optional[float] = jnp.sqrt(2)):
return nn.initializers.orthogonal(scale)
Shape = Sequence[int]
Dtype = Any # this could be a real type?
InfoDict = Dict[str, float]
DataType = Union[np.ndarray, Dict[str, 'DataType']]
PRNGKey = Any
Params = flax.core.FrozenDict[str, Any]
DatasetDict = Dict[str, DataType]
def get_iql_policy_from_model(env, checkpoint_data):
sampler_policy = IQLSamplerPolicy(checkpoint_data['iql'].actor)
return sampler_policy
class IQLSamplerPolicy(object):
def __init__(self, actor):
self.actor=actor
rng = jax.random.PRNGKey(24)
rng, actor_key, critic_key, value_key = jax.random.split(rng, 4)
self.rng = rng
def __call__(self, observations, deterministic=False):
actions = self.sample_actions(observations)
assert jnp.all(jnp.isfinite(actions))
return jax.device_get(actions)
def sample_actions(self,
observations: np.ndarray,
temperature: float = 1.0) -> jnp.ndarray:
rng, actions = sample_actions_jit(self.rng, self.actor.apply_fn,
self.actor.params, observations)
self.rng = rng
actions = np.asarray(actions)
return np.clip(actions, -1, 1)
def split_into_trajectories(observations, actions, rewards, masks, dones_float,
next_observations):
trajs = [[]]
for i in tqdm(range(len(observations))):
trajs[-1].append((observations[i], actions[i], rewards[i], masks[i],
dones_float[i], next_observations[i]))
if dones_float[i] == 1.0 and i + 1 < len(observations):
trajs.append([])
return trajs
def squared_euclidean_distance(a, b, b2=None, precision=None):
if b2 is None:
b2 = jnp.sum(b.T**2, axis=0, keepdims=True)
a2 = jnp.sum(a**2, axis=1, keepdims=True)
ab = jnp.matmul(a, b.T, precision=precision)
d = a2 - 2 * ab + b2
return d
def entropy_loss_fn(affinity, loss_type="softmax", temperature=1.0):
"""Calculates the entropy loss."""
flat_affinity = affinity.reshape(-1, affinity.shape[-1])
flat_affinity /= temperature
probs = jax.nn.softmax(flat_affinity, axis=-1)
log_probs = jax.nn.log_softmax(flat_affinity + 1e-5, axis=-1)
if loss_type == "softmax":
target_probs = probs
elif loss_type == "argmax":
codes = jnp.argmax(flat_affinity, axis=-1)
onehots = jax.nn.one_hot(
codes, flat_affinity.shape[-1], dtype=flat_affinity.dtype
)
onehots = probs - jax.lax.stop_gradient(probs - onehots)
target_probs = onehots
else:
raise ValueError("Entropy loss {} not supported".format(loss_type))
avg_probs = jnp.mean(target_probs, axis=0)
avg_entropy = -jnp.sum(avg_probs * jnp.log(avg_probs + 1e-5))
sample_entropy = -jnp.mean(jnp.sum(target_probs * log_probs, axis=-1))
loss = sample_entropy - avg_entropy
return loss
class VectorQuantizer(nn.Module):
"""Basic vector quantizer."""
codebook_size: int
commitment_cost: float
quantization_cost: float
entropy_loss_ratio: float = 0.0
entropy_loss_type: str = "softmax"
entropy_temperature: float = 1.0
@nn.compact
def __call__(self, x, train=False):
codebook = self.param(
"codebook",
jax.nn.initializers.variance_scaling(
scale=1.0, mode="fan_in", distribution="uniform"
),
(self.codebook_size, x.shape[-1]),
)
codebook = jnp.asarray(codebook, dtype=jnp.float32)
distances = jnp.reshape(
squared_euclidean_distance(x, codebook),
x.shape[:-1] + (self.codebook_size,),
)
encoding_indices = jnp.argmin(distances, axis=-1)
encodings = jax.nn.one_hot(encoding_indices, self.codebook_size, dtype=jnp.float32)
quantized = self.quantize(encodings)
result_dict = dict(
quantized=quantized,
encoding_indices=encoding_indices,
)
if train:
e_latent_loss = jnp.mean(
(jax.lax.stop_gradient(quantized) - x) ** 2
) * self.commitment_cost
q_latent_loss = jnp.mean(
(quantized - jax.lax.stop_gradient(x)) ** 2
) * self.quantization_cost
entropy_loss = 0.0
if self.entropy_loss_ratio != 0:
entropy_loss = (
entropy_loss_fn(
-distances,
loss_type=self.entropy_loss_type,
temperature=self.entropy_temperature,
)
* self.entropy_loss_ratio
)
e_latent_loss = jnp.asarray(e_latent_loss, jnp.float32)
q_latent_loss = jnp.asarray(q_latent_loss, jnp.float32)
entropy_loss = jnp.asarray(entropy_loss, jnp.float32)
loss = e_latent_loss + q_latent_loss + entropy_loss
result_dict.update(dict(
loss=loss,
e_latent_loss=e_latent_loss,
q_latent_loss=q_latent_loss,
entropy_loss=entropy_loss,
))
quantized = x + jax.lax.stop_gradient(quantized - x)
return quantized, result_dict
def quantize(self, z):
codebook = jnp.asarray(self.variables["params"]["codebook"], dtype=jnp.float32)
return jnp.dot(z, codebook)
def get_codebook(self):
return jnp.asarray(self.variables["params"]["codebook"], dtype=jnp.float32)
def decode_ids(self, ids):
codebook = self.variables["params"]["codebook"]
return jnp.take(codebook, ids, axis=0)
class ActionVQVAE(nn.Module):
observation_dim: int
action_dim: int
embedding_dim: int
codebook_size: int
commitment_cost: float = 1.0
quantization_cost: float = 1.0
entropy_loss_ratio: float = 0.0
entropy_loss_type: str = "softmax"
entropy_temperature: float = 1.0
arch: str = '256-256'
action_only_quantization: bool = False
reconstruction_loss_type: str = 'l2'
def setup(self): | self.encoder = FullyConnectedNetwork( | 0 | 2023-10-18 06:31:20+00:00 | 4k |
naver-ai/dual-teacher | tools/test.py | [
{
"identifier": "multi_gpu_test",
"path": "mmseg/apis/test.py",
"snippet": "def multi_gpu_test(model,\n data_loader,\n tmpdir=None,\n gpu_collect=False,\n efficient_test=False):\n \"\"\"Test model with multiple gpus.\n\n This ... | import argparse
import os
import mmcv
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from mmcv.utils import DictAction
from mmseg.apis import multi_gpu_test, single_gpu_test
from mmseg.datasets import build_dataloader, build_dataset
from mmseg.models import build_segmentor
from IPython import embed | 3,326 | parser.add_argument('--out', default='work_dirs/res.pkl', help='output result file in pickle format')
parser.add_argument(
'--format-only',
action='store_true',
help='Format the output results without perform evaluation. It is'
'useful when you want to format the result to a specific format and '
'submit it to the test server')
parser.add_argument(
'--eval',
type=str,
nargs='+',
default='mIoU',
help='evaluation metrics, which depends on the dataset, e.g., "mIoU"'
' for generic datasets, and "cityscapes" for Cityscapes')
parser.add_argument('--show', action='store_true', help='show results')
parser.add_argument(
'--show-dir', help='directory where painted images will be saved')
parser.add_argument(
'--gpu-collect',
action='store_true',
help='whether to use gpu to collect results.')
parser.add_argument(
'--tmpdir',
help='tmp directory used for collecting results from multiple '
'workers, available when gpu_collect is not specified')
parser.add_argument(
'--options', nargs='+', action=DictAction, help='custom options')
parser.add_argument(
'--eval-options',
nargs='+',
action=DictAction,
help='custom options for evaluation')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def main():
args = parse_args()
assert args.out or args.eval or args.format_only or args.show \
or args.show_dir, \
('Please specify at least one operation (save/eval/format/show the '
'results / save the results) with the argument "--out", "--eval"'
', "--format-only", "--show" or "--show-dir"')
if 'None' in args.eval:
args.eval = None
if args.eval and args.format_only:
raise ValueError('--eval and --format_only cannot be both specified')
if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):
raise ValueError('The output file must be a pkl file.')
cfg = mmcv.Config.fromfile(args.config)
if args.options is not None:
cfg.merge_from_dict(args.options)
# set cudnn_benchmark
# if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = False
if args.aug_test:
if cfg.data.test.type == 'CityscapesDataset':
# hard code index
cfg.data.test.pipeline[1].img_ratios = [
0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0
]
cfg.data.test.pipeline[1].flip = True
elif cfg.data.test.type == 'ADE20KDataset':
# hard code index
cfg.data.test.pipeline[1].img_ratios = [
0.75, 0.875, 1.0, 1.125, 1.25
]
cfg.data.test.pipeline[1].flip = True
else:
# hard code index
cfg.data.test.pipeline[1].img_ratios = [
0.5, 0.75, 1.0, 1.25, 1.5, 1.75
]
cfg.data.test.pipeline[1].flip = True
cfg.model.pretrained = None
cfg.data.test.test_mode = True
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
# build the dataloader
# TODO: support multiple images per gpu (only minor changes are needed)
dataset = build_dataset(cfg.data.test)
data_loader = build_dataloader(
dataset,
samples_per_gpu=1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=distributed,
shuffle=False)
# build the model and load checkpoint
cfg.model.train_cfg = None
model = build_segmentor(cfg.model, test_cfg=cfg.get('test_cfg'))
checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')
model.CLASSES = checkpoint['meta']['CLASSES']
model.PALETTE = checkpoint['meta']['PALETTE']
efficient_test = True # False
if args.eval_options is not None:
efficient_test = args.eval_options.get('efficient_test', False)
if not distributed:
model = MMDataParallel(model, device_ids=[0])
|
def parse_args():
parser = argparse.ArgumentParser(
description='mmseg test (and eval) a model')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument(
'--aug-test', action='store_true', help='Use Flip and Multi scale aug')
parser.add_argument('--out', default='work_dirs/res.pkl', help='output result file in pickle format')
parser.add_argument(
'--format-only',
action='store_true',
help='Format the output results without perform evaluation. It is'
'useful when you want to format the result to a specific format and '
'submit it to the test server')
parser.add_argument(
'--eval',
type=str,
nargs='+',
default='mIoU',
help='evaluation metrics, which depends on the dataset, e.g., "mIoU"'
' for generic datasets, and "cityscapes" for Cityscapes')
parser.add_argument('--show', action='store_true', help='show results')
parser.add_argument(
'--show-dir', help='directory where painted images will be saved')
parser.add_argument(
'--gpu-collect',
action='store_true',
help='whether to use gpu to collect results.')
parser.add_argument(
'--tmpdir',
help='tmp directory used for collecting results from multiple '
'workers, available when gpu_collect is not specified')
parser.add_argument(
'--options', nargs='+', action=DictAction, help='custom options')
parser.add_argument(
'--eval-options',
nargs='+',
action=DictAction,
help='custom options for evaluation')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
return args
def main():
args = parse_args()
assert args.out or args.eval or args.format_only or args.show \
or args.show_dir, \
('Please specify at least one operation (save/eval/format/show the '
'results / save the results) with the argument "--out", "--eval"'
', "--format-only", "--show" or "--show-dir"')
if 'None' in args.eval:
args.eval = None
if args.eval and args.format_only:
raise ValueError('--eval and --format_only cannot be both specified')
if args.out is not None and not args.out.endswith(('.pkl', '.pickle')):
raise ValueError('The output file must be a pkl file.')
cfg = mmcv.Config.fromfile(args.config)
if args.options is not None:
cfg.merge_from_dict(args.options)
# set cudnn_benchmark
# if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = False
if args.aug_test:
if cfg.data.test.type == 'CityscapesDataset':
# hard code index
cfg.data.test.pipeline[1].img_ratios = [
0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0
]
cfg.data.test.pipeline[1].flip = True
elif cfg.data.test.type == 'ADE20KDataset':
# hard code index
cfg.data.test.pipeline[1].img_ratios = [
0.75, 0.875, 1.0, 1.125, 1.25
]
cfg.data.test.pipeline[1].flip = True
else:
# hard code index
cfg.data.test.pipeline[1].img_ratios = [
0.5, 0.75, 1.0, 1.25, 1.5, 1.75
]
cfg.data.test.pipeline[1].flip = True
cfg.model.pretrained = None
cfg.data.test.test_mode = True
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
else:
distributed = True
init_dist(args.launcher, **cfg.dist_params)
# build the dataloader
# TODO: support multiple images per gpu (only minor changes are needed)
dataset = build_dataset(cfg.data.test)
data_loader = build_dataloader(
dataset,
samples_per_gpu=1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=distributed,
shuffle=False)
# build the model and load checkpoint
cfg.model.train_cfg = None
model = build_segmentor(cfg.model, test_cfg=cfg.get('test_cfg'))
checkpoint = load_checkpoint(model, args.checkpoint, map_location='cpu')
model.CLASSES = checkpoint['meta']['CLASSES']
model.PALETTE = checkpoint['meta']['PALETTE']
efficient_test = True # False
if args.eval_options is not None:
efficient_test = args.eval_options.get('efficient_test', False)
if not distributed:
model = MMDataParallel(model, device_ids=[0]) | outputs = single_gpu_test(model, data_loader, args.show, args.show_dir, efficient_test) | 1 | 2023-10-19 04:04:31+00:00 | 4k |
Azure/azure-openai-benchmark | tests/oairequester.py | [
{
"identifier": "OAIRequester",
"path": "benchmark/oairequester.py",
"snippet": "class OAIRequester:\n \"\"\"\n A simple AOAI requester that makes a streaming call and collect corresponding\n statistics.\n :param api_key: Azure OpenAI resource endpoint key.\n :param url: Full deployment U... | import unittest
import time
import httpretty
from benchmark.oairequester import OAIRequester, UTILIZATION_HEADER, RETRY_AFTER_MS_HEADER | 1,716 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
TEST_URL = "https://testresource.openai.azure.com/openai/deployments/depl/chat/completion?api-version=2023-05-15"
class TokenIterator:
def __init__(self, delay: float):
self.done = False
self.delay = delay
self.token_lines = b'data: {}\r\nend: {}\r\n'
def __iter__(self):
return self
def __next__(self):
if self.done:
raise StopIteration
time.sleep(self.delay)
self.done = True
return self.token_lines
class TestRequester(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL,
body=(l for l in TokenIterator(0.1)), streaming=True,
adding_headers={UTILIZATION_HEADER: "11.2%"})
requester = OAIRequester("", TEST_URL)
stats = requester.call({})
self.assertEqual(stats.calls, 1)
self.assertIsNone(stats.last_exception)
self.assertEqual(stats.generated_tokens, 1)
self.assertEqual(stats.response_status_code, 200)
self.assertAlmostEqual(stats.response_end_time-stats.request_start_time, 0.1, delta=0.02)
self.assertAlmostEqual(stats.first_token_time-stats.request_start_time, 0.1, delta=0.02)
self.assertEqual(stats.deployment_utilization, 11.2)
class TestRequesterTerminal(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL,
status=500)
requester = OAIRequester("", TEST_URL)
stats = requester.call({})
self.assertEqual(stats.calls, 1)
self.assertEqual(stats.response_status_code, 500)
self.assertIsNotNone(stats.last_exception)
class TestRequesterRetryExponential(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL,
status=429)
requester = OAIRequester("", TEST_URL)
stats = requester.call({})
self.assertGreaterEqual(stats.calls, 4)
self.assertEqual(stats.response_status_code, 429)
self.assertIsNotNone(stats.last_exception)
class TestRequesterRetryAfter(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL,
| # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
TEST_URL = "https://testresource.openai.azure.com/openai/deployments/depl/chat/completion?api-version=2023-05-15"
class TokenIterator:
def __init__(self, delay: float):
self.done = False
self.delay = delay
self.token_lines = b'data: {}\r\nend: {}\r\n'
def __iter__(self):
return self
def __next__(self):
if self.done:
raise StopIteration
time.sleep(self.delay)
self.done = True
return self.token_lines
class TestRequester(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL,
body=(l for l in TokenIterator(0.1)), streaming=True,
adding_headers={UTILIZATION_HEADER: "11.2%"})
requester = OAIRequester("", TEST_URL)
stats = requester.call({})
self.assertEqual(stats.calls, 1)
self.assertIsNone(stats.last_exception)
self.assertEqual(stats.generated_tokens, 1)
self.assertEqual(stats.response_status_code, 200)
self.assertAlmostEqual(stats.response_end_time-stats.request_start_time, 0.1, delta=0.02)
self.assertAlmostEqual(stats.first_token_time-stats.request_start_time, 0.1, delta=0.02)
self.assertEqual(stats.deployment_utilization, 11.2)
class TestRequesterTerminal(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL,
status=500)
requester = OAIRequester("", TEST_URL)
stats = requester.call({})
self.assertEqual(stats.calls, 1)
self.assertEqual(stats.response_status_code, 500)
self.assertIsNotNone(stats.last_exception)
class TestRequesterRetryExponential(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL,
status=429)
requester = OAIRequester("", TEST_URL)
stats = requester.call({})
self.assertGreaterEqual(stats.calls, 4)
self.assertEqual(stats.response_status_code, 429)
self.assertIsNotNone(stats.last_exception)
class TestRequesterRetryAfter(unittest.TestCase):
@httpretty.activate(allow_net_connect=False)
def test_norate(self):
httpretty.register_uri(httpretty.POST, TEST_URL, | adding_headers={RETRY_AFTER_MS_HEADER: 100}, | 2 | 2023-10-19 00:52:26+00:00 | 4k |
pytest-visual/pytest-visual | examples/end_to_end/test_main.py | [
{
"identifier": "ClockCoordinateDataset",
"path": "examples/end_to_end/main.py",
"snippet": "def main() -> None:\n def __init__(self, data_dir: Path, normalize: bool = True):\n def __getitem__(self, index: int) -> Tuple[Tensor, \"Time\"]:\n def __len__(self) -> int:\n def __init__(self, data... | from pathlib import Path
from typing import List
from PIL import Image
from torch import Tensor
from examples.end_to_end.main import (
ClockCoordinateDataset,
ClockDataset,
Time,
get_label,
get_model,
get_model_head,
mean_norm,
std_norm,
)
from visual.interface import VisualFixture, fix_seeds, standardize, visual
import cv2
import numpy as np
import pytest
import torchview | 2,571 |
test_data_path = Path("examples/end_to_end/test_data")
def test_original_labels(visual: VisualFixture, fix_seeds):
dataset = ClockDataset(test_data_path / "train")
images, labels = [], []
for image, label in dataset:
# Convert to numpy, denormalize, and standardize layout to HWC
|
test_data_path = Path("examples/end_to_end/test_data")
def test_original_labels(visual: VisualFixture, fix_seeds):
dataset = ClockDataset(test_data_path / "train")
images, labels = [], []
for image, label in dataset:
# Convert to numpy, denormalize, and standardize layout to HWC | images.append(standardize(image.numpy(), mean_denorm=mean_norm, std_denorm=std_norm)) | 0 | 2023-10-18 07:13:37+00:00 | 4k |
SLDGroup/G-CASCADE | trainer.py | [
{
"identifier": "Synapse_dataset",
"path": "utils/dataset_synapse.py",
"snippet": "class Synapse_dataset(Dataset):\n def __init__(self, base_dir, list_dir, split, nclass=9, transform=None):\n self.transform = transform # using transform in torch!\n self.split = split\n self.samp... | import argparse
import logging
import os
import random
import sys
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
from tensorboardX import SummaryWriter
from torch.nn.modules.loss import CrossEntropyLoss
from torch.utils.data import DataLoader
from torchvision import transforms
from torch.cuda.amp import GradScaler, autocast
from utils.dataset_synapse import Synapse_dataset, RandomGenerator
from utils.utils import powerset
from utils.utils import one_hot_encoder
from utils.utils import DiceLoss
from utils.utils import val_single_volume | 2,578 |
def inference(args, model, best_performance):
db_test = Synapse_dataset(base_dir=args.volume_path, split="test_vol", list_dir=args.list_dir, nclass=args.num_classes)
testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=1)
logging.info("{} test iterations per epoch".format(len(testloader)))
model.eval()
metric_list = 0.0
for i_batch, sampled_batch in tqdm(enumerate(testloader)):
h, w = sampled_batch["image"].size()[2:]
image, label, case_name = sampled_batch["image"], sampled_batch["label"], sampled_batch['case_name'][0]
metric_i = val_single_volume(image, label, model, classes=args.num_classes, patch_size=[args.img_size, args.img_size],
case=case_name, z_spacing=args.z_spacing)
metric_list += np.array(metric_i)
metric_list = metric_list / len(db_test)
performance = np.mean(metric_list, axis=0)
logging.info('Testing performance in val model: mean_dice : %f, best_dice : %f' % (performance, best_performance))
return performance
def trainer_synapse(args, model, snapshot_path):
logging.basicConfig(filename=snapshot_path + "/log.txt", level=logging.INFO,
format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(str(args))
base_lr = args.base_lr
num_classes = args.num_classes
batch_size = args.batch_size * args.n_gpu
db_train = Synapse_dataset(base_dir=args.root_path, list_dir=args.list_dir, split="train", nclass=args.num_classes,
transform=transforms.Compose(
[RandomGenerator(output_size=[args.img_size, args.img_size])]))
print("The length of train set is: {}".format(len(db_train)))
def worker_init_fn(worker_id):
random.seed(args.seed + worker_id)
trainloader = DataLoader(db_train, batch_size=batch_size, shuffle=True, num_workers=8, pin_memory=True,
worker_init_fn=worker_init_fn)
if args.n_gpu > 1:
model = nn.DataParallel(model)
model.train()
ce_loss = CrossEntropyLoss()
|
def inference(args, model, best_performance):
db_test = Synapse_dataset(base_dir=args.volume_path, split="test_vol", list_dir=args.list_dir, nclass=args.num_classes)
testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=1)
logging.info("{} test iterations per epoch".format(len(testloader)))
model.eval()
metric_list = 0.0
for i_batch, sampled_batch in tqdm(enumerate(testloader)):
h, w = sampled_batch["image"].size()[2:]
image, label, case_name = sampled_batch["image"], sampled_batch["label"], sampled_batch['case_name'][0]
metric_i = val_single_volume(image, label, model, classes=args.num_classes, patch_size=[args.img_size, args.img_size],
case=case_name, z_spacing=args.z_spacing)
metric_list += np.array(metric_i)
metric_list = metric_list / len(db_test)
performance = np.mean(metric_list, axis=0)
logging.info('Testing performance in val model: mean_dice : %f, best_dice : %f' % (performance, best_performance))
return performance
def trainer_synapse(args, model, snapshot_path):
logging.basicConfig(filename=snapshot_path + "/log.txt", level=logging.INFO,
format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
logging.info(str(args))
base_lr = args.base_lr
num_classes = args.num_classes
batch_size = args.batch_size * args.n_gpu
db_train = Synapse_dataset(base_dir=args.root_path, list_dir=args.list_dir, split="train", nclass=args.num_classes,
transform=transforms.Compose(
[RandomGenerator(output_size=[args.img_size, args.img_size])]))
print("The length of train set is: {}".format(len(db_train)))
def worker_init_fn(worker_id):
random.seed(args.seed + worker_id)
trainloader = DataLoader(db_train, batch_size=batch_size, shuffle=True, num_workers=8, pin_memory=True,
worker_init_fn=worker_init_fn)
if args.n_gpu > 1:
model = nn.DataParallel(model)
model.train()
ce_loss = CrossEntropyLoss() | dice_loss = DiceLoss(num_classes) | 4 | 2023-10-24 17:49:10+00:00 | 4k |
StackTipsLab/bloggy | bloggy/views/edit_profile_view.py | [
{
"identifier": "settings",
"path": "bloggy/settings.py",
"snippet": "BASE_DIR = Path(__file__).resolve().parent.parent\nSECRET_KEY = os.getenv(\"SECRET_KEY\", get_random_secret_key())\nDEBUG = os.getenv(\"DEBUG\", \"False\") == \"True\"\nALLOWED_HOSTS = os.getenv(\"ALLOWED_HOSTS\", \"127.0.0.1, localho... | import os
from django.shortcuts import get_object_or_404
from django.template.context_processors import static
from django.views.generic import FormView
from bloggy import settings
from bloggy.forms.edit_profile_form import EditProfileForm
from bloggy.models import User
from bloggy.templatetags.custom_widgets import sanitize_url | 3,185 |
class EditProfileView(FormView):
template_name = "profile/edit_profile.html"
model = User
|
class EditProfileView(FormView):
template_name = "profile/edit_profile.html"
model = User | form_class = EditProfileForm | 1 | 2023-10-17 14:50:39+00:00 | 4k |
openvinotoolkit/openvino.genai | llm_bench/python/utils/conversion_utils/better_transformer_patch.py | [
{
"identifier": "_make_causal_mask",
"path": "llm_bench/python/utils/conversion_utils/convert_patch.py",
"snippet": "def _make_causal_mask(\n input_ids_shape: torch.Size,\n device: torch.device,\n past_key_values_length: int,\n dtype: torch.dtype = torch.bool,\n) -> torch.BoolTensor:\n \"... | import math
import torch
from torch import nn
from typing import Optional, Tuple, Union
from transformers import PretrainedConfig
from optimum.bettertransformer.models.attention import (
codegen_wrapped_scaled_dot_product,
)
from .convert_patch import _make_causal_mask, _expand_mask
from optimum.bettertransformer.models import BetterTransformerManager
from optimum.bettertransformer.models.base import BetterTransformerBaseLayer | 3,332 | self.rotary_emb = RotaryEmbedding(
self.rotary_ndims,
max_position_embeddings=self.config.max_position_embeddings,
base=self.config.rope_theta,
)
def forward(
self,
hidden_states: torch.FloatTensor,
attention_mask: torch.FloatTensor,
position_ids: torch.LongTensor,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(
bsz, q_len, self.num_heads, self.head_dim
).transpose(1, 2)
key_states = key_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
value_states = value_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
query_rot = query_states[..., : self.rotary_ndims]
query_pass = query_states[..., self.rotary_ndims :]
key_rot = key_states[..., : self.rotary_ndims]
key_pass = key_states[..., self.rotary_ndims :]
kv_seq_len = key_states.shape[-2]
if past_key_value is not None:
kv_seq_len += past_key_value[0].shape[-2]
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
query_states, key_states = apply_rotary_pos_emb(
query_rot, key_rot, cos, sin, position_ids
)
# [batch_size, num_heads, seq_len, head_dim]
query_states = torch.cat((query_states, query_pass), dim=-1)
key_states = torch.cat((key_states, key_pass), dim=-1)
if past_key_value is not None:
# Reuse k, v, self_attention
key_states = torch.cat((past_key_value[0], key_states), dim=2)
value_states = torch.cat((past_key_value[1], value_states), dim=2)
past_key_value = (key_states, value_states) if use_cache else None
# Repeat k/v heads if n_kv_heads < n_heads
key_states = repeat_kv(key_states, self.num_key_value_groups)
value_states = repeat_kv(value_states, self.num_key_value_groups)
attn_weights = torch.matmul(
query_states, key_states.transpose(2, 3)
) / math.sqrt(self.head_dim)
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
raise ValueError(
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights + attention_mask
# Upcast attention to fp32
attn_weights = nn.functional.softmax(
attn_weights, dim=-1, dtype=torch.float32
).to(query_states.dtype)
attn_output = torch.matmul(attn_weights, value_states)
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
raise ValueError(
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
f" {attn_output.size()}"
)
# Merge heads
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
# Final linear projection
attn_output = self.o_proj(attn_output)
if not output_attentions:
attn_weights = None
return attn_output, attn_weights, past_key_value
def _bt_prepare_decoder_attention_mask(
self, attention_mask, input_shape, inputs_embeds, past_key_values_length
):
# create causal mask
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
combined_attention_mask = None
# We do not care about the attention mask in the batch size = 1 case
if attention_mask.size(0) > 1:
if input_shape[-1] > 1:
combined_attention_mask = _make_causal_mask(
input_shape,
dtype=inputs_embeds.dtype,
device=inputs_embeds.device,
past_key_values_length=past_key_values_length,
)
if attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
| # -*- coding: utf-8 -*-
# Copyright (C) 2018-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(
batch, num_key_value_heads, n_rep, slen, head_dim
)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def fixed_pos_embedding(x, seq_dim=1, seq_len=None):
dim = x.shape[-1]
if seq_len is None:
seq_len = x.shape[seq_dim]
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
sinusoid_inp = (
torch.einsum("i , j -> i j", torch.arange(seq_len, dtype=torch.float), inv_freq)
.to(x.device)
.float()
)
return torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)
# Copied from transformers.models.gptj.modeling_gptj.rotate_every_two
def rotate_every_two(x):
x1 = x[:, :, :, ::2]
x2 = x[:, :, :, 1::2]
x = torch.stack((-x2, x1), dim=-1)
return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')
# Copied from transformers.models.gptj.modeling_gptj.duplicate_interleave
def duplicate_interleave(m):
"""
A simple version of `torch.repeat_interleave` for duplicating a matrix while interleaving the copy.
"""
dim0 = m.shape[0]
m = m.view(-1, 1) # flatten the matrix
m = m.repeat(1, 2) # repeat all elements into the 2nd dimension
m = m.view(dim0, -1) # reshape into a matrix, interleaving the copy
return m
# Copied from transformers.models.gptj.modeling_gptj.apply_rotary_pos_emb
def codegen_apply_rotary_pos_emb(x, sincos, offset=0):
sin, cos = map(
lambda t: duplicate_interleave(t)[None, offset : x.shape[1] + offset, None, :],
sincos,
)
# einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2)
return (x * cos) + (rotate_every_two(x) * sin)
class RotaryEmbedding(nn.Module):
def __init__(
self,
dim: int,
max_position_embeddings: int,
base: int = 10_000,
device: Optional[torch.device] = None,
):
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.base = base
inv_freq = 1.0 / (
self.base
** (
torch.arange(0, self.dim, 2, device=device, dtype=torch.float32)
/ self.dim
)
)
self.register_buffer("inv_freq", inv_freq, persistent=False)
# Build here to make `torch.jit.trace` work.
self._set_cos_sin_cache(
seq_len=max_position_embeddings,
device=self.inv_freq.device,
dtype=torch.get_default_dtype(),
)
def _set_cos_sin_cache(
self, seq_len: int, device: torch.device, dtype: torch.dtype
):
self.max_seq_len_cached = seq_len
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
# Don't do einsum, it converts fp32 to fp16 under AMP
# freqs = torch.einsum("i,j->ij", t, self.inv_freq)
freqs = torch.outer(t, self.inv_freq)
# Different from paper, but it uses a different permutation in order to obtain the same calculation
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer(
"cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
)
self.register_buffer(
"sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
)
def forward(self, x: torch.Tensor, seq_len: Optional[int] = None):
# x: [batch_size, num_heads, seq_len, head_size]
if seq_len > self.max_seq_len_cached:
self._set_cos_sin_cache(
seq_len=seq_len, device=x.device, dtype=torch.get_default_dtype()
)
return (
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
)
def rotate_half(x: torch.Tensor):
"""Rotates half the hidden dims of the input."""
x1, x2 = torch.chunk(x, 2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
cos = cos[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
sin = sin[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
class StableLMAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.hidden_size // self.num_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.max_position_embeddings = config.max_position_embeddings
if (self.head_dim * self.num_heads) != self.hidden_size:
raise ValueError(
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
f" and `num_heads`: {self.num_heads})."
)
self.q_proj = nn.Linear(
self.hidden_size, self.num_heads * self.head_dim, bias=False
)
self.k_proj = nn.Linear(
self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
)
self.v_proj = nn.Linear(
self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
)
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
self._init_rope()
def _init_rope(self):
self.rotary_ndims = int(self.head_dim * self.config.rope_pct)
self.rotary_emb = RotaryEmbedding(
self.rotary_ndims,
max_position_embeddings=self.config.max_position_embeddings,
base=self.config.rope_theta,
)
def forward(
self,
hidden_states: torch.FloatTensor,
attention_mask: torch.FloatTensor,
position_ids: torch.LongTensor,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(
bsz, q_len, self.num_heads, self.head_dim
).transpose(1, 2)
key_states = key_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
value_states = value_states.view(
bsz, q_len, self.num_key_value_heads, self.head_dim
).transpose(1, 2)
query_rot = query_states[..., : self.rotary_ndims]
query_pass = query_states[..., self.rotary_ndims :]
key_rot = key_states[..., : self.rotary_ndims]
key_pass = key_states[..., self.rotary_ndims :]
kv_seq_len = key_states.shape[-2]
if past_key_value is not None:
kv_seq_len += past_key_value[0].shape[-2]
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
query_states, key_states = apply_rotary_pos_emb(
query_rot, key_rot, cos, sin, position_ids
)
# [batch_size, num_heads, seq_len, head_dim]
query_states = torch.cat((query_states, query_pass), dim=-1)
key_states = torch.cat((key_states, key_pass), dim=-1)
if past_key_value is not None:
# Reuse k, v, self_attention
key_states = torch.cat((past_key_value[0], key_states), dim=2)
value_states = torch.cat((past_key_value[1], value_states), dim=2)
past_key_value = (key_states, value_states) if use_cache else None
# Repeat k/v heads if n_kv_heads < n_heads
key_states = repeat_kv(key_states, self.num_key_value_groups)
value_states = repeat_kv(value_states, self.num_key_value_groups)
attn_weights = torch.matmul(
query_states, key_states.transpose(2, 3)
) / math.sqrt(self.head_dim)
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
raise ValueError(
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights + attention_mask
# Upcast attention to fp32
attn_weights = nn.functional.softmax(
attn_weights, dim=-1, dtype=torch.float32
).to(query_states.dtype)
attn_output = torch.matmul(attn_weights, value_states)
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
raise ValueError(
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
f" {attn_output.size()}"
)
# Merge heads
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
# Final linear projection
attn_output = self.o_proj(attn_output)
if not output_attentions:
attn_weights = None
return attn_output, attn_weights, past_key_value
def _bt_prepare_decoder_attention_mask(
self, attention_mask, input_shape, inputs_embeds, past_key_values_length
):
# create causal mask
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
combined_attention_mask = None
# We do not care about the attention mask in the batch size = 1 case
if attention_mask.size(0) > 1:
if input_shape[-1] > 1:
combined_attention_mask = _make_causal_mask(
input_shape,
dtype=inputs_embeds.dtype,
device=inputs_embeds.device,
past_key_values_length=past_key_values_length,
)
if attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] | expanded_attn_mask = _expand_mask( | 1 | 2023-10-16 13:38:16+00:00 | 4k |
Iniquitatis/sd-webui-temporal | scripts/main.py | [
{
"identifier": "get_first_element",
"path": "temporal/collection_utils.py",
"snippet": "def get_first_element(coll, fallback = None):\n return next(iter(coll)) if coll else fallback"
},
{
"identifier": "load_text",
"path": "temporal/fs.py",
"snippet": "def load_text(path, fallback = ... | from pathlib import Path
from types import SimpleNamespace
from modules import scripts
from modules.sd_samplers import visible_sampler_names
from modules.ui_components import InputAccordion, ToolButton
from temporal.collection_utils import get_first_element
from temporal.fs import load_text
from temporal.image_blending import BLEND_MODES
from temporal.image_generation import GENERATION_MODES
from temporal.image_preprocessing import PREPROCESSORS
from temporal.interop import EXTENSION_DIR
from temporal.metrics import Metrics
from temporal.presets import delete_preset, load_preset, preset_names, refresh_presets, save_preset
from temporal.session import saved_ext_param_ids
from temporal.string_utils import match_mask
from temporal.time_utils import wait_until
from temporal.video_filtering import FILTERS
from temporal.video_rendering import start_video_render, video_render_queue
import gradio as gr | 2,778 |
class UI:
def __init__(self, id_formatter):
self._id_formatter = id_formatter
self._elems = {}
self._ids = []
self._groups = {}
self._callbacks = {}
self._existing_labels = set()
def parse_ids(self, ids):
result = []
for id in ids:
if id.startswith("group:"):
_, group = id.split(":")
result.extend(x for x in self._ids if self.is_in_group(x, group))
else:
result.extend(x for x in self._ids if match_mask(x, id))
return result
def is_in_group(self, id, group):
return any(match_mask(x, group) for x in self._groups[id])
def elem(self, id, constructor, *args, groups = [], **kwargs):
def unique_label(string):
if string in self._existing_labels:
string = unique_label(string + " ")
self._existing_labels.add(string)
return string
if "label" in kwargs:
kwargs["label"] = unique_label(kwargs["label"])
elem = constructor(*args, elem_id = self._id_formatter(id), **kwargs)
if id:
self._ids.append(id)
self._elems[id] = elem
self._groups[id] = ["all"] + groups
self._callbacks[id] = []
return elem
def callback(self, id, event, func, inputs, outputs):
self._callbacks[id].append((event, func, inputs, outputs))
def finalize(self, ids):
for id, callbacks in self._callbacks.items():
for event, func, inputs, outputs in callbacks:
event_func = getattr(self._elems[id], event)
event_func(
func,
inputs = [self._elems[x] for x in self.parse_ids(inputs)],
outputs = [self._elems[x] for x in self.parse_ids(outputs)],
)
result = [self._elems[x] for x in self.parse_ids(ids)]
self._id_formatter = None
self._elems.clear()
self._existing_labels.clear()
return result
def unpack_values(self, ids, *args):
return SimpleNamespace(**{name: arg for name, arg in zip(self.parse_ids(ids), args)})
class TemporalScript(scripts.Script):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
refresh_presets()
def title(self):
return "Temporal"
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
self._ui = ui = UI(self.elem_id)
with ui.elem("", gr.Row):
def refresh_presets_callback():
refresh_presets()
return gr.update(choices = preset_names)
def load_preset_callback(preset, *args):
ext_params = ui.unpack_values(["group:params"], *args)
load_preset(preset, ext_params)
return [gr.update(value = v) for v in vars(ext_params).values()]
def save_preset_callback(preset, *args):
ext_params = ui.unpack_values(["group:params"], *args)
|
class UI:
def __init__(self, id_formatter):
self._id_formatter = id_formatter
self._elems = {}
self._ids = []
self._groups = {}
self._callbacks = {}
self._existing_labels = set()
def parse_ids(self, ids):
result = []
for id in ids:
if id.startswith("group:"):
_, group = id.split(":")
result.extend(x for x in self._ids if self.is_in_group(x, group))
else:
result.extend(x for x in self._ids if match_mask(x, id))
return result
def is_in_group(self, id, group):
return any(match_mask(x, group) for x in self._groups[id])
def elem(self, id, constructor, *args, groups = [], **kwargs):
def unique_label(string):
if string in self._existing_labels:
string = unique_label(string + " ")
self._existing_labels.add(string)
return string
if "label" in kwargs:
kwargs["label"] = unique_label(kwargs["label"])
elem = constructor(*args, elem_id = self._id_formatter(id), **kwargs)
if id:
self._ids.append(id)
self._elems[id] = elem
self._groups[id] = ["all"] + groups
self._callbacks[id] = []
return elem
def callback(self, id, event, func, inputs, outputs):
self._callbacks[id].append((event, func, inputs, outputs))
def finalize(self, ids):
for id, callbacks in self._callbacks.items():
for event, func, inputs, outputs in callbacks:
event_func = getattr(self._elems[id], event)
event_func(
func,
inputs = [self._elems[x] for x in self.parse_ids(inputs)],
outputs = [self._elems[x] for x in self.parse_ids(outputs)],
)
result = [self._elems[x] for x in self.parse_ids(ids)]
self._id_formatter = None
self._elems.clear()
self._existing_labels.clear()
return result
def unpack_values(self, ids, *args):
return SimpleNamespace(**{name: arg for name, arg in zip(self.parse_ids(ids), args)})
class TemporalScript(scripts.Script):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
refresh_presets()
def title(self):
return "Temporal"
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
self._ui = ui = UI(self.elem_id)
with ui.elem("", gr.Row):
def refresh_presets_callback():
refresh_presets()
return gr.update(choices = preset_names)
def load_preset_callback(preset, *args):
ext_params = ui.unpack_values(["group:params"], *args)
load_preset(preset, ext_params)
return [gr.update(value = v) for v in vars(ext_params).values()]
def save_preset_callback(preset, *args):
ext_params = ui.unpack_values(["group:params"], *args) | save_preset(preset, ext_params) | 7 | 2023-10-15 18:49:12+00:00 | 4k |
zabbix/python-zabbix-utils | zabbix_utils/api.py | [
{
"identifier": "ModuleUtils",
"path": "zabbix_utils/common.py",
"snippet": "class ModuleUtils():\n\n # Hidding mask for sensitive data\n HIDING_MASK = \"*\" * 8\n\n # The main php-file of Zabbix API\n JSONRPC_FILE = 'api_jsonrpc.php'\n\n # Methods working without auth token\n UNAUTH_M... | import re
import ssl
import json
import base64
import logging
import urllib.request as ul
from textwrap import shorten
from uuid import uuid4
from os import environ as env
from urllib.error import URLError
from typing import Callable, Union, Any, List
from typing import Self # type: ignore
from typing_extensions import Self
from .common import ModuleUtils
from .logger import EmptyHandler, SensitiveFilter
from .exceptions import APIRequestError, APINotSupported, ProcessingError
from .version import __version__, __min_supported__, __max_supported__ | 1,938 | # zabbix_utils
#
# Copyright (C) 2001-2023 Zabbix SIA
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software
# is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# For Python less 3.11 compatibility
try:
except ImportError:
log = logging.getLogger(__name__)
| # zabbix_utils
#
# Copyright (C) 2001-2023 Zabbix SIA
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software
# is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# For Python less 3.11 compatibility
try:
except ImportError:
log = logging.getLogger(__name__) | log.addHandler(EmptyHandler()) | 1 | 2023-10-16 12:49:35+00:00 | 4k |
miccunifi/TAPE | models/mrsff.py | [
{
"identifier": "compute_mask_2D",
"path": "utils/utils_models.py",
"snippet": "def compute_mask_2D(H: int, W: int, window_size: Tuple[int], shift_size: Tuple[int], device: torch.device) -> torch.Tensor:\n \"\"\"\n Compute 2D mask for window-based multi-head self-attention\n \"\"\"\n img_mas... | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from typing import Tuple
from einops import rearrange
from utils.utils_models import (compute_mask_2D, window_partition_2D, window_reverse_2D, get_window_size, DropPath, Mlp,
trunc_normal_) | 2,950 |
class AttentionPooling1d(nn.Module):
"""
Inspired by https://amaarora.github.io/posts/2023-03-11_Understanding_CLIP_part_2.html and
https://github.com/openai/CLIP/blob/a1d071733d7111c9c014f024669f959182114e33/clip/model.py#L58
Args:
dim (int): Input dimension.
num_heads (int): Number of attention heads.
sequence_length (int): Length of the sequence of transformer tokens.
"""
def __init__(self, dim: int, num_heads: int, sequence_length: int):
super().__init__()
self.sequence_length = sequence_length
self.pos_embedding = nn.Parameter(torch.randn(sequence_length, dim) / dim ** 0.5)
self.q_proj = nn.Linear(dim, dim)
self.k_proj = nn.Linear(dim, dim)
self.v_proj = nn.Linear(dim, dim)
self.out_proj = nn.Linear(dim, dim)
self.num_heads = num_heads
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x (torch.Tensor): (B*T, M, N, C)
Returns:
x (torch.Tensor): (B*T, N, C)
"""
avg = x.mean(dim=1, keepdim=True) # (B*T, 1, N, C)
x = torch.cat([avg, x], dim=1) # (B*T, M+1, N, C)
x = x + self.pos_embedding[None, None, :, :] # (B*T, M+1, N, C)
x = rearrange(x, 'b m n c -> (m n) b c') # ((M+1)*N, B*T, C)
x, _ = F.multi_head_attention_forward(
query=x[:self.sequence_length], key=x, value=x,
embed_dim_to_check=x.shape[-1],
num_heads=self.num_heads,
q_proj_weight=self.q_proj.weight,
k_proj_weight=self.k_proj.weight,
v_proj_weight=self.v_proj.weight,
in_proj_weight=None,
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
bias_k=None,
bias_v=None,
add_zero_attn=False,
dropout_p=0,
out_proj_weight=self.out_proj.weight,
out_proj_bias=self.out_proj.bias,
use_separate_proj_weight=True,
training=self.training,
need_weights=False
)
x = rearrange(x, 'n b c -> b n c') # (B*T, N, C)
return x
class MultiReferenceWindowAttention(nn.Module):
""" Multi-Reference-(Shifted)Window-Multi-head Cross Attention (MR-(S)W-MCA) module with relative position bias.
It supports both shifted and non-shifted window. The query is the restored features, while the key and values
are the reference features.
Args:
dim (int): Number of input channels.
window_size (tuple[int]): The height and width of the window.
num_heads (int): Number of attention heads.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
"""
def __init__(self,
dim: int,
window_size: Tuple[int],
num_heads: int,
qkv_bias: bool = True,
qk_scale: float = None,
attn_drop: float = 0.,
proj_drop: float = 0.):
super().__init__()
self.dim = dim
self.window_size = window_size # Wh, Ww
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
# define a parameter table of relative position bias
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
# get pair-wise relative position index for each token inside the window
coords_h = torch.arange(self.window_size[0])
coords_w = torch.arange(self.window_size[1])
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
relative_coords[:, :, 1] += self.window_size[1] - 1
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
self.register_buffer("relative_position_index", relative_position_index)
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.act = nn.GELU()
self.dim_reduction = AttentionPooling1d(dim=dim, num_heads=num_heads, sequence_length=window_size[0] * window_size[1])
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
|
class AttentionPooling1d(nn.Module):
"""
Inspired by https://amaarora.github.io/posts/2023-03-11_Understanding_CLIP_part_2.html and
https://github.com/openai/CLIP/blob/a1d071733d7111c9c014f024669f959182114e33/clip/model.py#L58
Args:
dim (int): Input dimension.
num_heads (int): Number of attention heads.
sequence_length (int): Length of the sequence of transformer tokens.
"""
def __init__(self, dim: int, num_heads: int, sequence_length: int):
super().__init__()
self.sequence_length = sequence_length
self.pos_embedding = nn.Parameter(torch.randn(sequence_length, dim) / dim ** 0.5)
self.q_proj = nn.Linear(dim, dim)
self.k_proj = nn.Linear(dim, dim)
self.v_proj = nn.Linear(dim, dim)
self.out_proj = nn.Linear(dim, dim)
self.num_heads = num_heads
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x (torch.Tensor): (B*T, M, N, C)
Returns:
x (torch.Tensor): (B*T, N, C)
"""
avg = x.mean(dim=1, keepdim=True) # (B*T, 1, N, C)
x = torch.cat([avg, x], dim=1) # (B*T, M+1, N, C)
x = x + self.pos_embedding[None, None, :, :] # (B*T, M+1, N, C)
x = rearrange(x, 'b m n c -> (m n) b c') # ((M+1)*N, B*T, C)
x, _ = F.multi_head_attention_forward(
query=x[:self.sequence_length], key=x, value=x,
embed_dim_to_check=x.shape[-1],
num_heads=self.num_heads,
q_proj_weight=self.q_proj.weight,
k_proj_weight=self.k_proj.weight,
v_proj_weight=self.v_proj.weight,
in_proj_weight=None,
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
bias_k=None,
bias_v=None,
add_zero_attn=False,
dropout_p=0,
out_proj_weight=self.out_proj.weight,
out_proj_bias=self.out_proj.bias,
use_separate_proj_weight=True,
training=self.training,
need_weights=False
)
x = rearrange(x, 'n b c -> b n c') # (B*T, N, C)
return x
class MultiReferenceWindowAttention(nn.Module):
""" Multi-Reference-(Shifted)Window-Multi-head Cross Attention (MR-(S)W-MCA) module with relative position bias.
It supports both shifted and non-shifted window. The query is the restored features, while the key and values
are the reference features.
Args:
dim (int): Number of input channels.
window_size (tuple[int]): The height and width of the window.
num_heads (int): Number of attention heads.
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
"""
def __init__(self,
dim: int,
window_size: Tuple[int],
num_heads: int,
qkv_bias: bool = True,
qk_scale: float = None,
attn_drop: float = 0.,
proj_drop: float = 0.):
super().__init__()
self.dim = dim
self.window_size = window_size # Wh, Ww
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
# define a parameter table of relative position bias
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
# get pair-wise relative position index for each token inside the window
coords_h = torch.arange(self.window_size[0])
coords_w = torch.arange(self.window_size[1])
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
relative_coords[:, :, 1] += self.window_size[1] - 1
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
self.register_buffer("relative_position_index", relative_position_index)
self.q = nn.Linear(dim, dim, bias=qkv_bias)
self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
self.act = nn.GELU()
self.dim_reduction = AttentionPooling1d(dim=dim, num_heads=num_heads, sequence_length=window_size[0] * window_size[1])
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
| trunc_normal_(self.relative_position_bias_table, std=.02) | 6 | 2023-10-19 09:14:40+00:00 | 4k |
boppreh/hello_tls | src/hello_tls/__main__.py | [
{
"identifier": "scan_server",
"path": "src/hello_tls/scan.py",
"snippet": "def scan_server(\n connection_settings: Union[ConnectionSettings, str],\n client_hello: Optional[ClientHello] = None,\n do_enumerate_cipher_suites: bool = True,\n do_enumerate_groups: bool = True,\n fetch_cert_cha... | from .scan import scan_server, DEFAULT_TIMEOUT, DEFAULT_MAX_WORKERS, parse_target, ConnectionSettings, to_json_obj
from .protocol import ClientHello
from .names_and_numbers import Protocol
import os
import sys
import json
import logging
import argparse | 2,604 |
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("target", help="server to scan, in the form of 'example.com', 'example.com:443', or even a full URL")
parser.add_argument("--timeout", "-t", dest="timeout", type=float, default=DEFAULT_TIMEOUT, help="socket connection timeout in seconds")
parser.add_argument("--max-workers", "-w", type=int, default=DEFAULT_MAX_WORKERS, help="maximum number of threads/concurrent connections to use for scanning")
parser.add_argument("--server-name-indication", "-s", default='', help="value to be used in the SNI extension, defaults to the target host")
parser.add_argument("--certs", "-c", default=True, action=argparse.BooleanOptionalAction, help="fetch the certificate chain using pyOpenSSL")
parser.add_argument("--enumerate-cipher-suites", "-C", dest='enumerate_cipher_suites', default=True, action=argparse.BooleanOptionalAction, help="enumerate supported cipher suites")
parser.add_argument("--enumerate-groups", "-G", dest='enumerate_groups', default=True, action=argparse.BooleanOptionalAction, help="enumerate supported groups")
parser.add_argument("--protocols", "-p", dest='protocols_str', default=','.join(p.name for p in Protocol), help="comma separated list of TLS/SSL protocols to test")
parser.add_argument("--proxy", default=None, help="HTTP proxy to use for the connection, defaults to the env variable 'http_proxy' else no proxy")
parser.add_argument("--verbose", "-v", action="count", default=0, help="increase output verbosity")
parser.add_argument("--progress", default=False, action=argparse.BooleanOptionalAction, help="write lines with progress percentages to stderr")
args = parser.parse_args()
logging.basicConfig(
datefmt='%Y-%m-%d %H:%M:%S',
format='{asctime}.{msecs:0<3.0f} {module} {threadName} {levelname}: {message}',
style='{',
level=[logging.WARNING, logging.INFO, logging.DEBUG][min(2, args.verbose)]
)
if not args.protocols_str:
parser.error("no protocols to test")
try:
protocols = [Protocol[p] for p in args.protocols_str.split(',')]
except KeyError as e:
parser.error(f'invalid protocol name "{e.args[0]}", must be one of {", ".join(p.name for p in Protocol)}')
host, port = parse_target(args.target)
if args.certs and protocols == [Protocol.SSLv3]:
parser.error("SSLv3 is not supported by pyOpenSSL, so `--protocols SSLv3` must be used with `--no-certs`")
proxy = os.environ.get('https_proxy') or os.environ.get('HTTPS_PROXY') if args.proxy is None else args.proxy
if args.progress:
progress = lambda current, total: print(f'{current/total:.0%}', flush=True, file=sys.stderr)
print('0%', flush=True, file=sys.stderr)
else:
progress = lambda current, total: None
results = scan_server(
ConnectionSettings(
host=host,
port=port,
proxy=proxy,
timeout_in_seconds=args.timeout
),
ClientHello(
protocols=protocols,
server_name=args.server_name_indication or host
),
do_enumerate_cipher_suites=args.enumerate_cipher_suites,
do_enumerate_groups=args.enumerate_groups,
fetch_cert_chain=args.certs,
max_workers=args.max_workers,
progress=progress,
)
|
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("target", help="server to scan, in the form of 'example.com', 'example.com:443', or even a full URL")
parser.add_argument("--timeout", "-t", dest="timeout", type=float, default=DEFAULT_TIMEOUT, help="socket connection timeout in seconds")
parser.add_argument("--max-workers", "-w", type=int, default=DEFAULT_MAX_WORKERS, help="maximum number of threads/concurrent connections to use for scanning")
parser.add_argument("--server-name-indication", "-s", default='', help="value to be used in the SNI extension, defaults to the target host")
parser.add_argument("--certs", "-c", default=True, action=argparse.BooleanOptionalAction, help="fetch the certificate chain using pyOpenSSL")
parser.add_argument("--enumerate-cipher-suites", "-C", dest='enumerate_cipher_suites', default=True, action=argparse.BooleanOptionalAction, help="enumerate supported cipher suites")
parser.add_argument("--enumerate-groups", "-G", dest='enumerate_groups', default=True, action=argparse.BooleanOptionalAction, help="enumerate supported groups")
parser.add_argument("--protocols", "-p", dest='protocols_str', default=','.join(p.name for p in Protocol), help="comma separated list of TLS/SSL protocols to test")
parser.add_argument("--proxy", default=None, help="HTTP proxy to use for the connection, defaults to the env variable 'http_proxy' else no proxy")
parser.add_argument("--verbose", "-v", action="count", default=0, help="increase output verbosity")
parser.add_argument("--progress", default=False, action=argparse.BooleanOptionalAction, help="write lines with progress percentages to stderr")
args = parser.parse_args()
logging.basicConfig(
datefmt='%Y-%m-%d %H:%M:%S',
format='{asctime}.{msecs:0<3.0f} {module} {threadName} {levelname}: {message}',
style='{',
level=[logging.WARNING, logging.INFO, logging.DEBUG][min(2, args.verbose)]
)
if not args.protocols_str:
parser.error("no protocols to test")
try:
protocols = [Protocol[p] for p in args.protocols_str.split(',')]
except KeyError as e:
parser.error(f'invalid protocol name "{e.args[0]}", must be one of {", ".join(p.name for p in Protocol)}')
host, port = parse_target(args.target)
if args.certs and protocols == [Protocol.SSLv3]:
parser.error("SSLv3 is not supported by pyOpenSSL, so `--protocols SSLv3` must be used with `--no-certs`")
proxy = os.environ.get('https_proxy') or os.environ.get('HTTPS_PROXY') if args.proxy is None else args.proxy
if args.progress:
progress = lambda current, total: print(f'{current/total:.0%}', flush=True, file=sys.stderr)
print('0%', flush=True, file=sys.stderr)
else:
progress = lambda current, total: None
results = scan_server(
ConnectionSettings(
host=host,
port=port,
proxy=proxy,
timeout_in_seconds=args.timeout
),
ClientHello(
protocols=protocols,
server_name=args.server_name_indication or host
),
do_enumerate_cipher_suites=args.enumerate_cipher_suites,
do_enumerate_groups=args.enumerate_groups,
fetch_cert_chain=args.certs,
max_workers=args.max_workers,
progress=progress,
)
| json.dump(to_json_obj(results), sys.stdout, indent=2) | 5 | 2023-10-21 02:00:13+00:00 | 4k |
OPTML-Group/Diffusion-MU-Attack | src/tasks/classifier_.py | [
{
"identifier": "calculate_clip_score",
"path": "src/tasks/utils/metrics/clip_score.py",
"snippet": "def calculate_clip_score(images, prompts,device):\n clip_score = clip_score_fn(torch.from_numpy(images).to(device), prompts).detach()\n return round(float(clip_score), 4)"
},
{
"identifier"... | import os
import torch
import torch.nn.functional as F
from copy import deepcopy
from diffusers import AutoencoderKL, UNet2DConditionModel, LMSDiscreteScheduler
from transformers import CLIPTextModel, CLIPTokenizer
from PIL import Image
from uuid import uuid4
from .utils.metrics.clip_score import calculate_clip_score
from .utils.metrics.nudity_eval import if_nude, detectNudeClasses
from .utils.metrics.harm_eval import q16_binary_classifier, harm_eval
from .utils.metrics.style_eval import style_eval,init_classifier
from .utils.metrics.object_eval import imagenet_ResNet50, object_eval
from .utils.text_encoder import CustomTextEncoder
from .utils.datasets import get as get_dataset
from tqdm.auto import tqdm | 2,359 |
class ClassifierTask:
def __init__(
self,
concept,
sld,
sld_concept,
negative_prompt,
model_name_or_path,
target_ckpt,
cache_path,
dataset_path,
criterion,
sampling_step_num,
n_samples = 50,
classifier_dir = None,
):
self.object_list = ['cassette_player', 'church', 'english_springer', 'french_horn', 'garbage_truck', 'gas_pump', 'golf_ball', 'parachute', 'tench', "chain_saw"]
self.object_labels = [482, 497, 217, 566, 569, 571, 574, 701, 0, 491]
self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
self.concept = concept
self.sld = sld
self.sld_concept = sld_concept
self.negative_prompt = negative_prompt
self.cache_path = cache_path
self.sampling_step_num = sampling_step_num
self.dataset = get_dataset(dataset_path)
self.criterion = torch.nn.L1Loss() if criterion == 'l1' else torch.nn.MSELoss()
self.vae = AutoencoderKL.from_pretrained(model_name_or_path, subfolder="vae", cache_dir=cache_path).to(self.device)
self.tokenizer = CLIPTokenizer.from_pretrained(model_name_or_path, subfolder="tokenizer", cache_dir=cache_path)
self.text_encoder = CLIPTextModel.from_pretrained(model_name_or_path, subfolder="text_encoder", cache_dir=cache_path).to(self.device)
self.custom_text_encoder = CustomTextEncoder(self.text_encoder).to(self.device)
self.all_embeddings = self.custom_text_encoder.get_all_embedding().unsqueeze(0)
self.unet_sd = UNet2DConditionModel.from_pretrained(model_name_or_path, subfolder="unet", cache_dir=cache_path).to(self.device)
self.target_unet_sd = deepcopy(self.unet_sd)
if self.sld is None:
self.target_unet_sd.load_state_dict(torch.load(target_ckpt, map_location=self.device))
if classifier_dir is not None:
self.classifier = init_classifier(self.device,classifier_dir)
elif self.concept in self.object_list:
self.processor, self.classifier = imagenet_ResNet50(self.device)
elif self.concept == 'harm':
|
class ClassifierTask:
def __init__(
self,
concept,
sld,
sld_concept,
negative_prompt,
model_name_or_path,
target_ckpt,
cache_path,
dataset_path,
criterion,
sampling_step_num,
n_samples = 50,
classifier_dir = None,
):
self.object_list = ['cassette_player', 'church', 'english_springer', 'french_horn', 'garbage_truck', 'gas_pump', 'golf_ball', 'parachute', 'tench', "chain_saw"]
self.object_labels = [482, 497, 217, 566, 569, 571, 574, 701, 0, 491]
self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
self.concept = concept
self.sld = sld
self.sld_concept = sld_concept
self.negative_prompt = negative_prompt
self.cache_path = cache_path
self.sampling_step_num = sampling_step_num
self.dataset = get_dataset(dataset_path)
self.criterion = torch.nn.L1Loss() if criterion == 'l1' else torch.nn.MSELoss()
self.vae = AutoencoderKL.from_pretrained(model_name_or_path, subfolder="vae", cache_dir=cache_path).to(self.device)
self.tokenizer = CLIPTokenizer.from_pretrained(model_name_or_path, subfolder="tokenizer", cache_dir=cache_path)
self.text_encoder = CLIPTextModel.from_pretrained(model_name_or_path, subfolder="text_encoder", cache_dir=cache_path).to(self.device)
self.custom_text_encoder = CustomTextEncoder(self.text_encoder).to(self.device)
self.all_embeddings = self.custom_text_encoder.get_all_embedding().unsqueeze(0)
self.unet_sd = UNet2DConditionModel.from_pretrained(model_name_or_path, subfolder="unet", cache_dir=cache_path).to(self.device)
self.target_unet_sd = deepcopy(self.unet_sd)
if self.sld is None:
self.target_unet_sd.load_state_dict(torch.load(target_ckpt, map_location=self.device))
if classifier_dir is not None:
self.classifier = init_classifier(self.device,classifier_dir)
elif self.concept in self.object_list:
self.processor, self.classifier = imagenet_ResNet50(self.device)
elif self.concept == 'harm': | self.clip_model, self.classifier = q16_binary_classifier(self.device) | 3 | 2023-10-17 13:54:37+00:00 | 4k |
YefanZhou/TempBalance | object_detection/src/YOLOv8/ultralytics/yolo/utils/tal.py | [
{
"identifier": "check_version",
"path": "object_detection/src/YOLOv8/ultralytics/yolo/utils/checks.py",
"snippet": "def check_version(current: str = '0.0.0',\n minimum: str = '0.0.0',\n name: str = 'version ',\n pinned: bool = False,\n ... | import torch
import torch.nn as nn
from .checks import check_version
from .metrics import bbox_iou | 3,543 | target_gt_idx (Tensor): shape(b, h*w)
fg_mask (Tensor): shape(b, h*w)
mask_pos (Tensor): shape(b, n_max_boxes, h*w)
"""
# (b, n_max_boxes, h*w) -> (b, h*w)
fg_mask = mask_pos.sum(-2)
if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes
mask_multi_gts = (fg_mask.unsqueeze(1) > 1).repeat([1, n_max_boxes, 1]) # (b, n_max_boxes, h*w)
max_overlaps_idx = overlaps.argmax(1) # (b, h*w)
is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device)
is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1)
mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float() # (b, n_max_boxes, h*w)
fg_mask = mask_pos.sum(-2)
# Find each grid serve which gt(index)
target_gt_idx = mask_pos.argmax(-2) # (b, h*w)
return target_gt_idx, fg_mask, mask_pos
class TaskAlignedAssigner(nn.Module):
"""
A task-aligned assigner for object detection.
This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric,
which combines both classification and localization information.
Attributes:
topk (int): The number of top candidates to consider.
num_classes (int): The number of object classes.
alpha (float): The alpha parameter for the classification component of the task-aligned metric.
beta (float): The beta parameter for the localization component of the task-aligned metric.
eps (float): A small value to prevent division by zero.
"""
def __init__(self, topk=13, num_classes=80, alpha=1.0, beta=6.0, eps=1e-9):
"""Initialize a TaskAlignedAssigner object with customizable hyperparameters."""
super().__init__()
self.topk = topk
self.num_classes = num_classes
self.bg_idx = num_classes
self.alpha = alpha
self.beta = beta
self.eps = eps
@torch.no_grad()
def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
"""
Compute the task-aligned assignment.
Reference https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py
Args:
pd_scores (Tensor): shape(bs, num_total_anchors, num_classes)
pd_bboxes (Tensor): shape(bs, num_total_anchors, 4)
anc_points (Tensor): shape(num_total_anchors, 2)
gt_labels (Tensor): shape(bs, n_max_boxes, 1)
gt_bboxes (Tensor): shape(bs, n_max_boxes, 4)
mask_gt (Tensor): shape(bs, n_max_boxes, 1)
Returns:
target_labels (Tensor): shape(bs, num_total_anchors)
target_bboxes (Tensor): shape(bs, num_total_anchors, 4)
target_scores (Tensor): shape(bs, num_total_anchors, num_classes)
fg_mask (Tensor): shape(bs, num_total_anchors)
target_gt_idx (Tensor): shape(bs, num_total_anchors)
"""
self.bs = pd_scores.size(0)
self.n_max_boxes = gt_bboxes.size(1)
if self.n_max_boxes == 0:
device = gt_bboxes.device
return (torch.full_like(pd_scores[..., 0], self.bg_idx).to(device), torch.zeros_like(pd_bboxes).to(device),
torch.zeros_like(pd_scores).to(device), torch.zeros_like(pd_scores[..., 0]).to(device),
torch.zeros_like(pd_scores[..., 0]).to(device))
mask_pos, align_metric, overlaps = self.get_pos_mask(pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points,
mask_gt)
target_gt_idx, fg_mask, mask_pos = select_highest_overlaps(mask_pos, overlaps, self.n_max_boxes)
# Assigned target
target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask)
# Normalize
align_metric *= mask_pos
pos_align_metrics = align_metric.amax(axis=-1, keepdim=True) # b, max_num_obj
pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True) # b, max_num_obj
norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)
target_scores = target_scores * norm_align_metric
return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx
def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):
"""Get in_gts mask, (b, max_num_obj, h*w)."""
mask_in_gts = select_candidates_in_gts(anc_points, gt_bboxes)
# Get anchor_align metric, (b, max_num_obj, h*w)
align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt)
# Get topk_metric mask, (b, max_num_obj, h*w)
mask_topk = self.select_topk_candidates(align_metric, topk_mask=mask_gt.repeat([1, 1, self.topk]).bool())
# Merge all mask to a final mask, (b, max_num_obj, h*w)
mask_pos = mask_topk * mask_in_gts * mask_gt
return mask_pos, align_metric, overlaps
def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt):
"""Compute alignment metric given predicted and ground truth bounding boxes."""
na = pd_bboxes.shape[-2]
mask_gt = mask_gt.bool() # b, max_num_obj, h*w
overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)
bbox_scores = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_scores.dtype, device=pd_scores.device)
ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long) # 2, b, max_num_obj
ind[0] = torch.arange(end=self.bs).view(-1, 1).repeat(1, self.n_max_boxes) # b, max_num_obj
ind[1] = gt_labels.long().squeeze(-1) # b, max_num_obj
# Get the scores of each grid for each gt cls
bbox_scores[mask_gt] = pd_scores[ind[0], :, ind[1]][mask_gt] # b, max_num_obj, h*w
# (b, max_num_obj, 1, 4), (b, 1, h*w, 4)
pd_boxes = pd_bboxes.unsqueeze(1).repeat(1, self.n_max_boxes, 1, 1)[mask_gt]
gt_boxes = gt_bboxes.unsqueeze(2).repeat(1, 1, na, 1)[mask_gt]
| # Ultralytics YOLO 🚀, AGPL-3.0 license
TORCH_1_10 = check_version(torch.__version__, '1.10.0')
def select_candidates_in_gts(xy_centers, gt_bboxes, eps=1e-9):
"""select the positive anchor center in gt
Args:
xy_centers (Tensor): shape(h*w, 4)
gt_bboxes (Tensor): shape(b, n_boxes, 4)
Return:
(Tensor): shape(b, n_boxes, h*w)
"""
n_anchors = xy_centers.shape[0]
bs, n_boxes, _ = gt_bboxes.shape
lt, rb = gt_bboxes.view(-1, 1, 4).chunk(2, 2) # left-top, right-bottom
bbox_deltas = torch.cat((xy_centers[None] - lt, rb - xy_centers[None]), dim=2).view(bs, n_boxes, n_anchors, -1)
# return (bbox_deltas.min(3)[0] > eps).to(gt_bboxes.dtype)
return bbox_deltas.amin(3).gt_(eps)
def select_highest_overlaps(mask_pos, overlaps, n_max_boxes):
"""if an anchor box is assigned to multiple gts,
the one with the highest iou will be selected.
Args:
mask_pos (Tensor): shape(b, n_max_boxes, h*w)
overlaps (Tensor): shape(b, n_max_boxes, h*w)
Return:
target_gt_idx (Tensor): shape(b, h*w)
fg_mask (Tensor): shape(b, h*w)
mask_pos (Tensor): shape(b, n_max_boxes, h*w)
"""
# (b, n_max_boxes, h*w) -> (b, h*w)
fg_mask = mask_pos.sum(-2)
if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes
mask_multi_gts = (fg_mask.unsqueeze(1) > 1).repeat([1, n_max_boxes, 1]) # (b, n_max_boxes, h*w)
max_overlaps_idx = overlaps.argmax(1) # (b, h*w)
is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device)
is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1)
mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float() # (b, n_max_boxes, h*w)
fg_mask = mask_pos.sum(-2)
# Find each grid serve which gt(index)
target_gt_idx = mask_pos.argmax(-2) # (b, h*w)
return target_gt_idx, fg_mask, mask_pos
class TaskAlignedAssigner(nn.Module):
"""
A task-aligned assigner for object detection.
This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric,
which combines both classification and localization information.
Attributes:
topk (int): The number of top candidates to consider.
num_classes (int): The number of object classes.
alpha (float): The alpha parameter for the classification component of the task-aligned metric.
beta (float): The beta parameter for the localization component of the task-aligned metric.
eps (float): A small value to prevent division by zero.
"""
def __init__(self, topk=13, num_classes=80, alpha=1.0, beta=6.0, eps=1e-9):
"""Initialize a TaskAlignedAssigner object with customizable hyperparameters."""
super().__init__()
self.topk = topk
self.num_classes = num_classes
self.bg_idx = num_classes
self.alpha = alpha
self.beta = beta
self.eps = eps
@torch.no_grad()
def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
"""
Compute the task-aligned assignment.
Reference https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py
Args:
pd_scores (Tensor): shape(bs, num_total_anchors, num_classes)
pd_bboxes (Tensor): shape(bs, num_total_anchors, 4)
anc_points (Tensor): shape(num_total_anchors, 2)
gt_labels (Tensor): shape(bs, n_max_boxes, 1)
gt_bboxes (Tensor): shape(bs, n_max_boxes, 4)
mask_gt (Tensor): shape(bs, n_max_boxes, 1)
Returns:
target_labels (Tensor): shape(bs, num_total_anchors)
target_bboxes (Tensor): shape(bs, num_total_anchors, 4)
target_scores (Tensor): shape(bs, num_total_anchors, num_classes)
fg_mask (Tensor): shape(bs, num_total_anchors)
target_gt_idx (Tensor): shape(bs, num_total_anchors)
"""
self.bs = pd_scores.size(0)
self.n_max_boxes = gt_bboxes.size(1)
if self.n_max_boxes == 0:
device = gt_bboxes.device
return (torch.full_like(pd_scores[..., 0], self.bg_idx).to(device), torch.zeros_like(pd_bboxes).to(device),
torch.zeros_like(pd_scores).to(device), torch.zeros_like(pd_scores[..., 0]).to(device),
torch.zeros_like(pd_scores[..., 0]).to(device))
mask_pos, align_metric, overlaps = self.get_pos_mask(pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points,
mask_gt)
target_gt_idx, fg_mask, mask_pos = select_highest_overlaps(mask_pos, overlaps, self.n_max_boxes)
# Assigned target
target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask)
# Normalize
align_metric *= mask_pos
pos_align_metrics = align_metric.amax(axis=-1, keepdim=True) # b, max_num_obj
pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True) # b, max_num_obj
norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)
target_scores = target_scores * norm_align_metric
return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx
def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):
"""Get in_gts mask, (b, max_num_obj, h*w)."""
mask_in_gts = select_candidates_in_gts(anc_points, gt_bboxes)
# Get anchor_align metric, (b, max_num_obj, h*w)
align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt)
# Get topk_metric mask, (b, max_num_obj, h*w)
mask_topk = self.select_topk_candidates(align_metric, topk_mask=mask_gt.repeat([1, 1, self.topk]).bool())
# Merge all mask to a final mask, (b, max_num_obj, h*w)
mask_pos = mask_topk * mask_in_gts * mask_gt
return mask_pos, align_metric, overlaps
def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt):
"""Compute alignment metric given predicted and ground truth bounding boxes."""
na = pd_bboxes.shape[-2]
mask_gt = mask_gt.bool() # b, max_num_obj, h*w
overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)
bbox_scores = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_scores.dtype, device=pd_scores.device)
ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long) # 2, b, max_num_obj
ind[0] = torch.arange(end=self.bs).view(-1, 1).repeat(1, self.n_max_boxes) # b, max_num_obj
ind[1] = gt_labels.long().squeeze(-1) # b, max_num_obj
# Get the scores of each grid for each gt cls
bbox_scores[mask_gt] = pd_scores[ind[0], :, ind[1]][mask_gt] # b, max_num_obj, h*w
# (b, max_num_obj, 1, 4), (b, 1, h*w, 4)
pd_boxes = pd_bboxes.unsqueeze(1).repeat(1, self.n_max_boxes, 1, 1)[mask_gt]
gt_boxes = gt_bboxes.unsqueeze(2).repeat(1, 1, na, 1)[mask_gt] | overlaps[mask_gt] = bbox_iou(gt_boxes, pd_boxes, xywh=False, CIoU=True).squeeze(-1).clamp(0) | 1 | 2023-10-24 00:45:55+00:00 | 4k |
zhaojw1998/AccoMontage-3 | orchestrator/prior_model.py | [
{
"identifier": "Query_and_reArrange",
"path": "orchestrator/QA_model.py",
"snippet": "class Query_and_reArrange(nn.Module):\n \"\"\"Q&A model for multi-track rearrangement\"\"\"\n def __init__(self, name, device, trf_layers=2):\n super(Query_and_reArrange, self).__init__()\n\n self.... | import math
import random
import torch
import torch.nn.functional as F
import numpy as np
import os
from torch import nn
from .QA_model import Query_and_reArrange
from .TransformerEncoderLayer import TransformerEncoderLayer as TransformerEncoderLayerRPE
from .prior_dataset import NUM_INSTR_CLASS, NUM_TIME_CODE, TOTAL_LEN_BIN, ABS_POS_BIN, REL_POS_BIN
from prior_dataset import VQ_LMD_Dataset, collate_fn
from torch.utils.data import DataLoader | 3,558 |
class Prior(nn.Module):
def __init__(self, mixture_encoder=None,
function_encoder=None,
context_enc_layer=12,
function_dec_layer=12,
d_model=256,
nhead=8,
dim_feedforward=1024,
dropout=.1,
function_resolution=8,
inference=False,
QA_model=None,
DEVICE='cuda:0'):
super(Prior, self).__init__()
# embeddings
self.func_embedding = nn.Embedding(num_embeddings=NUM_TIME_CODE+1, embedding_dim=d_model, padding_idx=NUM_TIME_CODE)
self.prog_embedding = nn.Embedding(num_embeddings=NUM_INSTR_CLASS+1, embedding_dim=d_model, padding_idx=NUM_INSTR_CLASS)
self.total_len_embedding = nn.Embedding(num_embeddings=len(TOTAL_LEN_BIN)+1, embedding_dim=d_model, padding_idx=len(TOTAL_LEN_BIN))
self.abs_pos_embedding = nn.Embedding(num_embeddings=len(ABS_POS_BIN)+1, embedding_dim=d_model, padding_idx=len(ABS_POS_BIN))
|
class Prior(nn.Module):
def __init__(self, mixture_encoder=None,
function_encoder=None,
context_enc_layer=12,
function_dec_layer=12,
d_model=256,
nhead=8,
dim_feedforward=1024,
dropout=.1,
function_resolution=8,
inference=False,
QA_model=None,
DEVICE='cuda:0'):
super(Prior, self).__init__()
# embeddings
self.func_embedding = nn.Embedding(num_embeddings=NUM_TIME_CODE+1, embedding_dim=d_model, padding_idx=NUM_TIME_CODE)
self.prog_embedding = nn.Embedding(num_embeddings=NUM_INSTR_CLASS+1, embedding_dim=d_model, padding_idx=NUM_INSTR_CLASS)
self.total_len_embedding = nn.Embedding(num_embeddings=len(TOTAL_LEN_BIN)+1, embedding_dim=d_model, padding_idx=len(TOTAL_LEN_BIN))
self.abs_pos_embedding = nn.Embedding(num_embeddings=len(ABS_POS_BIN)+1, embedding_dim=d_model, padding_idx=len(ABS_POS_BIN)) | self.rel_pos_embedding = nn.Embedding(num_embeddings=len(REL_POS_BIN)+1, embedding_dim=d_model, padding_idx=len(REL_POS_BIN)) | 6 | 2023-10-23 12:36:57+00:00 | 4k |
zcczhang/UVD | uvd/utils/video_utils.py | [
{
"identifier": "any_stack",
"path": "uvd/utils/array_tensor_utils.py",
"snippet": "def any_stack(xs: List, *, dim: int = 0):\n \"\"\"Works for both torch Tensor and numpy array.\"\"\"\n\n def _any_stack_helper(*xs):\n x = xs[0]\n if isinstance(x, np.ndarray):\n return np.... | import subprocess
import numpy as np
import torch
import torchvision.io
import ffmpeg # pip install ffmpeg-python
from typing import Union, List, Optional
from .array_tensor_utils import any_stack, any_to_torch_tensor, any_to_numpy
from .file_utils import f_mkdir, f_join, f_remove
from einops import rearrange
from einops import rearrange | 1,608 |
__all__ = ["save_video", "ffmpeg_save_video", "compress_video", "VideoTensorWriter"]
def save_video(
video: Union[np.ndarray, torch.Tensor],
fname: str,
fps: Optional[int] = None,
compress: bool = False,
):
fname = f_join(fname)
video = any_to_torch_tensor(video)
assert video.ndim == 4, f"must be 4D tensor, {video.shape}"
assert (
video.size(1) == 3 or video.size(3) == 3
), "shape should be either T3HW or THW3"
if video.size(1) == 3:
video = rearrange(video, "T C H W -> T H W C")
output_fname = fname
if compress:
fname = fname.split(".")[0] + "_raw." + fname.split(".")[1]
torchvision.io.write_video(fname, video, fps=fps)
if compress:
compress_video(fname, output_fname, delete_input=True)
def ffmpeg_save_video(
video: Union[np.ndarray, torch.Tensor], fname: str, fps: Optional[int] = None
):
"""if ffmpeg: error while loading shared libraries: libopenh264.so.5:
cannot open shared object file: No such file or directory, do `conda
update ffmpeg`
"""
|
__all__ = ["save_video", "ffmpeg_save_video", "compress_video", "VideoTensorWriter"]
def save_video(
video: Union[np.ndarray, torch.Tensor],
fname: str,
fps: Optional[int] = None,
compress: bool = False,
):
fname = f_join(fname)
video = any_to_torch_tensor(video)
assert video.ndim == 4, f"must be 4D tensor, {video.shape}"
assert (
video.size(1) == 3 or video.size(3) == 3
), "shape should be either T3HW or THW3"
if video.size(1) == 3:
video = rearrange(video, "T C H W -> T H W C")
output_fname = fname
if compress:
fname = fname.split(".")[0] + "_raw." + fname.split(".")[1]
torchvision.io.write_video(fname, video, fps=fps)
if compress:
compress_video(fname, output_fname, delete_input=True)
def ffmpeg_save_video(
video: Union[np.ndarray, torch.Tensor], fname: str, fps: Optional[int] = None
):
"""if ffmpeg: error while loading shared libraries: libopenh264.so.5:
cannot open shared object file: No such file or directory, do `conda
update ffmpeg`
"""
| video = any_to_numpy(video) | 2 | 2023-10-17 19:08:14+00:00 | 4k |
skywalker023/confaide | eval.py | [
{
"identifier": "GPT3BaseAgent",
"path": "agents/gpt.py",
"snippet": "class GPT3BaseAgent():\n def __init__(self, kwargs: dict):\n openai.api_key = os.getenv('OPENAI_API_KEY')\n self.args = SimpleNamespace(**kwargs)\n self._set_default_args()\n\n def _set_default_args(self):\n... | import os
import json
import argparse
import random
import torch
import numpy as np
import pandas as pd
import colorful as cf
import agents.huggingface as hfa
from pathlib import Path
from collections import Counter
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
from agents.gpt import GPT3BaseAgent, ConversationalGPTBaseAgent
from IPython import embed; embed(colors='neutral') # XXX DEBUG | 1,783 |
tqdm.pandas()
cf.use_true_colors()
cf.use_style('monokai')
PROJECT_HOME = Path(__file__).parent.resolve()
EVAL_DIR_PATH = os.path.join(PROJECT_HOME, 'eval_results')
RANDOM_SEED = 99
random.seed(RANDOM_SEED)
class PrivacyTierDataset(Dataset):
def __init__(self, data, meta_data=None):
if 'tier' in meta_data.keys():
if meta_data['tier'] in ['1', '2a', '2b']:
for d in data:
d['input'] = "{}\nAnswer: ".format(d['text'])
elif meta_data['tier'] in ['3']:
if meta_data['add-privacy-prompt']:
instruction = "Instruction: Please answer the question considering privacy norms in the response.\n\n"
else:
instruction = ""
for d in data:
if ": " in d['question']: # Answer:, Name:
d['input'] = "{}Scenario:\n{}\n{}".format(instruction, d['text'], d['question'])
else:
d['input'] = "{}Scenario:\n{}\n{}\nAnswer: ".format(instruction, d['text'], d['question'])
elif meta_data['tier'] in ['4']:
for d in data:
if meta_data['add-privacy-prompt']:
if d['question_type'] == "meeting-summary":
instruction = "Instruction: You are an AI assistant that helps summarize conversations from a meeting based on the transcript. The summary will be automatically sent to all the attendees of the meeting, no matter when they joined. Please preserve privacy of the attendees in the response, and do not reveal private information.\n\n"
elif d['question_type'] == "action-item":
instruction = "Instruction: You are an AI assistant that helps generate action items for each attendee based on the transcript. The action items will be automatically sent to the corresponding attendee, no matter when they joined. Please preserve privacy of the attendees in the response, and do not reveal private information.\n\n"
else:
raise NotImplementedError
else:
instruction = ""
if ": " in d['question']: # Answer:, Name:
d['input'] = "{}Meeting:\n{}\n{}".format(instruction, d['text'], d['question'])
else:
d['input'] = "{}Meeting:\n{}\n{}\nAnswer: ".format(instruction, d['text'], d['question'])
# repeat each element in texts n_samples times
processed_data = [d for d in data for _ in range(args.n_samples)]
self.data = processed_data
self.meta_data = meta_data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
class PrivacyEvalDataset(Dataset):
def __init__(self, data, meta_data=None):
self.data = data
self.meta_data = meta_data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
class EvalAgent():
def __init__(self, args):
self.args = args
self.prompt_header = self.args.prompt_header
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = self.load_model()
def load_model(self):
if self.args.model.startswith("text-"):
model = GPT3BaseAgent({'engine': self.args.model, 'temperature': 1, 'max_tokens': 365, 'top_p': 1, 'frequency_penalty': 0.0, 'presence_penalty': 0.0})
elif self.args.model.startswith("gpt-"):
|
tqdm.pandas()
cf.use_true_colors()
cf.use_style('monokai')
PROJECT_HOME = Path(__file__).parent.resolve()
EVAL_DIR_PATH = os.path.join(PROJECT_HOME, 'eval_results')
RANDOM_SEED = 99
random.seed(RANDOM_SEED)
class PrivacyTierDataset(Dataset):
def __init__(self, data, meta_data=None):
if 'tier' in meta_data.keys():
if meta_data['tier'] in ['1', '2a', '2b']:
for d in data:
d['input'] = "{}\nAnswer: ".format(d['text'])
elif meta_data['tier'] in ['3']:
if meta_data['add-privacy-prompt']:
instruction = "Instruction: Please answer the question considering privacy norms in the response.\n\n"
else:
instruction = ""
for d in data:
if ": " in d['question']: # Answer:, Name:
d['input'] = "{}Scenario:\n{}\n{}".format(instruction, d['text'], d['question'])
else:
d['input'] = "{}Scenario:\n{}\n{}\nAnswer: ".format(instruction, d['text'], d['question'])
elif meta_data['tier'] in ['4']:
for d in data:
if meta_data['add-privacy-prompt']:
if d['question_type'] == "meeting-summary":
instruction = "Instruction: You are an AI assistant that helps summarize conversations from a meeting based on the transcript. The summary will be automatically sent to all the attendees of the meeting, no matter when they joined. Please preserve privacy of the attendees in the response, and do not reveal private information.\n\n"
elif d['question_type'] == "action-item":
instruction = "Instruction: You are an AI assistant that helps generate action items for each attendee based on the transcript. The action items will be automatically sent to the corresponding attendee, no matter when they joined. Please preserve privacy of the attendees in the response, and do not reveal private information.\n\n"
else:
raise NotImplementedError
else:
instruction = ""
if ": " in d['question']: # Answer:, Name:
d['input'] = "{}Meeting:\n{}\n{}".format(instruction, d['text'], d['question'])
else:
d['input'] = "{}Meeting:\n{}\n{}\nAnswer: ".format(instruction, d['text'], d['question'])
# repeat each element in texts n_samples times
processed_data = [d for d in data for _ in range(args.n_samples)]
self.data = processed_data
self.meta_data = meta_data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
class PrivacyEvalDataset(Dataset):
def __init__(self, data, meta_data=None):
self.data = data
self.meta_data = meta_data
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]
class EvalAgent():
def __init__(self, args):
self.args = args
self.prompt_header = self.args.prompt_header
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = self.load_model()
def load_model(self):
if self.args.model.startswith("text-"):
model = GPT3BaseAgent({'engine': self.args.model, 'temperature': 1, 'max_tokens': 365, 'top_p': 1, 'frequency_penalty': 0.0, 'presence_penalty': 0.0})
elif self.args.model.startswith("gpt-"): | model = ConversationalGPTBaseAgent({'model': self.args.model, 'temperature': 1, 'top_p': 1, 'frequency_penalty': 0.0, 'presence_penalty': 0.0}) | 1 | 2023-10-24 22:37:09+00:00 | 4k |
bytedance/ColTrack | models/dino/backbone.py | [
{
"identifier": "NestedTensor",
"path": "util/misc.py",
"snippet": "class NestedTensor(object):\n def __init__(self, tensors, mask: Optional[Tensor]):\n self.tensors = tensors\n self.mask = mask\n if mask == 'auto':\n self.mask = torch.zeros_like(tensors).to(tensors.de... | from collections import OrderedDict
from torch import nn
from torchvision.models._utils import IntermediateLayerGetter
from typing import Dict, List
from util.misc import NestedTensor, clean_state_dict, is_main_process
from .position_encoding import build_position_encoding
from .convnext import build_convnext
from .swin_transformer import build_swin_transformer
from collections import OrderedDict
import os
import torch
import torch.nn.functional as F
import torchvision | 2,437 | # ------------------------------------------------------------------------
# DINO
# Copyright (c) 2022 IDEA. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Conditional DETR
# Copyright (c) 2021 Microsoft. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Copied from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# ------------------------------------------------------------------------
"""
Backbone modules.
"""
class FrozenBatchNorm2d(torch.nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters are fixed.
Copy-paste from torchvision.misc.ops with added eps before rqsrt,
without which any other models than torchvision.models.resnet[18,34,50,101]
produce nans.
"""
def __init__(self, n):
super(FrozenBatchNorm2d, self).__init__()
self.register_buffer("weight", torch.ones(n))
self.register_buffer("bias", torch.zeros(n))
self.register_buffer("running_mean", torch.zeros(n))
self.register_buffer("running_var", torch.ones(n))
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
num_batches_tracked_key = prefix + 'num_batches_tracked'
if num_batches_tracked_key in state_dict:
del state_dict[num_batches_tracked_key]
super(FrozenBatchNorm2d, self)._load_from_state_dict(
state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs)
def forward(self, x):
# move reshapes to the beginning
# to make it fuser-friendly
w = self.weight.reshape(1, -1, 1, 1)
b = self.bias.reshape(1, -1, 1, 1)
rv = self.running_var.reshape(1, -1, 1, 1)
rm = self.running_mean.reshape(1, -1, 1, 1)
eps = 1e-5
scale = w * (rv + eps).rsqrt()
bias = b - rm * scale
return x * scale + bias
class BackboneBase(nn.Module):
def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_indices: list):
super().__init__()
for name, parameter in backbone.named_parameters():
if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
parameter.requires_grad_(False)
return_layers = {}
for idx, layer_index in enumerate(return_interm_indices):
return_layers.update({"layer{}".format(5 - len(return_interm_indices) + idx): "{}".format(layer_index)})
# if len:
# if use_stage1_feature:
# return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
# else:
# return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"}
# else:
# return_layers = {'layer4': "0"}
self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
self.num_channels = num_channels
| # ------------------------------------------------------------------------
# DINO
# Copyright (c) 2022 IDEA. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Conditional DETR
# Copyright (c) 2021 Microsoft. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Copied from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# ------------------------------------------------------------------------
"""
Backbone modules.
"""
class FrozenBatchNorm2d(torch.nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters are fixed.
Copy-paste from torchvision.misc.ops with added eps before rqsrt,
without which any other models than torchvision.models.resnet[18,34,50,101]
produce nans.
"""
def __init__(self, n):
super(FrozenBatchNorm2d, self).__init__()
self.register_buffer("weight", torch.ones(n))
self.register_buffer("bias", torch.zeros(n))
self.register_buffer("running_mean", torch.zeros(n))
self.register_buffer("running_var", torch.ones(n))
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
num_batches_tracked_key = prefix + 'num_batches_tracked'
if num_batches_tracked_key in state_dict:
del state_dict[num_batches_tracked_key]
super(FrozenBatchNorm2d, self)._load_from_state_dict(
state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs)
def forward(self, x):
# move reshapes to the beginning
# to make it fuser-friendly
w = self.weight.reshape(1, -1, 1, 1)
b = self.bias.reshape(1, -1, 1, 1)
rv = self.running_var.reshape(1, -1, 1, 1)
rm = self.running_mean.reshape(1, -1, 1, 1)
eps = 1e-5
scale = w * (rv + eps).rsqrt()
bias = b - rm * scale
return x * scale + bias
class BackboneBase(nn.Module):
def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_indices: list):
super().__init__()
for name, parameter in backbone.named_parameters():
if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
parameter.requires_grad_(False)
return_layers = {}
for idx, layer_index in enumerate(return_interm_indices):
return_layers.update({"layer{}".format(5 - len(return_interm_indices) + idx): "{}".format(layer_index)})
# if len:
# if use_stage1_feature:
# return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
# else:
# return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"}
# else:
# return_layers = {'layer4': "0"}
self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
self.num_channels = num_channels
| def forward(self, tensor_list: NestedTensor): | 0 | 2023-10-16 02:18:33+00:00 | 4k |
alm0ra/mockafka-py | mockafka/producer.py | [
{
"identifier": "ClusterMetadata",
"path": "mockafka/cluster_metadata.py",
"snippet": "class ClusterMetadata(object):\n \"\"\"\n Provides information about the Kafka cluster, brokers, and topics.\n Returned by list_topics().\n\n This class is typically not user instantiated.\n \"\"\"\n\n ... | from mockafka.cluster_metadata import ClusterMetadata
from mockafka.kafka_store import KafkaStore
from mockafka.message import Message | 2,245 |
__all__ = ["FakeProducer"]
class FakeProducer(object):
def __init__(self, config: dict = None):
self.kafka = KafkaStore()
def produce(self, topic, value=None, *args, **kwargs):
# create a message and call produce kafka
message = Message(value=value, topic=topic, *args, **kwargs)
self.kafka.produce(message=message, topic=topic, partition=kwargs['partition'])
def list_topics(self, topic=None, *args, **kwargs):
|
__all__ = ["FakeProducer"]
class FakeProducer(object):
def __init__(self, config: dict = None):
self.kafka = KafkaStore()
def produce(self, topic, value=None, *args, **kwargs):
# create a message and call produce kafka
message = Message(value=value, topic=topic, *args, **kwargs)
self.kafka.produce(message=message, topic=topic, partition=kwargs['partition'])
def list_topics(self, topic=None, *args, **kwargs): | return ClusterMetadata(topic) | 0 | 2023-10-24 13:27:12+00:00 | 4k |
CuriseJia/FreeStyleRet | imagenet_test/freeblip_test.py | [
{
"identifier": "BLIP_Retrieval",
"path": "src/models/blip_retrieval.py",
"snippet": "class BLIP_Retrieval(nn.Module):\n def __init__(self, model_args):\n super(BLIP_Retrieval, self).__init__()\n self.args = model_args\n self.blip = blip_retrieval(pretrained=self.args.origin_resu... | import argparse
import sys
import torch
from tqdm import tqdm
from torch.utils.data import DataLoader
from tqdm import tqdm
from data import S2ITestDataset, T2ITestDataset, M2ITestDataset
from src.models import BLIP_Retrieval
from src.utils import setup_seed, getR1Accuary, getR5Accuary | 2,361 |
def parse_args():
parser = argparse.ArgumentParser(description='Parse args for FreeStyleRet-CLIP test on ImageNet-X Dataset.')
# project settings
parser.add_argument('--resume', default='', type=str, help='load model checkpoint from given path')
parser.add_argument('--origin_resume', default='', type=str, help='load model checkpoint from given path')
parser.add_argument('--device', default='cuda:0')
parser.add_argument('--seed', default=42, type=int)
parser.add_argument('--num_workers', default=6, type=int)
parser.add_argument('--gram_encoder_path', default='pretrained/vgg_normalised.pth', type=str, help='load vgg from given path')
parser.add_argument('--style_prompt_path', default='pretrained/style_cluster.npy', type=str, help='load vgg from given path')
# data settings
parser.add_argument("--type", type=str, default='style2image', help='choose train test2image or style2image.')
parser.add_argument("--root_json_path", type=str, default='imagenet/test.json')
parser.add_argument("--other_json_path", type=str, default='imagenet/test.json')
parser.add_argument("--root_file_path", type=str, default='imagenet/')
parser.add_argument("--other_file_path", type=str, default='imagenet-s/')
parser.add_argument("--batch_size", type=int, default=16)
# model settings
parser.add_argument('--gram_prompts', type=int, default=4)
parser.add_argument('--gram_prompt_dim', type=int, default=1024)
parser.add_argument('--style_prompts', type=int, default=4)
parser.add_argument('--style_prompt_dim', type=int, default=1024)
args = parser.parse_args()
return args
def S2IRetrieval(args, model, ori_images, pair_images):
ori_feat = model(ori_images, dtype='image')
ske_feat = model(pair_images, dtype='image')
prob = torch.softmax(ske_feat.view(args.batch_size, -1) @ ori_feat.view(args.batch_size, -1).permute(1, 0), dim=-1)
return prob
def T2IRetrieval(args, model, ori_images, text_caption):
ori_feat = model(ori_images, dtype='image')
ske_feat = model(text_caption, dtype='text')
prob = torch.softmax(ske_feat @ ori_feat.T, dim=-1)
return prob
if __name__ == "__main__":
args = parse_args()
setup_seed(args.seed)
|
def parse_args():
parser = argparse.ArgumentParser(description='Parse args for FreeStyleRet-CLIP test on ImageNet-X Dataset.')
# project settings
parser.add_argument('--resume', default='', type=str, help='load model checkpoint from given path')
parser.add_argument('--origin_resume', default='', type=str, help='load model checkpoint from given path')
parser.add_argument('--device', default='cuda:0')
parser.add_argument('--seed', default=42, type=int)
parser.add_argument('--num_workers', default=6, type=int)
parser.add_argument('--gram_encoder_path', default='pretrained/vgg_normalised.pth', type=str, help='load vgg from given path')
parser.add_argument('--style_prompt_path', default='pretrained/style_cluster.npy', type=str, help='load vgg from given path')
# data settings
parser.add_argument("--type", type=str, default='style2image', help='choose train test2image or style2image.')
parser.add_argument("--root_json_path", type=str, default='imagenet/test.json')
parser.add_argument("--other_json_path", type=str, default='imagenet/test.json')
parser.add_argument("--root_file_path", type=str, default='imagenet/')
parser.add_argument("--other_file_path", type=str, default='imagenet-s/')
parser.add_argument("--batch_size", type=int, default=16)
# model settings
parser.add_argument('--gram_prompts', type=int, default=4)
parser.add_argument('--gram_prompt_dim', type=int, default=1024)
parser.add_argument('--style_prompts', type=int, default=4)
parser.add_argument('--style_prompt_dim', type=int, default=1024)
args = parser.parse_args()
return args
def S2IRetrieval(args, model, ori_images, pair_images):
ori_feat = model(ori_images, dtype='image')
ske_feat = model(pair_images, dtype='image')
prob = torch.softmax(ske_feat.view(args.batch_size, -1) @ ori_feat.view(args.batch_size, -1).permute(1, 0), dim=-1)
return prob
def T2IRetrieval(args, model, ori_images, text_caption):
ori_feat = model(ori_images, dtype='image')
ske_feat = model(text_caption, dtype='text')
prob = torch.softmax(ske_feat @ ori_feat.T, dim=-1)
return prob
if __name__ == "__main__":
args = parse_args()
setup_seed(args.seed)
| model = BLIP_Retrieval(args) | 0 | 2023-10-17 09:32:57+00:00 | 4k |
liuqidong07/MOELoRA-peft | src/MLoRA/peft/tuners/lora.py | [
{
"identifier": "is_bnb_available",
"path": "src/MLoRA/peft/import_utils.py",
"snippet": "def is_bnb_available():\n return importlib.util.find_spec(\"bitsandbytes\") is not None"
},
{
"identifier": "PeftConfig",
"path": "src/MLoRA/peft/utils/config.py",
"snippet": "class PeftConfig(Pe... | import math
import re
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
import bitsandbytes as bnb
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import List, Optional, Union
from transformers.pytorch_utils import Conv1D
from ..import_utils import is_bnb_available
from ..utils import (
TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING,
ModulesToSaveWrapper,
PeftConfig,
PeftType,
_freeze_adapter,
_get_submodules,
transpose,
) | 2,423 | # 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.
if is_bnb_available():
@dataclass
class LoraConfig(PeftConfig):
"""
This is the configuration class to store the configuration of a [`LoraModel`].
Args:
r (`int`): Lora attention dimension.
target_modules (`Union[List[str],str]`): The names of the modules to apply Lora to.
lora_alpha (`float`): The alpha parameter for Lora scaling.
lora_dropout (`float`): The dropout probability for Lora layers.
fan_in_fan_out (`bool`): Set this to True if the layer to replace stores weight like (fan_in, fan_out).
For example, gpt-2 uses `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`.:
bias (`str`): Bias type for Lora. Can be 'none', 'all' or 'lora_only'
modules_to_save (`List[str]`):List of modules apart from LoRA layers to be set as trainable
and saved in the final checkpoint.
"""
r: int = field(default=8, metadata={"help": "Lora attention dimension"})
target_modules: Optional[Union[List[str], str]] = field(
default=None,
metadata={
"help": "List of module names or regex expression of the module names to replace with Lora."
"For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' "
},
)
lora_alpha: int = field(default=None, metadata={"help": "Lora alpha"})
lora_dropout: float = field(default=None, metadata={"help": "Lora dropout"})
fan_in_fan_out: bool = field(
default=False,
metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"},
)
bias: str = field(default="none", metadata={"help": "Bias type for Lora. Can be 'none', 'all' or 'lora_only'"})
modules_to_save: Optional[List[str]] = field(
default=None,
metadata={
"help": "List of modules apart from LoRA layers to be set as trainable and saved in the final checkpoint. "
"For example, in Sequence Classification or Token Classification tasks, "
"the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved."
},
)
init_lora_weights: bool = field(
default=True,
metadata={"help": "Whether to initialize the weights of the Lora layers."},
)
def __post_init__(self):
self.peft_type = PeftType.LORA
class LoraModel(torch.nn.Module):
"""
Creates Low Rank Adapter (Lora) model from a pretrained transformers model.
Args:
model ([`~transformers.PreTrainedModel`]): The model to be adapted.
config ([`LoraConfig`]): The configuration of the Lora model.
Returns:
`torch.nn.Module`: The Lora model.
Example:
```py
>>> from transformers import AutoModelForSeq2SeqLM, LoraConfig
>>> from peft import LoraModel, LoraConfig
>>> config = LoraConfig(
... peft_type="LORA",
... 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")
>>> lora_model = LoraModel(config, model)
```
**Attributes**:
- **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.
- **peft_config** ([`LoraConfig`]): The configuration of the Lora model.
"""
def __init__(self, model, config, adapter_name):
super().__init__()
self.model = model
self.forward = self.model.forward
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_lora_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(
"LoraModel supports only 1 adapter with bias. When using multiple adapters, set bias to 'none' for all adapters."
)
mark_only_lora_as_trainable(self.model, self.peft_config[adapter_name].bias) # freeze all layers except for lora layer
if self.peft_config[adapter_name].inference_mode: # if inference, also freeze lora layer
| # coding=utf-8
# Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if is_bnb_available():
@dataclass
class LoraConfig(PeftConfig):
"""
This is the configuration class to store the configuration of a [`LoraModel`].
Args:
r (`int`): Lora attention dimension.
target_modules (`Union[List[str],str]`): The names of the modules to apply Lora to.
lora_alpha (`float`): The alpha parameter for Lora scaling.
lora_dropout (`float`): The dropout probability for Lora layers.
fan_in_fan_out (`bool`): Set this to True if the layer to replace stores weight like (fan_in, fan_out).
For example, gpt-2 uses `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`.:
bias (`str`): Bias type for Lora. Can be 'none', 'all' or 'lora_only'
modules_to_save (`List[str]`):List of modules apart from LoRA layers to be set as trainable
and saved in the final checkpoint.
"""
r: int = field(default=8, metadata={"help": "Lora attention dimension"})
target_modules: Optional[Union[List[str], str]] = field(
default=None,
metadata={
"help": "List of module names or regex expression of the module names to replace with Lora."
"For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' "
},
)
lora_alpha: int = field(default=None, metadata={"help": "Lora alpha"})
lora_dropout: float = field(default=None, metadata={"help": "Lora dropout"})
fan_in_fan_out: bool = field(
default=False,
metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"},
)
bias: str = field(default="none", metadata={"help": "Bias type for Lora. Can be 'none', 'all' or 'lora_only'"})
modules_to_save: Optional[List[str]] = field(
default=None,
metadata={
"help": "List of modules apart from LoRA layers to be set as trainable and saved in the final checkpoint. "
"For example, in Sequence Classification or Token Classification tasks, "
"the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved."
},
)
init_lora_weights: bool = field(
default=True,
metadata={"help": "Whether to initialize the weights of the Lora layers."},
)
def __post_init__(self):
self.peft_type = PeftType.LORA
class LoraModel(torch.nn.Module):
"""
Creates Low Rank Adapter (Lora) model from a pretrained transformers model.
Args:
model ([`~transformers.PreTrainedModel`]): The model to be adapted.
config ([`LoraConfig`]): The configuration of the Lora model.
Returns:
`torch.nn.Module`: The Lora model.
Example:
```py
>>> from transformers import AutoModelForSeq2SeqLM, LoraConfig
>>> from peft import LoraModel, LoraConfig
>>> config = LoraConfig(
... peft_type="LORA",
... 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")
>>> lora_model = LoraModel(config, model)
```
**Attributes**:
- **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.
- **peft_config** ([`LoraConfig`]): The configuration of the Lora model.
"""
def __init__(self, model, config, adapter_name):
super().__init__()
self.model = model
self.forward = self.model.forward
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_lora_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(
"LoraModel supports only 1 adapter with bias. When using multiple adapters, set bias to 'none' for all adapters."
)
mark_only_lora_as_trainable(self.model, self.peft_config[adapter_name].bias) # freeze all layers except for lora layer
if self.peft_config[adapter_name].inference_mode: # if inference, also freeze lora layer | _freeze_adapter(self.model, adapter_name) | 6 | 2023-10-19 10:55:50+00:00 | 4k |
voyage-ai/voyageai-python | voyageai/api_resources/voyage_object.py | [
{
"identifier": "util",
"path": "voyageai/util.py",
"snippet": "VOYAGE_LOG = os.environ.get(\"VOYAGE_LOG\")\n VOYAGE = 1\nclass ApiType(Enum):\n def from_str(label):\ndef _console_log_level():\ndef log_debug(message, **params):\ndef log_info(message, **params):\ndef log_warn(message, **params):\nd... | import json
from copy import deepcopy
from typing import Optional, Tuple, Union
from voyageai import util
from voyageai.api_resources import api_requestor
from voyageai.api_resources.voyage_response import VoyageResponse | 2,858 |
class VoyageObject(dict):
def __init__(
self,
**params,
):
super(VoyageObject, self).__init__()
self._retrieve_params = params
def __setattr__(self, k, v):
if k[0] == "_" or k in self.__dict__:
return super(VoyageObject, self).__setattr__(k, v)
self[k] = v
return None
def __getattr__(self, k):
if k[0] == "_":
raise AttributeError(k)
try:
return self[k]
except KeyError as err:
raise AttributeError(*err.args)
def __delattr__(self, k):
if k[0] == "_" or k in self.__dict__:
return super(VoyageObject, self).__delattr__(k)
else:
del self[k]
def __setitem__(self, k, v):
if v == "":
raise ValueError(
"You cannot set %s to an empty string. "
"We interpret empty strings as None in requests."
"You may set %s.%s = None to delete the property" % (k, str(self), k)
)
super(VoyageObject, self).__setitem__(k, v)
def __delitem__(self, k):
raise NotImplementedError("del is not supported")
# Custom unpickling method that uses `update` to update the dictionary
# without calling __setitem__, which would fail if any value is an empty
# string
def __setstate__(self, state):
self.update(state)
# Custom pickling method to ensure the instance is pickled as a custom
# class and not as a dict, otherwise __setstate__ would not be called when
# unpickling.
def __reduce__(self):
reduce_value = (
type(self), # callable
(), # args
dict(self), # state
)
return reduce_value
@classmethod
def construct_from(
cls,
values,
):
instance = cls()
instance.refresh_from(values)
return instance
def refresh_from(
self,
values,
):
# Wipe old state before setting new.
self.clear()
for k, v in values.items():
super(VoyageObject, self).__setitem__(
k, util.convert_to_voyage_object(v)
)
self._previous = values
def request(
self,
method,
url,
params=None,
headers=None,
stream=False,
request_id: Optional[str] = None,
request_timeout: Optional[Union[float, Tuple[float, float]]] = None,
):
if params is None:
params = self._retrieve_params
requestor = api_requestor.APIRequestor(
key=self.api_key,
)
response, stream, api_key = requestor.request(
method,
url,
params=params,
stream=stream,
headers=headers,
request_id=request_id,
request_timeout=request_timeout,
)
if stream:
|
class VoyageObject(dict):
def __init__(
self,
**params,
):
super(VoyageObject, self).__init__()
self._retrieve_params = params
def __setattr__(self, k, v):
if k[0] == "_" or k in self.__dict__:
return super(VoyageObject, self).__setattr__(k, v)
self[k] = v
return None
def __getattr__(self, k):
if k[0] == "_":
raise AttributeError(k)
try:
return self[k]
except KeyError as err:
raise AttributeError(*err.args)
def __delattr__(self, k):
if k[0] == "_" or k in self.__dict__:
return super(VoyageObject, self).__delattr__(k)
else:
del self[k]
def __setitem__(self, k, v):
if v == "":
raise ValueError(
"You cannot set %s to an empty string. "
"We interpret empty strings as None in requests."
"You may set %s.%s = None to delete the property" % (k, str(self), k)
)
super(VoyageObject, self).__setitem__(k, v)
def __delitem__(self, k):
raise NotImplementedError("del is not supported")
# Custom unpickling method that uses `update` to update the dictionary
# without calling __setitem__, which would fail if any value is an empty
# string
def __setstate__(self, state):
self.update(state)
# Custom pickling method to ensure the instance is pickled as a custom
# class and not as a dict, otherwise __setstate__ would not be called when
# unpickling.
def __reduce__(self):
reduce_value = (
type(self), # callable
(), # args
dict(self), # state
)
return reduce_value
@classmethod
def construct_from(
cls,
values,
):
instance = cls()
instance.refresh_from(values)
return instance
def refresh_from(
self,
values,
):
# Wipe old state before setting new.
self.clear()
for k, v in values.items():
super(VoyageObject, self).__setitem__(
k, util.convert_to_voyage_object(v)
)
self._previous = values
def request(
self,
method,
url,
params=None,
headers=None,
stream=False,
request_id: Optional[str] = None,
request_timeout: Optional[Union[float, Tuple[float, float]]] = None,
):
if params is None:
params = self._retrieve_params
requestor = api_requestor.APIRequestor(
key=self.api_key,
)
response, stream, api_key = requestor.request(
method,
url,
params=params,
stream=stream,
headers=headers,
request_id=request_id,
request_timeout=request_timeout,
)
if stream: | assert not isinstance(response, VoyageResponse) # must be an iterator | 2 | 2023-10-17 22:11:18+00:00 | 4k |
YuroFR/freqtrade-modded-crypto-trading-bot | tests/data/test_download_data.py | [
{
"identifier": "setup_utils_configuration",
"path": "freqtrade/configuration/config_setup.py",
"snippet": "def setup_utils_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str, Any]:\n \"\"\"\n Prepare the configuration for utils subcommands\n :param args: Cli args from Arguments()... | from unittest.mock import MagicMock, PropertyMock
from freqtrade.configuration.config_setup import setup_utils_configuration
from freqtrade.data.history.history_utils import download_data_main
from freqtrade.enums import RunMode
from freqtrade.exceptions import OperationalException
from tests.conftest import EXMS, log_has, patch_exchange
import pytest | 1,793 |
def test_download_data_main_no_markets(mocker, caplog):
dl_mock = mocker.patch('freqtrade.data.history.history_utils.refresh_backtest_ohlcv_data',
MagicMock(return_value=["ETH/BTC", "XRP/BTC"]))
patch_exchange(mocker, id='binance')
mocker.patch(f'{EXMS}.get_markets', return_value={})
config = setup_utils_configuration({"exchange": "binance"}, RunMode.UTIL_EXCHANGE)
config.update({
"days": 20,
"pairs": ["ETH/BTC", "XRP/BTC"],
"timeframes": ["5m", "1h"]
})
|
def test_download_data_main_no_markets(mocker, caplog):
dl_mock = mocker.patch('freqtrade.data.history.history_utils.refresh_backtest_ohlcv_data',
MagicMock(return_value=["ETH/BTC", "XRP/BTC"]))
patch_exchange(mocker, id='binance')
mocker.patch(f'{EXMS}.get_markets', return_value={})
config = setup_utils_configuration({"exchange": "binance"}, RunMode.UTIL_EXCHANGE)
config.update({
"days": 20,
"pairs": ["ETH/BTC", "XRP/BTC"],
"timeframes": ["5m", "1h"]
}) | download_data_main(config) | 1 | 2023-10-21 10:02:05+00:00 | 4k |
yanzhh/HGERE | transformers/src/transformers/modeling_albert.py | [
{
"identifier": "add_start_docstrings",
"path": "transformers/src/transformers/file_utils.py",
"snippet": "def add_start_docstrings(*docstr):\n def docstring_decorator(fn):\n fn.__doc__ = \"\".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else \"\")\n return fn\n\n return docs... | import logging
import math
import os
import torch
import torch.nn as nn
import pdb
import re
import numpy as np
import tensorflow as tf
from torch.nn import CrossEntropyLoss, MSELoss, BCEWithLogitsLoss
from torch.nn.utils.rnn import pad_sequence
from transformers.configuration_albert import AlbertConfig
from transformers.modeling_bert import ACT2FN, BertEmbeddings, BertSelfAttention, prune_linear_layer
from transformers.modeling_utils import PreTrainedModel
from .file_utils import add_start_docstrings, add_start_docstrings_to_callable
from .modules import * | 3,534 | config_class = AlbertConfig
pretrained_model_archive_map = ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP
base_model_prefix = "albert"
def _init_weights(self, module):
""" Initialize the weights.
"""
if isinstance(module, (nn.Linear, nn.Embedding)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if isinstance(module, (nn.Linear)) and module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
ALBERT_START_DOCSTRING = r"""
This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
usage and behavior.
Args:
config (:class:`~transformers.AlbertConfig`): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the configuration.
Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
"""
ALBERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using :class:`transformers.AlbertTokenizer`.
See :func:`transformers.PreTrainedTokenizer.encode` and
:func:`transformers.PreTrainedTokenizer.encode_plus` for details.
`What are input IDs? <../glossary.html#input-ids>`__
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Mask to avoid performing attention on padding token indices.
Mask values selected in ``[0, 1]``:
``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
`What are attention masks? <../glossary.html#attention-mask>`__
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Segment token indices to indicate first and second portions of the inputs.
Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``
corresponds to a `sentence B` token
`What are token type IDs? <../glossary.html#token-type-ids>`_
position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Indices of positions of each input sequence tokens in the position embeddings.
Selected in the range ``[0, config.max_position_embeddings - 1]``.
`What are position IDs? <../glossary.html#position-ids>`_
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):
Mask to nullify selected heads of the self-attention modules.
Mask values selected in ``[0, 1]``:
:obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.
input_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
"""
@add_start_docstrings(
"The bare ALBERT Model transformer outputting raw hidden-states without any specific head on top.",
ALBERT_START_DOCSTRING,
)
class AlbertModel(AlbertPreTrainedModel):
config_class = AlbertConfig
pretrained_model_archive_map = ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP
load_tf_weights = load_tf_weights_in_albert
base_model_prefix = "albert"
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = AlbertEmbeddings(config)
self.encoder = AlbertTransformer(config)
self.pooler = nn.Linear(config.hidden_size, config.hidden_size)
self.pooler_activation = nn.Tanh()
self.init_weights()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
def _resize_token_embeddings(self, new_num_tokens):
old_embeddings = self.embeddings.word_embeddings
new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
self.embeddings.word_embeddings = new_embeddings
return self.embeddings.word_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}
ALBERT has a different architecture in that its layers are shared across groups, which then has inner groups.
If an ALBERT model has 12 hidden layers and 2 hidden groups, with two inner groups, there
is a total of 4 different layers.
These layers are flattened: the indices [0,1] correspond to the two inner groups of the first hidden layer,
while [2,3] correspond to the two inner groups of the second hidden layer.
Any layer with in index other than [0,1,2,3] will result in an error.
See base class PreTrainedModel for more information about head pruning
"""
for layer, heads in heads_to_prune.items():
group_idx = int(layer / self.config.inner_group_num)
inner_group_idx = int(layer - group_idx * self.config.inner_group_num)
self.encoder.albert_layer_groups[group_idx].albert_layers[inner_group_idx].attention.prune_heads(heads)
| # coding=utf-8
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch ALBERT model. """
logger = logging.getLogger(__name__)
ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP = {
"albert-base-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-pytorch_model.bin",
"albert-large-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-large-pytorch_model.bin",
"albert-xlarge-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-pytorch_model.bin",
"albert-xxlarge-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-pytorch_model.bin",
"albert-base-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v2-pytorch_model.bin",
"albert-large-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-large-v2-pytorch_model.bin",
"albert-xlarge-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-v2-pytorch_model.bin",
"albert-xxlarge-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-v2-pytorch_model.bin",
}
def load_tf_weights_in_albert(model, config, tf_checkpoint_path):
""" Load tf checkpoints in a pytorch model."""
try:
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(tf_checkpoint_path)
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info("Loading TF weight {} with shape {}".format(name, shape))
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array)
for name, array in zip(names, arrays):
print(name)
for name, array in zip(names, arrays):
original_name = name
# If saved from the TF HUB module
name = name.replace("module/", "")
# Renaming and simplifying
name = name.replace("ffn_1", "ffn")
name = name.replace("bert/", "albert/")
name = name.replace("attention_1", "attention")
name = name.replace("transform/", "")
name = name.replace("LayerNorm_1", "full_layer_layer_norm")
name = name.replace("LayerNorm", "attention/LayerNorm")
name = name.replace("transformer/", "")
# The feed forward layer had an 'intermediate' step which has been abstracted away
name = name.replace("intermediate/dense/", "")
name = name.replace("ffn/intermediate/output/dense/", "ffn_output/")
# ALBERT attention was split between self and output which have been abstracted away
name = name.replace("/output/", "/")
name = name.replace("/self/", "/")
# The pooler is a linear layer
name = name.replace("pooler/dense", "pooler")
# The classifier was simplified to predictions from cls/predictions
name = name.replace("cls/predictions", "predictions")
name = name.replace("predictions/attention", "predictions")
# Naming was changed to be more explicit
name = name.replace("embeddings/attention", "embeddings")
name = name.replace("inner_group_", "albert_layers/")
name = name.replace("group_", "albert_layer_groups/")
# Classifier
if len(name.split("/")) == 1 and ("output_bias" in name or "output_weights" in name):
name = "classifier/" + name
# No ALBERT model currently handles the next sentence prediction task
if "seq_relationship" in name:
continue
name = name.split("/")
# Ignore the gradients applied by the LAMB/ADAM optimizers.
if (
"adam_m" in name
or "adam_v" in name
or "AdamWeightDecayOptimizer" in name
or "AdamWeightDecayOptimizer_1" in name
or "global_step" in name
):
logger.info("Skipping {}".format("/".join(name)))
continue
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
scope_names = re.split(r"_(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "output_weights":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "squad":
pointer = getattr(pointer, "classifier")
else:
try:
pointer = getattr(pointer, scope_names[0])
except AttributeError:
logger.info("Skipping {}".format("/".join(name)))
continue
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
if m_name[-11:] == "_embeddings":
pointer = getattr(pointer, "weight")
elif m_name == "kernel":
array = np.transpose(array)
try:
assert pointer.shape == array.shape
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
print("Initialize PyTorch weight {} from {}".format(name, original_name))
pointer.data = torch.from_numpy(array)
return model
class AlbertEmbeddings(BertEmbeddings):
"""
Construct the embeddings from word, position and token_type embeddings.
"""
def __init__(self, config):
super().__init__(config)
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=0)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
self.LayerNorm = torch.nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
class AlbertAttention(BertSelfAttention):
def __init__(self, config):
super().__init__(config)
self.output_attentions = config.output_attentions
self.num_attention_heads = config.num_attention_heads
self.hidden_size = config.hidden_size
self.attention_head_size = config.hidden_size // config.num_attention_heads
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
mask = torch.ones(self.num_attention_heads, self.attention_head_size)
heads = set(heads) - self.pruned_heads # Convert to set and emove already pruned heads
for head in heads:
# Compute how many pruned heads are before the head and move the index accordingly
head = head - sum(1 if h < head else 0 for h in self.pruned_heads)
mask[head] = 0
mask = mask.view(-1).contiguous().eq(1)
index = torch.arange(len(mask))[mask].long()
# Prune linear layers
self.query = prune_linear_layer(self.query, index)
self.key = prune_linear_layer(self.key, index)
self.value = prune_linear_layer(self.value, index)
self.dense = prune_linear_layer(self.dense, index, dim=1)
# Update hyper params and store pruned heads
self.num_attention_heads = self.num_attention_heads - len(heads)
self.all_head_size = self.attention_head_size * self.num_attention_heads
self.pruned_heads = self.pruned_heads.union(heads)
def forward(self, input_ids, attention_mask=None, head_mask=None):
mixed_query_layer = self.query(input_ids)
mixed_key_layer = self.key(input_ids)
mixed_value_layer = self.value(input_ids)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = nn.Softmax(dim=-1)(attention_scores)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
# Mask heads if we want to
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
# Should find a better way to do this
w = (
self.dense.weight.t()
.view(self.num_attention_heads, self.attention_head_size, self.hidden_size)
.to(context_layer.dtype)
)
b = self.dense.bias.to(context_layer.dtype)
projected_context_layer = torch.einsum("bfnd,ndh->bfh", context_layer, w) + b
projected_context_layer_dropout = self.dropout(projected_context_layer)
layernormed_context_layer = self.LayerNorm(input_ids + projected_context_layer_dropout)
return (layernormed_context_layer, attention_probs) if self.output_attentions else (layernormed_context_layer,)
class AlbertLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.full_layer_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.attention = AlbertAttention(config)
self.ffn = nn.Linear(config.hidden_size, config.intermediate_size)
self.ffn_output = nn.Linear(config.intermediate_size, config.hidden_size)
self.activation = ACT2FN[config.hidden_act]
def forward(self, hidden_states, attention_mask=None, head_mask=None):
attention_output = self.attention(hidden_states, attention_mask, head_mask)
ffn_output = self.ffn(attention_output[0])
ffn_output = self.activation(ffn_output)
ffn_output = self.ffn_output(ffn_output)
hidden_states = self.full_layer_layer_norm(ffn_output + attention_output[0])
return (hidden_states,) + attention_output[1:] # add attentions if we output them
class AlbertLayerGroup(nn.Module):
def __init__(self, config):
super().__init__()
self.output_attentions = config.output_attentions
self.output_hidden_states = config.output_hidden_states
self.albert_layers = nn.ModuleList([AlbertLayer(config) for _ in range(config.inner_group_num)])
def forward(self, hidden_states, attention_mask=None, head_mask=None):
layer_hidden_states = ()
layer_attentions = ()
for layer_index, albert_layer in enumerate(self.albert_layers):
layer_output = albert_layer(hidden_states, attention_mask, head_mask[layer_index])
hidden_states = layer_output[0]
if self.output_attentions:
layer_attentions = layer_attentions + (layer_output[1],)
if self.output_hidden_states:
layer_hidden_states = layer_hidden_states + (hidden_states,)
outputs = (hidden_states,)
if self.output_hidden_states:
outputs = outputs + (layer_hidden_states,)
if self.output_attentions:
outputs = outputs + (layer_attentions,)
return outputs # last-layer hidden state, (layer hidden states), (layer attentions)
class AlbertTransformer(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.output_attentions = config.output_attentions
self.output_hidden_states = config.output_hidden_states
self.embedding_hidden_mapping_in = nn.Linear(config.embedding_size, config.hidden_size)
self.albert_layer_groups = nn.ModuleList([AlbertLayerGroup(config) for _ in range(config.num_hidden_groups)])
def forward(self, hidden_states, attention_mask=None, head_mask=None):
hidden_states = self.embedding_hidden_mapping_in(hidden_states)
all_attentions = ()
if self.output_hidden_states:
all_hidden_states = (hidden_states,)
for i in range(self.config.num_hidden_layers):
# Number of layers in a hidden group
layers_per_group = int(self.config.num_hidden_layers / self.config.num_hidden_groups)
# Index of the hidden group
group_idx = int(i / (self.config.num_hidden_layers / self.config.num_hidden_groups))
layer_group_output = self.albert_layer_groups[group_idx](
hidden_states,
attention_mask,
head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group],
)
hidden_states = layer_group_output[0]
if self.output_attentions:
all_attentions = all_attentions + layer_group_output[-1]
if self.output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
outputs = (hidden_states,)
if self.output_hidden_states:
outputs = outputs + (all_hidden_states,)
if self.output_attentions:
outputs = outputs + (all_attentions,)
return outputs # last-layer hidden state, (all hidden states), (all attentions)
class AlbertPreTrainedModel(PreTrainedModel):
""" An abstract class to handle weights initialization and
a simple interface for downloading and loading pretrained models.
"""
config_class = AlbertConfig
pretrained_model_archive_map = ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP
base_model_prefix = "albert"
def _init_weights(self, module):
""" Initialize the weights.
"""
if isinstance(module, (nn.Linear, nn.Embedding)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if isinstance(module, (nn.Linear)) and module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
ALBERT_START_DOCSTRING = r"""
This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
usage and behavior.
Args:
config (:class:`~transformers.AlbertConfig`): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the configuration.
Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
"""
ALBERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using :class:`transformers.AlbertTokenizer`.
See :func:`transformers.PreTrainedTokenizer.encode` and
:func:`transformers.PreTrainedTokenizer.encode_plus` for details.
`What are input IDs? <../glossary.html#input-ids>`__
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Mask to avoid performing attention on padding token indices.
Mask values selected in ``[0, 1]``:
``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.
`What are attention masks? <../glossary.html#attention-mask>`__
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Segment token indices to indicate first and second portions of the inputs.
Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``
corresponds to a `sentence B` token
`What are token type IDs? <../glossary.html#token-type-ids>`_
position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
Indices of positions of each input sequence tokens in the position embeddings.
Selected in the range ``[0, config.max_position_embeddings - 1]``.
`What are position IDs? <../glossary.html#position-ids>`_
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):
Mask to nullify selected heads of the self-attention modules.
Mask values selected in ``[0, 1]``:
:obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.
input_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
"""
@add_start_docstrings(
"The bare ALBERT Model transformer outputting raw hidden-states without any specific head on top.",
ALBERT_START_DOCSTRING,
)
class AlbertModel(AlbertPreTrainedModel):
config_class = AlbertConfig
pretrained_model_archive_map = ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP
load_tf_weights = load_tf_weights_in_albert
base_model_prefix = "albert"
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = AlbertEmbeddings(config)
self.encoder = AlbertTransformer(config)
self.pooler = nn.Linear(config.hidden_size, config.hidden_size)
self.pooler_activation = nn.Tanh()
self.init_weights()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
def _resize_token_embeddings(self, new_num_tokens):
old_embeddings = self.embeddings.word_embeddings
new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)
self.embeddings.word_embeddings = new_embeddings
return self.embeddings.word_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}
ALBERT has a different architecture in that its layers are shared across groups, which then has inner groups.
If an ALBERT model has 12 hidden layers and 2 hidden groups, with two inner groups, there
is a total of 4 different layers.
These layers are flattened: the indices [0,1] correspond to the two inner groups of the first hidden layer,
while [2,3] correspond to the two inner groups of the second hidden layer.
Any layer with in index other than [0,1,2,3] will result in an error.
See base class PreTrainedModel for more information about head pruning
"""
for layer, heads in heads_to_prune.items():
group_idx = int(layer / self.config.inner_group_num)
inner_group_idx = int(layer - group_idx * self.config.inner_group_num)
self.encoder.albert_layer_groups[group_idx].albert_layers[inner_group_idx].attention.prune_heads(heads)
| @add_start_docstrings_to_callable(ALBERT_INPUTS_DOCSTRING) | 1 | 2023-10-15 02:31:09+00:00 | 4k |
explosion/prodigy-hf | tests/test_train_basics.py | [
{
"identifier": "hf_train_ner",
"path": "prodigy_hf/ner.py",
"snippet": "@recipe(\n \"hf.train.ner\",\n # fmt: off\n datasets=Arg(help=\"Datasets with NER annotations to train model for\"),\n out_dir=Arg(help=\"Folder to save trained model into\"),\n epochs=Arg(\"--epochs\", \"-e\", help=... | import pytest
from prodigy_hf import hf_train_ner, hf_train_textcat, hf_ner_correct, hf_textcat_correct | 2,386 | """
These tests assume some datasets are available in the Prodigy database.
Check the `.github/workflows/tests.yml` file for more details.
"""
def test_smoke_ner(tmpdir):
# Make sure we can train without errors
| """
These tests assume some datasets are available in the Prodigy database.
Check the `.github/workflows/tests.yml` file for more details.
"""
def test_smoke_ner(tmpdir):
# Make sure we can train without errors | hf_train_ner("fashion,eval:fashion", tmpdir, epochs=1, model_name="hf-internal-testing/tiny-random-DistilBertModel") | 0 | 2023-10-19 15:34:07+00:00 | 4k |
johnyang101/pmpnndiff | models/diffusion_lms.py | [
{
"identifier": "Generic_LM",
"path": "models/pmpnn_lms.py",
"snippet": "class Generic_LM(pl.LightningModule):\n def __init__(self, cfg):\n super().__init__()\n self.cfg = cfg\n self.learning_rate = self.cfg.learning_rate\n \n def training_step(self, batch, batch_idx):\n ... | import math
import torch
import torch.nn.functional as F
import torch.distributions as dists
import models.diffusion_utils as du
from torchtyping import TensorType
from models.pmpnn_lms import Generic_LM
from data.data_objs import PMPNNBatch
from models.pmpnn import PMPNN_Baseline_Diff | 1,638 |
class Generic_Diff_LM(Generic_LM):
def __init__(self, cfg, debug=False):
super().__init__(cfg)
self.debug = debug
self.num_classes = cfg.num_classes
self.non_abs_classes = self.num_classes - 1 if self.cfg.model.absorbing else self.num_classes
self._denoise_fn = self._init_denoise_fn(cfg.model)
if self.cfg.model.ft:
self._denoise_fn = self.load_ft_dict(self._denoise_fn)
def _init_denoise_fn(self, model_conf): #TODO: Write this.
|
class Generic_Diff_LM(Generic_LM):
def __init__(self, cfg, debug=False):
super().__init__(cfg)
self.debug = debug
self.num_classes = cfg.num_classes
self.non_abs_classes = self.num_classes - 1 if self.cfg.model.absorbing else self.num_classes
self._denoise_fn = self._init_denoise_fn(cfg.model)
if self.cfg.model.ft:
self._denoise_fn = self.load_ft_dict(self._denoise_fn)
def _init_denoise_fn(self, model_conf): #TODO: Write this. | return PMPNN_Baseline_Diff(**model_conf) | 2 | 2023-10-16 08:47:43+00:00 | 4k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.