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
wdlctc/rtp
rtp/module/top2gate.py
[ { "identifier": "affine_weight", "path": "rtp/module/utils.py", "snippet": "def affine_weight(\n weight: torch.Tensor,\n master_weight: torch.Tensor,\n per_partition_size: int,\n partition_dim: int,\n world_size: int,\n rank: int,\n stride: int = 1,\n) -> Optional[torch.Tensor]:\n ...
from typing import Callable, Dict, Tuple from torch import Tensor from .utils import affine_weight from .utils import divide_and_check_no_remainder, affine_weight from .collectives import set_full_param, allign_storage, set_full_param2 from .collectives import _WeightParallelRegion_test, _WeightParallelRegion_moe from .collectives import _WeightParallelRegion_before, _WeightParallelRegion_after, hook_fn from functools import partial import torch import torch.nn.functional as F
3,943
# Create a mask for 2nd's expert per token using Gumbel-max trick # https://timvieira.github.io/blog/post/2014/07/31/gumbel-max-trick/ logits_w_noise = logits + gumbel_rsample(logits.shape, device=logits.device) # Replace top-expert with min value logits_except1 = logits_w_noise.masked_fill(mask1.bool(), float("-inf")) indices2_s = torch.argmax(logits_except1, dim=1) mask2 = one_hot(indices2_s, num_classes=num_experts) # Compute locations in capacity buffer locations1 = torch.cumsum(mask1, dim=0) - 1 locations2 = torch.cumsum(mask2, dim=0) - 1 # Update 2nd's location by accounting for locations of 1st locations2 += torch.sum(mask1, dim=0, keepdim=True) # Compute l_aux me = torch.mean(gates, dim=0) ce = torch.mean(mask1.float(), dim=0) l_aux = torch.mean(me * ce) # Remove locations outside capacity from mask mask1 *= torch.lt(locations1, capacity) mask2 *= torch.lt(locations2, capacity) # Store the capacity location for each token locations1_s = torch.sum(locations1 * mask1, dim=1) locations2_s = torch.sum(locations2 * mask2, dim=1) # Normalize gate probabilities gates1_s = (gates * mask1).sum(dim=1) # einsum("se,se->s") gates2_s = (gates * mask2).sum(dim=1) # einsum("se,se->s") denom_s = gates1_s + gates2_s # Avoid divide-by-zero denom_s = torch.clamp(denom_s, min=torch.finfo(denom_s.dtype).eps) gates1_s /= denom_s gates2_s /= denom_s # Calculate combine_weights and dispatch_mask gates1 = gates1_s.unsqueeze(-1) * mask1 # einsum("s,se->se") gates2 = gates2_s.unsqueeze(-1) * mask2 # einsum("s,se->se") locations1_sc = one_hot(locations1_s, num_classes=capacity) locations2_sc = one_hot(locations2_s, num_classes=capacity) combine1_sec = gates1.unsqueeze(2) * locations1_sc.unsqueeze(1) # einsum("se,sc->sec") combine2_sec = gates2.unsqueeze(2) * locations2_sc.unsqueeze(1) # einsum("se,sc->sec") combine_weights = combine1_sec + combine2_sec dispatch_mask = combine_weights.bool() return l_aux.to(logits.dtype), combine_weights.to(logits.dtype), dispatch_mask class Top2Gate(torch.nn.Module): """Gate module which implements Top2Gating as described in Gshard_. :: gate = Top2Gate(model_dim, num_experts) l_aux, combine_weights, dispatch_mask = gate(input) .. Gshard_: https://arxiv.org/pdf/2006.16668.pdf Args: model_dim (int): size of model embedding dimension num_experts (ints): number of experts in model """ wg: torch.nn.Linear def __init__( self, model_dim: int, num_experts: int, ) -> None: super().__init__() self.wg = torch.nn.Linear(model_dim, num_experts, bias=False) def forward(self, input: torch.Tensor) -> Tuple[Tensor, Tensor, Tensor]: # type: ignore logits = self.wg(input) return top2gating(logits) class WeightTop2Gate(torch.nn.Module): """Gate module which implements Top2Gating as described in Gshard_. :: gate = Top2Gate(model_dim, num_experts) l_aux, combine_weights, dispatch_mask = gate(input) .. Gshard_: https://arxiv.org/pdf/2006.16668.pdf Args: model_dim (int): size of model embedding dimension num_experts (ints): number of experts in model """ wg: torch.nn.Linear def __init__( self, model_dim: int, num_experts: int, gate = None, device = None, dtype = None, ) -> None: super().__init__() self.model_dim = model_dim self.num_experts = num_experts self.world_size = torch.distributed.get_world_size() self.rank = torch.distributed.get_rank() self.num_local_experts = divide_and_check_no_remainder(num_experts, self.world_size) self.linears = [] # self.wg = torch.nn.Linear(model_dim, num_experts, bias=False) self.wgs = [] for i in range(self.world_size): wg = torch.nn.Linear(model_dim, self.num_local_experts, bias=False).to(device) if i == 0:
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # Implementation of Top2Gating described in https://arxiv.org/pdf/2006.16668.pdf # Code is inspired by Top2GatingOnLogits from lingvo: # https://github.com/tensorflow/lingvo/blob/21b8106c5f1d30a196c98eedc441d4fd70833b11/lingvo/core/moe_layers.py#L477 gumbel_map: Dict[torch.device, Callable] = {} def gumbel_rsample(shape: Tuple, device: torch.device) -> Tensor: gumbel = gumbel_map.get(device) if gumbel is None: one = torch.tensor(1.0, device=device) zero = torch.tensor(0.0, device=device) gumbel = torch.distributions.gumbel.Gumbel(zero, one).rsample # type: ignore gumbel_map[device] = gumbel return gumbel(shape) def one_hot(tensor: torch.Tensor, num_classes: int) -> Tensor: """Workaround for https://github.com/pytorch/pytorch/issues/55579""" assert num_classes > 0, "num_classes must be a positive integer" ret = torch.zeros(tensor.shape + (num_classes,), device=tensor.device, dtype=tensor.dtype) ret.scatter_(-1, tensor.unsqueeze(-1), 1) return ret def top2gating(logits: torch.Tensor) -> Tuple[Tensor, Tensor, Tensor]: """Implements Top2Gating on logits.""" # NOTE(msb) softmax requires FP32: https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/ gates = F.softmax(logits, dim=1, dtype=torch.float) # gates has shape of SE num_tokens = gates.shape[0] num_experts = gates.shape[1] # capacity = 2S/E capacity = 2 * num_tokens // num_experts assert num_tokens % num_experts == 0 # Create a mask for 1st's expert per token indices1_s = torch.argmax(gates, dim=1) mask1 = one_hot(indices1_s, num_classes=num_experts) # Create a mask for 2nd's expert per token using Gumbel-max trick # https://timvieira.github.io/blog/post/2014/07/31/gumbel-max-trick/ logits_w_noise = logits + gumbel_rsample(logits.shape, device=logits.device) # Replace top-expert with min value logits_except1 = logits_w_noise.masked_fill(mask1.bool(), float("-inf")) indices2_s = torch.argmax(logits_except1, dim=1) mask2 = one_hot(indices2_s, num_classes=num_experts) # Compute locations in capacity buffer locations1 = torch.cumsum(mask1, dim=0) - 1 locations2 = torch.cumsum(mask2, dim=0) - 1 # Update 2nd's location by accounting for locations of 1st locations2 += torch.sum(mask1, dim=0, keepdim=True) # Compute l_aux me = torch.mean(gates, dim=0) ce = torch.mean(mask1.float(), dim=0) l_aux = torch.mean(me * ce) # Remove locations outside capacity from mask mask1 *= torch.lt(locations1, capacity) mask2 *= torch.lt(locations2, capacity) # Store the capacity location for each token locations1_s = torch.sum(locations1 * mask1, dim=1) locations2_s = torch.sum(locations2 * mask2, dim=1) # Normalize gate probabilities gates1_s = (gates * mask1).sum(dim=1) # einsum("se,se->s") gates2_s = (gates * mask2).sum(dim=1) # einsum("se,se->s") denom_s = gates1_s + gates2_s # Avoid divide-by-zero denom_s = torch.clamp(denom_s, min=torch.finfo(denom_s.dtype).eps) gates1_s /= denom_s gates2_s /= denom_s # Calculate combine_weights and dispatch_mask gates1 = gates1_s.unsqueeze(-1) * mask1 # einsum("s,se->se") gates2 = gates2_s.unsqueeze(-1) * mask2 # einsum("s,se->se") locations1_sc = one_hot(locations1_s, num_classes=capacity) locations2_sc = one_hot(locations2_s, num_classes=capacity) combine1_sec = gates1.unsqueeze(2) * locations1_sc.unsqueeze(1) # einsum("se,sc->sec") combine2_sec = gates2.unsqueeze(2) * locations2_sc.unsqueeze(1) # einsum("se,sc->sec") combine_weights = combine1_sec + combine2_sec dispatch_mask = combine_weights.bool() return l_aux.to(logits.dtype), combine_weights.to(logits.dtype), dispatch_mask class Top2Gate(torch.nn.Module): """Gate module which implements Top2Gating as described in Gshard_. :: gate = Top2Gate(model_dim, num_experts) l_aux, combine_weights, dispatch_mask = gate(input) .. Gshard_: https://arxiv.org/pdf/2006.16668.pdf Args: model_dim (int): size of model embedding dimension num_experts (ints): number of experts in model """ wg: torch.nn.Linear def __init__( self, model_dim: int, num_experts: int, ) -> None: super().__init__() self.wg = torch.nn.Linear(model_dim, num_experts, bias=False) def forward(self, input: torch.Tensor) -> Tuple[Tensor, Tensor, Tensor]: # type: ignore logits = self.wg(input) return top2gating(logits) class WeightTop2Gate(torch.nn.Module): """Gate module which implements Top2Gating as described in Gshard_. :: gate = Top2Gate(model_dim, num_experts) l_aux, combine_weights, dispatch_mask = gate(input) .. Gshard_: https://arxiv.org/pdf/2006.16668.pdf Args: model_dim (int): size of model embedding dimension num_experts (ints): number of experts in model """ wg: torch.nn.Linear def __init__( self, model_dim: int, num_experts: int, gate = None, device = None, dtype = None, ) -> None: super().__init__() self.model_dim = model_dim self.num_experts = num_experts self.world_size = torch.distributed.get_world_size() self.rank = torch.distributed.get_rank() self.num_local_experts = divide_and_check_no_remainder(num_experts, self.world_size) self.linears = [] # self.wg = torch.nn.Linear(model_dim, num_experts, bias=False) self.wgs = [] for i in range(self.world_size): wg = torch.nn.Linear(model_dim, self.num_local_experts, bias=False).to(device) if i == 0:
set_full_param(wg, device, dtype)
3
2023-10-29 23:19:44+00:00
8k
LambdaLabsML/newsy
app.py
[ { "identifier": "lm", "path": "newsletter/lm.py", "snippet": "def _call_llm(*args, model=\"gpt-3.5-turbo-16k\", **kwargs):\ndef summarize_post(title: str, content: str) -> str:\ndef summarize_abstract(title: str, content: str) -> str:\ndef summarize_comment(title: str, summary: str, comment: str) -> str...
import json import os import ssl import certifi import requests from typing import Callable from slack_sdk.web import WebClient from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler from newsletter import ( lm, parse_arxiv, parse_hn, parse_reddit, parse_rss, parse_youtube, util, parse_pdf, ) from newsletter.slack import EditableMessage from langchain.chat_models import ChatOpenAI from langchain.schema import HumanMessage, AIMessage, SystemMessage from langchain.chat_models import ChatOpenAI from langchain.schema import HumanMessage, SystemMessage, AIMessage
3,790
discussions.append(("reddit", parse_reddit.search_for_url(url))) for name, discussion in discussions: if discussion is None: sections.append(f"*{name}* doesn't have a discussion for this url yet.") continue lines = [ f"*<{discussion['comments_url']}|{discussion['source']}>* has a +{discussion['score']} discussion" ] if len(discussion["comments"]) == 0: lines[0] += ", but there aren't any comments." else: lines[0] += " centered around:" for i, c in enumerate(discussion["comments"]): slack_msg.edit_line(f"_Summarizing comment {i + 1} on {name}..._") if summary is not None: comment_summary = lm.summarize_comment( discussion["title"], summary, c["content"] ) else: comment_summary = c["content"][:50].replace("\n", "") + "..." if "score" in c: lines.append( f"{i + 1}. (+{c['score']}) <{c['url']}|{comment_summary}>" ) else: lines.append(f"{i + 1}. <{c['url']}|{comment_summary}>") sections.append("\n".join(lines)) if not is_twitter_post: sections.append( f"You can search for tweets discussing this url on *<https://twitter.com/search?q=url:{url}&src=typed_query|Twitter>*" ) msg = "\n\n".join(sections) slack_msg.edit_line(msg) if summary is None: return chat = ChatOpenAI(model=model, request_timeout=30) response = chat( [ SystemMessage(content=content), AIMessage(content=summary), HumanMessage( content="Suggest 5 follow up questions to learn more about this post. The questions should be answerable based on the content in the article." ), ] ) printl( "Here are some follow up questions to help you dive deeper into this post (tag me and and I can answer them!):\n" + response.content ) def _do_news(channel): news = EditableMessage( app.client, channel, "Here's the latest news from today for you!" ) news.start_new_section() news.add_line("*HackerNews:*") news.set_progress_msg("Retrieving posts") num = 0 total = 0 for post in parse_hn.iter_top_posts(num_posts=25): if "error" in post: print( f"Error while processing {post['comments_url']}: {type(post['error'])} {repr(post['error'])}" ) continue news.set_progress_msg(f"Processing <{post['content_url']}|{post['title']}>") total += 1 try: should_show = lm.matches_filter( post["title"] + "\n\n" + post["content"], ARTICLE_FILTER ) except Exception as err: print( f"Error while processing {post['comments_url']}: {type(err)} {repr(err)}" ) continue msg = f"{num + 1}. [<{post['comments_url']}|Comments>] <{post['content_url']}|{post['title']}>" if should_show: num += 1 news.lazy_add_line(msg) if num == 0: news.add_line("_No more relevant posts from today._") news.add_line(f"_Checked {total} posts._") news.start_new_section() news.add_line("*/r/MachineLearning:*") news.set_progress_msg("Retrieving posts") num = 0 for post in parse_reddit.iter_top_posts("MachineLearning", num_posts=2): if "error" in post: print( f"Error while processing {post['comments_url']}: {type(post['error'])} {repr(post['error'])}" ) continue news.set_progress_msg(f"Processing <{post['content_url']}|{post['title']}>") msg = f"{num + 1}. [<{post['comments_url']}|Comments>] (+{post['score']}) <{post['content_url']}|{post['title']}>" num += 1 news.lazy_add_line(msg) news.start_new_section() news.add_line(f"*Blogs:*") num = 0 for name, rss_feed in [ ("OpenAI Blog", "https://openai.com/blog/rss.xml"), ("StabilityAI Blog", "https://stability.ai/news?format=rss"), ("Microsoft Research", "https://www.microsoft.com/en-us/research/feed/"), ("Deepmind Blog", "https://deepmind.google/blog/rss.xml"), ("NVIDIA Blog", "https://feeds.feedburner.com/nvidiablog"), ]: news.set_progress_msg(f"Retrieving feed items from {name}")
app = App( client=WebClient( token=os.environ.get("SLACK_BOT_TOKEN"), ssl=ssl.create_default_context(cafile=certifi.where()), ), ) ARTICLE_FILTER = """Articles related to Artificial intelligence (AI), Machine Learning (ML), foundation models, LLMs (large language models), GPT, generation models. """ PAPER_FILTER = """Papers related to: 1. Prompting techniques for language models 2. Techniques for increasing sequence length of transformers. 3. Techniques for optimizing size or efficiency of language models (like quantization or sparsification) """ HELP = """Valid commands are: *`news`* > Pulls from a list of news sources related to AI/ML. *`summarize <url>`* > Given any url, summarizes the content, and searches for related discussions on hacker news. *`arxiv <main category> <sub category> <description of papers to find>`* > Crawls arxiv for papers in the category & sub category that are related to the description that you give. > Main & sub categories can be found on this page <https://arxiv.org/category_taxonomy>. > For example, given the category `cs.AI`, the main category is `cs` and the sub category is `AI`. > Example command: `arxiv cs AI Papers related to Large language models, GPT, and prompting.` *`reddit <subreddit name> <description of posts to find>`* > Crawls a specific subreddit for *top posts over the last day* that match the descrtiption you give. > Example command: `reddit Programming Posts related to security breaches or cyber security.` *`hackernews <description of posts to find>`* > Crawls hackernews for current top stories that match the description you give. > Example command: `hackernews Anything to do with world history, human history, ancient civilizations.` """ @app.event("message") @app.event("app_mention") def handle_app_mention(event): def printl(msg): app.client.chat_postMessage( text=msg, channel=event["channel"], thread_ts=event["ts"], unfurl_links=False, unfurl_media=False, ) # message_changed events happen when slack adds the preview for urls # app_mention's also get an identical message event, but we filter them out by checking for channel_type != im if event["type"] == "message" and ( event["channel_type"] != "im" or event.get("subtype", "") == "message_changed" ): return assert len(event["blocks"]) == 1 assert event["blocks"][0]["type"] == "rich_text" assert len(event["blocks"][0]["elements"]) == 1 assert event["blocks"][0]["elements"][0]["type"] == "rich_text_section" parts = event["blocks"][0]["elements"][0]["elements"] # strip out the app mention part if event["type"] == "app_mention": parts = [p for p in parts if p["type"] != "user"] print("Starting", event["text"]) try: if parts[0]["type"] == "link": _do_summarize( parts[0]["url"], EditableMessage( app.client, event["channel"], "_Working on it..._", ts=event["event_ts"], ), printl, ) print("Finished", event["text"]) return if parts[0]["type"] != "text": printl(f"Unrecognized command `{parts[0]}`. " + HELP) print("Finished", event["text"]) return command = parts[0]["text"].strip() if command == "news": _do_news(channel=event["channel"]) elif ( "summarize" in command or "summary" in command or "explain" in command ) and any(p["type"] == "link" for p in parts): if len(parts) != 2 or parts[1]["type"] != "link": printl("Missing a link to summarize. " + HELP) print("Finished", event["text"]) return _do_summarize( parts[1]["url"], EditableMessage( app.client, event["channel"], "_Working on it..._", ts=event["event_ts"], ), printl, ) elif command.startswith("arxiv"): assert len(parts) == 1 parts = command.split(" ") if len(parts) < 4: printl("Must include a arxiv category and description. " + HELP) print("Finished", event["text"]) return category = parts[1] sub_category = parts[2] description = " ".join(parts[3:]) _arxiv_search(category, sub_category, description, channel=event["channel"]) elif command.startswith("reddit"): assert len(parts) == 1 parts = command.split(" ") if len(parts) < 3: printl("Must include a subreddit name and description. " + HELP) print("Finished", event["text"]) return subreddit_name = parts[1] description = " ".join(parts[2:]) _reddit_search(subreddit_name, description, channel=event["channel"]) elif command.startswith("hackernews"): assert len(parts) == 1 parts = command.split(" ") if len(parts) < 2: printl("Must include a description. " + HELP) print("Finished", event["text"]) return description = " ".join(parts[1:]) _hackernews_search(description, channel=event["channel"]) else: if "thread_ts" in event: ts = event["thread_ts"] else: ts = event["event_ts"] # this is probably a question in a summary thread conversation = app.client.conversations_replies( channel=event["channel"], ts=ts ) _do_interactive( conversation["messages"], EditableMessage( app.client, event["channel"], "_Let me check..._", ts=ts, ), ) except Exception as err: printl(f"Sorry I encountered an error: {type(err)} {repr(err)}") print("Finished", event["text"]) def _do_summarize( url, slack_msg: EditableMessage, printl: Callable[[str], None], model="gpt-3.5-turbo-16k", ): sections = [] content = ( "Unable to access Article - no questions can be answered nor summary provided." ) summary = None try: is_twitter_post = "twitter.com" in url is_reddit_comments = "reddit.com" in url and "comments" in url is_hn_comments = "news.ycombinator.com/item" in url if is_twitter_post: raise util.ScrapePreventedError() elif is_reddit_comments or is_hn_comments: slack_msg.edit_line(f"_Scraping <{url}>..._") if "reddit.com" in url: item = parse_reddit.get_item(url) else: item = parse_hn.get_item(url) content = ( f"[begin Article]\n{item['title']}\n\n{item['content']}\n[end Article]" ) slack_msg.edit_line(f"_Summarizing content..._") summary = lm.summarize_post(item["title"], item["content"]) lines = [ f"*<{item['content_url']}|{item['title']}>* discusses:", summary, "", f"*<{item['comments_url']}|{item['source']}>* has a +{item['score']} discussion", ] if len(item["comments"]) == 0: lines[-1] += ", but there aren't any comments." else: lines[-1] += " centered around:" for i, c in enumerate(item["comments"]): slack_msg.edit_line(f"_Summarizing comment {i + 1}..._") comment_summary = lm.summarize_comment( item["title"], summary, c["content"] ) if "score" in c: lines.append( f"{i + 1}. (+{c['score']}) <{c['url']}|{comment_summary}>" ) else: lines.append(f"{i + 1}. <{c['url']}|{comment_summary}>") sections.append("\n".join(lines)) elif "arxiv.org" in url: # arxiv abstract slack_msg.edit_line(f"_Scraping <{url}>..._") item = parse_arxiv.get_item(url) content = ( f"[begin Article]\n{item['title']}\n\n{item['abstract']}\n[end Article]" ) slack_msg.edit_line(f"_Summarizing abstract..._") summary = lm.summarize_abstract(item["title"], item["abstract"]) sections.append( f"The abstract for *<{url}|{item['title']}>* discusses:\n{summary}" ) elif "youtube.com" in url: slack_msg.edit_line(f"_Scraping <{url}>..._") item = parse_youtube.get_item(url) content = ( f"[begin Article]\n{item['title']}\n\n{item['content']}\n[end Article]" ) slack_msg.edit_line(f"_Summarizing video..._") summary = lm.summarize_post(item["title"], item["content"]) sections.append(f"*<{url}|{item['title']}>* discusses:\n{summary}") else: # generic web page slack_msg.edit_line(f"_Scraping <{url}>..._") item = util.get_details_from_url(url) content = ( f"[begin Article]\n{item['title']}\n\n{item['text']}\n[end Article]" ) slack_msg.edit_line(f"_Summarizing content..._") summary = lm.summarize_post(item["title"], item["text"]) sections.append(f"*<{url}|{item['title']}>* discusses:\n{summary}") except requests.exceptions.HTTPError as err: sections.append( f"I'm unable to access this link for some reason (I get a {err.response.status_code} status code when I request access). Sorry!" ) except util.ScrapePreventedError as err: sections.append(f"This website prevented me accessing its content, sorry!") except requests.exceptions.ReadTimeout as err: sections.append(f"My request to {err.request.url} timed out, sorry!") except Exception as err: sections.append(f"Sorry I encountered an error: {type(err)} {repr(err)}") discussions = [] if not is_hn_comments: slack_msg.edit_line("_Searching for hackernews posts..._") discussions.append(("HackerNews", parse_hn.search_for_url(url))) if not is_reddit_comments: slack_msg.edit_line("_Searching for reddit posts..._") discussions.append(("reddit", parse_reddit.search_for_url(url))) for name, discussion in discussions: if discussion is None: sections.append(f"*{name}* doesn't have a discussion for this url yet.") continue lines = [ f"*<{discussion['comments_url']}|{discussion['source']}>* has a +{discussion['score']} discussion" ] if len(discussion["comments"]) == 0: lines[0] += ", but there aren't any comments." else: lines[0] += " centered around:" for i, c in enumerate(discussion["comments"]): slack_msg.edit_line(f"_Summarizing comment {i + 1} on {name}..._") if summary is not None: comment_summary = lm.summarize_comment( discussion["title"], summary, c["content"] ) else: comment_summary = c["content"][:50].replace("\n", "") + "..." if "score" in c: lines.append( f"{i + 1}. (+{c['score']}) <{c['url']}|{comment_summary}>" ) else: lines.append(f"{i + 1}. <{c['url']}|{comment_summary}>") sections.append("\n".join(lines)) if not is_twitter_post: sections.append( f"You can search for tweets discussing this url on *<https://twitter.com/search?q=url:{url}&src=typed_query|Twitter>*" ) msg = "\n\n".join(sections) slack_msg.edit_line(msg) if summary is None: return chat = ChatOpenAI(model=model, request_timeout=30) response = chat( [ SystemMessage(content=content), AIMessage(content=summary), HumanMessage( content="Suggest 5 follow up questions to learn more about this post. The questions should be answerable based on the content in the article." ), ] ) printl( "Here are some follow up questions to help you dive deeper into this post (tag me and and I can answer them!):\n" + response.content ) def _do_news(channel): news = EditableMessage( app.client, channel, "Here's the latest news from today for you!" ) news.start_new_section() news.add_line("*HackerNews:*") news.set_progress_msg("Retrieving posts") num = 0 total = 0 for post in parse_hn.iter_top_posts(num_posts=25): if "error" in post: print( f"Error while processing {post['comments_url']}: {type(post['error'])} {repr(post['error'])}" ) continue news.set_progress_msg(f"Processing <{post['content_url']}|{post['title']}>") total += 1 try: should_show = lm.matches_filter( post["title"] + "\n\n" + post["content"], ARTICLE_FILTER ) except Exception as err: print( f"Error while processing {post['comments_url']}: {type(err)} {repr(err)}" ) continue msg = f"{num + 1}. [<{post['comments_url']}|Comments>] <{post['content_url']}|{post['title']}>" if should_show: num += 1 news.lazy_add_line(msg) if num == 0: news.add_line("_No more relevant posts from today._") news.add_line(f"_Checked {total} posts._") news.start_new_section() news.add_line("*/r/MachineLearning:*") news.set_progress_msg("Retrieving posts") num = 0 for post in parse_reddit.iter_top_posts("MachineLearning", num_posts=2): if "error" in post: print( f"Error while processing {post['comments_url']}: {type(post['error'])} {repr(post['error'])}" ) continue news.set_progress_msg(f"Processing <{post['content_url']}|{post['title']}>") msg = f"{num + 1}. [<{post['comments_url']}|Comments>] (+{post['score']}) <{post['content_url']}|{post['title']}>" num += 1 news.lazy_add_line(msg) news.start_new_section() news.add_line(f"*Blogs:*") num = 0 for name, rss_feed in [ ("OpenAI Blog", "https://openai.com/blog/rss.xml"), ("StabilityAI Blog", "https://stability.ai/news?format=rss"), ("Microsoft Research", "https://www.microsoft.com/en-us/research/feed/"), ("Deepmind Blog", "https://deepmind.google/blog/rss.xml"), ("NVIDIA Blog", "https://feeds.feedburner.com/nvidiablog"), ]: news.set_progress_msg(f"Retrieving feed items from {name}")
for item in parse_rss.iter_items_from_today(rss_feed):
4
2023-10-31 19:28:44+00:00
8k
ctreude/SoftwareImpactHackathon2023_BiDirectional
main.py
[ { "identifier": "ArXiVDownloader", "path": "src/arxiv.py", "snippet": "class ArXiVDownloader:\n PDFS_FOLDER = \"pdfs\"\n SOURCES_FOLDER = \"sources\"\n SLEEP_TIME = 0.5\n\n def __init__(self):\n self._url_pdf = \"https://arxiv.org/pdf/{arxiv_id}.pdf\"\n self._url_latex = \"http...
import argparse import os from src.arxiv import ArXiVDownloader from src.github import GitHubAPI from src.latex.latex_matcher import LatexMatcher from src.latex.latex_merger import LatexMerger from src.logger import setup_logger from src.pdf.pdf_extractor import PDFExtractor from src.pdf.pdf_matcher import PDFMatcher from src.zenodo import ZenodoAPI
4,769
def download_sources(source_type, query, limit): downloader = ArXiVDownloader() if source_type == "pdf": downloader.download_pdfs(query, limit) elif source_type == "latex": downloader.download_sources(query, limit) elif source_type == "both": downloader.download(query, limit) def run_program(run_type): access_token = os.environ.get("GITHUB_TOKEN") if not access_token: raise Exception( "GitHub token undefined in env var `GITHUB_TOKEN`. Get a new token at https://github.com/settings/tokens and set the env var `GITHUB_TOKEN`." ) github = GitHubAPI(access_token) zenodo = ZenodoAPI() if run_type == "pdf": matcher = PDFMatcher(github, zenodo) elif run_type == "latex": matcher = LatexMatcher(github, zenodo) matcher.run() def extract_pdfs():
def download_sources(source_type, query, limit): downloader = ArXiVDownloader() if source_type == "pdf": downloader.download_pdfs(query, limit) elif source_type == "latex": downloader.download_sources(query, limit) elif source_type == "both": downloader.download(query, limit) def run_program(run_type): access_token = os.environ.get("GITHUB_TOKEN") if not access_token: raise Exception( "GitHub token undefined in env var `GITHUB_TOKEN`. Get a new token at https://github.com/settings/tokens and set the env var `GITHUB_TOKEN`." ) github = GitHubAPI(access_token) zenodo = ZenodoAPI() if run_type == "pdf": matcher = PDFMatcher(github, zenodo) elif run_type == "latex": matcher = LatexMatcher(github, zenodo) matcher.run() def extract_pdfs():
PDFExtractor().run()
5
2023-10-26 16:17:04+00:00
8k
Cuberick-Orion/Bi-Blip4CIR
src/blip_modules/blip.py
[ { "identifier": "VisionTransformer", "path": "src/blip_modules/vit.py", "snippet": "class VisionTransformer(nn.Module):\n \"\"\" Vision Transformer\n A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -\n https://arxiv.org/abs/2010.11929\n \...
import warnings import torch import torch.nn.functional as F import os from .vit import VisionTransformer, interpolate_pos_embed from .med import BertConfig, BertModel, BertLMHeadModel from transformers import BertTokenizer from torch import nn from urllib.parse import urlparse from timm.models.hub import download_cached_file
4,161
def __init__(self, med_config = 'configs/med_config.json', image_size = 384, vit = 'base', vit_grad_ckpt = False, vit_ckpt_layer = 0, prompt = 'a picture of ', ): """ Args: med_config (str): path for the mixture of encoder-decoder model's configuration file image_size (int): input image size vit (str): model size of vision transformer """ super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) self.tokenizer = init_tokenizer() med_config = BertConfig.from_json_file(med_config) med_config.encoder_width = vision_width self.text_decoder = BertLMHeadModel(config=med_config) self.prompt = prompt self.prompt_length = len(self.tokenizer(self.prompt).input_ids)-1 def forward(self, image, caption): image_embeds = self.visual_encoder(image) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) text = self.tokenizer(caption, padding='longest', truncation=True, max_length=40, return_tensors="pt").to(image.device) text.input_ids[:,0] = self.tokenizer.bos_token_id decoder_targets = text.input_ids.masked_fill(text.input_ids == self.tokenizer.pad_token_id, -100) decoder_targets[:,:self.prompt_length] = -100 decoder_output = self.text_decoder(text.input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, labels = decoder_targets, return_dict = True, ) loss_lm = decoder_output.loss return loss_lm def generate(self, image, sample=False, num_beams=3, max_length=30, min_length=10, top_p=0.9, repetition_penalty=1.0): image_embeds = self.visual_encoder(image) if not sample: image_embeds = image_embeds.repeat_interleave(num_beams,dim=0) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) model_kwargs = {"encoder_hidden_states": image_embeds, "encoder_attention_mask":image_atts} prompt = [self.prompt] * image.size(0) input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(image.device) input_ids[:,0] = self.tokenizer.bos_token_id input_ids = input_ids[:, :-1] if sample: #nucleus sampling outputs = self.text_decoder.generate(input_ids=input_ids, max_length=max_length, min_length=min_length, do_sample=True, top_p=top_p, num_return_sequences=1, eos_token_id=self.tokenizer.sep_token_id, pad_token_id=self.tokenizer.pad_token_id, repetition_penalty=1.1, **model_kwargs) else: #beam search outputs = self.text_decoder.generate(input_ids=input_ids, max_length=max_length, min_length=min_length, num_beams=num_beams, eos_token_id=self.tokenizer.sep_token_id, pad_token_id=self.tokenizer.pad_token_id, repetition_penalty=repetition_penalty, **model_kwargs) captions = [] for output in outputs: caption = self.tokenizer.decode(output, skip_special_tokens=True) captions.append(caption[len(self.prompt):]) return captions def blip_decoder(pretrained='',**kwargs): model = BLIP_Decoder(**kwargs) if pretrained: model,msg = load_checkpoint(model,pretrained) assert(len(msg.missing_keys)==0) return model def blip_feature_extractor(pretrained='',**kwargs): model = BLIP_Base(**kwargs) if pretrained: model,msg = load_checkpoint(model,pretrained) assert(len(msg.missing_keys)==0) return model def init_tokenizer(): tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') tokenizer.add_special_tokens({'bos_token':'[DEC]'}) tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']}) tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0] return tokenizer def create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0): assert vit in ['base', 'large'], "vit parameter must be base or large" if vit=='base': vision_width = 768
''' * Copyright (c) 2022, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause * By Junnan Li ''' warnings.filterwarnings("ignore") class BLIP_Base(nn.Module): def __init__(self, med_config = 'configs/med_config.json', image_size = 224, vit = 'base', vit_grad_ckpt = False, vit_ckpt_layer = 0, ): """ Args: med_config (str): path for the mixture of encoder-decoder model's configuration file image_size (int): input image size vit (str): model size of vision transformer """ super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) self.tokenizer = init_tokenizer() med_config = BertConfig.from_json_file(med_config) med_config.encoder_width = vision_width self.text_encoder = BertModel(config=med_config, add_pooling_layer=False) def forward(self, image, caption, mode): assert mode in ['image', 'text', 'multimodal'], "mode parameter must be image, text, or multimodal" text = self.tokenizer(caption, return_tensors="pt").to(image.device) if mode=='image': # return image features image_embeds = self.visual_encoder(image) return image_embeds elif mode=='text': # return text features text_output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, return_dict = True, mode = 'text') return text_output.last_hidden_state elif mode=='multimodal': # return multimodel features image_embeds = self.visual_encoder(image) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) text.input_ids[:,0] = self.tokenizer.enc_token_id output = self.text_encoder(text.input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, return_dict = True, ) return output.last_hidden_state class BLIP_Decoder(nn.Module): def __init__(self, med_config = 'configs/med_config.json', image_size = 384, vit = 'base', vit_grad_ckpt = False, vit_ckpt_layer = 0, prompt = 'a picture of ', ): """ Args: med_config (str): path for the mixture of encoder-decoder model's configuration file image_size (int): input image size vit (str): model size of vision transformer """ super().__init__() self.visual_encoder, vision_width = create_vit(vit,image_size, vit_grad_ckpt, vit_ckpt_layer) self.tokenizer = init_tokenizer() med_config = BertConfig.from_json_file(med_config) med_config.encoder_width = vision_width self.text_decoder = BertLMHeadModel(config=med_config) self.prompt = prompt self.prompt_length = len(self.tokenizer(self.prompt).input_ids)-1 def forward(self, image, caption): image_embeds = self.visual_encoder(image) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) text = self.tokenizer(caption, padding='longest', truncation=True, max_length=40, return_tensors="pt").to(image.device) text.input_ids[:,0] = self.tokenizer.bos_token_id decoder_targets = text.input_ids.masked_fill(text.input_ids == self.tokenizer.pad_token_id, -100) decoder_targets[:,:self.prompt_length] = -100 decoder_output = self.text_decoder(text.input_ids, attention_mask = text.attention_mask, encoder_hidden_states = image_embeds, encoder_attention_mask = image_atts, labels = decoder_targets, return_dict = True, ) loss_lm = decoder_output.loss return loss_lm def generate(self, image, sample=False, num_beams=3, max_length=30, min_length=10, top_p=0.9, repetition_penalty=1.0): image_embeds = self.visual_encoder(image) if not sample: image_embeds = image_embeds.repeat_interleave(num_beams,dim=0) image_atts = torch.ones(image_embeds.size()[:-1],dtype=torch.long).to(image.device) model_kwargs = {"encoder_hidden_states": image_embeds, "encoder_attention_mask":image_atts} prompt = [self.prompt] * image.size(0) input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(image.device) input_ids[:,0] = self.tokenizer.bos_token_id input_ids = input_ids[:, :-1] if sample: #nucleus sampling outputs = self.text_decoder.generate(input_ids=input_ids, max_length=max_length, min_length=min_length, do_sample=True, top_p=top_p, num_return_sequences=1, eos_token_id=self.tokenizer.sep_token_id, pad_token_id=self.tokenizer.pad_token_id, repetition_penalty=1.1, **model_kwargs) else: #beam search outputs = self.text_decoder.generate(input_ids=input_ids, max_length=max_length, min_length=min_length, num_beams=num_beams, eos_token_id=self.tokenizer.sep_token_id, pad_token_id=self.tokenizer.pad_token_id, repetition_penalty=repetition_penalty, **model_kwargs) captions = [] for output in outputs: caption = self.tokenizer.decode(output, skip_special_tokens=True) captions.append(caption[len(self.prompt):]) return captions def blip_decoder(pretrained='',**kwargs): model = BLIP_Decoder(**kwargs) if pretrained: model,msg = load_checkpoint(model,pretrained) assert(len(msg.missing_keys)==0) return model def blip_feature_extractor(pretrained='',**kwargs): model = BLIP_Base(**kwargs) if pretrained: model,msg = load_checkpoint(model,pretrained) assert(len(msg.missing_keys)==0) return model def init_tokenizer(): tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') tokenizer.add_special_tokens({'bos_token':'[DEC]'}) tokenizer.add_special_tokens({'additional_special_tokens':['[ENC]']}) tokenizer.enc_token_id = tokenizer.additional_special_tokens_ids[0] return tokenizer def create_vit(vit, image_size, use_grad_checkpointing=False, ckpt_layer=0, drop_path_rate=0): assert vit in ['base', 'large'], "vit parameter must be base or large" if vit=='base': vision_width = 768
visual_encoder = VisionTransformer(img_size=image_size, patch_size=16, embed_dim=vision_width, depth=12,
0
2023-10-25 04:19:15+00:00
8k
medsagou/massar-direction-sagoubot
main_noGUI.py
[ { "identifier": "Massar_Direction_Sagou", "path": "Interaction_browser/interaction.py", "snippet": "class Massar_Direction_Sagou:\n def __init__(self, driver: webdriver =\"\", console=\"\"):\n self.driver = driver\n self.console = console\n return\n\n def get_driver(self):\n ...
import sys from Interaction_browser import Massar_Direction_Sagou from absence_app import Absence from utilities import User_Interface from absence_app import Read_Db
6,205
def main(): ui = User_Interface() # main menu while True: # ui.clear_screen() main_choice_1, main_choice_1_value = ui.main_menu() if str(main_choice_1) == "1": while True: ui.clear_screen() choice01, choice01_value = ui.menu01() if str(choice01) == "1": reader = Read_Db() reader.fill_all_class_sheets() elif str(choice01) == "2": choice02, choice02_value = ui.menu_valider() if str(choice02) == "1":
def main(): ui = User_Interface() # main menu while True: # ui.clear_screen() main_choice_1, main_choice_1_value = ui.main_menu() if str(main_choice_1) == "1": while True: ui.clear_screen() choice01, choice01_value = ui.menu01() if str(choice01) == "1": reader = Read_Db() reader.fill_all_class_sheets() elif str(choice01) == "2": choice02, choice02_value = ui.menu_valider() if str(choice02) == "1":
interaction_object = Massar_Direction_Sagou()
0
2023-10-29 18:10:27+00:00
8k
hsma-programme/Teaching_DES_Concepts_Streamlit
pages/1_🚶‍♂️_Simulating_Arrivals.py
[ { "identifier": "add_logo", "path": "helper_functions.py", "snippet": "def add_logo():\n '''\n Add a logo at the top of the page navigation sidebar\n\n Approach written by blackary on\n https://discuss.streamlit.io/t/put-logo-and-title-above-on-top-of-page-navigation-in-sidebar-of-multipage-...
import time import asyncio import datetime as dt import gc import numpy as np import plotly.express as px import pandas as pd import streamlit as st from helper_functions import add_logo, mermaid, center_running from model_classes import Scenario, multiple_replications from distribution_classes import Exponential
4,117
''' A Streamlit application based on Monks and Allows users to interact with an increasingly more complex treatment simulation ''' st.set_page_config( page_title="Simulating Arrivals", layout="wide", initial_sidebar_state="expanded", ) add_logo() center_running() # try: # running_on_st_community = st.secrets["IS_ST_COMMUNITY"] # except FileNotFoundError: # running_on_st_community = False with open("style.css") as css: st.markdown(f'<style>{css.read()}</style>', unsafe_allow_html=True) # We add in a title for our web app's page st.title("Discrete Event Simulation Playground") st.subheader("Simulating Patients Arriving at the Centre") gc.collect() tab1, tab2, tab3 = st.tabs(["Playground", "Exercise", "Information"]) with tab3: st.markdown( "Let's start with just having some patients arriving into our treatment centre.") mermaid(height=350, code=""" %%{ init: { 'flowchart': { 'curve': 'step'} } }%% %%{ init: { 'theme': 'base', 'themeVariables': {'lineColor': '#b4b4b4'} } }%% flowchart LR A[Arrival] --> B{Trauma or non-trauma} B --> B1{Trauma Pathway} B --> B2{Non-Trauma Pathway} B1 --> C[Stabilisation] C --> E[Treatment] E ----> F B2 --> D[Registration] D --> G[Examination] G --> H[Treat?] H ----> F[Discharge] H --> I[Non-Trauma Treatment] I --> F C -.-> Z([Trauma Room]) Z -.-> C E -.-> Y([Cubicle - 1]) Y -.-> E D -.-> X([Clerks]) X -.-> D G -.-> W([Exam Room]) W -.-> G I -.-> V([Cubicle - 2]) V -.-> I classDef highlight fill:#02CD55,stroke:#E8AD02,stroke-width:4px,color:#0C0D11,font-size:12pt,font-family:lexend; classDef unlight fill:#b4b4b4,stroke:#787878,stroke-width:2px,color:#787878,font-size:6pt,font-family:lexend; class A highlight; class B,B1,B2,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z unlight; """ ) st.markdown( """ To start with, we need to create some simulated patients who will turn up to our centre. To simulate patient arrivals, we will use the exponential distribution, which looks a bit like this. """ )
''' A Streamlit application based on Monks and Allows users to interact with an increasingly more complex treatment simulation ''' st.set_page_config( page_title="Simulating Arrivals", layout="wide", initial_sidebar_state="expanded", ) add_logo() center_running() # try: # running_on_st_community = st.secrets["IS_ST_COMMUNITY"] # except FileNotFoundError: # running_on_st_community = False with open("style.css") as css: st.markdown(f'<style>{css.read()}</style>', unsafe_allow_html=True) # We add in a title for our web app's page st.title("Discrete Event Simulation Playground") st.subheader("Simulating Patients Arriving at the Centre") gc.collect() tab1, tab2, tab3 = st.tabs(["Playground", "Exercise", "Information"]) with tab3: st.markdown( "Let's start with just having some patients arriving into our treatment centre.") mermaid(height=350, code=""" %%{ init: { 'flowchart': { 'curve': 'step'} } }%% %%{ init: { 'theme': 'base', 'themeVariables': {'lineColor': '#b4b4b4'} } }%% flowchart LR A[Arrival] --> B{Trauma or non-trauma} B --> B1{Trauma Pathway} B --> B2{Non-Trauma Pathway} B1 --> C[Stabilisation] C --> E[Treatment] E ----> F B2 --> D[Registration] D --> G[Examination] G --> H[Treat?] H ----> F[Discharge] H --> I[Non-Trauma Treatment] I --> F C -.-> Z([Trauma Room]) Z -.-> C E -.-> Y([Cubicle - 1]) Y -.-> E D -.-> X([Clerks]) X -.-> D G -.-> W([Exam Room]) W -.-> G I -.-> V([Cubicle - 2]) V -.-> I classDef highlight fill:#02CD55,stroke:#E8AD02,stroke-width:4px,color:#0C0D11,font-size:12pt,font-family:lexend; classDef unlight fill:#b4b4b4,stroke:#787878,stroke-width:2px,color:#787878,font-size:6pt,font-family:lexend; class A highlight; class B,B1,B2,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z unlight; """ ) st.markdown( """ To start with, we need to create some simulated patients who will turn up to our centre. To simulate patient arrivals, we will use the exponential distribution, which looks a bit like this. """ )
exp_dist = Exponential(mean=5)
5
2023-10-26 09:57:52+00:00
8k
chenhao-zju/PMNet
train.py
[ { "identifier": "DAM", "path": "model/DAM.py", "snippet": "class DAM(nn.Module):\n\n def __init__(self, backbone, pretrained_path, use_original_imgsize, original=True, \n add_4dconv=False, skip_mode='concat', \n pooling_mix='concat', mixing_mode='concat',...
import torch.optim as optim import torch.nn as nn import torch from model.DAM import DAM from common.logger import Logger, AverageMeter from common.vis import Visualizer from common.evaluation import Evaluator from common.config import parse_opts from common import utils from data.dataset import FSSDataset
7,163
r""" training (validation) code """ def train(args, epoch, model, dataloader, optimizer, training, add_loss=True, k=1., nshot=1): r""" Train """ # Force randomness during training / freeze randomness during testing utils.fix_randseed(None) if training else utils.fix_randseed(0) model.module.train_mode() if training else model.module.eval() average_meter = AverageMeter(dataloader.dataset) for idx, batch in enumerate(dataloader): # 1. forward pass batch = utils.to_cuda(batch) if nshot==1: logit_mask = model(batch['query_img'], batch['query_mask'], batch['support_imgs'].squeeze(1), batch['support_masks'].squeeze(1)) else: logit_mask = model.module.predict_mask_nshot(batch, nshot=nshot) if add_loss: logit_mask, mid_loss, _ = logit_mask pred_mask = logit_mask.argmax(dim=1) # 2. Compute loss & update model parameters loss = model.module.compute_objective(logit_mask, batch['query_mask']) if add_loss: loss = loss + k*mid_loss if training: optimizer.zero_grad() loss.backward() optimizer.step() # 3. Evaluate prediction
r""" training (validation) code """ def train(args, epoch, model, dataloader, optimizer, training, add_loss=True, k=1., nshot=1): r""" Train """ # Force randomness during training / freeze randomness during testing utils.fix_randseed(None) if training else utils.fix_randseed(0) model.module.train_mode() if training else model.module.eval() average_meter = AverageMeter(dataloader.dataset) for idx, batch in enumerate(dataloader): # 1. forward pass batch = utils.to_cuda(batch) if nshot==1: logit_mask = model(batch['query_img'], batch['query_mask'], batch['support_imgs'].squeeze(1), batch['support_masks'].squeeze(1)) else: logit_mask = model.module.predict_mask_nshot(batch, nshot=nshot) if add_loss: logit_mask, mid_loss, _ = logit_mask pred_mask = logit_mask.argmax(dim=1) # 2. Compute loss & update model parameters loss = model.module.compute_objective(logit_mask, batch['query_mask']) if add_loss: loss = loss + k*mid_loss if training: optimizer.zero_grad() loss.backward() optimizer.step() # 3. Evaluate prediction
area_inter, area_union = Evaluator.classify_prediction(pred_mask, batch)
4
2023-10-26 03:14:47+00:00
8k
hyperspy/exspy
exspy/signals/eels.py
[ { "identifier": "EELSMODEL_PARAMETERS", "path": "exspy/docstrings/model.py", "snippet": "EELSMODEL_PARAMETERS = \"\"\"ll : None or EELSSpectrum\n If an EELSSpectrum is provided, it will be assumed that it is\n a low-loss EELS spectrum, and it will be used to simulate the\n ...
import numbers import logging import numpy as np import dask.array as da import traits.api as t import hyperspy.api as hs import hyperspy.axes from scipy import constants from prettytable import PrettyTable from matplotlib.collections import LineCollection from hyperspy.signal import BaseSetMetadataItems, BaseSignal from hyperspy._signals.signal1d import Signal1D, LazySignal1D from hyperspy.components1d import PowerLaw from hyperspy.misc.utils import display, isiterable, underline from hyperspy.misc.math_tools import optimal_fft_size from hyperspy.ui_registry import add_gui_method, DISPLAY_DT, TOOLKIT_DT from hyperspy.utils.markers import Texts, Lines from hyperspy.docstrings.signal1d import ( CROP_PARAMETER_DOC, SPIKES_DIAGNOSIS_DOCSTRING, MASK_ZERO_LOSS_PEAK_WIDTH, SPIKES_REMOVAL_TOOL_DOCSTRING, ) from hyperspy.docstrings.signal import ( SHOW_PROGRESSBAR_ARG, NUM_WORKERS_ARG, SIGNAL_MASK_ARG, NAVIGATION_MASK_ARG, LAZYSIGNAL_DOC, ) from exspy.docstrings.model import EELSMODEL_PARAMETERS from exspy.misc.elements import elements as elements_db from exspy.misc.eels.tools import get_edges_near_energy from exspy.misc.eels.electron_inelastic_mean_free_path import ( iMFP_Iakoubovskii, iMFP_angular_correction, ) from exspy.signal_tools import EdgesRange from scipy.integrate import simps from hyperspy.components1d import Gaussian from exspy.models.eelsmodel import EELSModel from scipy.ndimage import binary_dilation, binary_erosion
5,939
# Create threshold with the same shape as the navigation dims. threshold = self._get_navigation_signal().transpose(signal_axes=0) # Progress Bar axis = self.axes_manager.signal_axes[0] min_index, max_index = axis.value_range_to_indices(start, start + window) if max_index < min_index + 10: raise ValueError("Please select a bigger window") s = self.isig[min_index:max_index].deepcopy() if window_length: s.smooth_savitzky_golay( polynomial_order=polynomial_order, window_length=window_length, differential_order=1, ) else: s = s.derivative(-1) if tol is None: tol = np.max(abs(s.data).min(axis.index_in_array)) saxis = s.axes_manager[-1] inflexion = (abs(s.data) <= tol).argmax(saxis.index_in_array) if isinstance(inflexion, da.Array): inflexion = inflexion.compute() threshold.data[:] = saxis.index2value(inflexion) if isinstance(inflexion, np.ndarray): threshold.data[inflexion == 0] = np.nan else: # Single spectrum if inflexion == 0: threshold.data[:] = np.nan del s if np.isnan(threshold.data).any(): _logger.warning( "No inflexion point could be found in some positions " "that have been marked with nans." ) # Create spectrum image, stop and return value threshold.metadata.General.title = ( self.metadata.General.title + " elastic scattering threshold" ) if self.tmp_parameters.has_item("filename"): threshold.tmp_parameters.filename = ( self.tmp_parameters.filename + "_elastic_scattering_threshold" ) threshold.tmp_parameters.folder = self.tmp_parameters.folder threshold.tmp_parameters.extension = self.tmp_parameters.extension threshold.set_signal_type("") return threshold def estimate_thickness( self, threshold=None, zlp=None, density=None, mean_free_path=None, ): """Estimates the thickness (relative and absolute) of a sample using the log-ratio method. The current EELS spectrum must be a low-loss spectrum containing the zero-loss peak. The hyperspectrum must be well calibrated and aligned. To obtain the thickness relative to the mean free path don't set the `density` and the `mean_free_path`. Parameters ---------- threshold : {BaseSignal, float}, optional If the zero-loss-peak is not provided, use this energy threshold to roughly estimate its intensity by truncation. If the threshold is constant across the dataset use a float. Otherwise, provide a signal of the same dimension as the input spectrum navigation space containing the threshold value in the energy units. zlp : BaseSignal, optional If not None the zero-loss peak intensity is calculated from the ZLP spectrum supplied by integration. mean_free_path : float, optional The mean free path of the material in nanometers. If not provided, the thickness is given relative to the mean free path. density : float, optional The density of the material in g/cm**3. This is used to estimate the mean free path when the mean free path is not known and to perform the angular corrections. Returns ------- s : BaseSignal The thickness relative to the MFP. It returns a Signal1D, Signal2D or a BaseSignal, depending on the current navigation dimensions. Notes ----- For details see Egerton, R. Electron Energy-Loss Spectroscopy in the Electron Microscope. Springer-Verlag, 2011. """ axis = self.axes_manager.signal_axes[0] total_intensity = self.integrate1D(axis.index_in_array).data if threshold is None and zlp is None: raise ValueError( "Please provide one of the following keywords: " "`threshold`, `zlp`" ) if zlp is not None: I0 = zlp.integrate1D(axis.index_in_array).data else: I0 = self.estimate_elastic_scattering_intensity( threshold=threshold, ).data t_over_lambda = np.log(total_intensity / I0) if density is not None: if self._are_microscope_parameters_missing(): raise RuntimeError( "Some microscope parameters are missing. Please use the " "`set_microscope_parameters()` method to set them. " "If you don't know them, don't set the `density` keyword." ) else: md = self.metadata.Acquisition_instrument.TEM
# -*- coding: utf-8 -*- # Copyright 2007-2023 The exSpy developers # # This file is part of exSpy. # # exSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # exSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with exSpy. If not, see <https://www.gnu.org/licenses/#GPL>. _logger = logging.getLogger(__name__) @add_gui_method(toolkey="exspy.microscope_parameters_EELS") class EELSTEMParametersUI(BaseSetMetadataItems): convergence_angle = t.Float(t.Undefined, label="Convergence semi-angle (mrad)") beam_energy = t.Float(t.Undefined, label="Beam energy (keV)") collection_angle = t.Float(t.Undefined, label="Collection semi-angle (mrad)") mapping = { "Acquisition_instrument.TEM.convergence_angle": "convergence_angle", "Acquisition_instrument.TEM.beam_energy": "beam_energy", "Acquisition_instrument.TEM.Detector.EELS.collection_angle": "collection_angle", } class EELSSpectrum(Signal1D): """Signal class for EELS spectra.""" _signal_type = "EELS" _alias_signal_types = ["TEM EELS"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Attributes defaults self.subshells = set() self.elements = set() self.edges = list() if hasattr(self.metadata, "Sample") and hasattr( self.metadata.Sample, "elements" ): self.add_elements(self.metadata.Sample.elements) self.axes_manager.signal_axes[0].is_binned = True self._edge_markers = {"names": [], "lines": None, "texts": None} def add_elements(self, elements, include_pre_edges=False): """Declare the elemental composition of the sample. The ionisation edges of the elements present in the current energy range will be added automatically. Parameters ---------- elements : tuple of strings The symbol of the elements. Note this input must always be in the form of a tuple. Meaning: add_elements(('C',)) will work, while add_elements(('C')) will NOT work. include_pre_edges : bool If True, the ionization edges with an onset below the lower energy limit of the SI will be included Examples -------- >>> s = hs.signals.EELSSpectrum(np.arange(1024)) >>> s.add_elements(('C', 'O')) Raises ------ ValueError """ if not isiterable(elements) or isinstance(elements, str): raise ValueError( "Input must be in the form of a tuple. For example, " "if `s` is the variable containing this EELS spectrum:\n " ">>> s.add_elements(('C',))\n" "See the docstring for more information." ) for element in elements: if isinstance(element, bytes): element = element.decode() if element in elements_db: self.elements.add(element) else: raise ValueError( "%s is not a valid symbol of a chemical element" % element ) if not hasattr(self.metadata, "Sample"): self.metadata.add_node("Sample") self.metadata.Sample.elements = list(self.elements) if self.elements: self.generate_subshells(include_pre_edges) def generate_subshells(self, include_pre_edges=False): """Calculate the subshells for the current energy range for the elements present in self.elements Parameters ---------- include_pre_edges : bool If True, the ionization edges with an onset below the lower energy limit of the SI will be included """ Eaxis = self.axes_manager.signal_axes[0].axis if not include_pre_edges: start_energy = Eaxis[0] else: start_energy = 0.0 end_energy = Eaxis[-1] for element in self.elements: e_shells = list() for shell in elements_db[element]["Atomic_properties"]["Binding_energies"]: if shell[-1] != "a": energy = elements_db[element]["Atomic_properties"][ "Binding_energies" ][shell]["onset_energy (eV)"] if start_energy <= energy <= end_energy: subshell = "%s_%s" % (element, shell) if subshell not in self.subshells: self.subshells.add("%s_%s" % (element, shell)) e_shells.append(subshell) def edges_at_energy( self, energy="interactive", width=10, only_major=False, order="closest", display=True, toolkit=None, ): """Show EELS edges according to an energy range selected from the spectrum or within a provided energy window Parameters ---------- energy : 'interactive' or float If it is 'interactive', a table with edges are shown and it depends on the energy range selected in the spectrum. If it is a float, a table with edges are shown and it depends on the energy window defined by energy +/- (width/2). The default is 'interactive'. width : float Width of window, in eV, around energy in which to find nearby energies, i.e. a value of 10 eV (the default) means to search +/- 5 eV. The default is 10. only_major : bool Whether to show only the major edges. The default is False. order : str Sort the edges, if 'closest', return in the order of energy difference, if 'ascending', return in ascending order, similarly for 'descending'. The default is 'closest'. Returns ------- An interactive widget if energy is 'interactive', or a html-format table or ASCII table, depends on the environment. """ if energy == "interactive": er = EdgesRange(self, interactive=True) return er.gui(display=display, toolkit=toolkit) else: self.print_edges_near_energy(energy, width, only_major, order) @staticmethod def print_edges_near_energy( energy=None, width=10, only_major=False, order="closest", edges=None ): """Find and print a table of edges near a given energy that are within the given energy window. Parameters ---------- energy : float Energy to search, in eV width : float Width of window, in eV, around energy in which to find nearby energies, i.e. a value of 10 eV (the default) means to search +/- 5 eV. The default is 10. only_major : bool Whether to show only the major edges. The default is False. order : str Sort the edges, if 'closest', return in the order of energy difference, if 'ascending', return in ascending order, similarly for 'descending'. The default is 'closest'. edges : iterable A sequence of edges, if provided, it overrides energy, width, only_major and order. Returns ------- A PrettyText object where its representation is ASCII in terminal and html-formatted in Jupyter notebook """ if edges is None and energy is not None: edges = get_edges_near_energy( energy=energy, width=width, only_major=only_major, order=order ) elif edges is None and energy is None: raise ValueError("Either energy or edges should be provided.") table = PrettyTable() table.field_names = ["edge", "onset energy (eV)", "relevance", "description"] for edge in edges: element, shell = edge.split("_") shell_dict = elements_db[element]["Atomic_properties"]["Binding_energies"][ shell ] onset = shell_dict["onset_energy (eV)"] relevance = shell_dict["relevance"] threshold = shell_dict["threshold"] edge_ = shell_dict["edge"] description = threshold + ". " * (threshold != "" and edge_ != "") + edge_ table.add_row([edge, onset, relevance, description]) # this ensures the html version try its best to mimick the ASCII one table.format = True display(table) def estimate_zero_loss_peak_centre(self, mask=None): """Estimate the position of the zero-loss peak. This function provides just a coarse estimation of the position of the zero-loss peak centre by computing the position of the maximum of the spectra. For subpixel accuracy use `estimate_shift1D`. Parameters ---------- mask : Signal1D of bool data type or bool array It must have signal_dimension = 0 and navigation_shape equal to the navigation shape of the current signal. Where mask is True the shift is not computed and set to nan. Returns ------- zlpc : Signal1D subclass The estimated position of the maximum of the ZLP peak. Notes ----- This function only works when the zero-loss peak is the most intense feature in the spectrum. If it is not in most cases the spectrum can be cropped to meet this criterion. Alternatively use `estimate_shift1D`. See Also -------- estimate_shift1D, align_zero_loss_peak """ self._check_signal_dimension_equals_one() self._check_navigation_mask(mask) if isinstance(mask, BaseSignal): mask = mask.data zlpc = self.valuemax(-1) if mask is not None: zlpc.data = np.where(mask, np.nan, zlpc.data) zlpc.set_signal_type("") title = self.metadata.General.title zlpc.metadata.General.title = "ZLP(%s)" % title return zlpc def align_zero_loss_peak( self, calibrate=True, also_align=[], print_stats=True, subpixel=True, mask=None, signal_range=None, show_progressbar=None, crop=True, **kwargs, ): """Align the zero-loss peak. This function first aligns the spectra using the result of `estimate_zero_loss_peak_centre` which finds the maximum in the given energy range, then if subpixel is True, proceeds to align with subpixel accuracy using `align1D`. The offset is automatically correct if `calibrate` is True. Parameters ---------- calibrate : bool If True, set the offset of the spectral axis so that the zero-loss peak is at position zero. also_align : list of signals A list containing other spectra of identical dimensions to align using the shifts applied to the current spectrum. If `calibrate` is True, the calibration is also applied to the spectra in the list. print_stats : bool If True, print summary statistics of the ZLP maximum before the alignment. subpixel : bool If True, perform the alignment with subpixel accuracy using cross-correlation. mask : Signal1D of bool data type or bool array. It must have signal_dimension = 0 and navigation_shape equal to the shape of the current signal. Where mask is True the shift is not computed and set to nan. signal_range : tuple of integers, tuple of floats. Optional Will only search for the ZLP within the signal_range. If given in integers, the range will be in index values. If given floats, the range will be in spectrum values. Useful if there are features in the spectrum which are more intense than the ZLP. Default is searching in the whole signal. Note that ROIs can be used in place of a tuple. %s %s Raises ------ NotImplementedError If the signal axis is a non-uniform axis. Examples -------- >>> s_ll = hs.signals.EELSSpectrum(np.zeros(1000)) >>> s_ll.data[100] = 100 >>> s_ll.align_zero_loss_peak() Aligning both the lowloss signal and another signal >>> s = hs.signals.EELSSpectrum(np.range(1000)) >>> s_ll.align_zero_loss_peak(also_align=[s]) Aligning within a narrow range of the lowloss signal >>> s_ll.align_zero_loss_peak(signal_range=(-10.,10.)) See Also -------- estimate_zero_loss_peak_centre, align1D, estimate_shift1D. Notes ----- Any extra keyword arguments are passed to `align1D`. For more information read its docstring. """ def substract_from_offset(value, signals): # Test that axes is uniform if not self.axes_manager[-1].is_uniform: raise NotImplementedError( "Support for EELS signals with " "non-uniform signal axes is not yet implemented." ) if isinstance(value, da.Array): value = value.compute() for signal in signals: signal.axes_manager[-1].offset -= value signal.events.data_changed.trigger(signal) def estimate_zero_loss_peak_centre(s, mask, signal_range): if signal_range: zlpc = s.isig[ signal_range[0] : signal_range[1] ].estimate_zero_loss_peak_centre(mask=mask) else: zlpc = s.estimate_zero_loss_peak_centre(mask=mask) return zlpc zlpc = estimate_zero_loss_peak_centre( self, mask=mask, signal_range=signal_range ) mean_ = np.nanmean(zlpc.data) if print_stats is True: print(underline("Initial ZLP position statistics")) zlpc.print_summary_statistics() for signal in also_align + [self]: shift_array = -zlpc.data + mean_ if zlpc._lazy: # We must compute right now because otherwise any changes to the # axes_manager of the signal later in the workflow may result in # a wrong shift_array shift_array = shift_array.compute() signal.shift1D(shift_array, crop=crop, show_progressbar=show_progressbar) if calibrate is True: zlpc = estimate_zero_loss_peak_centre( self, mask=mask, signal_range=signal_range ) substract_from_offset(np.nanmean(zlpc.data), also_align + [self]) if subpixel is False: return start, end = signal_range or (-3.0, 3.0) if calibrate is False: start += mean_ end += mean_ start = ( start if start > self.axes_manager[-1].axis[0] else self.axes_manager[-1].axis[0] ) end = ( end if end < self.axes_manager[-1].axis[-1] else self.axes_manager[-1].axis[-1] ) if self.axes_manager.navigation_size > 1: self.align1D( start, end, also_align=also_align, show_progressbar=show_progressbar, mask=mask, crop=crop, **kwargs, ) if calibrate is True: zlpc = estimate_zero_loss_peak_centre( self, mask=mask, signal_range=signal_range ) substract_from_offset(np.nanmean(zlpc.data), also_align + [self]) align_zero_loss_peak.__doc__ %= (SHOW_PROGRESSBAR_ARG, CROP_PARAMETER_DOC) def get_zero_loss_peak_mask(self, zero_loss_peak_mask_width=5.0, signal_mask=None): """Return boolean array with True value at the position of the zero loss peak. This mask can be used to restrict operation to the signal locations not marked as True (masked). Parameters ---------- zero_loss_peak_mask_width: float Width of the zero loss peak mask. %s Returns ------- bool array """ zlpc = self.estimate_zero_loss_peak_centre() (signal_axis,) = self.axes_manager[self.axes_manager.signal_axes] axis = signal_axis.axis mini_value = zlpc.data.mean() - zero_loss_peak_mask_width / 2 maxi_value = zlpc.data.mean() + zero_loss_peak_mask_width / 2 mask = np.logical_and(mini_value <= axis, axis <= maxi_value) if signal_mask is not None: signal_mask = np.logical_or(mask, signal_mask) else: signal_mask = mask return signal_mask get_zero_loss_peak_mask.__doc__ %= SIGNAL_MASK_ARG def spikes_diagnosis( self, signal_mask=None, navigation_mask=None, zero_loss_peak_mask_width=None, **kwargs, ): if zero_loss_peak_mask_width is not None: signal_mask = self.get_zero_loss_peak_mask( zero_loss_peak_mask_width, signal_mask ) super().spikes_diagnosis( signal_mask=signal_mask, navigation_mask=None, **kwargs ) spikes_diagnosis.__doc__ = SPIKES_DIAGNOSIS_DOCSTRING % MASK_ZERO_LOSS_PEAK_WIDTH def spikes_removal_tool( self, signal_mask=None, navigation_mask=None, threshold="auto", zero_loss_peak_mask_width=None, interactive=True, display=True, toolkit=None, ): if zero_loss_peak_mask_width is not None: axis = self.axes_manager.signal_axes[0].axis # check the zero_loss is in the signal if ( axis[0] - zero_loss_peak_mask_width / 2 > 0 or axis[-1] + zero_loss_peak_mask_width / 2 < 0 ): raise ValueError("The zero loss peaks isn't in the energy range.") signal_mask = self.get_zero_loss_peak_mask( zero_loss_peak_mask_width, signal_mask ) super().spikes_removal_tool( signal_mask=signal_mask, navigation_mask=navigation_mask, threshold=threshold, interactive=interactive, display=display, toolkit=toolkit, ) spikes_removal_tool.__doc__ = SPIKES_REMOVAL_TOOL_DOCSTRING % ( SIGNAL_MASK_ARG, NAVIGATION_MASK_ARG, MASK_ZERO_LOSS_PEAK_WIDTH, DISPLAY_DT, TOOLKIT_DT, ) def estimate_elastic_scattering_intensity(self, threshold, show_progressbar=None): """Rough estimation of the elastic scattering intensity by truncation of a EELS low-loss spectrum. Parameters ---------- threshold : {Signal1D, float, int} Truncation energy to estimate the intensity of the elastic scattering. The threshold can be provided as a signal of the same dimension as the input spectrum navigation space containing the threshold value in the energy units. Alternatively a constant threshold can be specified in energy/index units by passing float/int. %s Returns ------- I0: Signal1D The elastic scattering intensity. See Also -------- estimate_elastic_scattering_threshold """ # TODO: Write units tests self._check_signal_dimension_equals_one() if show_progressbar is None: show_progressbar = hs.preferences.General.show_progressbar if isinstance(threshold, numbers.Number): I0 = self.isig[:threshold].integrate1D(-1) else: ax = self.axes_manager.signal_axes[0] # I0 = self._get_navigation_signal() # I0 = I0.transpose(signal_axes=[]) threshold = threshold.transpose(signal_axes=[]) binned = ax.is_binned def estimating_function(data, threshold=None): if np.isnan(threshold): return np.nan else: # the object is just an array, so have to reimplement # integrate1D. However can make certain assumptions, for # example 1D signal and pretty much always binned. Should # probably at some point be joint ind = ax.value2index(threshold) data = data[:ind] if binned: return data.sum() else: axis = ax.axis[:ind] return simps(y=data, x=axis) I0 = self.map( estimating_function, threshold=threshold, ragged=False, show_progressbar=show_progressbar, inplace=False, ) I0.metadata.General.title = self.metadata.General.title + " elastic intensity" I0.set_signal_type("") if self.tmp_parameters.has_item("filename"): I0.tmp_parameters.filename = ( self.tmp_parameters.filename + "_elastic_intensity" ) I0.tmp_parameters.folder = self.tmp_parameters.folder I0.tmp_parameters.extension = self.tmp_parameters.extension return I0 estimate_elastic_scattering_intensity.__doc__ %= SHOW_PROGRESSBAR_ARG def estimate_elastic_scattering_threshold( self, window=10.0, tol=None, window_length=5, polynomial_order=3, start=1.0 ): """Calculate the first inflexion point of the spectrum derivative within a window. This method assumes that the zero-loss peak is located at position zero in all the spectra. Currently it looks for an inflexion point, that can be a local maximum or minimum. Therefore, to estimate the elastic scattering threshold `start` + `window` must be less than the first maximum for all spectra (often the bulk plasmon maximum). If there is more than one inflexion point in energy the window it selects the smoother one what, often, but not always, is a good choice in this case. Parameters ---------- window : {None, float} If None, the search for the local inflexion point is performed using the full energy range. A positive float will restrict the search to the (0,window] energy window, where window is given in the axis units. If no inflexion point is found in this spectral range the window value is returned instead. tol : {None, float} The threshold tolerance for the derivative. If "auto" it is automatically calculated as the minimum value that guarantees finding an inflexion point in all the spectra in given energy range. window_length : int If non zero performs order three Savitzky-Golay smoothing to the data to avoid falling in local minima caused by the noise. It must be an odd integer. polynomial_order : int Savitzky-Golay filter polynomial order. start : float Position from the zero-loss peak centre from where to start looking for the inflexion point. Returns ------- threshold : Signal1D A Signal1D of the same dimension as the input spectrum navigation space containing the estimated threshold. Where the threshold couldn't be estimated the value is set to nan. See Also -------- estimate_elastic_scattering_intensity,align_zero_loss_peak, find_peaks1D_ohaver, fourier_ratio_deconvolution. Notes ----- The main purpose of this method is to be used as input for `estimate_elastic_scattering_intensity`. Indeed, for currently achievable energy resolutions, there is not such a thing as a elastic scattering threshold. Therefore, please be aware of the limitations of this method when using it. """ self._check_signal_dimension_equals_one() # Create threshold with the same shape as the navigation dims. threshold = self._get_navigation_signal().transpose(signal_axes=0) # Progress Bar axis = self.axes_manager.signal_axes[0] min_index, max_index = axis.value_range_to_indices(start, start + window) if max_index < min_index + 10: raise ValueError("Please select a bigger window") s = self.isig[min_index:max_index].deepcopy() if window_length: s.smooth_savitzky_golay( polynomial_order=polynomial_order, window_length=window_length, differential_order=1, ) else: s = s.derivative(-1) if tol is None: tol = np.max(abs(s.data).min(axis.index_in_array)) saxis = s.axes_manager[-1] inflexion = (abs(s.data) <= tol).argmax(saxis.index_in_array) if isinstance(inflexion, da.Array): inflexion = inflexion.compute() threshold.data[:] = saxis.index2value(inflexion) if isinstance(inflexion, np.ndarray): threshold.data[inflexion == 0] = np.nan else: # Single spectrum if inflexion == 0: threshold.data[:] = np.nan del s if np.isnan(threshold.data).any(): _logger.warning( "No inflexion point could be found in some positions " "that have been marked with nans." ) # Create spectrum image, stop and return value threshold.metadata.General.title = ( self.metadata.General.title + " elastic scattering threshold" ) if self.tmp_parameters.has_item("filename"): threshold.tmp_parameters.filename = ( self.tmp_parameters.filename + "_elastic_scattering_threshold" ) threshold.tmp_parameters.folder = self.tmp_parameters.folder threshold.tmp_parameters.extension = self.tmp_parameters.extension threshold.set_signal_type("") return threshold def estimate_thickness( self, threshold=None, zlp=None, density=None, mean_free_path=None, ): """Estimates the thickness (relative and absolute) of a sample using the log-ratio method. The current EELS spectrum must be a low-loss spectrum containing the zero-loss peak. The hyperspectrum must be well calibrated and aligned. To obtain the thickness relative to the mean free path don't set the `density` and the `mean_free_path`. Parameters ---------- threshold : {BaseSignal, float}, optional If the zero-loss-peak is not provided, use this energy threshold to roughly estimate its intensity by truncation. If the threshold is constant across the dataset use a float. Otherwise, provide a signal of the same dimension as the input spectrum navigation space containing the threshold value in the energy units. zlp : BaseSignal, optional If not None the zero-loss peak intensity is calculated from the ZLP spectrum supplied by integration. mean_free_path : float, optional The mean free path of the material in nanometers. If not provided, the thickness is given relative to the mean free path. density : float, optional The density of the material in g/cm**3. This is used to estimate the mean free path when the mean free path is not known and to perform the angular corrections. Returns ------- s : BaseSignal The thickness relative to the MFP. It returns a Signal1D, Signal2D or a BaseSignal, depending on the current navigation dimensions. Notes ----- For details see Egerton, R. Electron Energy-Loss Spectroscopy in the Electron Microscope. Springer-Verlag, 2011. """ axis = self.axes_manager.signal_axes[0] total_intensity = self.integrate1D(axis.index_in_array).data if threshold is None and zlp is None: raise ValueError( "Please provide one of the following keywords: " "`threshold`, `zlp`" ) if zlp is not None: I0 = zlp.integrate1D(axis.index_in_array).data else: I0 = self.estimate_elastic_scattering_intensity( threshold=threshold, ).data t_over_lambda = np.log(total_intensity / I0) if density is not None: if self._are_microscope_parameters_missing(): raise RuntimeError( "Some microscope parameters are missing. Please use the " "`set_microscope_parameters()` method to set them. " "If you don't know them, don't set the `density` keyword." ) else: md = self.metadata.Acquisition_instrument.TEM
t_over_lambda *= iMFP_angular_correction(
4
2023-10-28 20:04:10+00:00
8k
geriskenderi/graph-jepa
train/exp.py
[ { "identifier": "cfg", "path": "core/config.py", "snippet": "def set_cfg(cfg):\ndef update_cfg(cfg, args_str=None):" }, { "identifier": "create_dataset", "path": "core/get_data.py", "snippet": "def create_dataset(cfg):\n pre_transform = PositionalEncodingTransform(\n rw_dim=cfg...
import torch import numpy as np from core.config import cfg, update_cfg from core.get_data import create_dataset from core.get_model import create_model from core.trainer import run_k_fold
3,741
def train(train_loader, model, optimizer, evaluator, device, momentum_weight,sharp=None, criterion_type=0): criterion = torch.nn.SmoothL1Loss() step_losses, num_targets = [], [] for data in train_loader: if model.use_lap: # Sign flips for eigenvalue PEs batch_pos_enc = data.lap_pos_enc sign_flip = torch.rand(batch_pos_enc.size(1)) sign_flip[sign_flip >= 0.5] = 1.0 sign_flip[sign_flip < 0.5] = -1.0 data.lap_pos_enc = batch_pos_enc * sign_flip.unsqueeze(0) data = data.to(device) optimizer.zero_grad() target_x, target_y = model(data) loss = criterion(target_x, target_y) # Will need these for the weighted average at the end of the epoch step_losses.append(loss.item()) num_targets.append(len(target_y)) # Update weights of the network loss.backward() optimizer.step() # Other than the target encoder, here we use exponential smoothing with torch.no_grad(): for param_q, param_k in zip(model.context_encoder.parameters(), model.target_encoder.parameters()): param_k.data.mul_(momentum_weight).add_((1.-momentum_weight) * param_q.detach().data) epoch_loss = np.average(step_losses, weights=num_targets) return None, epoch_loss # Leave none for now since maybe we'd like to return the embeddings for visualization @ torch.no_grad() def test(loader, model, evaluator, device, criterion_type=0): criterion = torch.nn.SmoothL1Loss() step_losses, num_targets = [], [] for data in loader: data = data.to(device) target_x, target_y = model(data) loss = criterion(target_y, target_x) # Will need these for the weighted average at the end of the epoch step_losses.append(loss.item()) num_targets.append(len(target_y)) epoch_loss = np.average(step_losses, weights=num_targets) return None, epoch_loss if __name__ == '__main__': cfg.merge_from_file('train/configs/exp.yaml') cfg = update_cfg(cfg) # we can specify the config file for the update here cfg.k = 10
def train(train_loader, model, optimizer, evaluator, device, momentum_weight,sharp=None, criterion_type=0): criterion = torch.nn.SmoothL1Loss() step_losses, num_targets = [], [] for data in train_loader: if model.use_lap: # Sign flips for eigenvalue PEs batch_pos_enc = data.lap_pos_enc sign_flip = torch.rand(batch_pos_enc.size(1)) sign_flip[sign_flip >= 0.5] = 1.0 sign_flip[sign_flip < 0.5] = -1.0 data.lap_pos_enc = batch_pos_enc * sign_flip.unsqueeze(0) data = data.to(device) optimizer.zero_grad() target_x, target_y = model(data) loss = criterion(target_x, target_y) # Will need these for the weighted average at the end of the epoch step_losses.append(loss.item()) num_targets.append(len(target_y)) # Update weights of the network loss.backward() optimizer.step() # Other than the target encoder, here we use exponential smoothing with torch.no_grad(): for param_q, param_k in zip(model.context_encoder.parameters(), model.target_encoder.parameters()): param_k.data.mul_(momentum_weight).add_((1.-momentum_weight) * param_q.detach().data) epoch_loss = np.average(step_losses, weights=num_targets) return None, epoch_loss # Leave none for now since maybe we'd like to return the embeddings for visualization @ torch.no_grad() def test(loader, model, evaluator, device, criterion_type=0): criterion = torch.nn.SmoothL1Loss() step_losses, num_targets = [], [] for data in loader: data = data.to(device) target_x, target_y = model(data) loss = criterion(target_y, target_x) # Will need these for the weighted average at the end of the epoch step_losses.append(loss.item()) num_targets.append(len(target_y)) epoch_loss = np.average(step_losses, weights=num_targets) return None, epoch_loss if __name__ == '__main__': cfg.merge_from_file('train/configs/exp.yaml') cfg = update_cfg(cfg) # we can specify the config file for the update here cfg.k = 10
run_k_fold(cfg, create_dataset, create_model, train, test)
1
2023-10-30 19:53:26+00:00
8k
oniisancr/COC_robot
game_script.py
[ { "identifier": "adb_command", "path": "adb.py", "snippet": "def adb_command(cmd):\n adb_command = adb_command_full( cmd)\n subprocess.run(adb_command, shell=True)" }, { "identifier": "adb_command_full", "path": "adb.py", "snippet": "def adb_command_full(command, adbpath = config.a...
from datetime import timedelta from transitions import Machine from adb import adb_command, adb_command_full from game_controller import GameController import os import subprocess import sys import time import config import logging
4,030
return f"{hours:02d}:{minutes:02d}:{seconds:02d}" class GameScript: states = ['initializing', 'waiting', 'processing', 'finishing'] waitting_time = 0 start_task = False last_yyz = 0 last_gain = 0 last_donate = 0 def __init__(self): self.machine = Machine(model=self, states=GameScript.states, initial='initializing') self.game_controller = GameController() self.machine.add_transition('initializing2waiting', 'initializing', 'waiting') self.machine.add_transition("waiting2initializing", 'waiting', 'initializing') self.machine.add_transition('start_processing', 'waiting', 'processing') self.machine.add_transition('finish', 'processing', 'finishing') self.machine.add_transition('start_init', 'waiting', 'initializing') self.machine.add_transition('processing2waiting','processing','waiting') def init(self): global offline_timer offline_timer = config.MAX_ONLINE_TIME # 转到等待状态 self.waitting_time = 0 self.initializing2waiting() def keep_clear_home(self): ''' 关闭主界面其余窗口,避免因误触界面其他按钮导致脚本暂停 ''' # 多次关闭,避免进入n级菜单 for n in range(3): # 只使用一张截图判断 game_script.game_controller.take_screenshot(True) game_script.game_controller.shot_new = False # 关闭大窗口window -(误触add、商店、布局、) if game_script.game_controller.click_by_name("close_window", False): continue # 关闭中窗口window -(误触邮件、进攻、设置) if game_script.game_controller.click_by_name("close_medium_window", False): continue # 关闭个人信息window if game_script.game_controller.click_by_name("close_info_window", False): continue # 关闭批量升级window if game_script.game_controller.click_by_name("close_update_window", False): continue # 误触建筑物 if game_script.game_controller._match_template(["target_info"]): # 点击空白 2192、534 game_script.game_controller.click([2192,532]) continue # 关闭超级兵界面 if game_script.game_controller.click_by_name("close_supertroop_window", False): continue # 关闭每周精选close_weekly_window if game_script.game_controller.click_by_name("close_weekly_window", False): continue # 长时间未操作 if game_script.game_controller.click_by_name("reload", False): continue game_script.game_controller.shot_new = True def execute_game_action(self): global offline_timer if int(time.time()) - self.last_gain > config.gain_interval: if self.start_task is False: self.keep_clear_home() self.start_task = True if config.CLICK_LOG: logging.info("gain_base") update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: gain resourse") self.last_gain = int(time.time()) self.game_controller.gain_base() offline_timer -= int(time.time()) - self.last_gain if config.yyzhan and int(time.time()) - self.last_yyz > config.yyzhan_Interval: #控制频率 if self.start_task is False: self.keep_clear_home() self.start_task = True if config.CLICK_LOG: logging.info('start yyzhan') update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: yyzhan") self.last_yyz = int(time.time()) self.game_controller.yyzhan() offline_timer -= int(time.time()) - self.last_yyz if config.donate_troops and int(time.time()) - self.last_donate > config.donate_Interval: if self.start_task is False: self.keep_clear_home() self.start_task = True if config.CLICK_LOG: logging.info('start donate_troops') update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: donate troops") self.last_donate = int(time.time()) self.game_controller.donate_troops() offline_timer -= int(time.time()) - self.last_donate if len(self.game_controller.heap_tarin_troops) > 0 or self.game_controller.queue_tarin_spells.qsize() > 0: update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: train troops") self.last_train = int(time.time()) self.game_controller.train() offline_timer -= int(time.time()) - self.last_train self.start_task = False if __name__ == "__main__": game_script = GameScript() while game_script.state != 'finishing': if game_script.state == 'initializing': update_text(f"initializing... ") check_prepare() time.sleep(1) # 回到主界面
# -*- coding: utf-8 -*- """ Created on Mon Oct 30 19:21:36 2023 @author: Rui """ # 配置日志记录到文件 logging.basicConfig(filename='coc_robot.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',filemode='w') offline_timer = 0 wait_wakeup_timer = 0 def check_prepare(): if not os.path.exists(config.adb_path): print("no adb.exe") exit(0) cmd = adb_command_full( " devices") result = subprocess.run(cmd, shell=True, capture_output=True, text=True) print(result.stdout) # 解析输出 output_lines = result.stdout.split('\n') # 检查是否存在设备,需要开启开发者模式 if output_lines[1] == '': print("Pls confirm USB Debugging Mode has opened!") exit(0) def update_text(text): sys.stdout.write("\r\033[K" + text) sys.stdout.flush() def seconds_to_hms_string(seconds): td = timedelta(seconds=seconds) hours, remainder = divmod(td.seconds, 3600) minutes, seconds = divmod(remainder, 60) return f"{hours:02d}:{minutes:02d}:{seconds:02d}" class GameScript: states = ['initializing', 'waiting', 'processing', 'finishing'] waitting_time = 0 start_task = False last_yyz = 0 last_gain = 0 last_donate = 0 def __init__(self): self.machine = Machine(model=self, states=GameScript.states, initial='initializing') self.game_controller = GameController() self.machine.add_transition('initializing2waiting', 'initializing', 'waiting') self.machine.add_transition("waiting2initializing", 'waiting', 'initializing') self.machine.add_transition('start_processing', 'waiting', 'processing') self.machine.add_transition('finish', 'processing', 'finishing') self.machine.add_transition('start_init', 'waiting', 'initializing') self.machine.add_transition('processing2waiting','processing','waiting') def init(self): global offline_timer offline_timer = config.MAX_ONLINE_TIME # 转到等待状态 self.waitting_time = 0 self.initializing2waiting() def keep_clear_home(self): ''' 关闭主界面其余窗口,避免因误触界面其他按钮导致脚本暂停 ''' # 多次关闭,避免进入n级菜单 for n in range(3): # 只使用一张截图判断 game_script.game_controller.take_screenshot(True) game_script.game_controller.shot_new = False # 关闭大窗口window -(误触add、商店、布局、) if game_script.game_controller.click_by_name("close_window", False): continue # 关闭中窗口window -(误触邮件、进攻、设置) if game_script.game_controller.click_by_name("close_medium_window", False): continue # 关闭个人信息window if game_script.game_controller.click_by_name("close_info_window", False): continue # 关闭批量升级window if game_script.game_controller.click_by_name("close_update_window", False): continue # 误触建筑物 if game_script.game_controller._match_template(["target_info"]): # 点击空白 2192、534 game_script.game_controller.click([2192,532]) continue # 关闭超级兵界面 if game_script.game_controller.click_by_name("close_supertroop_window", False): continue # 关闭每周精选close_weekly_window if game_script.game_controller.click_by_name("close_weekly_window", False): continue # 长时间未操作 if game_script.game_controller.click_by_name("reload", False): continue game_script.game_controller.shot_new = True def execute_game_action(self): global offline_timer if int(time.time()) - self.last_gain > config.gain_interval: if self.start_task is False: self.keep_clear_home() self.start_task = True if config.CLICK_LOG: logging.info("gain_base") update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: gain resourse") self.last_gain = int(time.time()) self.game_controller.gain_base() offline_timer -= int(time.time()) - self.last_gain if config.yyzhan and int(time.time()) - self.last_yyz > config.yyzhan_Interval: #控制频率 if self.start_task is False: self.keep_clear_home() self.start_task = True if config.CLICK_LOG: logging.info('start yyzhan') update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: yyzhan") self.last_yyz = int(time.time()) self.game_controller.yyzhan() offline_timer -= int(time.time()) - self.last_yyz if config.donate_troops and int(time.time()) - self.last_donate > config.donate_Interval: if self.start_task is False: self.keep_clear_home() self.start_task = True if config.CLICK_LOG: logging.info('start donate_troops') update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: donate troops") self.last_donate = int(time.time()) self.game_controller.donate_troops() offline_timer -= int(time.time()) - self.last_donate if len(self.game_controller.heap_tarin_troops) > 0 or self.game_controller.queue_tarin_spells.qsize() > 0: update_text(f"processing. {seconds_to_hms_string(offline_timer)} s remaining. task: train troops") self.last_train = int(time.time()) self.game_controller.train() offline_timer -= int(time.time()) - self.last_train self.start_task = False if __name__ == "__main__": game_script = GameScript() while game_script.state != 'finishing': if game_script.state == 'initializing': update_text(f"initializing... ") check_prepare() time.sleep(1) # 回到主界面
adb_command("shell input keyevent 3")
0
2023-10-31 10:58:06+00:00
8k
TimZhang001/Defect_GAN-PyTorch
train.py
[ { "identifier": "DefectGANDataset", "path": "dataset.py", "snippet": "class DefectGANDataset(data.Dataset):\r\n def __init__(\r\n self,\r\n root: str,\r\n image_size: int = 224,\r\n num_classes: int = 2,\r\n device_id: str = \"cpu\",\r\n ) -> ...
import argparse import random import time import warnings import numpy as np import torch import yaml import wandb from typing import Any from torch import nn, optim from torch.backends import cudnn from torch.cuda import amp from torch.optim.swa_utils import AveragedModel from torch.utils import data from dataset import DefectGANDataset, CPUPrefetcher, CUDAPrefetcher from model import defectnet, path_discriminator, gradient_penalty_loss from utils import load_pretrained_state_dict, load_resume_state_dict, make_directory, AverageMeter, Summary, ProgressMeter
6,833
if self.device.type == "cuda": # 将数据加载器替换为CUDA以加速 self.train_data_prefetcher = CUDAPrefetcher(defect_dataloader, self.device) if self.device.type == "cpu": # 将数据加载器替换为CPU以加速 self.train_data_prefetcher = CPUPrefetcher(defect_dataloader) def define_loss(self): if self.rec_criterion_name == "l1": self.rec_criterion = nn.L1Loss() else: raise NotImplementedError(f"Loss {self.rec_criterion_name} is not supported.") if self.cls_criterion_name == "cross_entropy": self.cls_criterion = nn.CrossEntropyLoss() else: raise NotImplementedError(f"Loss {self.cls_criterion_name} is not supported.") if self.gp_criterion_name == "gradient_penalty": self.gp_criterion = gradient_penalty_loss() else: raise NotImplementedError(f"Loss {self.gp_criterion_name} is not supported.") self.rec_criterion = self.rec_criterion.to(self.device) self.cls_criterion = self.cls_criterion.to(self.device) self.gp_criterion = self.gp_criterion.to(self.device) def define_optimizer(self): if self.g_optimizer_name == "adam": self.g_optimizer = optim.Adam(self.g_model.parameters(), self.g_optimizer_lr, self.g_optimizer_betas) else: raise NotImplementedError(f"Optimizer {self.g_optimizer_name} is not supported.") if self.d_optimizer_name == "adam": self.d_optimizer = optim.Adam(self.d_model.parameters(), self.d_optimizer_lr, self.d_optimizer_betas) else: raise NotImplementedError(f"Optimizer {self.d_optimizer_name} is not supported.") def define_scheduler(self): pass def load_model_weights(self): if self.pretrained_g_model_weights_path != "": self.g_model = load_pretrained_state_dict(self.g_model, self.pretrained_g_model_weights_path, self.g_model_compiled) self.g_model = torch.load(self.pretrained_g_model_weights_path) print(f"Loaded `{self.pretrained_g_model_weights_path}` pretrained model weights successfully.") if self.pretrained_d_model_weights_path != "": self.d_model = load_pretrained_state_dict(self.d_model, self.pretrained_d_model_weights_path, self.d_model_compiled) print(f"Loaded `{self.pretrained_d_model_weights_path}` pretrained model weights successfully.") if self.resumed_g_model_weights_path != "": self.g_model, self.ema_g_model, self.start_epoch, self.g_optimizer, self.g_scheduler = load_resume_state_dict( self.g_model, self.ema_g_model, self.g_optimizer, self.g_scheduler, self.resumed_g_model_weights_path, self.g_model_compiled, ) print(f"Loaded `{self.resumed_g_model_weights_path}` resume model weights successfully.") if self.resumed_d_model_weights_path != "": self.d_model, self.ema_d_model, self.start_epoch, self.d_optimizer, self.d_scheduler = load_resume_state_dict( self.d_model, self.ema_d_model, self.d_optimizer, self.d_scheduler, self.resumed_d_model_weights_path, self.d_model_compiled, ) print(f"Loaded `{self.resumed_d_model_weights_path}` resume model weights successfully.") def train(self): # 将模型调整为训练模式 self.g_model.train() self.d_model.train() # 用于生成器输入和重建时候噪声输入 fake_noise = torch.randn( self.train_batch_size, self.g_model_in_channels, self.g_model_noise_image_size, self.g_model_noise_image_size).to(self.device) rec_noise = torch.randn( self.train_batch_size, self.g_model_in_channels, self.g_model_noise_image_size, self.g_model_noise_image_size).to(self.device) # 将正常,缺陷样本的标签设置为0,1 normal_class_index = torch.as_tensor([self.normal_label] * self.train_batch_size).type(torch.LongTensor).to(self.device) defect_class_index = torch.as_tensor([self.defect_label] * self.train_batch_size).type(torch.LongTensor).to(self.device) # 损失函数权重 self.g_gp_loss_weight = torch.Tensor([self.g_gp_loss_weight]).to(self.device) self.g_fake_cls_loss_weight = torch.Tensor([self.g_fake_cls_loss_weight]).to(self.device) self.g_rec_loss_weight = torch.Tensor([self.g_rec_loss_weight]).to(self.device) self.g_cycle_rec_loss_weight = torch.Tensor([self.g_cycle_rec_loss_weight]).to(self.device) self.g_cycle_mask_rec_loss_weight = torch.Tensor([self.g_cycle_mask_rec_loss_weight]).to(self.device) self.g_cycle_mask_vanishing_loss_weight = torch.Tensor([self.g_cycle_mask_vanishing_loss_weight]).to(self.device) self.g_cycle_spatial_loss_weight = torch.Tensor([self.g_cycle_spatial_loss_weight]).to(self.device) self.d_gp_loss_weight = torch.Tensor([self.d_gp_loss_weight]).to(self.device) self.d_real_cls_loss_weight = torch.Tensor([self.d_real_cls_loss_weight]).to(self.device) for epoch in range(self.start_epoch, self.epochs): batch_index = 1 self.train_data_prefetcher.reset() end = time.time() batch_data = self.train_data_prefetcher.next() # 计算一个epoch的批次数量 batches = len(self.train_data_prefetcher) # 进度条信息 batch_time = AverageMeter("Time", ":6.3f", Summary.NONE) data_time = AverageMeter("Data", ":6.3f", Summary.NONE) g_losses = AverageMeter("G loss", ":6.6f", Summary.NONE) d_losses = AverageMeter("D loss", ":6.6f", Summary.NONE)
# Copyright 2023 AlphaBetter Corporation. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== class Trainer(object): def __init__(self, config: Any): # 运行环境相关参数 self.project_name = config["PROJECT_NAME"] self.exp_name = config["EXP_NAME"] + time.strftime("-%Y%m%d-%H_%M_%S", time.localtime(int(round(time.time() * 1000)) / 1000)) self.seed = config["SEED"] self.mixing_precision = config["MIXING_PRECISION"] self.scaler = None # TODO: 未来支持混合精度训练 self.device = config["DEVICE"] self.cudnn_benchmark = config["CUDNN_BENCHMARK"] self.wandb_config = config self.wandb_project_name = config["PROJECT_NAME"] self.samples_dir = f"./samples/{self.exp_name}" self.results_dir = f"./results/{self.exp_name}" self.visuals_dir = f"./results/visuals/{self.exp_name}" # 模型相关参数 self.g_model = None self.ema_g_model = None self.g_model_name = config["MODEL"]["G"]["NAME"] self.g_model_in_channels = config["MODEL"]["G"]["IN_CHANNELS"] self.g_model_out_channels = config["MODEL"]["G"]["OUT_CHANNELS"] self.g_model_channels = config["MODEL"]["G"]["CHANNELS"] self.g_model_num_blocks = config["MODEL"]["G"]["NUM_BLOCKS"] self.g_model_num_down_blocks = config["MODEL"]["G"]["NUM_DOWN_BLOCKS"] self.g_model_noise_image_size = config["MODEL"]["G"]["NOISE_IMAGE_SIZE"] self.g_model_num_spatial_layers = config["MODEL"]["G"]["NUM_SPATIAL_LAYERS"] self.g_model_spectral_norm = config["MODEL"]["G"]["SPECTRAL_NORM"] self.g_model_ema = config["MODEL"]["G"]["EMA"] self.g_model_compiled = config["MODEL"]["G"]["COMPILED"] self.d_model = None self.ema_d_model = None self.d_model_name = config["MODEL"]["D"]["NAME"] self.d_model_in_channels = config["MODEL"]["D"]["IN_CHANNELS"] self.d_model_out_channels = config["MODEL"]["D"]["OUT_CHANNELS"] self.d_model_channels = config["MODEL"]["D"]["CHANNELS"] self.d_model_num_blocks = config["MODEL"]["D"]["NUM_BLOCKS"] self.d_model_image_size = config["MODEL"]["D"]["IMAGE_SIZE"] self.d_model_num_classes = config["MODEL"]["D"]["NUM_CLASSES"] self.d_model_spectral_norm = config["MODEL"]["D"]["SPECTRAL_NORM"] self.d_model_ema = config["MODEL"]["D"]["EMA"] self.d_model_compiled = config["MODEL"]["D"]["COMPILED"] self.ema_avg_fn = None self.ema_decay = config["MODEL"]["EMA"]["DECAY"] self.ema_compiled = config["MODEL"]["EMA"]["COMPILED"] self.pretrained_g_model_weights_path = config["MODEL"]["CHECKPOINT"]["PRETRAINED_G_MODEL_WEIGHTS_PATH"] self.pretrained_d_model_weights_path = config["MODEL"]["CHECKPOINT"]["PRETRAINED_D_MODEL_WEIGHTS_PATH"] self.resumed_g_model_weights_path = config["MODEL"]["CHECKPOINT"]["RESUME_G_MODEL_WEIGHTS_PATH"] self.resumed_d_model_weights_path = config["MODEL"]["CHECKPOINT"]["RESUME_D_MODEL_WEIGHTS_PATH"] # 数据集相关参数 self.train_root_dir = config["TRAIN"]["DATASET"]["ROOT_DIR"] self.train_batch_size = config["TRAIN"]["HYP"]["IMGS_PER_BATCH"] self.train_shuffle = config["TRAIN"]["HYP"]["SHUFFLE"] self.train_num_workers = config["TRAIN"]["HYP"]["NUM_WORKERS"] self.train_pin_memory = config["TRAIN"]["HYP"]["PIN_MEMORY"] self.train_drop_last = config["TRAIN"]["HYP"]["DROP_LAST"] self.train_persistent_workers = config["TRAIN"]["HYP"]["PERSISTENT_WORKERS"] self.train_data_prefetcher = None # 损失函数参数 self.rec_criterion = None self.cls_criterion = None self.gp_criterion = None self.rec_criterion_name = config["TRAIN"]["LOSSES"]["REC_CRITERION"]["NAME"] self.cls_criterion_name = config["TRAIN"]["LOSSES"]["CLS_CRITERION"]["NAME"] self.gp_criterion_name = config["TRAIN"]["LOSSES"]["GP_CRITERION"]["NAME"] self.g_gp_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["G_GP_LOSS_WEIGHT"] self.g_fake_cls_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["G_FAKE_CLS_LOSS_WEIGHT"] self.g_rec_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["G_REC_LOSS_WEIGHT"] self.g_cycle_rec_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["G_CYCLE_REC_LOSS_WEIGHT"] self.g_cycle_mask_rec_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["G_CYCLE_MASK_REC_LOSS_WEIGHT"] self.g_cycle_mask_vanishing_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["G_CYCLE_MASK_VANISHING_LOSS_WEIGHT"] self.g_cycle_spatial_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["G_CYCLE_SPATIAL_LOSS_WEIGHT"] self.d_gp_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["D_GP_LOSS_WEIGHT"] self.d_real_cls_loss_weight = config["TRAIN"]["LOSSES"]["LAMBDA"]["D_REAL_CLS_LOSS_WEIGHT"] # 优化器参数 self.g_optimizer = None self.g_optimizer_name = config["TRAIN"]["OPTIMIZER"]["G"]["NAME"] self.g_optimizer_lr = config["TRAIN"]["OPTIMIZER"]["G"]["LR"] self.g_optimizer_betas = config["TRAIN"]["OPTIMIZER"]["G"]["BETAS"] self.d_optimizer = None self.d_optimizer_name = config["TRAIN"]["OPTIMIZER"]["D"]["NAME"] self.d_optimizer_lr = config["TRAIN"]["OPTIMIZER"]["D"]["LR"] self.d_optimizer_betas = config["TRAIN"]["OPTIMIZER"]["D"]["BETAS"] # 学习率调度器参数 self.g_scheduler = None self.d_scheduler = None # 训练参数 self.start_epoch = 0 self.epochs = config["TRAIN"]["HYP"]["EPOCHS"] self.print_freq = config["TRAIN"]["PRINT_FREQ"] self.normal_label = 0 self.defect_label = 1 self.g_gp_loss = torch.Tensor([0.0]) self.g_fake_cls_loss = torch.Tensor([0.0]) self.g_rec_loss = torch.Tensor([0.0]) self.g_cycle_rec_loss = torch.Tensor([0.0]) self.g_cycle_mask_rec_loss = torch.Tensor([0.0]) self.g_cycle_mask_vanishing_loss = torch.Tensor([0.0]) self.g_cycle_spatial_loss = torch.Tensor([0.0]) self.d_gp_loss = torch.Tensor([0.0]) self.d_real_cls_loss = torch.Tensor([0.0]) self.g_loss = torch.Tensor([0.0]) self.d_loss = torch.Tensor([0.0]) # 训练环境 make_directory(self.samples_dir) make_directory(self.results_dir) make_directory(self.visuals_dir) self.setup_seed() self.setup_mixing_precision() self.setup_device() self.setup_wandb() # 模型 self.build_models() # 数据集 self.load_datasets() # 损失函数 self.define_loss() # 优化器 self.define_optimizer() # 学习率调度器 self.define_scheduler() # 加载模型权重 self.load_model_weights() def setup_seed(self): # 固定随机数种子 random.seed(self.seed) np.random.seed(self.seed) torch.manual_seed(self.seed) torch.cuda.manual_seed_all(self.seed) def setup_mixing_precision(self): # 初始化混合精度训练方法 if self.mixing_precision: self.scaler = amp.GradScaler() else: print("Mixing precision training is not enabled.") def setup_device(self): # 初始化训练的设备名称 device = "cpu" if self.device != "cpu" and self.device != "": if not torch.cuda.is_available(): warnings.warn("No GPU detected, defaulting to `cpu`.") else: device = self.device if self.device == "": warnings.warn("No device specified, defaulting to `cpu`.") self.device = torch.device(device) # 如果输入图像尺寸是固定的,固定卷积算法可以提升训练速度 if self.cudnn_benchmark: cudnn.benchmark = True else: cudnn.benchmark = False def setup_wandb(self): # 初始化wandb wandb.init(config=self.wandb_config, project=self.wandb_project_name, name=self.exp_name) def build_models(self): if self.g_model_name == "defectnet": self.g_model = defectnet(spectral_norm=self.g_model_spectral_norm, in_channels=self.g_model_in_channels, out_channels=self.g_model_out_channels, channels=self.g_model_channels, num_blocks=self.g_model_num_blocks, num_down_blocks=self.g_model_num_down_blocks, noise_image_size=self.g_model_noise_image_size, num_spatial_layers=self.g_model_num_spatial_layers) else: raise ValueError(f"The `{self.g_model_name}` is not supported.") if self.d_model_name == "path_discriminator": self.d_model = path_discriminator(spectral_norm=self.d_model_spectral_norm, in_channels=self.d_model_in_channels, out_channels=self.d_model_out_channels, channels=self.d_model_channels, num_blocks=self.d_model_num_blocks, image_size=self.d_model_image_size, num_classes=self.d_model_num_classes) else: raise ValueError(f"The `{self.d_model_name}` is not supported.") # 送至指定设备上运行 self.g_model = self.g_model.to(self.device) self.d_model = self.d_model.to(self.device) if self.ema_decay != 0: self.ema_avg_fn = lambda averaged_model_parameter, model_parameter, num_averaged: \ (1 - self.ema_decay) * averaged_model_parameter + self.ema_decay * model_parameter if self.ema_g_model: self.ema_g_model = AveragedModel(self.g_model, device=self.device, avg_fn=self.ema_avg_fn) if self.ema_d_model: self.ema_d_model = AveragedModel(self.d_model, device=self.device, avg_fn=self.ema_avg_fn) # 编译模型 if config["MODEL"]["G"]["COMPILED"]: self.g_model = torch.compile(self.g_model) if config["MODEL"]["D"]["COMPILED"]: self.d_model = torch.compile(self.d_model) if config["MODEL"]["EMA"]["COMPILED"]: if self.ema_g_model is not None: self.ema_g_model = torch.compile(self.ema_g_model) if self.ema_d_model is not None: self.ema_d_model = torch.compile(self.ema_d_model) warnings.warn("Dynamic compilation of discriminator is not recommended, " "and the support on PyTorch2.0.1 version is not good enough.") def load_datasets(self): defect_dataset = DefectGANDataset(self.train_root_dir) defect_dataloader = data.DataLoader( defect_dataset, batch_size=self.train_batch_size, shuffle=self.train_shuffle, num_workers=self.train_num_workers, pin_memory=self.train_pin_memory, drop_last=self.train_drop_last, persistent_workers=self.train_persistent_workers, ) if self.device.type == "cuda": # 将数据加载器替换为CUDA以加速 self.train_data_prefetcher = CUDAPrefetcher(defect_dataloader, self.device) if self.device.type == "cpu": # 将数据加载器替换为CPU以加速 self.train_data_prefetcher = CPUPrefetcher(defect_dataloader) def define_loss(self): if self.rec_criterion_name == "l1": self.rec_criterion = nn.L1Loss() else: raise NotImplementedError(f"Loss {self.rec_criterion_name} is not supported.") if self.cls_criterion_name == "cross_entropy": self.cls_criterion = nn.CrossEntropyLoss() else: raise NotImplementedError(f"Loss {self.cls_criterion_name} is not supported.") if self.gp_criterion_name == "gradient_penalty": self.gp_criterion = gradient_penalty_loss() else: raise NotImplementedError(f"Loss {self.gp_criterion_name} is not supported.") self.rec_criterion = self.rec_criterion.to(self.device) self.cls_criterion = self.cls_criterion.to(self.device) self.gp_criterion = self.gp_criterion.to(self.device) def define_optimizer(self): if self.g_optimizer_name == "adam": self.g_optimizer = optim.Adam(self.g_model.parameters(), self.g_optimizer_lr, self.g_optimizer_betas) else: raise NotImplementedError(f"Optimizer {self.g_optimizer_name} is not supported.") if self.d_optimizer_name == "adam": self.d_optimizer = optim.Adam(self.d_model.parameters(), self.d_optimizer_lr, self.d_optimizer_betas) else: raise NotImplementedError(f"Optimizer {self.d_optimizer_name} is not supported.") def define_scheduler(self): pass def load_model_weights(self): if self.pretrained_g_model_weights_path != "": self.g_model = load_pretrained_state_dict(self.g_model, self.pretrained_g_model_weights_path, self.g_model_compiled) self.g_model = torch.load(self.pretrained_g_model_weights_path) print(f"Loaded `{self.pretrained_g_model_weights_path}` pretrained model weights successfully.") if self.pretrained_d_model_weights_path != "": self.d_model = load_pretrained_state_dict(self.d_model, self.pretrained_d_model_weights_path, self.d_model_compiled) print(f"Loaded `{self.pretrained_d_model_weights_path}` pretrained model weights successfully.") if self.resumed_g_model_weights_path != "": self.g_model, self.ema_g_model, self.start_epoch, self.g_optimizer, self.g_scheduler = load_resume_state_dict( self.g_model, self.ema_g_model, self.g_optimizer, self.g_scheduler, self.resumed_g_model_weights_path, self.g_model_compiled, ) print(f"Loaded `{self.resumed_g_model_weights_path}` resume model weights successfully.") if self.resumed_d_model_weights_path != "": self.d_model, self.ema_d_model, self.start_epoch, self.d_optimizer, self.d_scheduler = load_resume_state_dict( self.d_model, self.ema_d_model, self.d_optimizer, self.d_scheduler, self.resumed_d_model_weights_path, self.d_model_compiled, ) print(f"Loaded `{self.resumed_d_model_weights_path}` resume model weights successfully.") def train(self): # 将模型调整为训练模式 self.g_model.train() self.d_model.train() # 用于生成器输入和重建时候噪声输入 fake_noise = torch.randn( self.train_batch_size, self.g_model_in_channels, self.g_model_noise_image_size, self.g_model_noise_image_size).to(self.device) rec_noise = torch.randn( self.train_batch_size, self.g_model_in_channels, self.g_model_noise_image_size, self.g_model_noise_image_size).to(self.device) # 将正常,缺陷样本的标签设置为0,1 normal_class_index = torch.as_tensor([self.normal_label] * self.train_batch_size).type(torch.LongTensor).to(self.device) defect_class_index = torch.as_tensor([self.defect_label] * self.train_batch_size).type(torch.LongTensor).to(self.device) # 损失函数权重 self.g_gp_loss_weight = torch.Tensor([self.g_gp_loss_weight]).to(self.device) self.g_fake_cls_loss_weight = torch.Tensor([self.g_fake_cls_loss_weight]).to(self.device) self.g_rec_loss_weight = torch.Tensor([self.g_rec_loss_weight]).to(self.device) self.g_cycle_rec_loss_weight = torch.Tensor([self.g_cycle_rec_loss_weight]).to(self.device) self.g_cycle_mask_rec_loss_weight = torch.Tensor([self.g_cycle_mask_rec_loss_weight]).to(self.device) self.g_cycle_mask_vanishing_loss_weight = torch.Tensor([self.g_cycle_mask_vanishing_loss_weight]).to(self.device) self.g_cycle_spatial_loss_weight = torch.Tensor([self.g_cycle_spatial_loss_weight]).to(self.device) self.d_gp_loss_weight = torch.Tensor([self.d_gp_loss_weight]).to(self.device) self.d_real_cls_loss_weight = torch.Tensor([self.d_real_cls_loss_weight]).to(self.device) for epoch in range(self.start_epoch, self.epochs): batch_index = 1 self.train_data_prefetcher.reset() end = time.time() batch_data = self.train_data_prefetcher.next() # 计算一个epoch的批次数量 batches = len(self.train_data_prefetcher) # 进度条信息 batch_time = AverageMeter("Time", ":6.3f", Summary.NONE) data_time = AverageMeter("Data", ":6.3f", Summary.NONE) g_losses = AverageMeter("G loss", ":6.6f", Summary.NONE) d_losses = AverageMeter("D loss", ":6.6f", Summary.NONE)
progress = ProgressMeter(batches,
11
2023-10-31 03:17:51+00:00
8k
rationalspark/JTFT
Formers/Pyraformer/pyraformer/Pyraformer_LR.py
[ { "identifier": "EncoderLayer", "path": "Formers/Pyraformer/pyraformer/Layers.py", "snippet": "class EncoderLayer(nn.Module):\n \"\"\" Compose with two layers \"\"\"\n\n def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1, normalize_before=True, use_tvm=False, q_k_mask=None, k_q_mas...
import torch import torch.nn as nn from .Layers import EncoderLayer, Decoder, Predictor from .Layers import Bottleneck_Construct, Conv_Construct, MaxPooling_Construct, AvgPooling_Construct from .Layers import get_mask, get_subsequent_mask, refer_points, get_k_q, get_q_k from .embed import DataEmbedding, CustomEmbedding
4,525
class Encoder(nn.Module): """ A encoder model with self attention mechanism. """ def __init__(self, opt): super().__init__() self.d_model = opt.d_model self.model_type = opt.model self.window_size = opt.window_size self.truncate = opt.truncate if opt.decoder == 'attention':
class Encoder(nn.Module): """ A encoder model with self attention mechanism. """ def __init__(self, opt): super().__init__() self.d_model = opt.d_model self.model_type = opt.model self.window_size = opt.window_size self.truncate = opt.truncate if opt.decoder == 'attention':
self.mask, self.all_size = get_mask(opt.input_size, opt.window_size, opt.inner_size, opt.device)
7
2023-10-26 10:08:11+00:00
8k
Soname-Solutions/salmon
src/lib/event_mapper/impl/glue_crawler_event_mapper.py
[ { "identifier": "GeneralAwsEventMapper", "path": "src/lib/event_mapper/impl/general_aws_event_mapper.py", "snippet": "class GeneralAwsEventMapper(ABC):\n \"\"\"Abstract class containing common logic to map AWS events to notification messages.\n\n Attributes:\n settings(Settings): Settings o...
from .general_aws_event_mapper import GeneralAwsEventMapper from ...settings import Settings from ...core.constants import EventResult from ...aws.glue_manager import GlueManager
5,765
class GlueCrawlerEventMapper(GeneralAwsEventMapper): def get_resource_name(self, event): return event["detail"]["crawlerName"] def get_resource_state(self, event): return event["detail"]["state"] def get_event_result(self, event):
class GlueCrawlerEventMapper(GeneralAwsEventMapper): def get_resource_name(self, event): return event["detail"]["crawlerName"] def get_resource_state(self, event): return event["detail"]["state"] def get_event_result(self, event):
if self.get_resource_state(event) in GlueManager.Crawlers_States_Failure:
3
2023-10-27 17:05:00+00:00
8k
Sllambias/yucca
yucca/network_architectures/networks/MedNeXt.py
[ { "identifier": "MedNeXtBlock", "path": "yucca/network_architectures/blocks_and_layers/conv_blocks.py", "snippet": "class MedNeXtBlock(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n exp_r: int = 4,\n kernel_size: int = 7,\n do_...
import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from yucca.network_architectures.blocks_and_layers.conv_blocks import ( MedNeXtBlock, MedNeXtDownBlock, MedNeXtUpBlock, OutBlock, ) from yucca.network_architectures.networks.YuccaNet import YuccaNet
5,105
out_channels=n_channels * 16, exp_r=exp_r[4], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[4]) ] ) self.up_3 = MedNeXtUpBlock( in_channels=16 * n_channels, out_channels=8 * n_channels, exp_r=exp_r[5], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_3 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 8, out_channels=n_channels * 8, exp_r=exp_r[5], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[5]) ] ) self.up_2 = MedNeXtUpBlock( in_channels=8 * n_channels, out_channels=4 * n_channels, exp_r=exp_r[6], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_2 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 4, out_channels=n_channels * 4, exp_r=exp_r[6], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[6]) ] ) self.up_1 = MedNeXtUpBlock( in_channels=4 * n_channels, out_channels=2 * n_channels, exp_r=exp_r[7], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_1 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 2, out_channels=n_channels * 2, exp_r=exp_r[7], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[7]) ] ) self.up_0 = MedNeXtUpBlock( in_channels=2 * n_channels, out_channels=n_channels, exp_r=exp_r[8], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_0 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels, out_channels=n_channels, exp_r=exp_r[8], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[8]) ] )
# %% class MedNeXt(YuccaNet): """ From the paper: https://arxiv.org/pdf/2303.09975.pdf code source: https://github.com/MIC-DKFZ/MedNeXt/tree/main Using the 5-kernel L version presented in the paper. """ def __init__( self, input_channels: int, num_classes: int = 1, conv_op=None, n_channels: int = 32, exp_r=[3, 4, 8, 8, 8, 8, 8, 4, 3], # Expansion ratio as in Swin Transformers kernel_size: int = 5, # Ofcourse can test kernel_size enc_kernel_size: int = None, dec_kernel_size: int = None, deep_supervision: bool = False, # Can be used to test deep supervision do_res: bool = True, # Can be used to individually test residual connection do_res_up_down: bool = True, # Additional 'res' connection on up and down convs checkpoint_style="outside_block", # Either inside block or outside block block_counts: list = [ 3, 4, 8, 8, 8, 8, 8, 4, 3, ], # Can be used to test staging ratio: norm_type="group", grn=False, ): super().__init__() self.deep_supervision = deep_supervision self.num_classes = num_classes assert checkpoint_style in [None, "outside_block"] if checkpoint_style == "outside_block": self.outside_block_checkpointing = True else: self.outside_block_checkpointing = False if kernel_size is not None: enc_kernel_size = kernel_size dec_kernel_size = kernel_size if conv_op == nn.Conv2d: dim = "2d" else: dim = "3d" self.stem = conv_op(input_channels, n_channels, kernel_size=1) if type(exp_r) == int: exp_r = [exp_r for i in range(len(block_counts))] self.enc_block_0 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels, out_channels=n_channels, exp_r=exp_r[0], kernel_size=enc_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[0]) ] ) self.down_0 = MedNeXtDownBlock( in_channels=n_channels, out_channels=2 * n_channels, exp_r=exp_r[1], kernel_size=enc_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, ) self.enc_block_1 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 2, out_channels=n_channels * 2, exp_r=exp_r[1], kernel_size=enc_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[1]) ] ) self.down_1 = MedNeXtDownBlock( in_channels=2 * n_channels, out_channels=4 * n_channels, exp_r=exp_r[2], kernel_size=enc_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.enc_block_2 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 4, out_channels=n_channels * 4, exp_r=exp_r[2], kernel_size=enc_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[2]) ] ) self.down_2 = MedNeXtDownBlock( in_channels=4 * n_channels, out_channels=8 * n_channels, exp_r=exp_r[3], kernel_size=enc_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.enc_block_3 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 8, out_channels=n_channels * 8, exp_r=exp_r[3], kernel_size=enc_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[3]) ] ) self.down_3 = MedNeXtDownBlock( in_channels=8 * n_channels, out_channels=16 * n_channels, exp_r=exp_r[4], kernel_size=enc_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.bottleneck = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 16, out_channels=n_channels * 16, exp_r=exp_r[4], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[4]) ] ) self.up_3 = MedNeXtUpBlock( in_channels=16 * n_channels, out_channels=8 * n_channels, exp_r=exp_r[5], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_3 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 8, out_channels=n_channels * 8, exp_r=exp_r[5], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[5]) ] ) self.up_2 = MedNeXtUpBlock( in_channels=8 * n_channels, out_channels=4 * n_channels, exp_r=exp_r[6], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_2 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 4, out_channels=n_channels * 4, exp_r=exp_r[6], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[6]) ] ) self.up_1 = MedNeXtUpBlock( in_channels=4 * n_channels, out_channels=2 * n_channels, exp_r=exp_r[7], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_1 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels * 2, out_channels=n_channels * 2, exp_r=exp_r[7], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[7]) ] ) self.up_0 = MedNeXtUpBlock( in_channels=2 * n_channels, out_channels=n_channels, exp_r=exp_r[8], kernel_size=dec_kernel_size, do_res=do_res_up_down, norm_type=norm_type, dim=dim, grn=grn, ) self.dec_block_0 = nn.Sequential( *[ MedNeXtBlock( in_channels=n_channels, out_channels=n_channels, exp_r=exp_r[8], kernel_size=dec_kernel_size, do_res=do_res, norm_type=norm_type, dim=dim, grn=grn, ) for i in range(block_counts[8]) ] )
self.out_0 = OutBlock(in_channels=n_channels, n_classes=self.num_classes, dim=dim)
3
2023-10-26 08:13:03+00:00
8k
artnoage/expllama
pretrain/llama.py
[ { "identifier": "GPT", "path": "lit_gpt/model.py", "snippet": "class Loralinear(nn.Module):\nclass GPT(nn.Module):\nclass Block(nn.Module):\nclass CausalSelfAttention(nn.Module):\nclass GptNeoxMLP(nn.Module):\nclass LLaMAMLP(nn.Module):\n def __init__(self, input_dim:int, lora_dim:int, output_dim:int...
import glob import math import sys import time import math import lightning as L import torch import random from pathlib import Path from typing import Optional, Tuple, Union from lightning.fabric.strategies import FSDPStrategy, XLAStrategy from torch.utils.data import DataLoader from functools import partial from lit_gpt.model import GPT, Block, Config, CausalSelfAttention from lit_gpt.packed_dataset import CombinedDataset, PackedDataset from lit_gpt.speed_monitor import SpeedMonitorFabric as Monitor from lit_gpt.speed_monitor import estimate_flops, measure_flops from lit_gpt.utils import chunked_cross_entropy, get_default_supported_precision, num_parameters, step_csv_logger, lazy_load from pytorch_lightning.loggers import WandbLogger from lit_gpt import FusedCrossEntropyLoss from jsonargparse import CLI
6,147
total_t0 = time.perf_counter() initial_iter = state["iter_num"] curr_iter = 0 loss_func = FusedCrossEntropyLoss() for train_data in train_dataloader: # resume loader state. This is not elegant but it works. Should rewrite it in the future. if resume: if curr_iter < initial_iter: curr_iter += 1 continue else: resume = False curr_iter = -1 fabric.barrier() fabric.print("resume finished, taken {} seconds".format(time.perf_counter() - total_t0)) if state["iter_num"] >= max_iters: break # determine and set the learning rate for this iteration lr = get_lr(state["iter_num"]) if decay_lr else learning_rate for param_group in optimizer.param_groups: param_group["lr"] = lr iter_t0 = time.perf_counter() input_ids = train_data[:, 0 : model.config.block_size].contiguous() targets = train_data[:, 1 : model.config.block_size + 1].contiguous() is_accumulating = (state["iter_num"] + 1) % gradient_accumulation_steps != 0 with fabric.no_backward_sync(model, enabled=is_accumulating): logits = model(input_ids) loss = loss_func(logits, targets) # loss = chunked_cross_entropy(logits, targets, chunk_size=0) fabric.backward(loss / gradient_accumulation_steps) if not is_accumulating: fabric.clip_gradients(model, optimizer, max_norm=grad_clip) optimizer.step() optimizer.zero_grad() state["step_count"] += 1 elif fabric.device.type == "xla": xm.mark_step() state["iter_num"] += 1 # input_id: B L total_lengths += input_ids.size(1) t1 = time.perf_counter() fabric.print( f"iter {state['iter_num']} step {state['step_count']}: loss {loss.item():.4f}, iter time:" f" {(t1 - iter_t0) * 1000:.2f}ms{' (optimizer.step)' if not is_accumulating else ''}" f" remaining time: {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600:.2f} hours. " # print days as well f" or {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600 / 24:.2f} days. " ) monitor.on_train_batch_end( state["iter_num"] * micro_batch_size, t1 - total_t0, # this assumes that device FLOPs are the same and that all devices have the same batch size fabric.world_size, flops_per_batch=estimated_flops, lengths=total_lengths, train_loss = loss.item() ) if val_dataloader is not None and not is_accumulating and state["step_count"] % eval_step_interval == 0: t0 = time.perf_counter() val_loss = validate(fabric, model, val_dataloader) t1 = time.perf_counter() - t0 monitor.eval_end(t1) fabric.print(f"step {state['iter_num']}: val loss {val_loss:.4f}, val time: {t1 * 1000:.2f}ms") fabric.log_dict({"metric/val_loss": val_loss.item(), "total_tokens": model.config.block_size * (state["iter_num"] + 1) * micro_batch_size * fabric.world_size},state["step_count"]) fabric.log_dict({"metric/val_ppl": math.exp(val_loss.item()), "total_tokens": model.config.block_size * (state["iter_num"] + 1) * micro_batch_size * fabric.world_size},state["step_count"]) fabric.barrier() if not is_accumulating and state["step_count"] % save_step_interval == 0: checkpoint_path = out_dir / f"iter-{state['iter_num']:06d}-ckpt.pth" fabric.print(f"Saving checkpoint to {str(checkpoint_path)!r}") fabric.save(checkpoint_path, state) @torch.no_grad() def validate(fabric: L.Fabric, model: torch.nn.Module, val_dataloader: DataLoader) -> torch.Tensor: fabric.print("Validating ...") model.eval() losses = torch.zeros(eval_iters, device=fabric.device) for k, val_data in enumerate(val_dataloader): if k >= eval_iters: break input_ids = val_data[:, 0 : model.config.block_size].contiguous() targets = val_data[:, 1 : model.config.block_size + 1].contiguous() logits = model(input_ids) loss = chunked_cross_entropy(logits, targets, chunk_size=0) # loss_func = FusedCrossEntropyLoss() # loss = loss_func(logits, targets) losses[k] = loss.item() out = losses.mean() model.train() return out def create_dataloader( batch_size: int, block_size: int, data_dir: Path, fabric, shuffle: bool = True, seed: int = 12345, split="train" ) -> DataLoader: datasets = [] data_config = train_data_config if split == "train" else val_data_config for prefix, _ in data_config: filenames = sorted(glob.glob(str(data_dir / f"{prefix}*"))) random.seed(seed) random.shuffle(filenames)
# support running without installing as a package wd = Path(__file__).parent.parent.resolve() sys.path.append(str(wd)) # from apex.optimizers import FusedAdam #torch optimizer has a cuda backend, which is faster actually model_name = "tiny_LLaMA_120M" name = model_name out_dir = Path("out") / name # Hyperparameters num_of_devices = 5 gradient_accumulation_steps=3 learning_rate = 4e-4 micro_batch_size = 14 max_step = 500000 warmup_steps = 2000 log_step_interval = 10 eval_iters = 500 save_step_interval = 20000 eval_step_interval = 2000 config = Config.from_name(model_name) weight_decay = 1e-1 beta1 = 0.9 beta2 = 0.95 grad_clip = 1.0 decay_lr = True min_lr = 8e-6 global_batch_size=num_of_devices*gradient_accumulation_steps*micro_batch_size print("Tokens per step",global_batch_size*config.block_size/10**6, "M" ,"total tokens:",global_batch_size*2048*max_step/10**9,"B") warmup_iters = warmup_steps * gradient_accumulation_steps max_iters = max_step * gradient_accumulation_steps lr_decay_iters = 300000 * gradient_accumulation_steps log_iter_interval = log_step_interval * gradient_accumulation_steps # Treat all dataset equally by their size. If you want to use a different weight for a dataset, add it to the list with the weight. train_data_config = [ ("train_slim", 0.693584), ("train_star", 0.306416), ] val_data_config = [ ("validation", 1.0), ] hparams = {k: v for k, v in locals().items() if isinstance(v, (int, float, str)) and not k.startswith("_")} logger = step_csv_logger("out", name, flush_logs_every_n_steps=log_iter_interval) wandb_logger = WandbLogger(project="Llama",name=model_name, resume="9rc2f7k6") def setup( devices: int = 5, train_data_dir: Path = Path("/scratch/laschos/data/slim_star_combined"), val_data_dir: Optional[Path] =Path("/scratch/laschos/data/slim_star_combined"), precision: Optional[str] = None, tpu: bool = False, resume: Union[bool, Path] = True, ) -> None: precision = precision or get_default_supported_precision(training=True, tpu=tpu) if devices > 1: if tpu: # For multi-host TPU training, the device count for Fabric is limited to the count on a single host. devices = "auto" strategy = XLAStrategy(sync_module_states=False) else: strategy = FSDPStrategy( auto_wrap_policy={Block}, activation_checkpointing_policy=None, state_dict_type="full", limit_all_gathers=True, cpu_offload=False, ) else: strategy = "auto" fabric = L.Fabric(devices=devices, strategy=strategy, precision=precision, loggers=[logger, wandb_logger]) fabric.print(hparams) #fabric.launch(main, train_data_dir, val_data_dir, resume) main(fabric, train_data_dir, val_data_dir, resume) def main(fabric, train_data_dir, val_data_dir, resume): monitor = Monitor(fabric, window_size=2, time_unit="seconds", log_iter_interval=log_iter_interval) if fabric.global_rank == 0: out_dir.mkdir(parents=True, exist_ok=True) train_dataloader, val_dataloader = create_dataloaders( batch_size=micro_batch_size, block_size=config.block_size, fabric=fabric, train_data_dir=train_data_dir, val_data_dir=val_data_dir, seed=3407, ) if val_dataloader is None: train_dataloader = fabric.setup_dataloaders(train_dataloader) else: train_dataloader, val_dataloader = fabric.setup_dataloaders(train_dataloader, val_dataloader) fabric.seed_everything(3407) # same seed for every process to init model (FSDP) fabric.print(f"Loading model with {config.__dict__}") t0 = time.perf_counter() with fabric.init_module(empty_init=True): model = GPT(config) model.apply(partial(model._init_weights ,n_layer=config.n_layer)) fabric.print(f"Time to instantiate model: {time.perf_counter() - t0:.02f} seconds.") fabric.print(f"Total parameters {num_parameters(model):,}") model = fabric.setup(model) optimizer = torch.optim.AdamW( model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2), foreach=False ) # optimizer = FusedAdam(model.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=(beta1, beta2),adam_w_mode=True) optimizer = fabric.setup_optimizers(optimizer) state = {"model": model, "optimizer": optimizer, "hparams": hparams, "iter_num": 0, "step_count": 0} if resume is True: resume = sorted(out_dir.glob("*.pth"))[-1] if resume : fabric.print(f"Resuming training from {resume}") fabric.load(resume, state) train_time = time.perf_counter() train(fabric, state, train_dataloader, val_dataloader, monitor, resume) fabric.print(f"Training time: {(time.perf_counter()-train_time):.2f}s") if fabric.device.type == "cuda": fabric.print(f"Memory used: {torch.cuda.max_memory_allocated() / 1e9:.02f} GB") def train(fabric, state, train_dataloader, val_dataloader, monitor, resume): model = state["model"] optimizer = state["optimizer"] if val_dataloader is not None: validate(fabric, model, val_dataloader) # sanity check with torch.device("meta"): meta_model = GPT(model.config) # "estimated" is not as precise as "measured". Estimated is optimistic but widely used in the wild. # When comparing MFU or FLOP numbers with other projects that use estimated FLOPs, # consider passing `SpeedMonitor(flops_per_batch=estimated_flops)` instead estimated_flops = estimate_flops(meta_model) * micro_batch_size fabric.print(f"Estimated TFLOPs: {estimated_flops * fabric.world_size / 1e12:.2f}") x = torch.randint(0, 1, (micro_batch_size, model.config.block_size)) # measured_flos run in meta. Will trigger fusedRMSNorm error #measured_flops = measure_flops(meta_model, x) #fabric.print(f"Measured TFLOPs: {measured_flops * fabric.world_size / 1e12:.2f}") del meta_model, x total_lengths = 0 total_t0 = time.perf_counter() initial_iter = state["iter_num"] curr_iter = 0 loss_func = FusedCrossEntropyLoss() for train_data in train_dataloader: # resume loader state. This is not elegant but it works. Should rewrite it in the future. if resume: if curr_iter < initial_iter: curr_iter += 1 continue else: resume = False curr_iter = -1 fabric.barrier() fabric.print("resume finished, taken {} seconds".format(time.perf_counter() - total_t0)) if state["iter_num"] >= max_iters: break # determine and set the learning rate for this iteration lr = get_lr(state["iter_num"]) if decay_lr else learning_rate for param_group in optimizer.param_groups: param_group["lr"] = lr iter_t0 = time.perf_counter() input_ids = train_data[:, 0 : model.config.block_size].contiguous() targets = train_data[:, 1 : model.config.block_size + 1].contiguous() is_accumulating = (state["iter_num"] + 1) % gradient_accumulation_steps != 0 with fabric.no_backward_sync(model, enabled=is_accumulating): logits = model(input_ids) loss = loss_func(logits, targets) # loss = chunked_cross_entropy(logits, targets, chunk_size=0) fabric.backward(loss / gradient_accumulation_steps) if not is_accumulating: fabric.clip_gradients(model, optimizer, max_norm=grad_clip) optimizer.step() optimizer.zero_grad() state["step_count"] += 1 elif fabric.device.type == "xla": xm.mark_step() state["iter_num"] += 1 # input_id: B L total_lengths += input_ids.size(1) t1 = time.perf_counter() fabric.print( f"iter {state['iter_num']} step {state['step_count']}: loss {loss.item():.4f}, iter time:" f" {(t1 - iter_t0) * 1000:.2f}ms{' (optimizer.step)' if not is_accumulating else ''}" f" remaining time: {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600:.2f} hours. " # print days as well f" or {(t1 - total_t0) / (state['iter_num'] - initial_iter) * (max_iters - state['iter_num']) / 3600 / 24:.2f} days. " ) monitor.on_train_batch_end( state["iter_num"] * micro_batch_size, t1 - total_t0, # this assumes that device FLOPs are the same and that all devices have the same batch size fabric.world_size, flops_per_batch=estimated_flops, lengths=total_lengths, train_loss = loss.item() ) if val_dataloader is not None and not is_accumulating and state["step_count"] % eval_step_interval == 0: t0 = time.perf_counter() val_loss = validate(fabric, model, val_dataloader) t1 = time.perf_counter() - t0 monitor.eval_end(t1) fabric.print(f"step {state['iter_num']}: val loss {val_loss:.4f}, val time: {t1 * 1000:.2f}ms") fabric.log_dict({"metric/val_loss": val_loss.item(), "total_tokens": model.config.block_size * (state["iter_num"] + 1) * micro_batch_size * fabric.world_size},state["step_count"]) fabric.log_dict({"metric/val_ppl": math.exp(val_loss.item()), "total_tokens": model.config.block_size * (state["iter_num"] + 1) * micro_batch_size * fabric.world_size},state["step_count"]) fabric.barrier() if not is_accumulating and state["step_count"] % save_step_interval == 0: checkpoint_path = out_dir / f"iter-{state['iter_num']:06d}-ckpt.pth" fabric.print(f"Saving checkpoint to {str(checkpoint_path)!r}") fabric.save(checkpoint_path, state) @torch.no_grad() def validate(fabric: L.Fabric, model: torch.nn.Module, val_dataloader: DataLoader) -> torch.Tensor: fabric.print("Validating ...") model.eval() losses = torch.zeros(eval_iters, device=fabric.device) for k, val_data in enumerate(val_dataloader): if k >= eval_iters: break input_ids = val_data[:, 0 : model.config.block_size].contiguous() targets = val_data[:, 1 : model.config.block_size + 1].contiguous() logits = model(input_ids) loss = chunked_cross_entropy(logits, targets, chunk_size=0) # loss_func = FusedCrossEntropyLoss() # loss = loss_func(logits, targets) losses[k] = loss.item() out = losses.mean() model.train() return out def create_dataloader( batch_size: int, block_size: int, data_dir: Path, fabric, shuffle: bool = True, seed: int = 12345, split="train" ) -> DataLoader: datasets = [] data_config = train_data_config if split == "train" else val_data_config for prefix, _ in data_config: filenames = sorted(glob.glob(str(data_dir / f"{prefix}*"))) random.seed(seed) random.shuffle(filenames)
dataset = PackedDataset(
2
2023-10-31 13:28:51+00:00
8k
HydrogenStorage/molecular-stability-computer
compute_emin.py
[ { "identifier": "load_database", "path": "emin/app.py", "snippet": "def load_database(run_path: str | Path, level: str, relax: bool) -> tuple[Path, dict[str, float]]:\n \"\"\"Load the energies of molecules for our known settings\n\n Creates the output file for the run if needed\n\n Args:\n ...
from functools import partial, update_wrapper from concurrent.futures import Future from argparse import ArgumentParser from threading import Semaphore from time import perf_counter from typing import Iterable from pathlib import Path from parsl import Config, HighThroughputExecutor, python_app, ThreadPoolExecutor from rdkit.Chem import rdMolDescriptors from rdkit import Chem, RDLogger from emin.app import load_database, write_result from emin.generate import generate_molecules_with_surge, get_random_selection_with_surge from emin.parsl import run_molecule, load_config from emin.source import get_molecules_from_pubchem import logging import gzip import sys import parsl
4,051
logger = logging.getLogger('main') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') for handler in handlers: handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) our_key = Chem.MolToInchiKey(mol) logger.info(f'Starting E_min run for {args.molecule} (InChI Key: {our_key}) in {out_dir}') logger.info(f'Running accuracy level: {args.level}. Relaxation: {not args.no_relax}') # Make the Parsl configuration if args.compute_config is None: logger.info('Using default Parsl configuration of a single worker on the local machine') config = Config( executors=[HighThroughputExecutor(max_workers=1, address='127.0.0.1')] ) else: logger.info(f'Loading Parsl configuration from {args.compute_config}') config = load_config(args.compute_config) compute_execs = [e.label for e in config.executors] config.executors = list(config.executors) + [ThreadPoolExecutor(max_threads=1, label='writer')] # Add a process that only writes config.run_dir = str(out_dir / 'runinfo') dfk = parsl.load(config) pinned_fun = partial(run_molecule, level=args.level, relax=not args.no_relax) update_wrapper(pinned_fun, run_molecule) run_app = python_app(pinned_fun, executors=compute_execs) logger.info('Started Parsl and created the app to be run') # Load any previous computations energy_file, known_energies = load_database(out_dir, args.level, not args.no_relax) logger.info(f'Loaded {len(known_energies)} energies from previous runs') # Open the output files result_file = out_dir / 'results.json.gz' with gzip.open(result_file, 'at') as fr, energy_file.open('a') as fe: # Make utility functions write_fn = partial(write_result, relax=not args.no_relax, level=args.level, energy_database_fp=fe, record_fp=fr) update_wrapper(write_fn, write_result) write_app = python_app(write_fn, executors=['writer']) def _run_if_needed(my_smiles: str, my_save_results: bool = True) -> tuple[bool, str, float | Future]: """Get the energy either by looking up result or running a new computation Returns: - Whether the energy is done now - The InChI Key for the molecule - Either the energy or a future with the label "key" associated with it """ my_key = get_key(my_smiles) if my_key not in known_energies: future = run_app(my_smiles, return_full_record=my_save_results) return False, my_key, future else: return True, my_key, known_energies[my_key] # Start by running our molecule our_smiles = Chem.MolToSmiles(mol) is_done, our_key, our_energy = _run_if_needed(our_smiles) if not is_done: our_write = write_app(our_key, our_smiles, our_energy, known_energies, save_result=True) our_energy, runtime, xyz, result = our_energy.result() our_write.result() # Make sure we write logger.info(f'Target molecule has an energy of {our_energy:.3f} Ha') # Gather molecules from PubChem pubchem = get_molecules_from_pubchem(formula) logger.info(f'Pulled {len(pubchem)} molecules for {formula} from PubChem') def _submit_all(my_mol_list: Iterable[str], my_warnings: bool = False, my_save_results: bool = False) -> int: """Run all molecules Returns: Number submitted """ count = 0 # Number of new computations # Submit all the molecules submit_controller = Semaphore(max(args.num_parallel, 2)) # Control the maximum number of submissions for my_smiles in my_mol_list: try: submit_controller.acquire() # Block until resources are freed by the callback my_is_done, my_key, my_result = _run_if_needed(my_smiles, my_save_results) except ValueError: if my_warnings: logger.warning(f'Failed to parse SMILES: {my_smiles}') continue # Add the write app, if needed if not my_is_done: count += 1 my_result.add_done_callback(lambda x: submit_controller.release()) write_app(my_key, my_smiles, my_result, known_energies, save_result=my_save_results) else: submit_controller.release() # We didn't create a future # Block until all finish dfk.wait_for_current_tasks() return count # Run them all before_count = len(known_energies) submit_count = _submit_all(pubchem, my_warnings=True, my_save_results=True) success_count = len(known_energies) - before_count logger.info(f'Successfully ran {success_count} molecules from PubChem of {submit_count} submitted') logger.info(f'Emin of molecule compared to PubChem: {(our_energy - min(known_energies.values())) * 1000:.1f} mHa') # Test molecules from surge if args.surge_amount is not None and args.surge_amount <= 0: logger.info('Skipping comparison against Surge-generated molecules') else: if args.surge_amount is None: logger.info('Comparing against all molecules generated by Surge') mol_list = generate_molecules_with_surge(formula) else: logger.info(f'Selecting a random subset from Surge molecules. Amount to select: {args.surge_amount}')
"""Compute the E_min of a target molecule""" RDLogger.DisableLog('rdApp.*') def get_key(smiles: str) -> str: """Get InChI key from a SMILES""" mol = Chem.MolFromSmiles(smiles) if mol is None: raise ValueError(f'SMILES failed to parse: {smiles}') return Chem.MolToInchiKey(mol) if __name__ == "__main__": # Parse arguments start_time = perf_counter() parser = ArgumentParser() parser.add_argument('--level', default='xtb', help='Accuracy level at which to compute energies') parser.add_argument('--no-relax', action='store_true', help='Skip relaxing the molecular structure') parser.add_argument('--skip-store', action='store_true', help='Skip storing the full QCEngine record') parser.add_argument('--num-parallel', default=10000, type=int, help='Maximum number of chemistry computations to run at the same time') parser.add_argument('--compute-config', help='Path to the file defining the Parsl configuration. Configuration should be in variable named ``config``') parser.add_argument('--surge-amount', type=float, help='Maximum number or fraction of molecules to generate from Surge. Set to 0 or less to disable surge. Default is to run all') parser.add_argument('molecule', help='SMILES or InChI of the target molecule') args = parser.parse_args() # Parse the molecule if args.molecule.startswith('InChI='): mol = Chem.MolFromInchi(args.molecule) else: mol = Chem.MolFromSmiles(args.molecule) if mol is None: raise ValueError(f'Molecule failed to parse: "{args.molecule}"') # Get the composition of the molecule, which will define our output directory formula = rdMolDescriptors.CalcMolFormula(mol) out_dir = Path('runs') / formula out_dir.mkdir(parents=True, exist_ok=True) # Set up the logging handlers = [logging.FileHandler(out_dir / 'runtime.log'), logging.StreamHandler(sys.stdout)] logger = logging.getLogger('main') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') for handler in handlers: handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) our_key = Chem.MolToInchiKey(mol) logger.info(f'Starting E_min run for {args.molecule} (InChI Key: {our_key}) in {out_dir}') logger.info(f'Running accuracy level: {args.level}. Relaxation: {not args.no_relax}') # Make the Parsl configuration if args.compute_config is None: logger.info('Using default Parsl configuration of a single worker on the local machine') config = Config( executors=[HighThroughputExecutor(max_workers=1, address='127.0.0.1')] ) else: logger.info(f'Loading Parsl configuration from {args.compute_config}') config = load_config(args.compute_config) compute_execs = [e.label for e in config.executors] config.executors = list(config.executors) + [ThreadPoolExecutor(max_threads=1, label='writer')] # Add a process that only writes config.run_dir = str(out_dir / 'runinfo') dfk = parsl.load(config) pinned_fun = partial(run_molecule, level=args.level, relax=not args.no_relax) update_wrapper(pinned_fun, run_molecule) run_app = python_app(pinned_fun, executors=compute_execs) logger.info('Started Parsl and created the app to be run') # Load any previous computations energy_file, known_energies = load_database(out_dir, args.level, not args.no_relax) logger.info(f'Loaded {len(known_energies)} energies from previous runs') # Open the output files result_file = out_dir / 'results.json.gz' with gzip.open(result_file, 'at') as fr, energy_file.open('a') as fe: # Make utility functions write_fn = partial(write_result, relax=not args.no_relax, level=args.level, energy_database_fp=fe, record_fp=fr) update_wrapper(write_fn, write_result) write_app = python_app(write_fn, executors=['writer']) def _run_if_needed(my_smiles: str, my_save_results: bool = True) -> tuple[bool, str, float | Future]: """Get the energy either by looking up result or running a new computation Returns: - Whether the energy is done now - The InChI Key for the molecule - Either the energy or a future with the label "key" associated with it """ my_key = get_key(my_smiles) if my_key not in known_energies: future = run_app(my_smiles, return_full_record=my_save_results) return False, my_key, future else: return True, my_key, known_energies[my_key] # Start by running our molecule our_smiles = Chem.MolToSmiles(mol) is_done, our_key, our_energy = _run_if_needed(our_smiles) if not is_done: our_write = write_app(our_key, our_smiles, our_energy, known_energies, save_result=True) our_energy, runtime, xyz, result = our_energy.result() our_write.result() # Make sure we write logger.info(f'Target molecule has an energy of {our_energy:.3f} Ha') # Gather molecules from PubChem pubchem = get_molecules_from_pubchem(formula) logger.info(f'Pulled {len(pubchem)} molecules for {formula} from PubChem') def _submit_all(my_mol_list: Iterable[str], my_warnings: bool = False, my_save_results: bool = False) -> int: """Run all molecules Returns: Number submitted """ count = 0 # Number of new computations # Submit all the molecules submit_controller = Semaphore(max(args.num_parallel, 2)) # Control the maximum number of submissions for my_smiles in my_mol_list: try: submit_controller.acquire() # Block until resources are freed by the callback my_is_done, my_key, my_result = _run_if_needed(my_smiles, my_save_results) except ValueError: if my_warnings: logger.warning(f'Failed to parse SMILES: {my_smiles}') continue # Add the write app, if needed if not my_is_done: count += 1 my_result.add_done_callback(lambda x: submit_controller.release()) write_app(my_key, my_smiles, my_result, known_energies, save_result=my_save_results) else: submit_controller.release() # We didn't create a future # Block until all finish dfk.wait_for_current_tasks() return count # Run them all before_count = len(known_energies) submit_count = _submit_all(pubchem, my_warnings=True, my_save_results=True) success_count = len(known_energies) - before_count logger.info(f'Successfully ran {success_count} molecules from PubChem of {submit_count} submitted') logger.info(f'Emin of molecule compared to PubChem: {(our_energy - min(known_energies.values())) * 1000:.1f} mHa') # Test molecules from surge if args.surge_amount is not None and args.surge_amount <= 0: logger.info('Skipping comparison against Surge-generated molecules') else: if args.surge_amount is None: logger.info('Comparing against all molecules generated by Surge') mol_list = generate_molecules_with_surge(formula) else: logger.info(f'Selecting a random subset from Surge molecules. Amount to select: {args.surge_amount}')
mol_list, total = get_random_selection_with_surge(formula, to_select=args.surge_amount)
3
2023-10-31 20:30:31+00:00
8k
wallneradam/esorm
esorm/model.py
[ { "identifier": "snake_case", "path": "esorm/utils.py", "snippet": "def snake_case(camel_str: str):\n \"\"\"\n Convert to snake case\n\n :param camel_str: The string to convert to snake case\n :return: Converted string\n \"\"\"\n if '_' in camel_str: # If it is already snake cased\n ...
from typing import TypeVar, Any, Dict, Optional, Tuple, Type, Union, get_args, get_origin, List, Callable, Awaitable from datetime import datetime, date, time from functools import wraps from elasticsearch import NotFoundError as ElasticNotFoundError from pydantic import main as pydantic_main from pydantic import BaseModel, ConfigDict from pydantic.fields import Field, FieldInfo, PrivateAttr from .utils import snake_case from .aggs import ESAggs, ESAggsResponse from .error import InvalidResponseError, NotFoundError from .esorm import es from .query import ESQuery from .response import ESResponse from .logger import logger from pprint import pformat import ast import inspect import textwrap import traceback import elasticsearch
3,639
size=page_size, sort=sort, routing=routing, aggs=aggs, **kwargs) @classmethod async def search(cls: Type[TModel], query: ESQuery, *, page_size: Optional[int] = None, page: Optional[int] = None, sort: Optional[Union[list, str]] = None, routing: Optional[str] = None, res_dict: bool = False, **kwargs) -> Union[List[TModel], Dict[str, TModel]]: """ Search Model with query dict :param query: ElasticSearch query dict :param page_size: Pagination page size :param page: Pagination page num, 1st page is 1 :param sort: Name of field to be sorted, or sort term list of dict, if not specified, model's default sort will be used, or no sorting :param routing: Shard routing value :param res_dict: If the result should be a dict with id as key and model as value instead of a list of models :param kwargs: Other search API params :return: The result list """ res = await cls._search(query, page_size=page_size, page=page, sort=sort, routing=routing, **kwargs) try: if res_dict: return {hit['_id']: cls.from_es(hit) for hit in res['hits']['hits']} return [cls.from_es(hit) for hit in res['hits']['hits']] except KeyError: return [] @classmethod async def search_one(cls: Type[TModel], query: ESQuery, *, routing: Optional[str] = None, **kwargs) \ -> Optional[TModel]: """ Search Model and return the first result :param query: ElasticSearch query dict :param routing: Shard routing value :param kwargs: Other search API params :return: The first result or None if no result """ res = await cls.search(query, page_size=1, routing=routing, **kwargs) if len(res) > 0: return res[0] else: return None @staticmethod def create_query_from_dict(fields: Dict[str, Union[str, int, float]]) -> ESQuery: """ Creates a query dict from a dictionary of fields and values :param fields: A dictionary of fields and values to search by :return: A query dict """ return { 'bool': { 'must': [{ 'match': { k: {'query': v, 'operator': 'and'}, } } for k, v in fields.items()] } } @classmethod async def search_by_fields(cls: Type[TModel], fields: Dict[str, Union[str, int, float]], *, page_size: Optional[int] = None, page: Optional[int] = None, sort: Optional[Union[list, str]] = None, routing: Optional[str] = None, aggs: Optional[ESAggs] = None, res_dict: bool = False, **kwargs) -> List[TModel]: """ Search Model by fields as key-value pairs :param fields: A dictionary of fields and values to search by :param page_size: Pagination page size :param page: Pagination page num, 1st page is 1 :param sort: Name of field to be sorted, or sort term list of dict, if not specified, model's default sort will be used, or no sorting :param routing: Shard routing value :param aggs: Aggregations :param res_dict: If the result should be a dict with id as key and model as value instead of a list of models :param kwargs: Other search API params :return: The result list """ query = cls.create_query_from_dict(fields) return await cls.search(query, page_size=page_size, page=page, sort=sort, routing=routing, aggs=aggs, res_dict=res_dict, **kwargs) @classmethod async def search_one_by_fields(cls: Type[TModel], fields: Dict[str, Union[str, int, float]], *, routing: Optional[str] = None, aggs: Optional[ESAggs] = None, **kwargs) -> Optional[TModel]: """ Search Model by fields as key-value pairs and return the first result :param fields: A dictionary of fields and values to search by :param routing: Shard routing value :param aggs: Aggregations :param kwargs: Other search API params :return: The first result or None if no result """ query = cls.create_query_from_dict(fields) return await cls.search_one(query, routing=routing, aggs=aggs, **kwargs) @classmethod async def aggregate(cls: Type[TModel], aggs: ESAggs, *, query: Optional[ESQuery] = None, routing: Optional[str] = None,
""" This module contains the ESModel classes and related functions """ __all__ = [ 'TModel', 'ESModel', 'ESModelTimestamp', 'Pagination', 'Sort', 'setup_mappings', 'create_index_template', 'set_default_index_prefix', 'lazy_property' ] # noinspection PyProtectedMember _model_construction = getattr(pydantic_main, '_model_construction') ModelMetaclass = _model_construction.ModelMetaclass _default_index_prefix = 'esorm' # Map python types to ES type _pydantic_type_map = { str: 'keyword', # Str is defaulted to keyword int: 'long', float: 'double', bool: 'boolean', datetime: 'date', date: 'date', time: 'date', } TModel = TypeVar('TModel', bound='ESModel') def _description_from_docstring(model: Type[BaseModel]): """ Set undefined field descriptions from variable docstrings :param model: The model to set the descriptions """ try: source = textwrap.dedent(inspect.getsource(model)) module = ast.parse(source) assert isinstance(module, ast.Module) class_def = module.body[0] assert isinstance(class_def, ast.ClassDef) if len(class_def.body) < 2: return except OSError: return for last, node in zip(class_def.body, class_def.body[1:]): try: if not (isinstance(last, ast.AnnAssign) and isinstance(last.target, ast.Name) and isinstance(node, ast.Expr)): continue info = model.model_fields[last.target.id] if info.description is not None: continue doc_node = node.value if isinstance(doc_node, ast.Constant): # 'regular' variable doc string docstring = doc_node.value.strip() else: raise NotImplementedError(doc_node) info.description = docstring except KeyError: pass def _patch_set_model_fields(): """ Monkey patchon _model_construction.set_model_fields to set undefined field descriptions from docstrings """ orig_set_model_fields = _model_construction.set_model_fields def set_model_fields(model: Type[BaseModel], bases: Tuple[Type[Any], ...], config_wrapper: Any, types_namespace: Dict[str, Any]) -> None: orig_set_model_fields(model, bases, config_wrapper, types_namespace) _description_from_docstring(model) _model_construction.set_model_fields = set_model_fields _patch_set_model_fields() class _ESModelMeta(ModelMetaclass): """ ESModel Metaclass """ # All model classes collected __models__: Dict[str, Type['ESModel']] = {} # noinspection PyUnresolvedReferences def __new__(cls: Type[ModelMetaclass], name: str, bases: Tuple[type, ...], namespace: Dict[str, Any], **kwds: Any): model: Type[BaseModel] = super().__new__(cls, name, bases, namespace, **kwds) if name not in ("ESModel", "ESModelTimestamp"): # ESConfig inheritance m_dict = {k: v for k, v in ESModel.ESConfig.__dict__.items() if k[0] != '_'} if bases and 'ESConfig' in bases[0].__dict__: m_dict.update({k: v for k, v in bases[0].ESConfig.__dict__.items() if k[0] != '_'}) del m_dict['index'] # It is only allowed to be set on the actual model class if 'ESConfig' in model.__dict__: m_dict.update({k: v for k, v in model.ESConfig.__dict__.items() if k[0] != '_'}) m_dict['_lazy_properties'] = {} # Create (new) ESConfig class inside the class model.ESConfig = type('ESConfig', (object,), dict(m_dict)) # Set default index name if not already set if not getattr(model.ESConfig, 'index', None): # Default index is the name of the class in snake_case model.ESConfig.index = _default_index_prefix + '-' + snake_case(name) # If there is an 'id' field, set it as id_field if 'id' in model.model_fields.keys(): model.ESConfig.id_field = 'id' # Add to models cls.__models__[model.ESConfig.index] = model # Collect lazy properties for attr_name, attr in namespace.items(): # Support computed fields if attr.__class__.__name__ == 'PydanticDescriptorProxy': attr = getattr(attr, 'wrapped') # Is it a lazy property? if isinstance(attr, property) and hasattr(attr.fget, '__lazy_property__'): # noinspection PyProtectedMember model.ESConfig._lazy_properties[attr_name] = getattr(attr.fget, '__lazy_property__') return model class ESModel(BaseModel, metaclass=_ESModelMeta): """ ElasticSearch Base Model """ _id: Optional[str] = PrivateAttr(None) """ The ES id of the document """ class ESConfig: """ ESModel Config """ # The index name index: Optional[str] = None # The name of the 'id' field id_field: Optional[str] = None # Default sort default_sort: Optional[List[Dict[str, Dict[str, str]]]] = None # ElasticSearch index settings settings: Optional[Dict[str, Any]] = None # Lazy properties - it is filled by the metaclass _lazy_properties: Dict[str, Callable[[], Awaitable[Any]]] = {} # Pydantic model config model_config = ConfigDict( str_strip_whitespace=True, extra="forbid", populate_by_name=True, arbitrary_types_allowed=True, ser_json_bytes='base64', validate_assignment=True, ) @property def __id__(self) -> str: """ The id of the document This can be overridden to make computed ids :return: The id of the document """ return getattr(self, self.ESConfig.id_field or '_id') @property def __routing__(self) -> Optional[str]: """ Shard route name :return: Shard route name """ return None @classmethod async def call(cls, method_name, *, wait_for=None, **kwargs) -> dict: """ Call an elasticsearch method This is a low level ES method call, it is not recommended to use this directly. :param method_name: The name of the method to call :param wait_for: Waits for all shards to sync before returning response :param kwargs: The arguments to pass to the method :return: The result dictionary from ElasticSearch """ kwargs = dict(kwargs) method = getattr(es, method_name) index = cls.ESConfig.index if wait_for is not None: kwargs['refresh'] = "wait_for" if 'request_timeout' not in kwargs: kwargs['request_timeout'] = 60 return await method(index=index, **kwargs) def to_es(self, **kwargs) -> dict: """ Generates a dictionary equivalent to what ElasticSearch returns in the '_source' property of a response. It automatically removes the id field from the document if it is set in ESConfig.id_field to prevent duplication of the id field. :param kwargs: Pydantic's model_dump parameters :return: The dictionary for ElasticSearch """ kwargs = dict(kwargs) def recursive_exclude(m) -> Dict[str, Union[bool, dict]]: """ Recursively exclude computed fields """ _exclude: Dict[str, Union[bool, dict]] = {k: True for k in m.model_computed_fields.keys()} for k, v in m: if k in _exclude: continue if isinstance(v, BaseModel): res = recursive_exclude(v) if res: _exclude[k] = res return _exclude # Update exclude field with computed fields exclude = kwargs.get('exclude', {}) exclude.update(recursive_exclude(self)) kwargs['exclude'] = exclude # Dump model to dict d = self.model_dump(**kwargs) def recursive_convert(_d: dict): """ Recursively modify data for Elasticsearch """ for k, v in _d.items(): # Encode datetime fields if isinstance(v, datetime): # Update ESTimestamp fields if k == 'modified_at' and d != _d: v = datetime.utcnow() elif k == 'created_at' and v is None and d != _d: v = datetime.utcnow() _d[k] = v.replace(tzinfo=None).isoformat() + 'Z' # Convert subclasses elif isinstance(v, dict): recursive_convert(v) recursive_convert(d) return d @classmethod def from_es(cls: Type[TModel], data: Dict[str, Any]) -> Optional[TModel]: """ Returns an ESModel from an elasticsearch document that has _id, _source :param data: Elasticsearch document that has _id, _source :raises esorm.error.InvalidResponseError: Returned when _id or _source is missing from data :return: The ESModel instance """ if not data: return None source: Optional[dict] = data.get("_source", None) _id = data.get("_id", None) if not source or not _id: raise InvalidResponseError # Add id field to document if source is not None and cls.ESConfig.id_field: source[cls.ESConfig.id_field] = _id obj = cls(**source) setattr(obj, '_id', _id) return obj async def calc_lazy_properties(self): """ (re)Calculate lazy properties """ # noinspection PyProtectedMember for attr_name, attr in self.ESConfig._lazy_properties.items(): setattr(self, '_' + attr_name, await attr(self)) async def save(self, *, wait_for=False, pipeline: Optional[str] = None, routing: Optional[str] = None) -> str: """ Save document into elasticsearch. If document already exists, existing document will be updated as per native elasticsearch index operation. If model has id (Config.id_field or __id__), this will be used as the elasticsearch _id. The id field will be removed from the document before indexing. If no id is provided, then document will be indexed and elasticsearch will generate a suitable id that will be populated on the returned model. :param wait_for: Waits for all shards to sync before returning response - useful when writing tests. Defaults to False. :param pipeline: Pipeline to use for indexing :param routing: Shard routing value :return: The new document's ID """ kwargs = dict( document=self.to_es(), wait_for=wait_for, ) kwargs['id'] = self.__id__ if self.ESConfig.id_field: del kwargs['document'][self.ESConfig.id_field] if pipeline is not None: kwargs['pipeline'] = pipeline if routing is not None: kwargs['routing'] = routing else: kwargs['routing'] = self.__routing__ es_res = await self.call('index', **kwargs) return es_res.get('_id') # noinspection PyShadowingBuiltins @classmethod async def get(cls: Type[TModel], id: Union[str, int, float], *, routing: Optional[str] = None) -> TModel: """ Fetches document and returns ESModel instance populated with properties. :param id: Document id :param routing: Shard routing value :raises esorm.error.NotFoundError: Returned if document not found :return: ESModel object """ kwargs = dict(id=str(id)) if routing: kwargs['routing'] = routing try: es_res = await cls.call('get', **kwargs) return cls.from_es(es_res) except ElasticNotFoundError: raise NotFoundError(f"Document with id {id} not found") async def delete(self, *, wait_for=False, routing: Optional[str] = None): """ Deletes document from elasticsearch. :param wait_for: Waits for all shards to sync before returning response - useful when writing tests. Defaults to False. :param routing: Shard routing value :raises esorm.error.NotFoundError: Returned if document not found :raises ValueError: Returned when id attribute missing from instance """ try: await self.call('delete', wait_for=wait_for, id=self.__id__, routing=routing) except ElasticNotFoundError: raise NotFoundError(f"Document with id {self.__id__} not found!") @classmethod async def _search(cls: Type[TModel], query: Optional[ESQuery] = None, *, page_size: Optional[int] = None, page: Optional[int] = None, sort: Optional[Union[list, str]] = None, routing: Optional[str] = None, aggs: Optional[ESAggs] = None, **kwargs) -> ESResponse: """ Raw ES search method :param query: ElasticSearch query dict :param page_size: Pagination page size :param page: Pagination page num, 1st page is 1 :param sort: Name of field to be sorted, or sort term list of dict, if not specified, model's default sort will be used, or no sorting :param routing: Shard routing value :param aggs: Aggregations :param kwargs: Other search API params :return: Raw ES response. """ if isinstance(sort, str): sort = [{sort: {'order': 'asc'}}] elif sort is None and cls.ESConfig.default_sort is not None: sort = cls.ESConfig.default_sort if page_size is not None and page is None: page = 1 return await cls.call('search', query=query, from_=((page - 1) * page_size) if page_size is not None else 0, size=page_size, sort=sort, routing=routing, aggs=aggs, **kwargs) @classmethod async def search(cls: Type[TModel], query: ESQuery, *, page_size: Optional[int] = None, page: Optional[int] = None, sort: Optional[Union[list, str]] = None, routing: Optional[str] = None, res_dict: bool = False, **kwargs) -> Union[List[TModel], Dict[str, TModel]]: """ Search Model with query dict :param query: ElasticSearch query dict :param page_size: Pagination page size :param page: Pagination page num, 1st page is 1 :param sort: Name of field to be sorted, or sort term list of dict, if not specified, model's default sort will be used, or no sorting :param routing: Shard routing value :param res_dict: If the result should be a dict with id as key and model as value instead of a list of models :param kwargs: Other search API params :return: The result list """ res = await cls._search(query, page_size=page_size, page=page, sort=sort, routing=routing, **kwargs) try: if res_dict: return {hit['_id']: cls.from_es(hit) for hit in res['hits']['hits']} return [cls.from_es(hit) for hit in res['hits']['hits']] except KeyError: return [] @classmethod async def search_one(cls: Type[TModel], query: ESQuery, *, routing: Optional[str] = None, **kwargs) \ -> Optional[TModel]: """ Search Model and return the first result :param query: ElasticSearch query dict :param routing: Shard routing value :param kwargs: Other search API params :return: The first result or None if no result """ res = await cls.search(query, page_size=1, routing=routing, **kwargs) if len(res) > 0: return res[0] else: return None @staticmethod def create_query_from_dict(fields: Dict[str, Union[str, int, float]]) -> ESQuery: """ Creates a query dict from a dictionary of fields and values :param fields: A dictionary of fields and values to search by :return: A query dict """ return { 'bool': { 'must': [{ 'match': { k: {'query': v, 'operator': 'and'}, } } for k, v in fields.items()] } } @classmethod async def search_by_fields(cls: Type[TModel], fields: Dict[str, Union[str, int, float]], *, page_size: Optional[int] = None, page: Optional[int] = None, sort: Optional[Union[list, str]] = None, routing: Optional[str] = None, aggs: Optional[ESAggs] = None, res_dict: bool = False, **kwargs) -> List[TModel]: """ Search Model by fields as key-value pairs :param fields: A dictionary of fields and values to search by :param page_size: Pagination page size :param page: Pagination page num, 1st page is 1 :param sort: Name of field to be sorted, or sort term list of dict, if not specified, model's default sort will be used, or no sorting :param routing: Shard routing value :param aggs: Aggregations :param res_dict: If the result should be a dict with id as key and model as value instead of a list of models :param kwargs: Other search API params :return: The result list """ query = cls.create_query_from_dict(fields) return await cls.search(query, page_size=page_size, page=page, sort=sort, routing=routing, aggs=aggs, res_dict=res_dict, **kwargs) @classmethod async def search_one_by_fields(cls: Type[TModel], fields: Dict[str, Union[str, int, float]], *, routing: Optional[str] = None, aggs: Optional[ESAggs] = None, **kwargs) -> Optional[TModel]: """ Search Model by fields as key-value pairs and return the first result :param fields: A dictionary of fields and values to search by :param routing: Shard routing value :param aggs: Aggregations :param kwargs: Other search API params :return: The first result or None if no result """ query = cls.create_query_from_dict(fields) return await cls.search_one(query, routing=routing, aggs=aggs, **kwargs) @classmethod async def aggregate(cls: Type[TModel], aggs: ESAggs, *, query: Optional[ESQuery] = None, routing: Optional[str] = None,
**kwargs) -> ESAggsResponse:
1
2023-10-30 16:15:00+00:00
8k
xruben136x/SZZ_unisannio
tests/test_unit.py
[ { "identifier": "get_bug_fix_commits_for_szz", "path": "src/main.py", "snippet": "def get_bug_fix_commits_for_szz():\n commits = repo.iter_commits()\n bug_fix_commits = []\n for commit in commits:\n commit_message = commit.message.lower()\n if 'bug' in commit_message and ('fix' in...
import unittest import re from unittest.mock import MagicMock, patch, call, mock_open from src.main import get_bug_fix_commits_for_szz, generate_changes_dict, get_candidate_commits, \ get_all_candidate_commits, extract_issue_number, match_comment, is_fix_contained, \ get_bug_fix_commits_szz_issue, \ search_candidate_commit_szz, \ print_candidate_commit, szz, \ load_regex_config, commit_is_more_recent, szz_issue, extract_commit_by_timestamp # Assicurati di sostituire 'your_script' con il nome reale del tuo script
4,673
] # Imposta la proprietà iter_commits del mock_repo mock_repo.iter_commits.return_value = mock_commits # Esegui la funzione di test bug_fix_commits = get_bug_fix_commits_for_szz() # Verifica che la funzione restituisca una lista vuota self.assertEqual(bug_fix_commits, []) @patch('src.main.is_fix_contained', autospec=True) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_szz_issue_true(self, mock_repo, mock_is_fix_contained): # Configura il mock del repository mock_commits = [ MagicMock(message="Fixing a bug"), MagicMock(message="Adding a new feature"), MagicMock(message="Fix: Another bug in the code") ] mock_repo.iter_commits.return_value = mock_commits mock_is_fix_contained.return_value = True # Chiamata alla funzione da testare result = get_bug_fix_commits_szz_issue() # Verifica che il risultato sia una lista di commit che contengono correzioni di bug self.assertEqual(result, [mock_commits[0], mock_commits[1], mock_commits[2]]) @patch('src.main.is_fix_contained', autospec=True) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_szz_issue_false(self, mock_repo, mock_is_fix_contained): # Configura il mock del repository mock_commits = [ MagicMock(message="Fixing a bug"), MagicMock(message="Adding a new feature"), MagicMock(message="Fix: Another bug in the code") ] mock_repo.iter_commits.return_value = mock_commits mock_is_fix_contained.return_value = False # Chiamata alla funzione da testare result = get_bug_fix_commits_szz_issue() # Verifica che il risultato sia una lista di commit che contengono correzioni di bug self.assertEqual(result, []) @patch('builtins.open', mock_open(read_data='regex')) def test_load_regex_config_success(self): result = load_regex_config('fake_path') self.assertEqual(result, 'regex') @patch('builtins.open', side_effect=FileNotFoundError) def test_load_regex_config_file_not_found(self, mock_open_file): result = load_regex_config('nonexistent_path') self.assertIsNone(result) def test_generate_changes_dict_diff_output_not_empty(self): # Esempio di output del diff diff_output = """ diff --git a/third_party/xla/xla/service/gpu/BUILD b/third_party/xla/xla/service/gpu/BUILD index 67468fef9b5..00f1d5ebe98 100644 --- a/third_party/xla/xla/service/gpu/BUILD +++ b/third_party/xla/xla/service/gpu/BUILD @@ -3469 +3468,0 @@ cc_library( - "@com_google_absl//absl/algorithm:container", @@ -3471 +3469,0 @@ cc_library( - "@com_google_absl//absl/log:check" """ # Esempio di output atteso dal tuo codice expected_output = { 'third_party/xla/xla/service/gpu/BUILD': [3469, 3471] } # Esegui la funzione e verifica se l'output è corretto changes_dict = generate_changes_dict(diff_output) self.assertEqual(changes_dict, expected_output) def test_generate_changes_dict_diff_output_empty(self): # Esempio di output del diff diff_output = "" # Esempio di output atteso dal tuo codice expected_output = {} # Esegui la funzione e verifica se l'output è corretto changes_dict = generate_changes_dict(diff_output) self.assertEqual(changes_dict, expected_output) @patch('src.main.args', recent=False) def test_get_candidate_commits_with_changes_no_recent_flag(self, mock_args): blame_result = """ f4529e80ab30a51207901b74b438980ac8b3ceaf 1 1 23 author Adrian Kuegel author-mail <akuegel@google.com> author-time 1695130818 author-tz -0700 committer TensorFlower Gardener committer-mail <gardener@tensorflow.org> committer-time 1695131394 committer-tz -0700 summary [XLA:GPU] Move buffer sharing logic into a separate target (NFC). filename third_party/xla/xla/service/gpu/buffer_sharing.cc /* Copyright 2023 The TensorFlow Authors. All Rights Reserved. 85ac1c6ddc93d4f53ff5b2c5c1c7bac7a8a44030 35 35 author Sergey Kozub author-mail <sergeykozub@google.com> author-time 1698139134 author-tz -0700 committer TensorFlower Gardener committer-mail <gardener@tensorflow.org> committer-time 1698139458 committer-tz -0700 summary Allow reduction users in multi-output fusions with buffer aliasing (FusionCanShareBufferHint) previous 2cf8b1c62a98c859bbe2ae69160680eea6aae160 third_party/xla/xla/service/gpu/buffer_sharing.cc filename third_party/xla/xla/service/gpu/buffer_sharing.cc #include "xla/stream_executor/device_description.pb.h" """ file_path = 'third_party/xla/xla/service/gpu/buffer_sharing.cc' changes_dict = {'third_party/xla/xla/service/gpu/buffer_sharing.cc': [1, 35]} expected_commits = {('85ac1c6ddc93d4f53ff5b2c5c1c7bac7a8a44030', 'Sergey Kozub'), ("f4529e80ab30a51207901b74b438980ac8b3ceaf", "Adrian Kuegel"), }
class UnitTest(unittest.TestCase): @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_for_szz_with_bug_and_fix(self, mock_repo): # Crea alcuni commit mock con messaggi specifici per il testing mock_commits = [ MagicMock(message="Fixing a bug"), MagicMock(message="Adding a new feature"), MagicMock(message="Fix: Another bug in the code") ] # Imposta la proprietà iter_commits del mock_repo mock_repo.iter_commits.return_value = mock_commits # Esegui la funzione di test bug_fix_commits = get_bug_fix_commits_for_szz() # Verifica che la funzione restituisca i commit corretti self.assertEqual(bug_fix_commits, [mock_commits[0], mock_commits[2]]) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_for_szz_with_bug_and_fixed(self, mock_repo): # Crea alcuni commit mock con messaggi specifici per il testing mock_commits = [ MagicMock(message="Fixed a bug"), MagicMock(message="Adding a new feature"), MagicMock(message="Bug fix: Another bug in the code") ] # Imposta la proprietà iter_commits del mock_repo mock_repo.iter_commits.return_value = mock_commits # Esegui la funzione di test bug_fix_commits = get_bug_fix_commits_for_szz() # Verifica che la funzione restituisca i commit corretti self.assertEqual(bug_fix_commits, [mock_commits[0], mock_commits[2]]) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_for_szz_with_fix_only(self, mock_repo): # Crea alcuni commit mock con messaggi specifici per il testing mock_commits = [ MagicMock(message="Fix #123456"), MagicMock(message="Fixing another issue"), MagicMock(message="Fix: Another problem in the code") ] # Imposta la proprietà iter_commits del mock_repo mock_repo.iter_commits.return_value = mock_commits # Esegui la funzione di test bug_fix_commits = get_bug_fix_commits_for_szz() # Verifica che la funzione restituisca una lista vuota self.assertEqual(bug_fix_commits, []) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_for_szz_with_bug_only(self, mock_repo): # Crea alcuni commit mock con messaggi specifici per il testing mock_commits = [ MagicMock(message="Bug #123456"), MagicMock(message="Fixing another issue"), MagicMock(message="Bug: Another problem in the code") ] # Imposta la proprietà iter_commits del mock_repo mock_repo.iter_commits.return_value = mock_commits # Esegui la funzione di test bug_fix_commits = get_bug_fix_commits_for_szz() # Verifica che la funzione restituisca una lista vuota self.assertEqual(bug_fix_commits, []) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_for_szz_with_empty_message(self, mock_repo): # Crea alcuni commit mock con messaggi specifici per il testing mock_commits = [ MagicMock(message=""), MagicMock(message=""), MagicMock(message="") ] # Imposta la proprietà iter_commits del mock_repo mock_repo.iter_commits.return_value = mock_commits # Esegui la funzione di test bug_fix_commits = get_bug_fix_commits_for_szz() # Verifica che la funzione restituisca una lista vuota self.assertEqual(bug_fix_commits, []) @patch('src.main.is_fix_contained', autospec=True) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_szz_issue_true(self, mock_repo, mock_is_fix_contained): # Configura il mock del repository mock_commits = [ MagicMock(message="Fixing a bug"), MagicMock(message="Adding a new feature"), MagicMock(message="Fix: Another bug in the code") ] mock_repo.iter_commits.return_value = mock_commits mock_is_fix_contained.return_value = True # Chiamata alla funzione da testare result = get_bug_fix_commits_szz_issue() # Verifica che il risultato sia una lista di commit che contengono correzioni di bug self.assertEqual(result, [mock_commits[0], mock_commits[1], mock_commits[2]]) @patch('src.main.is_fix_contained', autospec=True) @patch('src.main.repo', autospec=True) def test_get_bug_fix_commits_szz_issue_false(self, mock_repo, mock_is_fix_contained): # Configura il mock del repository mock_commits = [ MagicMock(message="Fixing a bug"), MagicMock(message="Adding a new feature"), MagicMock(message="Fix: Another bug in the code") ] mock_repo.iter_commits.return_value = mock_commits mock_is_fix_contained.return_value = False # Chiamata alla funzione da testare result = get_bug_fix_commits_szz_issue() # Verifica che il risultato sia una lista di commit che contengono correzioni di bug self.assertEqual(result, []) @patch('builtins.open', mock_open(read_data='regex')) def test_load_regex_config_success(self): result = load_regex_config('fake_path') self.assertEqual(result, 'regex') @patch('builtins.open', side_effect=FileNotFoundError) def test_load_regex_config_file_not_found(self, mock_open_file): result = load_regex_config('nonexistent_path') self.assertIsNone(result) def test_generate_changes_dict_diff_output_not_empty(self): # Esempio di output del diff diff_output = """ diff --git a/third_party/xla/xla/service/gpu/BUILD b/third_party/xla/xla/service/gpu/BUILD index 67468fef9b5..00f1d5ebe98 100644 --- a/third_party/xla/xla/service/gpu/BUILD +++ b/third_party/xla/xla/service/gpu/BUILD @@ -3469 +3468,0 @@ cc_library( - "@com_google_absl//absl/algorithm:container", @@ -3471 +3469,0 @@ cc_library( - "@com_google_absl//absl/log:check" """ # Esempio di output atteso dal tuo codice expected_output = { 'third_party/xla/xla/service/gpu/BUILD': [3469, 3471] } # Esegui la funzione e verifica se l'output è corretto changes_dict = generate_changes_dict(diff_output) self.assertEqual(changes_dict, expected_output) def test_generate_changes_dict_diff_output_empty(self): # Esempio di output del diff diff_output = "" # Esempio di output atteso dal tuo codice expected_output = {} # Esegui la funzione e verifica se l'output è corretto changes_dict = generate_changes_dict(diff_output) self.assertEqual(changes_dict, expected_output) @patch('src.main.args', recent=False) def test_get_candidate_commits_with_changes_no_recent_flag(self, mock_args): blame_result = """ f4529e80ab30a51207901b74b438980ac8b3ceaf 1 1 23 author Adrian Kuegel author-mail <akuegel@google.com> author-time 1695130818 author-tz -0700 committer TensorFlower Gardener committer-mail <gardener@tensorflow.org> committer-time 1695131394 committer-tz -0700 summary [XLA:GPU] Move buffer sharing logic into a separate target (NFC). filename third_party/xla/xla/service/gpu/buffer_sharing.cc /* Copyright 2023 The TensorFlow Authors. All Rights Reserved. 85ac1c6ddc93d4f53ff5b2c5c1c7bac7a8a44030 35 35 author Sergey Kozub author-mail <sergeykozub@google.com> author-time 1698139134 author-tz -0700 committer TensorFlower Gardener committer-mail <gardener@tensorflow.org> committer-time 1698139458 committer-tz -0700 summary Allow reduction users in multi-output fusions with buffer aliasing (FusionCanShareBufferHint) previous 2cf8b1c62a98c859bbe2ae69160680eea6aae160 third_party/xla/xla/service/gpu/buffer_sharing.cc filename third_party/xla/xla/service/gpu/buffer_sharing.cc #include "xla/stream_executor/device_description.pb.h" """ file_path = 'third_party/xla/xla/service/gpu/buffer_sharing.cc' changes_dict = {'third_party/xla/xla/service/gpu/buffer_sharing.cc': [1, 35]} expected_commits = {('85ac1c6ddc93d4f53ff5b2c5c1c7bac7a8a44030', 'Sergey Kozub'), ("f4529e80ab30a51207901b74b438980ac8b3ceaf", "Adrian Kuegel"), }
commit_set = get_candidate_commits(blame_result, file_path, changes_dict)
2
2023-10-30 07:59:15+00:00
8k
yaroslav318/chatGPT-discord-bot
src/bot.py
[ { "identifier": "logger", "path": "src/log.py", "snippet": "class CustomFormatter(logging.Formatter):\n LEVEL_COLORS = [\n (logging.DEBUG, '\\x1b[40;1m'),\n (logging.INFO, '\\x1b[34;1m'),\n (logging.WARNING, '\\x1b[33;1m'),\n (logging.ERROR, '\\x1b[31m'),\n (logging...
import os import openai import asyncio import discord from src.log import logger from random import randrange from src.aclient import client from discord import app_commands from src import log, art, personas, responses
6,449
def run_discord_bot(): @client.event async def on_ready(): await client.send_start_prompt() await client.tree.sync() loop = asyncio.get_event_loop() loop.create_task(client.process_messages())
def run_discord_bot(): @client.event async def on_ready(): await client.send_start_prompt() await client.tree.sync() loop = asyncio.get_event_loop() loop.create_task(client.process_messages())
logger.info(f'{client.user} is now running!')
0
2023-10-26 18:52:21+00:00
8k
vmurahari3/QualEval
generate_categories.py
[ { "identifier": "process_api_requests_from_file", "path": "api_request_parallel_processor.py", "snippet": "async def process_api_requests_from_file(\n requests_filepath: str,\n save_filepath: str,\n request_url: str,\n api_key: str,\n max_requests_per_minute: float,\n max_tokens_per_mi...
import re import argparse import openai import os import json import asyncio import random import inflect from datasets import load_dataset from api_request_parallel_processor import process_api_requests_from_file from utils.misc_utils import authenticate, get_prompt from utils.args import add_args from tqdm import tqdm from utils.templates import ( DEMONSTRATION_TEMPLATE, TASK_INSTRUCTIONS, CATEGORY_GENERATION_PROMPTS, )
4,301
# Insert code for taking arguments from command line inflect_engine = inflect.engine() # Import global variables def generate_categories( args, train_dataset, demonstration_template, task_instruction, category ): category_prompts = CATEGORY_GENERATION_PROMPTS[args.task_name] # loop through in-context samples, along with the task instruction prompt_file_path = os.path.join(args.output_dir, f"prompts_{category}.jsonl") response_file_path = os.path.join( args.output_dir, f"api_responses_{category}.jsonl" ) parsed_response_file_path = os.path.join( args.output_dir, f"api_generated_dataset_{category}.jsonl" ) metadata_file_path = os.path.join(args.output_dir, f"api_metadata_{category}.jsonl") if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) if args.delete_old_responses: if os.path.exists(response_file_path): os.remove(response_file_path) prompts = [] for _ in range(len(train_dataset) // args.few_shot_k): if args.incontext_sampling_strategy == "random": incontext_train = train_dataset.select( random.sample(range(len(train_dataset)), args.few_shot_k) ) elif args.incontext_sampling_strategy == "fixed": if len(train_dataset) > args.few_shot_k: print( "Warning: the number of samples in the train dataset is greater than k. Truncating up to k samples" ) incontext_train = train_dataset[: args.few_shot_k] else: print( "Warning: the number of samples in the train dataset is less than k." ) incontext_train = train_dataset[:] else: raise ValueError( "incontext_sampling_strategy must be either 'random' or 'fixed'" ) _, collated_demos = get_prompt( args, incontext_train, "", demonstration_template ) cur_prompt = ( collated_demos + f"*Task Instruction*:{task_instruction}" + category_prompts[category] ) prompts.append( { "prompt": cur_prompt, "type": category, "task_instruction": task_instruction, "collated_demos": collated_demos, } ) # use the collated demos to find skills # format the prompts into the OpenAI format as a jsonl file in the data directory with open(prompt_file_path, "w") as f, open(metadata_file_path, "w") as metadata_f: for prompt in prompts: if args.model == "gpt-3.5-turbo": formatted_request = { "model": "gpt-3.5-turbo-16k", "messages": [ {"role": "user", "content": prompt["collated_demos"]}, { "role": "user", "content": f"Understand and note these {args.few_shot_k} examples. Also understand the original task for these examples. Please note that the examples are not exhaustive.", }, { "role": "user", "content": f"Good Job, The original task instruction is: {prompt['task_instruction']}. {category_prompts[category]}", }, ], "temperature": args.temperature, "max_tokens": 1700, "top_p": args.top_p, "frequency_penalty": args.frequency_penalty, "presence_penalty": args.presence_penalty, } metadata = { "type": prompt["type"], "task_instruction": prompt["task_instruction"], } f.write(json.dumps(formatted_request)) f.write("\n") metadata_f.write(json.dumps(metadata)) metadata_f.write("\n") # Set the request url based on whether we are using a chat-based model if args.model == "gpt-3.5-turbo": request_url = "https://api.openai.com/v1/chat/completions" else: request_url = "https://api.openai.com/v1/completions" # Make API calls asyncio.run(
# Insert code for taking arguments from command line inflect_engine = inflect.engine() # Import global variables def generate_categories( args, train_dataset, demonstration_template, task_instruction, category ): category_prompts = CATEGORY_GENERATION_PROMPTS[args.task_name] # loop through in-context samples, along with the task instruction prompt_file_path = os.path.join(args.output_dir, f"prompts_{category}.jsonl") response_file_path = os.path.join( args.output_dir, f"api_responses_{category}.jsonl" ) parsed_response_file_path = os.path.join( args.output_dir, f"api_generated_dataset_{category}.jsonl" ) metadata_file_path = os.path.join(args.output_dir, f"api_metadata_{category}.jsonl") if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) if args.delete_old_responses: if os.path.exists(response_file_path): os.remove(response_file_path) prompts = [] for _ in range(len(train_dataset) // args.few_shot_k): if args.incontext_sampling_strategy == "random": incontext_train = train_dataset.select( random.sample(range(len(train_dataset)), args.few_shot_k) ) elif args.incontext_sampling_strategy == "fixed": if len(train_dataset) > args.few_shot_k: print( "Warning: the number of samples in the train dataset is greater than k. Truncating up to k samples" ) incontext_train = train_dataset[: args.few_shot_k] else: print( "Warning: the number of samples in the train dataset is less than k." ) incontext_train = train_dataset[:] else: raise ValueError( "incontext_sampling_strategy must be either 'random' or 'fixed'" ) _, collated_demos = get_prompt( args, incontext_train, "", demonstration_template ) cur_prompt = ( collated_demos + f"*Task Instruction*:{task_instruction}" + category_prompts[category] ) prompts.append( { "prompt": cur_prompt, "type": category, "task_instruction": task_instruction, "collated_demos": collated_demos, } ) # use the collated demos to find skills # format the prompts into the OpenAI format as a jsonl file in the data directory with open(prompt_file_path, "w") as f, open(metadata_file_path, "w") as metadata_f: for prompt in prompts: if args.model == "gpt-3.5-turbo": formatted_request = { "model": "gpt-3.5-turbo-16k", "messages": [ {"role": "user", "content": prompt["collated_demos"]}, { "role": "user", "content": f"Understand and note these {args.few_shot_k} examples. Also understand the original task for these examples. Please note that the examples are not exhaustive.", }, { "role": "user", "content": f"Good Job, The original task instruction is: {prompt['task_instruction']}. {category_prompts[category]}", }, ], "temperature": args.temperature, "max_tokens": 1700, "top_p": args.top_p, "frequency_penalty": args.frequency_penalty, "presence_penalty": args.presence_penalty, } metadata = { "type": prompt["type"], "task_instruction": prompt["task_instruction"], } f.write(json.dumps(formatted_request)) f.write("\n") metadata_f.write(json.dumps(metadata)) metadata_f.write("\n") # Set the request url based on whether we are using a chat-based model if args.model == "gpt-3.5-turbo": request_url = "https://api.openai.com/v1/chat/completions" else: request_url = "https://api.openai.com/v1/completions" # Make API calls asyncio.run(
process_api_requests_from_file(
0
2023-10-31 22:23:22+00:00
8k
mplawner/hourlynews
main.py
[ { "identifier": "extract_rss_urls_from_opml", "path": "opml_parser.py", "snippet": "def extract_rss_urls_from_opml(opml_file):\n logger.info(f\"Begin extraction from {opml_file}\")\n tree = ET.parse(opml_file)\n root = tree.getroot()\n\n # Extract RSS URLs\n rss_urls = []\n for outline...
import argparse import random import json import os import re import configparser import logging import zipfile from datetime import datetime from re import I from opml_parser import extract_rss_urls_from_opml from rss_parser import gather_news_from_rss from podcast_script_generator import generate_podcast_script from tts_converter import text_to_speech from telegram_sender import send_to_telegram from podcast_publisher import publish_to_spreaker from mastodon_publisher import post_status_with_audio from twitter_publisher import post_to_twitter from headline_generator import generate_headlines
4,992
# Configure logging #log_file = 'app.log' def read_file_content(filename): """Reads the entire content of a file if it exists, otherwise returns an empty string.""" if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as file: return file.read() else: logger.warning(f"File not found: {filename}. Skipping this step.") return "" def read_config(config_file): """Read configuration from an INI file.""" config = configparser.ConfigParser() config.read(config_file) return config def sanitize_filename(filename): return re.sub(r'[^\w\s-]', '', filename) def compress_files(file_name_prefix): directory = os.path.dirname(file_name_prefix) base_name = os.path.basename(file_name_prefix) zip_filename = f"{base_name}.zip" zip_path = os.path.join(directory, zip_filename) with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, _, files in os.walk(directory): for file in files: if file.startswith(base_name) and not file.endswith('.zip'): file_path = os.path.join(root, file) zipf.write(file_path, os.path.relpath(file_path, directory)) os.remove(file_path) return zip_path def main(args, show_title, sanitized_show_title): # Create a folder named after show_title if it doesn't exist if not os.path.exists(sanitized_show_title): os.makedirs(sanitized_show_title) logger.info(f"Created folder: {sanitized_show_title}") # Prepend the folder name to file_name_prefix file_name_prefix = os.path.join(sanitized_show_title, datetime.now().strftime('%Y-%m-%d_%H-%M')) logger.info(f"**** Start of Run: {file_name_prefix} ****") # Set Model Parameters current_hour = datetime.now().hour day_start = config.getint('OpenAI', 'day_start') day_end = config.getint('OpenAI', 'day_end') if day_start <= current_hour < day_end: logging.info(f"After {day_start}, using daytime model") model_name = config.get('OpenAI', 'model_day') else: logging.info(f"After {day_end}, using nighttime model") model_name = config.get('OpenAI', 'model_night') temperature = float(config.get('OpenAI', 'temperature', fallback=0.7)) seed = config.getint('OpenAI', 'seed', fallback=random.randint(10000, 99999)) key = config.get('OpenAI', 'openai') system_message = config.get('OpenAI', 'system_message') user_message = config.get('OpenAI', 'user_message') logger.info(f"Model: {model_name}") logger.info(f"Temperature: {temperature}") logger.info(f"Seed: {seed}") logger.info(f"OpenAI Key: {key}") logger.info(f"System Message: {system_message}") logger.info(f"User Message: {user_message}") # Reading RSS URLs from an OPML file or JSON file if args.news_items: logger.info(f"Reading news items from JSON file {args.news_items}") with open(args.news_items, 'r') as file: news_items = json.load(file) else: opml_file = config.get('News', 'opml', fallback="subscription.opml") timeframe_minutes = config.getint('News', 'period', fallback=60) logger.info(f"Reading news for last {timeframe_minutes} minutes items from RSS feeds in {opml_file}") rss_urls = extract_rss_urls_from_opml(opml_file) news_items = gather_news_from_rss(rss_urls, file_name_prefix, timeframe_minutes) # Generate podcast script host = config.get('News', 'host') host_tagline = config.get('News', 'host_tagline') disclaimer = config.get('News', 'disclaimer') podcast_script = generate_podcast_script(news_items[:50], model_name, temperature, seed, file_name_prefix, key, system_message, user_message, show_title, host, host_tagline, disclaimer) # Convert text to speech and get the audio filename if not args.no_audiofile: intro_music_file = config.get('Branding', 'intro_music') outro_music_file = config.get('Branding', 'outro_music') host_voice = config.get('News', 'host_voice') show_description = config.get('News', 'show_description') audio_filename = text_to_speech(podcast_script, file_name_prefix, intro_music_file, outro_music_file, host, host_voice, show_title, show_description) else: logger.info("No audio being generated") # Generated Headlines
# Configure logging #log_file = 'app.log' def read_file_content(filename): """Reads the entire content of a file if it exists, otherwise returns an empty string.""" if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as file: return file.read() else: logger.warning(f"File not found: {filename}. Skipping this step.") return "" def read_config(config_file): """Read configuration from an INI file.""" config = configparser.ConfigParser() config.read(config_file) return config def sanitize_filename(filename): return re.sub(r'[^\w\s-]', '', filename) def compress_files(file_name_prefix): directory = os.path.dirname(file_name_prefix) base_name = os.path.basename(file_name_prefix) zip_filename = f"{base_name}.zip" zip_path = os.path.join(directory, zip_filename) with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, _, files in os.walk(directory): for file in files: if file.startswith(base_name) and not file.endswith('.zip'): file_path = os.path.join(root, file) zipf.write(file_path, os.path.relpath(file_path, directory)) os.remove(file_path) return zip_path def main(args, show_title, sanitized_show_title): # Create a folder named after show_title if it doesn't exist if not os.path.exists(sanitized_show_title): os.makedirs(sanitized_show_title) logger.info(f"Created folder: {sanitized_show_title}") # Prepend the folder name to file_name_prefix file_name_prefix = os.path.join(sanitized_show_title, datetime.now().strftime('%Y-%m-%d_%H-%M')) logger.info(f"**** Start of Run: {file_name_prefix} ****") # Set Model Parameters current_hour = datetime.now().hour day_start = config.getint('OpenAI', 'day_start') day_end = config.getint('OpenAI', 'day_end') if day_start <= current_hour < day_end: logging.info(f"After {day_start}, using daytime model") model_name = config.get('OpenAI', 'model_day') else: logging.info(f"After {day_end}, using nighttime model") model_name = config.get('OpenAI', 'model_night') temperature = float(config.get('OpenAI', 'temperature', fallback=0.7)) seed = config.getint('OpenAI', 'seed', fallback=random.randint(10000, 99999)) key = config.get('OpenAI', 'openai') system_message = config.get('OpenAI', 'system_message') user_message = config.get('OpenAI', 'user_message') logger.info(f"Model: {model_name}") logger.info(f"Temperature: {temperature}") logger.info(f"Seed: {seed}") logger.info(f"OpenAI Key: {key}") logger.info(f"System Message: {system_message}") logger.info(f"User Message: {user_message}") # Reading RSS URLs from an OPML file or JSON file if args.news_items: logger.info(f"Reading news items from JSON file {args.news_items}") with open(args.news_items, 'r') as file: news_items = json.load(file) else: opml_file = config.get('News', 'opml', fallback="subscription.opml") timeframe_minutes = config.getint('News', 'period', fallback=60) logger.info(f"Reading news for last {timeframe_minutes} minutes items from RSS feeds in {opml_file}") rss_urls = extract_rss_urls_from_opml(opml_file) news_items = gather_news_from_rss(rss_urls, file_name_prefix, timeframe_minutes) # Generate podcast script host = config.get('News', 'host') host_tagline = config.get('News', 'host_tagline') disclaimer = config.get('News', 'disclaimer') podcast_script = generate_podcast_script(news_items[:50], model_name, temperature, seed, file_name_prefix, key, system_message, user_message, show_title, host, host_tagline, disclaimer) # Convert text to speech and get the audio filename if not args.no_audiofile: intro_music_file = config.get('Branding', 'intro_music') outro_music_file = config.get('Branding', 'outro_music') host_voice = config.get('News', 'host_voice') show_description = config.get('News', 'show_description') audio_filename = text_to_speech(podcast_script, file_name_prefix, intro_music_file, outro_music_file, host, host_voice, show_title, show_description) else: logger.info("No audio being generated") # Generated Headlines
headlines = generate_headlines(podcast_script, model_name, temperature, seed, key)
8
2023-10-27 14:24:20+00:00
8k
tb2-sy/TSP-Transformer
main.py
[ { "identifier": "mkdir_if_missing", "path": "utils/utils.py", "snippet": "def mkdir_if_missing(directory):\n if not os.path.exists(directory):\n try:\n os.makedirs(directory)\n except OSError as e:\n pass" }, { "identifier": "create_config", "path": "ut...
import argparse import cv2 import os import numpy as np import sys import torch import pdb import time import torch.distributed as dist import datetime import random from utils.utils import mkdir_if_missing from utils.config import create_config from utils.common_config import get_train_dataset, get_transformations,\ get_test_dataset, get_train_dataloader, get_test_dataloader,\ get_optimizer, get_model, get_criterion from utils.logger import Logger from utils.train_utils import train_phase from utils.test_utils import test_phase from evaluation.evaluate_utils import PerformanceMeter from torch.utils.tensorboard import SummaryWriter
4,118
start_time = time.time() # DDP dist.init_process_group(backend='nccl', init_method='env://', timeout=datetime.timedelta(0, 3600*2)) # Parser parser = argparse.ArgumentParser(description='Vanilla Training') parser.add_argument('--config_exp', help='Config file for the experiment') parser.add_argument('--local_rank', default=0, type=int, help='node rank for distributed training') parser.add_argument('--run_mode', help='Config file for the experiment') parser.add_argument('--trained_model', default=None, help='Config file for the experiment') args = parser.parse_args() print('local rank: %s' %args.local_rank) torch.cuda.set_device(args.local_rank) # CUDNN torch.backends.cudnn.benchmark = True # opencv cv2.setNumThreads(0) def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def main(): set_seed(0) # Retrieve config file params = {'run_mode': args.run_mode} p = create_config(args.config_exp, params) if args.local_rank == 0: sys.stdout = Logger(os.path.join(p['output_dir'], 'log_file.txt')) print(p) # tensorboard tb_log_dir = p.root_dir + '/tb_dir' p.tb_log_dir = tb_log_dir if args.local_rank == 0: train_tb_log_dir = tb_log_dir + '/train' test_tb_log_dir = tb_log_dir + '/test' tb_writer_train = SummaryWriter(train_tb_log_dir) tb_writer_test = SummaryWriter(test_tb_log_dir) if args.run_mode != 'infer': mkdir_if_missing(tb_log_dir) mkdir_if_missing(train_tb_log_dir) mkdir_if_missing(test_tb_log_dir) print(f"Tensorboard dir: {tb_log_dir}") else: tb_writer_train = None tb_writer_test = None # Get model model = get_model(p) # model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).cuda() model = model.cuda() model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) # Get criterion criterion = get_criterion(p).cuda() # Optimizer scheduler, optimizer = get_optimizer(p, model) # Performance meter init
start_time = time.time() # DDP dist.init_process_group(backend='nccl', init_method='env://', timeout=datetime.timedelta(0, 3600*2)) # Parser parser = argparse.ArgumentParser(description='Vanilla Training') parser.add_argument('--config_exp', help='Config file for the experiment') parser.add_argument('--local_rank', default=0, type=int, help='node rank for distributed training') parser.add_argument('--run_mode', help='Config file for the experiment') parser.add_argument('--trained_model', default=None, help='Config file for the experiment') args = parser.parse_args() print('local rank: %s' %args.local_rank) torch.cuda.set_device(args.local_rank) # CUDNN torch.backends.cudnn.benchmark = True # opencv cv2.setNumThreads(0) def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def main(): set_seed(0) # Retrieve config file params = {'run_mode': args.run_mode} p = create_config(args.config_exp, params) if args.local_rank == 0: sys.stdout = Logger(os.path.join(p['output_dir'], 'log_file.txt')) print(p) # tensorboard tb_log_dir = p.root_dir + '/tb_dir' p.tb_log_dir = tb_log_dir if args.local_rank == 0: train_tb_log_dir = tb_log_dir + '/train' test_tb_log_dir = tb_log_dir + '/test' tb_writer_train = SummaryWriter(train_tb_log_dir) tb_writer_test = SummaryWriter(test_tb_log_dir) if args.run_mode != 'infer': mkdir_if_missing(tb_log_dir) mkdir_if_missing(train_tb_log_dir) mkdir_if_missing(test_tb_log_dir) print(f"Tensorboard dir: {tb_log_dir}") else: tb_writer_train = None tb_writer_test = None # Get model model = get_model(p) # model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).cuda() model = model.cuda() model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) # Get criterion criterion = get_criterion(p).cuda() # Optimizer scheduler, optimizer = get_optimizer(p, model) # Performance meter init
performance_meter = PerformanceMeter(p, p.TASKS.NAMES)
13
2023-10-25 03:42:18+00:00
8k
qwerdvd/StarRailDamageCal
starrail_damage_cal/damage/AvatarDamage/AvatarDamage.py
[ { "identifier": "BaseAvatar", "path": "starrail_damage_cal/damage/Base/AvatarBase.py", "snippet": "class BaseAvatar:\n def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]):\n self.Skill = BaseSkills.create(char=char, skills=skills)\n self.Buff = BaseAvatarBu...
import copy from typing import Dict, List from starrail_damage_cal.damage.Base.AvatarBase import BaseAvatar, BaseAvatarBuff from starrail_damage_cal.damage.Base.model import ( DamageInstanceAvatar, DamageInstanceSkill, ) from starrail_damage_cal.damage.Role import ( break_damage, calculate_damage, calculate_heal, calculate_shield, ) from starrail_damage_cal.logger import logger
4,720
self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) # 计算持续伤害 skill_multiplier = self.Skill_num("BPSkill", "DOT") if self.avatar_rank >= 2: skill_multiplier += 0.4 damagelist4 = await calculate_damage( base_attr, attribute_bonus, "DOT", "DOT", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "单次持续伤害", "damagelist": damagelist4}) return skill_info_list class Gepard(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): pass def extra_ability(self): pass async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技护盾 skill_multiplier = self.Skill_num("Ultra", "Ultra") skill_num = self.Skill_num("Ultra", "Ultra_G")
class Seele(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank < 2: self.eidolon_attribute["SpeedAddedRatio"] = 0.25 if self.avatar_rank >= 1: self.eidolon_attribute["CriticalChanceBase"] = 0.15 if self.avatar_rank >= 2: self.eidolon_attribute["SpeedAddedRatio"] = 0.5 def extra_ability(self): # 额外能力 割裂 抗性穿透提高20 self.extra_ability_attribute["QuantumResistancePenetration"] = 0.2 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): # logger.info(base_attr) # logger.info(self.avatar_rank) # 希尔天赋再现加伤害 attribute_bonus["AllDamageAddedRatio"] = self.Skill_num( "Talent", "Talent", ) + attribute_bonus.get("AllDamageAddedRatio", 0) damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算大招伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) # 银狼降防终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") add_attr_bonus = copy.deepcopy(attribute_bonus) add_attr_bonus["ignore_defence"] = 0.45 + add_attr_bonus.get( "ignore_defence", 0, ) damagelist4 = await calculate_damage( base_attr, add_attr_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "银狼降防终结技", "damagelist": damagelist4}) logger.info(skill_info_list) return skill_info_list class JingYuan(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 2: self.eidolon_attribute["NormalDmgAdd"] = 0.2 self.eidolon_attribute["BPSkillDmgAdd"] = 0.2 self.eidolon_attribute["UltraDmgAdd"] = 0.2 if self.avatar_rank >= 6: self.eidolon_attribute["Talent_DmgRatio"] = 0.288 def extra_ability(self): logger.info("额外能力") logger.info( "【神君】下回合的攻击段数大于等于6段, 则其下回合的暴击伤害提高25%。", ) self.extra_ability_attribute["CriticalDamageBase"] = 0.25 logger.info("施放战技后, 暴击率提升10%") self.extra_ability_attribute["CriticalChanceBase"] = 0.1 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算大招伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) # 神君 skill_multiplier = self.Skill_num("Talent", "Talent") damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "10层神君伤害", "damagelist": damagelist4}) logger.info(skill_info_list) return skill_info_list class Welt(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): pass def extra_ability(self): logger.info("额外能力") logger.info("施放终结技时, 有100%基础概率使目标受到的伤害提高12%, 持续2回合。") self.extra_ability_attribute["DmgRatio"] = 0.12 logger.info("对被弱点击破的敌方目标造成的伤害提高20") self.extra_ability_attribute["AllDamageAddedRatio"] = 0.20 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 attnum = 3 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") / attnum damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) if self.avatar_rank >= 6: attnum = 4 damagelist2[0] = damagelist2[0] * attnum damagelist2[1] = damagelist2[1] * attnum damagelist2[2] = damagelist2[2] * attnum damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算大招伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) if self.avatar_rank >= 1: skill_multiplier = self.Skill_num("Normal", "Normal") * 0.5 damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[0] = damagelist1[0] + damagelist4[0] damagelist4[1] = damagelist1[1] + damagelist4[1] damagelist4[2] = damagelist1[2] + damagelist4[2] damagelist4[2] += damage3 skill_info_list.append({"name": "强化普攻", "damagelist": damagelist4}) skill_multiplier = (self.Skill_num("BPSkill", "BPSkill") / 3) * 0.8 damagelist5 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist5[0] = damagelist2[0] + damagelist5[0] damagelist5[1] = damagelist2[1] + damagelist5[1] damagelist5[2] = damagelist2[2] + damagelist5[2] damagelist5[2] += damage3 skill_info_list.append({"name": "强化战技", "damagelist": damagelist5}) logger.info(skill_info_list) return skill_info_list class Danhengil(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 6: self.extra_ability_attribute["Normal3_ImaginaryResistancePenetration"] = 0.6 def extra_ability(self): logger.info("额外能力") logger.info("对拥有虚数属性弱点的敌方目标造成伤害时, 暴击伤害提高24%。") self.extra_ability_attribute["CriticalDamageBase"] = 0.24 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): start_buff = 3 add_buff = 1 max_buff = 6 if self.avatar_rank >= 1: start_buff = 6 add_buff = 2 max_buff = 10 injury_add = self.Skill_num("Talent", "Talent") critical_damage_add = self.Skill_num("BPSkill", "BPSkill") critical_buff = 0 if self.avatar_rank >= 4: critical_buff = critical_damage_add * 4 skill_info_list = [] # 计算普攻1伤害 skill_multiplier = self.Skill_num("Normal", "Normal") / 2 damage_c = 0 damage_e = 0 damage_a = 0 add_attr_bonus: Dict[str, float] = {} for i in range(1, 3): add_attr_bonus = copy.deepcopy(attribute_bonus) damage_buff = min(max_buff, start_buff + (i - 1) * add_buff) add_attr_bonus["AllDamageAddedRatio"] = ( damage_buff * injury_add + add_attr_bonus.get("AllDamageAddedRatio", 0) ) if self.avatar_rank >= 4: add_attr_bonus["CriticalDamageBase"] = ( critical_buff + add_attr_bonus.get("CriticalDamageBase", 0) ) damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damage_c += damage1 damage_e += damage2 damage_a += damage3 damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal", "Thunder", 0.44, self.avatar_level, ) damage_a += damage3 skill_info_list.append( {"name": "普攻", "damagelist": [damage_c, damage_e, damage_a]}, ) # 计算瞬华伤害 skill_multiplier = self.Skill_num("Normal", "Normal1") / 3 damage_c = 0 damage_e = 0 damage_a = 0 add_attr_bonus: Dict[str, float] = {} for i in range(1, 4): add_attr_bonus = copy.deepcopy(attribute_bonus) damage_buff = min(max_buff, start_buff + (i - 1) * add_buff) add_attr_bonus["AllDamageAddedRatio"] = ( damage_buff * injury_add + add_attr_bonus.get("AllDamageAddedRatio", 0) ) if self.avatar_rank >= 4: add_attr_bonus["CriticalDamageBase"] = ( critical_buff + add_attr_bonus.get("CriticalDamageBase", 0) ) damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal1", self.avatar_element, skill_multiplier, self.avatar_level, ) damage_c += damage1 damage_e += damage2 damage_a += damage3 damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal", "Thunder", 0.44, self.avatar_level, ) damage_a += damage3 skill_info_list.append( {"name": "瞬华", "damagelist": [damage_c, damage_e, damage_a]}, ) # 计算天矢阴伤害 skill_multiplier = self.Skill_num("Normal", "Normal2") / 5 damage_c = 0 damage_e = 0 damage_a = 0 add_attr_bonus: Dict[str, float] = {} for i in range(1, 6): add_attr_bonus = copy.deepcopy(attribute_bonus) damage_buff = min(max_buff, start_buff + (i - 1) * add_buff) add_attr_bonus["AllDamageAddedRatio"] = ( damage_buff * injury_add + add_attr_bonus.get("AllDamageAddedRatio", 0) ) if self.avatar_rank >= 4: add_attr_bonus["CriticalDamageBase"] = ( critical_buff + add_attr_bonus.get("CriticalDamageBase", 0) ) elif i >= 4: critical_buff = (i - 3) * critical_damage_add add_attr_bonus["CriticalDamageBase"] = ( critical_buff + add_attr_bonus.get("CriticalDamageBase", 0) ) damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal2", self.avatar_element, skill_multiplier, self.avatar_level, ) damage_c += damage1 damage_e += damage2 damage_a += damage3 damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal", "Thunder", 0.44, self.avatar_level, ) damage_a += damage3 skill_info_list.append( {"name": "天矢阴", "damagelist": [damage_c, damage_e, damage_a]}, ) # 计算盘拏耀跃伤害 skill_multiplier = self.Skill_num("Normal", "Normal3") / 7 damage_c = 0 damage_e = 0 damage_a = 0 add_attr_bonus: Dict[str, float] = {} for i in range(1, 8): add_attr_bonus = copy.deepcopy(attribute_bonus) damage_buff = min(max_buff, start_buff + (i - 1) * add_buff) add_attr_bonus["AllDamageAddedRatio"] = ( damage_buff * injury_add + add_attr_bonus.get("AllDamageAddedRatio", 0) ) if self.avatar_rank >= 4: add_attr_bonus["CriticalDamageBase"] = ( critical_buff + add_attr_bonus.get("CriticalDamageBase", 0) ) elif i >= 4: critical_buff = (i - 3) * critical_damage_add add_attr_bonus["CriticalDamageBase"] = ( critical_buff + add_attr_bonus.get("CriticalDamageBase", 0) ) damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal3", self.avatar_element, skill_multiplier, self.avatar_level, ) damage_c += damage1 damage_e += damage2 damage_a += damage3 damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal", "Thunder", 0.44, self.avatar_level, ) damage_a += damage3 skill_info_list.append( {"name": "盘拏耀跃", "damagelist": [damage_c, damage_e, damage_a]}, ) # 计算大招伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") / 3 damage_c = 0 damage_e = 0 damage_a = 0 add_attr_bonus: Dict[str, float] = {} for _ in range(1, 4): add_attr_bonus = copy.deepcopy(attribute_bonus) damage_buff = min(max_buff, 10) add_attr_bonus["AllDamageAddedRatio"] = ( damage_buff * injury_add + add_attr_bonus.get("AllDamageAddedRatio", 0) ) critical_buff = 4 * critical_damage_add add_attr_bonus["CriticalDamageBase"] = critical_buff + add_attr_bonus.get( "CriticalDamageBase", 0, ) damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damage_c += damage1 damage_e += damage2 damage_a += damage3 damage1, damage2, damage3 = await calculate_damage( base_attr, add_attr_bonus, "Normal", "Normal", "Thunder", 0.44, self.avatar_level, ) damage_a += damage3 skill_info_list.append( {"name": "终结技", "damagelist": [damage_c, damage_e, damage_a]}, ) logger.info(skill_info_list) return skill_info_list class Argenti(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 1: self.eidolon_attribute["CriticalDamageBase"] = 0.4 if self.avatar_rank >= 2: self.eidolon_attribute["AttackAddedRatio"] = 0.4 if self.avatar_rank >= 6: self.eidolon_attribute["Ultra_PhysicalResistancePenetration"] = 0.3 def extra_ability(self): self.extra_ability_attribute["AllDamageAddedRatio"] = 0.15 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): talent_cc_add = self.Skill_num("Talent", "Talent") attribute_bonus["CriticalChanceBase"] = ( talent_cc_add * 10 + attribute_bonus.get("CriticalChanceBase", 0) ) if self.avatar_rank >= 4: attribute_bonus["CriticalDamageBase"] = 0.08 + attribute_bonus.get( "CriticalDamageBase", 0, ) attribute_bonus["CriticalChanceBase"] = ( talent_cc_add * 2 + attribute_bonus.get("CriticalChanceBase", 0) ) damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算大招1伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技(90耗能)", "damagelist": damagelist3}) # 计算大招2伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra1") damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 # 计算大招2额外伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra_add") damagelist5 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist5[0] = damagelist5[0] * 6 + damagelist4[0] damagelist5[1] = damagelist5[1] * 6 + damagelist4[1] damagelist5[2] = damagelist5[2] * 6 + damagelist4[2] skill_info_list.append( {"name": "强化终结技(180耗能)", "damagelist": damagelist5}, ) return skill_info_list class Clara(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 2: self.eidolon_attribute["AttackAddedRatio"] = 0.2 def extra_ability(self): logger.info("额外能力") logger.info("史瓦罗的反击造成的伤害提高30%") self.extra_ability_attribute["TalentDmgAdd"] = 0.3 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算反击伤害 skill_multiplier = self.Skill_num("Talent", "Talent") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "反击", "damagelist": damagelist3}) # 计算强化反击伤害 skill_multiplier = self.Skill_num("Talent", "Talent") + self.Skill_num( "Ultra", "Talent1", ) damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "强化反击", "damagelist": damagelist4}) # 计算1+1托帕反击伤害 skill_multiplier = self.Skill_num("Talent", "Talent") add_attr_bonus = copy.deepcopy(attribute_bonus) add_attr_bonus["Talent_DmgRatio"] = ( add_attr_bonus.get("Talent_DmgRatio", 0) + 0.5 ) add_attr_bonus["Talent_CriticalDamageBase"] = ( add_attr_bonus.get("Talent_CriticalDamageBase", 0) + 0.74 ) damagelist5 = await calculate_damage( base_attr, add_attr_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist5[2] += damage3 skill_info_list.append({"name": "(1+1托帕)反击", "damagelist": damagelist5}) # 计算反击伤害 skill_multiplier = self.Skill_num("Talent", "Talent") + self.Skill_num( "Ultra", "Talent1", ) add_attr_bonus = copy.deepcopy(attribute_bonus) add_attr_bonus["Talent_DmgRatio"] = ( add_attr_bonus.get("Talent_DmgRatio", 0) + 0.5 ) add_attr_bonus["Talent_CriticalDamageBase"] = ( add_attr_bonus.get("Talent_CriticalDamageBase", 0) + 0.74 ) damagelist6 = await calculate_damage( base_attr, add_attr_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist6[2] += damage3 skill_info_list.append({"name": "(1+1托帕)强化反击", "damagelist": damagelist6}) return skill_info_list class Silverwolf(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 6: self.extra_ability_attribute["AllDamageAddedRatio"] = 1 def extra_ability(self): logger.info("额外能力") logger.info("战技降抗") logger.info("战技使目标全属性抗性降低的效果额外降低3%") enemy_status_resistance = self.Skill_num("BPSkill", "BPSkill_D") + 0.03 self.extra_ability_attribute[ "QuantumResistancePenetration" ] = enemy_status_resistance logger.info("终结技降防") ultra_defence = self.Skill_num("Ultra", "Ultra_D") logger.info("天赋降防") talent_defence = self.Skill_num("Talent", "Talent") ignore_defence = ultra_defence + talent_defence self.extra_ability_attribute["ignore_defence"] = ignore_defence async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") if self.avatar_rank >= 4: skill_multiplier += 1 damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) return skill_info_list class Kafka(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 1: self.extra_ability_attribute["DOTDmgAdd"] = 0.3 if self.avatar_rank >= 2: self.extra_ability_attribute["DOTDmgAdd"] = 0.55 def extra_ability(self): pass async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) # 计算持续伤害 skill_multiplier = self.Skill_num("Ultra", "DOT") if self.avatar_rank >= 6: skill_multiplier += 1.56 damagelist4 = await calculate_damage( base_attr, attribute_bonus, "DOT", "DOT", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "单次持续伤害", "damagelist": damagelist4}) # 计算追加攻击伤害 skill_multiplier = self.Skill_num("Talent", "Talent") damagelist5 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist5[2] += damage3 skill_info_list.append({"name": "追加攻击", "damagelist": damagelist5}) return skill_info_list class Blade(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 2: self.eidolon_attribute["CriticalChanceBase"] = 0.15 if self.avatar_rank >= 4: self.eidolon_attribute["HPAddedRatio"] = 0.4 def extra_ability(self): logger.info("额外能力") logger.info("天赋施放的追加攻击伤害提高20%") self.extra_ability_attribute["TalentDmgAdd"] = 0.2 logger.info("战技加伤") self.extra_ability_attribute["AllDamageAddedRatio"] = self.Skill_num( "BPSkill", "BPSkill", ) async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算强化普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal1") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_multiplier = self.Skill_num("Normal", "Normal1_HP") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, 1, ) damagelist3[0] += damagelist2[0] damagelist3[1] += damagelist2[1] damagelist3[2] += damagelist2[2] skill_info_list.append({"name": "无间剑树", "damagelist": damagelist3}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_multiplier = self.Skill_num("Ultra", "Ultra_HP") if self.avatar_rank >= 1: skill_multiplier += 0.9 damagelist5 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, 1, ) damagelist5[0] += damagelist4[0] damagelist5[1] += damagelist4[1] damagelist5[2] += damagelist4[2] skill_info_list.append({"name": "终结技", "damagelist": damagelist5}) # 计算追加攻击伤害 skill_multiplier = self.Skill_num("Talent", "Talent") damagelist6 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist6[2] += damage3 skill_multiplier = self.Skill_num("Talent", "Talent_HP") damagelist7 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, 1, ) damagelist7[0] += damagelist6[0] damagelist7[1] += damagelist6[1] damagelist7[2] += damagelist6[2] if self.avatar_rank >= 6: hp = ( base_attr["hp"] * (1 + attribute_bonus["HPAddedRatio"]) + attribute_bonus["HPDelta"] ) damage_add = hp * 0.5 damagelist7[0] += damage_add damagelist7[1] += damage_add damagelist7[2] += damage_add skill_info_list.append({"name": "追加攻击", "damagelist": damagelist7}) return skill_info_list class Fuxuan(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 1: self.eidolon_attribute["CriticalDamageBase"] = 0.3 def extra_ability(self): logger.info("符玄战技【穷观阵】属性加成") self.extra_ability_attribute["CriticalChanceBase"] = self.Skill_num( "BPSkill", "BPSkill_CC", ) self.extra_ability_attribute["HPAddedRatio"] = self.Skill_num( "BPSkill", "BPSkill_HP", ) async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal_HP") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, 1, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra_HP") if self.avatar_rank >= 6: skill_multiplier += 1.2 damagelist2 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, 1, ) damagelist2[2] += damage2 skill_info_list.append({"name": "终结技", "damagelist": damagelist2}) # 计算终结技治疗 damagelist3 = await calculate_heal( base_attr, attribute_bonus, "Ultra", 0.05, 133, ) skill_info_list.append({"name": "终结技治疗", "damagelist": damagelist3}) return skill_info_list class Yanqing(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 4: self.eidolon_attribute["IceResistancePenetration"] = 0.15 def extra_ability(self): logger.info("额外能力") logger.info("触发暴击时, 速度提高10%") self.extra_ability_attribute["SpeedAddedRatio"] = 0.1 logger.info("【智剑连心】增益") critical_damage_base_t = self.Skill_num("Talent", "Talent_CD") critical_damage_base_u = self.Skill_num("Ultra", "Ultra_CD") self.extra_ability_attribute["CriticalDamageBase"] = ( critical_damage_base_t + critical_damage_base_u ) critical_chance_base = self.Skill_num("Talent", "Talent_CC") self.extra_ability_attribute["CriticalChanceBase"] = critical_chance_base + 0.6 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) # 计算附加伤害 skill_multiplier = self.Skill_num("Talent", "Talent") if self.avatar_rank >= 1: skill_multiplier += 0.9 else: skill_multiplier += 0.3 damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "附加伤害", "damagelist": damagelist4}) return skill_info_list class Himeko(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 1: self.eidolon_attribute["SpeedAddedRatio"] = 0.1 if self.avatar_rank >= 2: self.eidolon_attribute["AllDamageAddedRatio"] = 0.15 def extra_ability(self): logger.info("额外能力") logger.info("战技对灼烧状态下的敌方目标造成的伤害提高20%。") self.extra_ability_attribute["BPSkillDmgAdd"] = 0.2 logger.info("若当前生命值百分比大于等于80%, 则暴击率提高15%。") self.extra_ability_attribute["CriticalChanceBase"] = 0.15 async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) # 计算追加攻击伤害 skill_multiplier = self.Skill_num("Talent", "Talent") damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "追加攻击", "damagelist": damagelist4}) return skill_info_list class Qingque(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 1: self.eidolon_attribute["UltraDmgAdd"] = 0.1 def extra_ability(self): logger.info("额外能力") logger.info("施放强化普攻后, 青雀的速度提高10%, 持续1回合。") self.extra_ability_attribute["SpeedAddedRatio"] = 0.1 logger.info("默认4层战技加伤害") all_damage_added_ratio = self.Skill_num("BPSkill", "BPSkill") + 0.1 self.extra_ability_attribute["AllDamageAddedRatio"] = all_damage_added_ratio * 4 logger.info("默认暗杠加攻") self.extra_ability_attribute["AttackAddedRatio"] = self.Skill_num( "Talent", "Talent", ) async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算杠上开花伤害 skill_multiplier = self.Skill_num("Normal", "Normal1") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "杠上开花!", "damagelist": damagelist2}) # noqa: RUF001 # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) return skill_info_list class Jingliu(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 1: self.eidolon_attribute["CriticalDamageBase"] = 0.24 if self.avatar_rank >= 2: self.eidolon_attribute["BPSkill1DmgAdd"] = 0.8 if self.avatar_rank >= 4: self.eidolon_attribute["BPSkill1AttackAddedRatio"] = 0.3 self.eidolon_attribute["UltraAttackAddedRatio"] = 0.3 if self.avatar_rank >= 6: self.eidolon_attribute["Ultra_CriticalDamageBase"] = 0.5 self.eidolon_attribute["BPSkill1_CriticalDamageBase"] = 0.5 def extra_ability(self): logger.info("额外能力") logger.info("【转魄】状态下, 终结技造成的伤害提高20%。") logger.info("【转魄】状态下, 暴击率提高。") logger.info("【转魄】状态下, 攻击力提高。") self.extra_ability_attribute["UltraDmgAdd"] = 0.2 critical_chance_base = self.Skill_num("Talent", "Talent_CC") self.extra_ability_attribute["Ultra_CriticalChanceBase"] = critical_chance_base self.extra_ability_attribute[ "BPSkill1_CriticalChanceBase" ] = critical_chance_base attack_added_ratio = self.Skill_num("Talent", "Talent_atk") self.extra_ability_attribute["BPSkill1AttackAddedRatio"] = attack_added_ratio self.extra_ability_attribute["UltraAttackAddedRatio"] = attack_added_ratio async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算寒川映月伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill1") if self.avatar_rank >= 1: skill_multiplier += 1 damagelist3 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill1", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "寒川映月", "damagelist": damagelist3}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") if self.avatar_rank >= 1: skill_multiplier += 1 damagelist4 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist4}) return skill_info_list class Topaz(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): if self.avatar_rank >= 1: self.eidolon_attribute["Talent_CriticalDamageBase"] = 0.5 if self.avatar_rank >= 6: self.eidolon_attribute["Talent1_FireResistancePenetration"] = 0.1 def extra_ability(self): logger.info("额外能力") logger.info("托帕和账账对拥有火属性弱点的敌方目标造成的伤害提高15%。") self.extra_ability_attribute["AllDamageAddedRatio"] = 0.15 logger.info("涨幅惊人暴击伤害提高") self.extra_ability_attribute["Talent1_CriticalDamageBase"] = self.Skill_num( "Ultra", "Ultra_CD", ) logger.info("【负债证明】状态,使其受到的追加攻击伤害提高") self.extra_ability_attribute["Talent_DmgRatio"] = self.Skill_num( "BPSkill", "BPSkill_add", ) async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算账账伤害 skill_multiplier = self.Skill_num("Talent", "Talent") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "账账", "damagelist": damagelist2}) # 计算强化账账伤害 skill_multiplier = self.Skill_num("Talent", "Talent") + self.Skill_num( "Ultra", "Talent1", ) damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Talent", "Talent1", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "强化账账", "damagelist": damagelist3}) return skill_info_list class Guinaifen(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): pass def extra_ability(self): self.extra_ability_attribute["AllDamageAddedRatio"] = 0.2 if self.avatar_rank >= 6: self.extra_ability_attribute["DmgRatio"] = ( self.Skill_num("Talent", "Talent") * 4 ) else: self.extra_ability_attribute["DmgRatio"] = ( self.Skill_num("Talent", "Talent") * 3 ) async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技伤害 skill_multiplier = self.Skill_num("Ultra", "Ultra") damagelist3 = await calculate_damage( base_attr, attribute_bonus, "Ultra", "Ultra", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist3[2] += damage3 skill_info_list.append({"name": "终结技", "damagelist": damagelist3}) # 计算持续伤害 skill_multiplier = self.Skill_num("BPSkill", "DOT") if self.avatar_rank >= 2: skill_multiplier += 0.4 damagelist4 = await calculate_damage( base_attr, attribute_bonus, "DOT", "DOT", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist4[2] += damage3 skill_info_list.append({"name": "单次持续伤害", "damagelist": damagelist4}) return skill_info_list class Gepard(BaseAvatar): Buff: BaseAvatarBuff def __init__(self, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]): super().__init__(char=char, skills=skills) self.eidolon_attribute: Dict[str, float] = {} self.extra_ability_attribute: Dict[str, float] = {} self.eidolons() self.extra_ability() def Technique(self): pass def eidolons(self): pass def extra_ability(self): pass async def getdamage( self, base_attr: Dict[str, float], attribute_bonus: Dict[str, float], ): damage1, damage2, damage3 = await calculate_damage( base_attr, attribute_bonus, "fujia", "fujia", "Thunder", 0.44, self.avatar_level, ) skill_info_list = [] # 计算普攻伤害 skill_multiplier = self.Skill_num("Normal", "Normal") damagelist1 = await calculate_damage( base_attr, attribute_bonus, "Normal", "Normal", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist1[2] += damage3 skill_info_list.append({"name": "普攻", "damagelist": damagelist1}) # 计算战技伤害 skill_multiplier = self.Skill_num("BPSkill", "BPSkill") damagelist2 = await calculate_damage( base_attr, attribute_bonus, "BPSkill", "BPSkill", self.avatar_element, skill_multiplier, self.avatar_level, ) damagelist2[2] += damage3 skill_info_list.append({"name": "战技", "damagelist": damagelist2}) # 计算终结技护盾 skill_multiplier = self.Skill_num("Ultra", "Ultra") skill_num = self.Skill_num("Ultra", "Ultra_G")
damagelist3 = await calculate_shield(
7
2023-10-30 06:29:10+00:00
8k
nuhmanpk/text2imagebot
main.py
[ { "identifier": "START_BUTTON", "path": "utils.py", "snippet": "START_BUTTON = InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"ABOUT\", callback_data=\"cbabout\"),\n InlineKeyboardButton(\"HELP\", callback_data=\"cbhelp\"),\n ],\n [InlineKeyboardButto...
import os import json import io import torch from dotenv import load_dotenv from pyrogram import Client, filters from urllib.parse import quote from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton from utils import START_BUTTON, START_STRING, GITHUB_BUTTON, SETTINGS, GITHUB_LINK from callbacks import ( help_callback, about_callback, settings_callback, choose_model_callback, selected_model_callback, change_steps_callback, step_incre_callback, step_decre_callback, change_image_count_callback, image_incre_callback, image_decre_callback, back2settings_callback, start_callback, ) from models import MODELS from diffusers import StableDiffusionPipeline
3,652
json.dump(DEFAULT_SETTINGS, f, indent=4) text = START_STRING.format(update.from_user.mention) reply_markup = START_BUTTON await update.reply_text( text=text, disable_web_page_preview=True, reply_markup=reply_markup, quote=True ) @app.on_message(filters.command(["generate"]) & filters.private) async def generate(bot, update: Message): if update.reply_to_message: chat_id = update.chat.id settings_file_path = f"{chat_id}-settings.json" if not os.path.exists(settings_file_path): with open(settings_file_path, "w") as f: json.dump(DEFAULT_SETTINGS, f, indent=4) text = await update.reply_text("Loading settings...", quote=True) prompt = update.reply_to_message.text with open(f"{chat_id}-settings.json") as f: settings = json.load(f) await text.edit("Settings Loaded...") await text.edit(f'Downloading...\n{settings.get("model")}') model_loaded = await load_model(settings.get("model"), update) if not model_loaded: await update.reply_text("Failed to load the model.") return else: await text.edit("Generating Image...") try: images = await generate_image( update, prompt, settings.get("steps"), settings.get("seed"), settings.get("image_count"), ) await text.edit(f'Uploading {settings.get("image_count")} Image ....') for image in images: await update.reply_photo(image, reply_markup=GITHUB_BUTTON) await text.delete() except Exception as e: await text.delete() text = f"Failed to generate Image \nCreate an issue here" error = f"ERROR: {(str(e))}" error_link = f"{GITHUB_LINK}/issues/new?title={quote(error)}" issue_markup = InlineKeyboardMarkup( [[InlineKeyboardButton("Create Issue", url=error_link)]] ) await update.reply_text( text, disable_web_page_preview=True, quote=True, reply_markup=issue_markup, ) else: await update.reply_text( text="Reply /generate to a prompt", disable_web_page_preview=True, quote=True, ) async def load_model(model, update): global pipe try: pipe = StableDiffusionPipeline.from_pretrained(model, torch_dtype=torch.float16) pipe = pipe.to("cuda") return True except Exception as e: text = f"Failed to download Model \nCreate an issue here" error = f"ERROR: {(str(e))}" error_link = f"{GITHUB_LINK}/issues/new?title={quote(error)}" issue_markup = InlineKeyboardMarkup( [[InlineKeyboardButton("Create Issue", url=error_link)]] ) await update.reply_text( text, disable_web_page_preview=True, quote=True, reply_markup=issue_markup ) return False async def generate_image(update, prompt, steps, seed, count): global pipe steps = steps if seed == -1: torch.manual_seed(torch.seed()) else: torch.manual_seed(seed) pipe = pipe.to("cuda") # def custom_callback(step, timestep, latents): # text = f'Step: {step}, Timestep: {timestep}, Latents: {latents}' # print("🤖", text) # # await update.reply_text(text, disable_web_page_preview=True, quote=True,) images = pipe(prompt, num_inference_steps=steps, num_images_per_prompt=count).images image_streams = [] for image in images: image_stream = io.BytesIO() image.save(image_stream, format="PNG") image_stream.seek(0) image_streams.append(image_stream) return image_streams @app.on_message(filters.command(["settings"]) & filters.private) async def settings(bot, update: Message): chat_id = update.chat.id settings_file_path = f"{chat_id}-settings.json" if not os.path.exists(settings_file_path): with open(settings_file_path, "w") as f: json.dump(DEFAULT_SETTINGS, f, indent=4) text = "Settings file created. Please use the command again to access the settings." else: with open(settings_file_path, "r") as f: settings = json.load(f) model = settings.get("model") steps = settings.get("steps") text = f"Current Settings:\n🤖 Model: {model}\n🔄 Steps: {steps}"
load_dotenv() bot_token = os.getenv("BOT_TOKEN") api_id = os.getenv("API_ID") api_hash = os.getenv("API_HASH") if bot_token is None or api_id is None or api_hash is None: raise ValueError( "Please set the BOT_TOKEN, API_ID, and API_HASH environment variables." ) DEFAULT_SETTINGS = { "model": "digiplay/Juggernaut_final", # change default model in env "steps": 100, "seed": -1, "image_count": 1, } app = Client("text2image", bot_token=bot_token, api_id=int(api_id), api_hash=api_hash) pipe = None @app.on_callback_query() async def cb_data(bot, update): chat_id = update.message.chat.id settings_file_path = f"{chat_id}-settings.json" if not os.path.exists(settings_file_path): with open(settings_file_path, "w") as f: json.dump(DEFAULT_SETTINGS, f, indent=4) with open(settings_file_path, "r") as f: settings = json.load(f) if update.data == "cbhelp": await help_callback(update) elif update.data == "cbabout": await about_callback(update) elif update.data == "cbsettings": await settings_callback(update, settings) elif update.data == "choose_model": await choose_model_callback(update, settings) elif update.data.startswith("select_model_"): index = int(update.data.split("_")[2]) selected_model = MODELS[index] await selected_model_callback( update, selected_model, settings, settings_file_path ) elif update.data == "change_steps": await change_steps_callback(update, settings) elif update.data.startswith("+steps"): await step_incre_callback( update, settings, settings_file_path, ) elif update.data == "change_image_count": await change_image_count_callback(update, settings) elif update.data.startswith("+image"): await image_incre_callback(update, settings, settings_file_path) elif update.data.startswith("-image"): await image_decre_callback(update, settings, settings_file_path) elif update.data.startswith("-steps"): await step_decre_callback(update, settings, settings_file_path) elif update.data.startswith("cb_back_settings"): await back2settings_callback(update, settings) else: await start_callback(update) @app.on_message(filters.command(["start"]) & filters.private) async def start(bot, update: Message): chat_id = update.chat.id settings_file_path = f"{chat_id}-settings.json" if not os.path.exists(settings_file_path): with open(settings_file_path, "w") as f: json.dump(DEFAULT_SETTINGS, f, indent=4) text = START_STRING.format(update.from_user.mention) reply_markup = START_BUTTON await update.reply_text( text=text, disable_web_page_preview=True, reply_markup=reply_markup, quote=True ) @app.on_message(filters.command(["generate"]) & filters.private) async def generate(bot, update: Message): if update.reply_to_message: chat_id = update.chat.id settings_file_path = f"{chat_id}-settings.json" if not os.path.exists(settings_file_path): with open(settings_file_path, "w") as f: json.dump(DEFAULT_SETTINGS, f, indent=4) text = await update.reply_text("Loading settings...", quote=True) prompt = update.reply_to_message.text with open(f"{chat_id}-settings.json") as f: settings = json.load(f) await text.edit("Settings Loaded...") await text.edit(f'Downloading...\n{settings.get("model")}') model_loaded = await load_model(settings.get("model"), update) if not model_loaded: await update.reply_text("Failed to load the model.") return else: await text.edit("Generating Image...") try: images = await generate_image( update, prompt, settings.get("steps"), settings.get("seed"), settings.get("image_count"), ) await text.edit(f'Uploading {settings.get("image_count")} Image ....') for image in images: await update.reply_photo(image, reply_markup=GITHUB_BUTTON) await text.delete() except Exception as e: await text.delete() text = f"Failed to generate Image \nCreate an issue here" error = f"ERROR: {(str(e))}" error_link = f"{GITHUB_LINK}/issues/new?title={quote(error)}" issue_markup = InlineKeyboardMarkup( [[InlineKeyboardButton("Create Issue", url=error_link)]] ) await update.reply_text( text, disable_web_page_preview=True, quote=True, reply_markup=issue_markup, ) else: await update.reply_text( text="Reply /generate to a prompt", disable_web_page_preview=True, quote=True, ) async def load_model(model, update): global pipe try: pipe = StableDiffusionPipeline.from_pretrained(model, torch_dtype=torch.float16) pipe = pipe.to("cuda") return True except Exception as e: text = f"Failed to download Model \nCreate an issue here" error = f"ERROR: {(str(e))}" error_link = f"{GITHUB_LINK}/issues/new?title={quote(error)}" issue_markup = InlineKeyboardMarkup( [[InlineKeyboardButton("Create Issue", url=error_link)]] ) await update.reply_text( text, disable_web_page_preview=True, quote=True, reply_markup=issue_markup ) return False async def generate_image(update, prompt, steps, seed, count): global pipe steps = steps if seed == -1: torch.manual_seed(torch.seed()) else: torch.manual_seed(seed) pipe = pipe.to("cuda") # def custom_callback(step, timestep, latents): # text = f'Step: {step}, Timestep: {timestep}, Latents: {latents}' # print("🤖", text) # # await update.reply_text(text, disable_web_page_preview=True, quote=True,) images = pipe(prompt, num_inference_steps=steps, num_images_per_prompt=count).images image_streams = [] for image in images: image_stream = io.BytesIO() image.save(image_stream, format="PNG") image_stream.seek(0) image_streams.append(image_stream) return image_streams @app.on_message(filters.command(["settings"]) & filters.private) async def settings(bot, update: Message): chat_id = update.chat.id settings_file_path = f"{chat_id}-settings.json" if not os.path.exists(settings_file_path): with open(settings_file_path, "w") as f: json.dump(DEFAULT_SETTINGS, f, indent=4) text = "Settings file created. Please use the command again to access the settings." else: with open(settings_file_path, "r") as f: settings = json.load(f) model = settings.get("model") steps = settings.get("steps") text = f"Current Settings:\n🤖 Model: {model}\n🔄 Steps: {steps}"
await update.reply_text(text=text, reply_markup=SETTINGS, quote=True)
3
2023-10-30 14:25:26+00:00
8k
deforum-studio/deforum
src/deforum/models/depth_models/zoedepth/data/data_mono.py
[ { "identifier": "get_ddad_loader", "path": "src/deforum/models/depth_models/zoedepth/data/ddad.py", "snippet": "def get_ddad_loader(data_dir_root, resize_shape, batch_size=1, **kwargs):\n dataset = DDAD(data_dir_root, resize_shape)\n return DataLoader(dataset, batch_size, **kwargs)" }, { "...
import itertools import os import random import numpy as np import cv2 import torch import torch.nn as nn import torch.utils.data.distributed from zoedepth.utils.easydict import EasyDict as edict from PIL import Image, ImageOps from torch.utils.data import DataLoader, Dataset from torchvision import transforms from zoedepth.utils.config import change_dataset from .ddad import get_ddad_loader from .diml_indoor_test import get_diml_indoor_loader from .diml_outdoor_test import get_diml_outdoor_loader from .diode import get_diode_loader from .hypersim import get_hypersim_loader from .ibims import get_ibims_loader from .sun_rgbd_loader import get_sunrgbd_loader from .vkitti import get_vkitti_loader from .vkitti2 import get_vkitti2_loader from .preprocess import CropParams, get_white_border, get_black_border
3,662
return repetitive_roundrobin(*self.dataloaders) def __len__(self): # First samples get repeated, thats why the plus one return len(self.dataloaders) * (max(len(dl) for dl in self.dataloaders) + 1) class MixedNYUKITTI(object): def __init__(self, config, mode, device='cpu', **kwargs): config = edict(config) config.workers = config.workers // 2 self.config = config nyu_conf = change_dataset(edict(config), 'nyu') kitti_conf = change_dataset(edict(config), 'kitti') # make nyu default for testing self.config = config = nyu_conf img_size = self.config.get("img_size", None) img_size = img_size if self.config.get( "do_input_resize", False) else None if mode == 'train': nyu_loader = DepthDataLoader( nyu_conf, mode, device=device, transform=preprocessing_transforms(mode, size=img_size)).data kitti_loader = DepthDataLoader( kitti_conf, mode, device=device, transform=preprocessing_transforms(mode, size=img_size)).data # It has been changed to repetitive roundrobin self.data = RepetitiveRoundRobinDataLoader( nyu_loader, kitti_loader) else: self.data = DepthDataLoader(nyu_conf, mode, device=device).data def remove_leading_slash(s): if s[0] == '/' or s[0] == '\\': return s[1:] return s class CachedReader: def __init__(self, shared_dict=None): if shared_dict: self._cache = shared_dict else: self._cache = {} def open(self, fpath): im = self._cache.get(fpath, None) if im is None: im = self._cache[fpath] = Image.open(fpath) return im class ImReader: def __init__(self): pass # @cache def open(self, fpath): return Image.open(fpath) class DataLoadPreprocess(Dataset): def __init__(self, config, mode, transform=None, is_for_online_eval=False, **kwargs): self.config = config if mode == 'online_eval': with open(config.filenames_file_eval, 'r') as f: self.filenames = f.readlines() else: with open(config.filenames_file, 'r') as f: self.filenames = f.readlines() self.mode = mode self.transform = transform self.to_tensor = ToTensor(mode) self.is_for_online_eval = is_for_online_eval if config.use_shared_dict: self.reader = CachedReader(config.shared_dict) else: self.reader = ImReader() def postprocess(self, sample): return sample def __getitem__(self, idx): sample_path = self.filenames[idx] focal = float(sample_path.split()[2]) sample = {} if self.mode == 'train': if self.config.dataset == 'kitti' and self.config.use_right and random.random() > 0.5: image_path = os.path.join( self.config.data_path, remove_leading_slash(sample_path.split()[3])) depth_path = os.path.join( self.config.gt_path, remove_leading_slash(sample_path.split()[4])) else: image_path = os.path.join( self.config.data_path, remove_leading_slash(sample_path.split()[0])) depth_path = os.path.join( self.config.gt_path, remove_leading_slash(sample_path.split()[1])) image = self.reader.open(image_path) depth_gt = self.reader.open(depth_path) w, h = image.size if self.config.do_kb_crop: height = image.height width = image.width top_margin = int(height - 352) left_margin = int((width - 1216) / 2) depth_gt = depth_gt.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) image = image.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) # Avoid blank boundaries due to pixel registration? # Train images have white border. Test images have black border. if self.config.dataset == 'nyu' and self.config.avoid_boundary: # print("Avoiding Blank Boundaries!") # We just crop and pad again with reflect padding to original size # original_size = image.size
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # 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. # File author: Shariq Farooq Bhat # This file is partly inspired from BTS (https://github.com/cleinc/bts/blob/master/pytorch/bts_dataloader.py); author: Jin Han Lee def _is_pil_image(img): return isinstance(img, Image.Image) def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) def preprocessing_transforms(mode, **kwargs): return transforms.Compose([ ToTensor(mode=mode, **kwargs) ]) class DepthDataLoader(object): def __init__(self, config, mode, device='cpu', transform=None, **kwargs): """ Data loader for depth datasets Args: config (dict): Config dictionary. Refer to utils/config.py mode (str): "train" or "online_eval" device (str, optional): Device to load the data on. Defaults to 'cpu'. transform (torchvision.transforms, optional): Transform to apply to the data. Defaults to None. """ self.config = config if config.dataset == 'ibims': self.data = get_ibims_loader(config, batch_size=1, num_workers=1) return if config.dataset == 'sunrgbd': self.data = get_sunrgbd_loader( data_dir_root=config.sunrgbd_root, batch_size=1, num_workers=1) return if config.dataset == 'diml_indoor': self.data = get_diml_indoor_loader( data_dir_root=config.diml_indoor_root, batch_size=1, num_workers=1) return if config.dataset == 'diml_outdoor': self.data = get_diml_outdoor_loader( data_dir_root=config.diml_outdoor_root, batch_size=1, num_workers=1) return if "diode" in config.dataset: self.data = get_diode_loader( config[config.dataset+"_root"], batch_size=1, num_workers=1) return if config.dataset == 'hypersim_test': self.data = get_hypersim_loader( config.hypersim_test_root, batch_size=1, num_workers=1) return if config.dataset == 'vkitti': self.data = get_vkitti_loader( config.vkitti_root, batch_size=1, num_workers=1) return if config.dataset == 'vkitti2': self.data = get_vkitti2_loader( config.vkitti2_root, batch_size=1, num_workers=1) return if config.dataset == 'ddad': self.data = get_ddad_loader(config.ddad_root, resize_shape=( 352, 1216), batch_size=1, num_workers=1) return img_size = self.config.get("img_size", None) img_size = img_size if self.config.get( "do_input_resize", False) else None if transform is None: transform = preprocessing_transforms(mode, size=img_size) if mode == 'train': Dataset = DataLoadPreprocess self.training_samples = Dataset( config, mode, transform=transform, device=device) if config.distributed: self.train_sampler = torch.utils.data.distributed.DistributedSampler( self.training_samples) else: self.train_sampler = None self.data = DataLoader(self.training_samples, batch_size=config.batch_size, shuffle=(self.train_sampler is None), num_workers=config.workers, pin_memory=True, persistent_workers=True, # prefetch_factor=2, sampler=self.train_sampler) elif mode == 'online_eval': self.testing_samples = DataLoadPreprocess( config, mode, transform=transform) if config.distributed: # redundant. here only for readability and to be more explicit # Give whole test set to all processes (and report evaluation only on one) regardless self.eval_sampler = None else: self.eval_sampler = None self.data = DataLoader(self.testing_samples, 1, shuffle=kwargs.get("shuffle_test", False), num_workers=1, pin_memory=False, sampler=self.eval_sampler) elif mode == 'test': self.testing_samples = DataLoadPreprocess( config, mode, transform=transform) self.data = DataLoader(self.testing_samples, 1, shuffle=False, num_workers=1) else: print( 'mode should be one of \'train, test, online_eval\'. Got {}'.format(mode)) def repetitive_roundrobin(*iterables): """ cycles through iterables but sample wise first yield first sample from first iterable then first sample from second iterable and so on then second sample from first iterable then second sample from second iterable and so on If one iterable is shorter than the others, it is repeated until all iterables are exhausted repetitive_roundrobin('ABC', 'D', 'EF') --> A D E B D F C D E """ # Repetitive roundrobin iterables_ = [iter(it) for it in iterables] exhausted = [False] * len(iterables) while not all(exhausted): for i, it in enumerate(iterables_): try: yield next(it) except StopIteration: exhausted[i] = True iterables_[i] = itertools.cycle(iterables[i]) # First elements may get repeated if one iterable is shorter than the others yield next(iterables_[i]) class RepetitiveRoundRobinDataLoader(object): def __init__(self, *dataloaders): self.dataloaders = dataloaders def __iter__(self): return repetitive_roundrobin(*self.dataloaders) def __len__(self): # First samples get repeated, thats why the plus one return len(self.dataloaders) * (max(len(dl) for dl in self.dataloaders) + 1) class MixedNYUKITTI(object): def __init__(self, config, mode, device='cpu', **kwargs): config = edict(config) config.workers = config.workers // 2 self.config = config nyu_conf = change_dataset(edict(config), 'nyu') kitti_conf = change_dataset(edict(config), 'kitti') # make nyu default for testing self.config = config = nyu_conf img_size = self.config.get("img_size", None) img_size = img_size if self.config.get( "do_input_resize", False) else None if mode == 'train': nyu_loader = DepthDataLoader( nyu_conf, mode, device=device, transform=preprocessing_transforms(mode, size=img_size)).data kitti_loader = DepthDataLoader( kitti_conf, mode, device=device, transform=preprocessing_transforms(mode, size=img_size)).data # It has been changed to repetitive roundrobin self.data = RepetitiveRoundRobinDataLoader( nyu_loader, kitti_loader) else: self.data = DepthDataLoader(nyu_conf, mode, device=device).data def remove_leading_slash(s): if s[0] == '/' or s[0] == '\\': return s[1:] return s class CachedReader: def __init__(self, shared_dict=None): if shared_dict: self._cache = shared_dict else: self._cache = {} def open(self, fpath): im = self._cache.get(fpath, None) if im is None: im = self._cache[fpath] = Image.open(fpath) return im class ImReader: def __init__(self): pass # @cache def open(self, fpath): return Image.open(fpath) class DataLoadPreprocess(Dataset): def __init__(self, config, mode, transform=None, is_for_online_eval=False, **kwargs): self.config = config if mode == 'online_eval': with open(config.filenames_file_eval, 'r') as f: self.filenames = f.readlines() else: with open(config.filenames_file, 'r') as f: self.filenames = f.readlines() self.mode = mode self.transform = transform self.to_tensor = ToTensor(mode) self.is_for_online_eval = is_for_online_eval if config.use_shared_dict: self.reader = CachedReader(config.shared_dict) else: self.reader = ImReader() def postprocess(self, sample): return sample def __getitem__(self, idx): sample_path = self.filenames[idx] focal = float(sample_path.split()[2]) sample = {} if self.mode == 'train': if self.config.dataset == 'kitti' and self.config.use_right and random.random() > 0.5: image_path = os.path.join( self.config.data_path, remove_leading_slash(sample_path.split()[3])) depth_path = os.path.join( self.config.gt_path, remove_leading_slash(sample_path.split()[4])) else: image_path = os.path.join( self.config.data_path, remove_leading_slash(sample_path.split()[0])) depth_path = os.path.join( self.config.gt_path, remove_leading_slash(sample_path.split()[1])) image = self.reader.open(image_path) depth_gt = self.reader.open(depth_path) w, h = image.size if self.config.do_kb_crop: height = image.height width = image.width top_margin = int(height - 352) left_margin = int((width - 1216) / 2) depth_gt = depth_gt.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) image = image.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) # Avoid blank boundaries due to pixel registration? # Train images have white border. Test images have black border. if self.config.dataset == 'nyu' and self.config.avoid_boundary: # print("Avoiding Blank Boundaries!") # We just crop and pad again with reflect padding to original size # original_size = image.size
crop_params = get_white_border(np.array(image, dtype=np.uint8))
10
2023-10-28 14:23:27+00:00
8k
samholt/ActiveObservingInContinuous-timeControl
envs/oderl/ctrl/dynamics.py
[ { "identifier": "BENN", "path": "envs/oderl/utils/benn.py", "snippet": "class BENN(nn.Module):\n def __init__(\n self,\n n_ens: int,\n n_in: int,\n n_out: int,\n n_hid_layers: int = 2,\n n_hidden: int = 250,\n act: str = \"relu\",\n requires_gra...
from abc import ABCMeta, abstractmethod from envs.oderl.utils import BENN, ENN, EPNN, IBNN, DropoutBNN from envs.oderl.utils.utils import odesolve import numpy as np import torch import torch.nn as nn
4,917
class Dynamics(nn.Module, metaclass=ABCMeta): @abstractmethod def __init__(self, env, dynamics, L, nl=2, nn=100, act="relu", dropout=0.0, bnn=False): super().__init__() n, m = env.n, env.m self.qin, self.qout = n + m, n self.qin = self.qin self.env = env self.dynamics = dynamics self.L = L self.ens_method = False if self.dynamics == "ibnode": self._f = IBNN(L, self.qin, self.qout, n_hid_layers=nl, n_hidden=nn, act=act) elif self.dynamics == "benode": self._f = BENN(L, self.qin, self.qout, n_hid_layers=nl, n_hidden=nn, act=act) self.ens_method = True elif self.dynamics == "enode":
class Dynamics(nn.Module, metaclass=ABCMeta): @abstractmethod def __init__(self, env, dynamics, L, nl=2, nn=100, act="relu", dropout=0.0, bnn=False): super().__init__() n, m = env.n, env.m self.qin, self.qout = n + m, n self.qin = self.qin self.env = env self.dynamics = dynamics self.L = L self.ens_method = False if self.dynamics == "ibnode": self._f = IBNN(L, self.qin, self.qout, n_hid_layers=nl, n_hidden=nn, act=act) elif self.dynamics == "benode": self._f = BENN(L, self.qin, self.qout, n_hid_layers=nl, n_hidden=nn, act=act) self.ens_method = True elif self.dynamics == "enode":
self._f = ENN(L, self.qin, self.qout, n_hid_layers=nl, n_hidden=nn, act=act)
2
2023-10-24 16:19:14+00:00
8k
s1tools/s1-etad
s1etad/kmz.py
[ { "identifier": "Sentinel1Etad", "path": "s1etad/product.py", "snippet": "class Sentinel1Etad:\n \"\"\"Sentinel-1 ETAD product.\n\n Class to decode and access the elements of the Sentinel ETAD product\n which specification is governed by ETAD-DLR-PS-0014.\n\n The index operator [] (implement...
import shutil import pathlib import datetime import functools import numpy as np import matplotlib as mpl from simplekml import Kml, OverlayXY, ScreenXY, Units, RotationXY from osgeo import gdal from osgeo import osr from matplotlib import cm from matplotlib import pyplot from .product import Sentinel1Etad, ECorrectionType from .utils import iter_corrections
6,395
"""Support for Google KMZ preview generation.""" __all__ = ["etad_to_kmz", "Sentinel1EtadKmlWriter"] class Sentinel1EtadKmlWriter: # TODO: only SUM by default DEFAULT_CORRECTIONS = (ECorrectionType.SUM, ECorrectionType.TROPOSPHERIC) DEFAULT_TIMESPAN = 30 # [s] DEFAULT_LOOKAT_RANGE = 1500000 DEFAULT_OPEN_FOLDER = False def __init__( self, etad, corrections=None, timespan=DEFAULT_TIMESPAN, selection=None, decimation_factor=1, colorizing=True, open_folders=DEFAULT_OPEN_FOLDER, ):
"""Support for Google KMZ preview generation.""" __all__ = ["etad_to_kmz", "Sentinel1EtadKmlWriter"] class Sentinel1EtadKmlWriter: # TODO: only SUM by default DEFAULT_CORRECTIONS = (ECorrectionType.SUM, ECorrectionType.TROPOSPHERIC) DEFAULT_TIMESPAN = 30 # [s] DEFAULT_LOOKAT_RANGE = 1500000 DEFAULT_OPEN_FOLDER = False def __init__( self, etad, corrections=None, timespan=DEFAULT_TIMESPAN, selection=None, decimation_factor=1, colorizing=True, open_folders=DEFAULT_OPEN_FOLDER, ):
assert isinstance(etad, Sentinel1Etad)
0
2023-10-27 13:47:30+00:00
8k
ifrit98/storage-subnet
storage/validator/reward.py
[ { "identifier": "verify_store_with_seed", "path": "storage/validator/verify.py", "snippet": "def verify_store_with_seed(synapse, b64_encrypted_data, seed, verbose=False):\n \"\"\"\n Verifies the storing process in a decentralized network using the provided synapse and seed.\n This function deco...
import sys import torch import numpy as np import bittensor as bt from bittensor import Synapse from pprint import pformat from typing import Union, List from functools import partial from .verify import ( verify_store_with_seed, verify_challenge_with_seed, verify_retrieve_with_seed, ) from .database import add_metadata_to_hotkey from .bonding import update_statistics, get_tier_factor from .event import EventSchema from storage.constants import ( STORE_FAILURE_REWARD, RETRIEVAL_FAILURE_REWARD, CHALLENGE_FAILURE_REWARD, ) from storage.protocol import Store, Retrieve, Challenge
6,725
List[float]: Normalized response times scaled between 0 and 1. """ if times == []: return [] min_time = min(times) max_time = max(times) range_time = max_time - min_time if range_time == 0: # Avoid division by zero in case all times are the same return [0.5 for _ in times] return [(time - max_time) / range_time for time in times] def scale_rewards(uids, responses, rewards, timeout: float, mode: str): """ Scales the rewards for each axon based on their response times using `mode` normalization. Args: uids (List[int]): A list of unique identifiers for each axon. responses (List[Response]): A list of Response objects corresponding to each axon. rewards (List[float]): A list of initial reward values for each axon. timeout (float): The timeout value used for response time calculations. mode (str): The normalization mode to use. Can be either 'sigmoid' or 'minmax'. Returns: List[float]: A list of scaled rewards for each axon. """ sorted_axon_times = get_sorted_response_times(uids, responses, timeout=timeout) # Extract only the process times process_times = [proc_time for _, proc_time in sorted_axon_times] # Normalize the response times normalized_times = ( min_max_normalize(process_times) if mode == "minmax" else sigmoid_normalize(process_times, timeout) ) # Create a dictionary mapping UIDs to normalized times uid_to_normalized_time = { uid: normalized_time for (uid, _), normalized_time in zip(sorted_axon_times, normalized_times) } bt.logging.debug( f"scale_rewards_by_{mode}() uid_to_normalized_time: {uid_to_normalized_time}" ) # Scale the rewards with normalized times for i, uid in enumerate(uids): normalized_time_for_uid = uid_to_normalized_time[uid] rewards[i] += rewards[i] * normalized_time_for_uid bt.logging.debug(f"scale_rewards_by_{mode}() rewards: {rewards}") return rewards def apply_reward_scores( self, uids, responses, rewards, timeout: float, mode: str = "sigmoid" ): """ Adjusts the moving average scores for a set of UIDs based on their response times and reward values. This should reflect the distribution of axon response times (minmax norm) Parameters: uids (List[int]): A list of UIDs for which rewards are being applied. responses (List[Response]): A list of response objects received from the nodes. rewards (torch.FloatTensor): A tensor containing the computed reward values. """ if mode not in ["sigmoid", "minmax"]: raise ValueError(f"Invalid mode: {mode}") if self.config.neuron.verbose: bt.logging.debug(f"Applying rewards: {rewards}") bt.logging.debug(f"Reward shape: {rewards.shape}") bt.logging.debug(f"UIDs: {uids}") scaled_rewards = scale_rewards(uids, responses, rewards, timeout=timeout, mode=mode) bt.logging.debug(f"apply_reward_scores() Scaled rewards: {scaled_rewards}") # Compute forward pass rewards # shape: [ metagraph.n ] scattered_rewards: torch.FloatTensor = self.moving_averaged_scores.scatter( 0, torch.tensor(uids).to(self.device), scaled_rewards ).to(self.device) bt.logging.trace(f"Scattered rewards: {scattered_rewards}") # Update moving_averaged_scores with rewards produced by this step. # shape: [ metagraph.n ] alpha: float = self.config.neuron.moving_average_alpha self.moving_averaged_scores: torch.FloatTensor = alpha * scattered_rewards + ( 1 - alpha ) * self.moving_averaged_scores.to(self.device) bt.logging.trace(f"Updated moving avg scores: {self.moving_averaged_scores}") async def create_reward_vector( self, synapse: Union[Store, Retrieve, Challenge], rewards: torch.FloatTensor, uids: List[int], responses: List[Synapse], event: EventSchema, callback: callable, fail_callback: callable, ): # Determine if the commitment is valid success = False if isinstance(synapse, Store): verify_fn = partial( verify_store_with_seed, b64_encrypted_data=synapse.encrypted_data, seed=synapse.seed, ) task_type = "store" failure_reward = STORE_FAILURE_REWARD elif isinstance(synapse, Retrieve): verify_fn = partial(verify_retrieve_with_seed, seed=synapse.seed) task_type = "retrieve" failure_reward = RETRIEVAL_FAILURE_REWARD elif isinstance(synapse, Challenge): verify_fn = partial(verify_challenge_with_seed, seed=synapse.seed) task_type = "challenge"
# The MIT License (MIT) # Copyright © 2023 Yuma Rao # Copyright © 2023 philanthrope # 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. def adjusted_sigmoid(x, steepness=1, shift=0): """ Adjusted sigmoid function. This function is a modified version of the sigmoid function that is shifted to the right by a certain amount. """ return 1 / (1 + np.exp(-steepness * (x - shift))) def adjusted_sigmoid_inverse(x, steepness=1, shift=0): """ Inverse of the adjusted sigmoid function. This function is a modified version of the sigmoid function that is shifted to the right by a certain amount but inverted such that low completion times are rewarded and high completions dimes are punished. """ return 1 / (1 + np.exp(steepness * (x - shift))) def calculate_sigmoid_params(timeout): """ Calculate sigmoid parameters based on the timeout value. Args: - timeout (float): The current timeout value. Returns: - tuple: A tuple containing the 'steepness' and 'shift' values for the current timeout. """ base_timeout = 1 base_steepness = 5 base_shift = 0.6 # Calculate the ratio of the current timeout to the base timeout ratio = timeout / base_timeout # Calculate steepness and shift based on the pattern steepness = base_steepness / ratio shift = base_shift * ratio return steepness, shift def get_sorted_response_times(uids, responses, timeout: float): """ Sorts a list of axons based on their response times. This function pairs each uid with its corresponding axon's response time, and then sorts this list in ascending order. Lower response times are considered better. Args: uids (List[int]): List of unique identifiers for each axon. responses (List[Response]): List of Response objects corresponding to each axon. Returns: List[Tuple[int, float]]: A sorted list of tuples, where each tuple contains an axon's uid and its response time. Example: >>> get_sorted_response_times([1, 2, 3], [response1, response2, response3]) [(2, 0.1), (1, 0.2), (3, 0.3)] """ axon_times = [ ( uids[idx], response.dendrite.process_time if response.dendrite.process_time != None else timeout, ) for idx, response in enumerate(responses) ] # Sorting in ascending order since lower process time is better sorted_axon_times = sorted(axon_times, key=lambda x: x[1]) bt.logging.debug(f"sorted_axon_times: {sorted_axon_times}") return sorted_axon_times def sigmoid_normalize(process_times, timeout): # Center the completion times around 0 for effective sigmoid scaling centered_times = process_times - np.mean(process_times) # Calculate steepness and shift based on timeout steepness, shift = calculate_sigmoid_params(timeout) # Apply adjusted sigmoid function to scale the times return adjusted_sigmoid_inverse(centered_times, steepness, shift) def min_max_normalize(times): """ Normalizes the response times using Min-Max scaling. Args: times (List[float]): A list of response times. Returns: List[float]: Normalized response times scaled between 0 and 1. """ if times == []: return [] min_time = min(times) max_time = max(times) range_time = max_time - min_time if range_time == 0: # Avoid division by zero in case all times are the same return [0.5 for _ in times] return [(time - max_time) / range_time for time in times] def scale_rewards(uids, responses, rewards, timeout: float, mode: str): """ Scales the rewards for each axon based on their response times using `mode` normalization. Args: uids (List[int]): A list of unique identifiers for each axon. responses (List[Response]): A list of Response objects corresponding to each axon. rewards (List[float]): A list of initial reward values for each axon. timeout (float): The timeout value used for response time calculations. mode (str): The normalization mode to use. Can be either 'sigmoid' or 'minmax'. Returns: List[float]: A list of scaled rewards for each axon. """ sorted_axon_times = get_sorted_response_times(uids, responses, timeout=timeout) # Extract only the process times process_times = [proc_time for _, proc_time in sorted_axon_times] # Normalize the response times normalized_times = ( min_max_normalize(process_times) if mode == "minmax" else sigmoid_normalize(process_times, timeout) ) # Create a dictionary mapping UIDs to normalized times uid_to_normalized_time = { uid: normalized_time for (uid, _), normalized_time in zip(sorted_axon_times, normalized_times) } bt.logging.debug( f"scale_rewards_by_{mode}() uid_to_normalized_time: {uid_to_normalized_time}" ) # Scale the rewards with normalized times for i, uid in enumerate(uids): normalized_time_for_uid = uid_to_normalized_time[uid] rewards[i] += rewards[i] * normalized_time_for_uid bt.logging.debug(f"scale_rewards_by_{mode}() rewards: {rewards}") return rewards def apply_reward_scores( self, uids, responses, rewards, timeout: float, mode: str = "sigmoid" ): """ Adjusts the moving average scores for a set of UIDs based on their response times and reward values. This should reflect the distribution of axon response times (minmax norm) Parameters: uids (List[int]): A list of UIDs for which rewards are being applied. responses (List[Response]): A list of response objects received from the nodes. rewards (torch.FloatTensor): A tensor containing the computed reward values. """ if mode not in ["sigmoid", "minmax"]: raise ValueError(f"Invalid mode: {mode}") if self.config.neuron.verbose: bt.logging.debug(f"Applying rewards: {rewards}") bt.logging.debug(f"Reward shape: {rewards.shape}") bt.logging.debug(f"UIDs: {uids}") scaled_rewards = scale_rewards(uids, responses, rewards, timeout=timeout, mode=mode) bt.logging.debug(f"apply_reward_scores() Scaled rewards: {scaled_rewards}") # Compute forward pass rewards # shape: [ metagraph.n ] scattered_rewards: torch.FloatTensor = self.moving_averaged_scores.scatter( 0, torch.tensor(uids).to(self.device), scaled_rewards ).to(self.device) bt.logging.trace(f"Scattered rewards: {scattered_rewards}") # Update moving_averaged_scores with rewards produced by this step. # shape: [ metagraph.n ] alpha: float = self.config.neuron.moving_average_alpha self.moving_averaged_scores: torch.FloatTensor = alpha * scattered_rewards + ( 1 - alpha ) * self.moving_averaged_scores.to(self.device) bt.logging.trace(f"Updated moving avg scores: {self.moving_averaged_scores}") async def create_reward_vector( self, synapse: Union[Store, Retrieve, Challenge], rewards: torch.FloatTensor, uids: List[int], responses: List[Synapse], event: EventSchema, callback: callable, fail_callback: callable, ): # Determine if the commitment is valid success = False if isinstance(synapse, Store): verify_fn = partial( verify_store_with_seed, b64_encrypted_data=synapse.encrypted_data, seed=synapse.seed, ) task_type = "store" failure_reward = STORE_FAILURE_REWARD elif isinstance(synapse, Retrieve): verify_fn = partial(verify_retrieve_with_seed, seed=synapse.seed) task_type = "retrieve" failure_reward = RETRIEVAL_FAILURE_REWARD elif isinstance(synapse, Challenge): verify_fn = partial(verify_challenge_with_seed, seed=synapse.seed) task_type = "challenge"
failure_reward = CHALLENGE_FAILURE_REWARD
9
2023-10-26 18:54:47+00:00
8k
Eclectic-Sheep/sheeprlhf
sheeprlhf/task/train/rm.py
[ { "identifier": "TextDataset", "path": "sheeprlhf/data/base.py", "snippet": "class TextDataset(torch.utils.data.Dataset):\n \"\"\"A simple text dataset for loading data from a pandas dataframe.\"\"\"\n\n def __init__(self, dataframe_path: str):\n self.dataframe = pd.read_pickle(dataframe_pa...
import time import torch from pathlib import Path from typing import Any, Callable, Dict from lightning import Fabric from torch.utils.data import DataLoader from tqdm import tqdm from sheeprlhf.data.base import TextDataset from sheeprlhf.data.collate import CompareCollate from sheeprlhf.loss.reward import load_reward_loss from sheeprlhf.model.reward import RewardModel from sheeprlhf.structure.data import DataConfig from sheeprlhf.structure.model import ModelConfig from sheeprlhf.structure.task import RMConfig from sheeprlhf.utils.data import validate_dataset from sheeprlhf.utils.helper import create_tensorboard_logger, get_log_dir, trainable_parameter_summary from sheeprlhf.utils.hydra import instantiate_from_config from sheeprlhf.utils.metric import RMMetricManager, reward_accuracy from sheeprlhf.utils.model import compute_grad_norm, get_model_checkpoint, prepare_optimizer_parameters from sheeprlhf.utils.registry import register_task from sheeprlhf.utils.scheduler import CosineSchedulerWithWarmup
6,002
@torch.no_grad() def evaluate(model: RewardModel, val_dataloader: DataLoader, loss: Callable, pad_token_id: int, eval_iters: int): # noqa: D103 eval_counter = 0 average_acc = 0 average_loss = 0 for batch in val_dataloader: chosen_rewards = model(input_ids=batch["chosen_input_ids"], attention_mask=batch["chosen_attention_mask"]) rejected_rewards = model(input_ids=batch["rejected_input_ids"], attention_mask=batch["rejected_attention_mask"]) val_loss, choosen_last_rewards, rejected_last_rewards = loss( chosen=batch["chosen_input_ids"], rejected=batch["rejected_input_ids"], chosen_rewards=chosen_rewards, rejected_rewards=rejected_rewards, pad_token_id=pad_token_id, ) average_loss += val_loss.detach() acc = reward_accuracy(choosen_last_rewards, rejected_last_rewards) average_acc += acc eval_counter += 1 if eval_iters is not None and eval_counter >= eval_iters: break average_acc /= eval_counter average_loss /= eval_counter return ( average_loss, average_acc, )
@torch.no_grad() def evaluate(model: RewardModel, val_dataloader: DataLoader, loss: Callable, pad_token_id: int, eval_iters: int): # noqa: D103 eval_counter = 0 average_acc = 0 average_loss = 0 for batch in val_dataloader: chosen_rewards = model(input_ids=batch["chosen_input_ids"], attention_mask=batch["chosen_attention_mask"]) rejected_rewards = model(input_ids=batch["rejected_input_ids"], attention_mask=batch["rejected_attention_mask"]) val_loss, choosen_last_rewards, rejected_last_rewards = loss( chosen=batch["chosen_input_ids"], rejected=batch["rejected_input_ids"], chosen_rewards=chosen_rewards, rejected_rewards=rejected_rewards, pad_token_id=pad_token_id, ) average_loss += val_loss.detach() acc = reward_accuracy(choosen_last_rewards, rejected_last_rewards) average_acc += acc eval_counter += 1 if eval_iters is not None and eval_counter >= eval_iters: break average_acc /= eval_counter average_loss /= eval_counter return ( average_loss, average_acc, )
@register_task()
17
2023-10-31 12:02:02+00:00
8k
cpacker/MemGPT
tests/test_metadata_store.py
[ { "identifier": "MetadataStore", "path": "memgpt/metadata.py", "snippet": "class MetadataStore:\n def __init__(self, config: MemGPTConfig):\n # TODO: get DB URI or path\n if config.metadata_storage_type == \"postgres\":\n self.uri = config.metadata_storage_uri\n elif c...
import os import pytest from memgpt.metadata import MetadataStore from memgpt.config import MemGPTConfig from memgpt.data_types import User, AgentState, Source, LLMConfig, EmbeddingConfig
5,828
# @pytest.mark.parametrize("storage_connector", ["postgres", "sqlite"]) @pytest.mark.parametrize("storage_connector", ["sqlite"]) def test_storage(storage_connector): config = MemGPTConfig() if storage_connector == "postgres": if not os.getenv("PGVECTOR_TEST_DB_URL"): print("Skipping test, missing PG URI") return config.archival_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.recall_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.archival_storage_type = "postgres" config.recall_storage_type = "postgres" if storage_connector == "sqlite": config.recall_storage_type = "local" ms = MetadataStore(config) # generate data user_1 = User() user_2 = User() agent_1 = AgentState( user_id=user_1.id, name="agent_1", preset=user_1.default_preset, persona=user_1.default_persona, human=user_1.default_human, llm_config=config.default_llm_config, embedding_config=config.default_embedding_config, )
# @pytest.mark.parametrize("storage_connector", ["postgres", "sqlite"]) @pytest.mark.parametrize("storage_connector", ["sqlite"]) def test_storage(storage_connector): config = MemGPTConfig() if storage_connector == "postgres": if not os.getenv("PGVECTOR_TEST_DB_URL"): print("Skipping test, missing PG URI") return config.archival_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.recall_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.archival_storage_type = "postgres" config.recall_storage_type = "postgres" if storage_connector == "sqlite": config.recall_storage_type = "local" ms = MetadataStore(config) # generate data user_1 = User() user_2 = User() agent_1 = AgentState( user_id=user_1.id, name="agent_1", preset=user_1.default_preset, persona=user_1.default_persona, human=user_1.default_human, llm_config=config.default_llm_config, embedding_config=config.default_embedding_config, )
source_1 = Source(user_id=user_1.id, name="source_1")
4
2023-10-11 07:38:37+00:00
8k
NVIDIA/Stable-Diffusion-WebUI-TensorRT
ui_trt.py
[ { "identifier": "UNetModel", "path": "model_helper.py", "snippet": "class UNetModel(torch.nn.Module):\n def __init__(\n self, unet, embedding_dim: int, text_minlen: int = 77, is_xl: bool = False\n ) -> None:\n super().__init__()\n self.unet = unet\n self.is_xl = is_xl\n...
import os import gc import json import logging import torch import gradio as gr from collections import defaultdict from safetensors.torch import save_file from modules.shared import cmd_opts from modules.ui_components import FormRow from modules import sd_hijack, sd_models, shared from modules.ui_common import refresh_symbol from modules.ui_components import ToolButton from model_helper import UNetModel from exporter import export_onnx, export_trt, export_lora from model_manager import modelmanager, cc_major, TRT_MODEL_DIR from datastructures import SDVersion, ProfilePrests, ProfileSettings
4,972
profile_presets = ProfilePrests() logging.basicConfig(level=logging.INFO) def get_context_dim(): if shared.sd_model.is_sd1: return 768 elif shared.sd_model.is_sd2: return 1024 elif shared.sd_model.is_sdxl: return 2048 def is_fp32(): use_fp32 = False if cc_major < 7: use_fp32 = True print("FP16 has been disabled because your GPU does not support it.") return use_fp32 def export_unet_to_trt( batch_min, batch_opt, batch_max, height_min, height_opt, height_max, width_min, width_opt, width_max, token_count_min, token_count_opt, token_count_max, force_export, static_shapes, preset, ): sd_hijack.model_hijack.apply_optimizations("None") is_xl = shared.sd_model.is_sdxl model_name = shared.sd_model.sd_checkpoint_info.model_name profile_settings = ProfileSettings( batch_min, batch_opt, batch_max, height_min, height_opt, height_max, width_min, width_opt, width_max, token_count_min, token_count_opt, token_count_max, ) if preset == "Default": profile_settings = profile_presets.get_default(is_xl=is_xl) use_fp32 = is_fp32() print(f"Exporting {model_name} to TensorRT using - {profile_settings}") profile_settings.token_to_dim(static_shapes) model_hash = shared.sd_model.sd_checkpoint_info.hash model_name = shared.sd_model.sd_checkpoint_info.model_name onnx_filename, onnx_path = modelmanager.get_onnx_path(model_name) timing_cache = modelmanager.get_timing_cache() diable_optimizations = is_xl embedding_dim = get_context_dim()
profile_presets = ProfilePrests() logging.basicConfig(level=logging.INFO) def get_context_dim(): if shared.sd_model.is_sd1: return 768 elif shared.sd_model.is_sd2: return 1024 elif shared.sd_model.is_sdxl: return 2048 def is_fp32(): use_fp32 = False if cc_major < 7: use_fp32 = True print("FP16 has been disabled because your GPU does not support it.") return use_fp32 def export_unet_to_trt( batch_min, batch_opt, batch_max, height_min, height_opt, height_max, width_min, width_opt, width_max, token_count_min, token_count_opt, token_count_max, force_export, static_shapes, preset, ): sd_hijack.model_hijack.apply_optimizations("None") is_xl = shared.sd_model.is_sdxl model_name = shared.sd_model.sd_checkpoint_info.model_name profile_settings = ProfileSettings( batch_min, batch_opt, batch_max, height_min, height_opt, height_max, width_min, width_opt, width_max, token_count_min, token_count_opt, token_count_max, ) if preset == "Default": profile_settings = profile_presets.get_default(is_xl=is_xl) use_fp32 = is_fp32() print(f"Exporting {model_name} to TensorRT using - {profile_settings}") profile_settings.token_to_dim(static_shapes) model_hash = shared.sd_model.sd_checkpoint_info.hash model_name = shared.sd_model.sd_checkpoint_info.model_name onnx_filename, onnx_path = modelmanager.get_onnx_path(model_name) timing_cache = modelmanager.get_timing_cache() diable_optimizations = is_xl embedding_dim = get_context_dim()
modelobj = UNetModel(
0
2023-10-10 02:59:19+00:00
8k
PixArt-alpha/PixArt-alpha
diffusion/model/nets/PixArtMS.py
[ { "identifier": "MODELS", "path": "diffusion/model/builder.py", "snippet": "MODELS = Registry('models')" }, { "identifier": "auto_grad_checkpoint", "path": "diffusion/model/utils.py", "snippet": "def _ntuple(n):\n def parse(x):\ndef set_grad_checkpoint(model, use_fp32_attention=False,...
import torch import torch.nn as nn from timm.models.layers import DropPath from timm.models.vision_transformer import Mlp from diffusion.model.builder import MODELS from diffusion.model.utils import auto_grad_checkpoint, to_2tuple from diffusion.model.nets.PixArt_blocks import t2i_modulate, CaptionEmbedder, WindowAttention, MultiHeadCrossAttention, T2IFinalLayer, TimestepEmbedder, SizeEmbedder from diffusion.model.nets.PixArt import PixArt, get_2d_sincos_pos_embed
6,151
# 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 PatchEmbed(nn.Module): """ 2D Image to Patch Embedding """ def __init__( self, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True, bias=True, ): super().__init__() patch_size = to_2tuple(patch_size) self.patch_size = patch_size self.flatten = flatten self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() def forward(self, x): x = self.proj(x) if self.flatten: x = x.flatten(2).transpose(1, 2) # BCHW -> BNC x = self.norm(x) return x class PixArtMSBlock(nn.Module): """ A PixArt block with adaptive layer norm zero (adaLN-Zero) 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.hidden_size = hidden_size self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = WindowAttention(hidden_size, num_heads=num_heads, qkv_bias=True, input_size=input_size if window_size == 0 else (window_size, window_size), use_rel_pos=use_rel_pos, **block_kwargs)
# 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 PatchEmbed(nn.Module): """ 2D Image to Patch Embedding """ def __init__( self, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True, bias=True, ): super().__init__() patch_size = to_2tuple(patch_size) self.patch_size = patch_size self.flatten = flatten self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() def forward(self, x): x = self.proj(x) if self.flatten: x = x.flatten(2).transpose(1, 2) # BCHW -> BNC x = self.norm(x) return x class PixArtMSBlock(nn.Module): """ A PixArt block with adaptive layer norm zero (adaLN-Zero) 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.hidden_size = hidden_size self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.attn = WindowAttention(hidden_size, num_heads=num_heads, qkv_bias=True, input_size=input_size if window_size == 0 else (window_size, window_size), use_rel_pos=use_rel_pos, **block_kwargs)
self.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, **block_kwargs)
5
2023-10-12 14:16:33+00:00
8k
showlab/MotionDirector
MotionDirector_inference_multi.py
[ { "identifier": "export_to_video", "path": "MotionDirector_train.py", "snippet": "def export_to_video(video_frames, output_video_path, fps):\n video_writer = imageio.get_writer(output_video_path, fps=fps)\n for img in video_frames:\n video_writer.append_data(np.array(img))\n video_writer...
import argparse import os import platform import re import warnings import torch import random import imageio import decord from typing import Optional from diffusers import DDIMScheduler, TextToVideoSDPipeline from einops import rearrange from torch import Tensor from torch.nn.functional import interpolate from tqdm import trange from MotionDirector_train import export_to_video, handle_memory_attention, load_primary_models, unet_and_text_g_c, freeze_models from utils.lora_handler import LoraHandler from utils.ddim_utils import ddim_inversion
4,303
num_inv_steps=num_steps, prompt="")[-1] return ddim_inv_latent def prepare_input_latents( pipe: TextToVideoSDPipeline, batch_size: int, num_frames: int, height: int, width: int, latents_path:str, noise_prior: float ): # initialize with random gaussian noise scale = pipe.vae_scale_factor shape = (batch_size, pipe.unet.config.in_channels, num_frames, height // scale, width // scale) if noise_prior > 0.: cached_latents = torch.load(latents_path) if 'inversion_noise' not in cached_latents: latents = inverse_video(pipe, cached_latents['latents'].unsqueeze(0), 50).squeeze(0) else: latents = torch.load(latents_path)['inversion_noise'].unsqueeze(0) if latents.shape[0] != batch_size: latents = latents.repeat(batch_size, 1, 1, 1, 1) if latents.shape != shape: latents = interpolate(rearrange(latents, "b c f h w -> (b f) c h w", b=batch_size), (height // scale, width // scale), mode='bilinear') latents = rearrange(latents, "(b f) c h w -> b c f h w", b=batch_size) noise = torch.randn_like(latents, dtype=torch.half) latents = (noise_prior) ** 0.5 * latents + (1 - noise_prior) ** 0.5 * noise else: latents = torch.randn(shape, dtype=torch.half) return latents def encode(pipe: TextToVideoSDPipeline, pixels: Tensor, batch_size: int = 8): nf = pixels.shape[2] pixels = rearrange(pixels, "b c f h w -> (b f) c h w") latents = [] for idx in trange( 0, pixels.shape[0], batch_size, desc="Encoding to latents...", unit_scale=batch_size, unit="frame" ): pixels_batch = pixels[idx : idx + batch_size].to(pipe.device, dtype=torch.half) latents_batch = pipe.vae.encode(pixels_batch).latent_dist.sample() latents_batch = latents_batch.mul(pipe.vae.config.scaling_factor).cpu() latents.append(latents_batch) latents = torch.cat(latents) latents = rearrange(latents, "(b f) c h w -> b c f h w", f=nf) return latents @torch.inference_mode() def inference( model: str, prompt: str, negative_prompt: Optional[str] = None, width: int = 256, height: int = 256, num_frames: int = 24, num_steps: int = 50, guidance_scale: float = 15, device: str = "cuda", xformers: bool = False, sdp: bool = False, spatial_lora_path: str = "", temporal_lora_path: str = "", lora_rank: int = 64, spatial_lora_scale: float = 1.0, temporal_lora_scale: float = 1.0, seed: Optional[int] = None, latents_path: str="", noise_prior: float = 0., repeat_num: int = 1, ): with torch.autocast(device, dtype=torch.half): # prepare models pipe = initialize_pipeline(model, device, xformers, sdp, spatial_lora_path, temporal_lora_path, lora_rank, spatial_lora_scale, temporal_lora_scale) for i in range(repeat_num): if seed is None: random_seed = random.randint(100, 10000000) torch.manual_seed(random_seed) else: random_seed = seed torch.manual_seed(seed) # prepare input latents init_latents = prepare_input_latents( pipe=pipe, batch_size=len(prompt), num_frames=num_frames, height=height, width=width, latents_path=latents_path, noise_prior=noise_prior ) with torch.no_grad(): video_frames = pipe( prompt=prompt, negative_prompt=negative_prompt, width=width, height=height, num_frames=num_frames, num_inference_steps=num_steps, guidance_scale=guidance_scale, latents=init_latents ).frames # ========================================= # ========= write outputs to file ========= # ========================================= os.makedirs(args.output_dir, exist_ok=True) # save to mp4
def initialize_pipeline( model: str, device: str = "cuda", xformers: bool = False, sdp: bool = False, spatial_lora_path: str = "", temporal_lora_path: str = "", lora_rank: int = 64, spatial_lora_scale: float = 1.0, temporal_lora_scale: float = 1.0, ): with warnings.catch_warnings(): warnings.simplefilter("ignore") scheduler, tokenizer, text_encoder, vae, unet = load_primary_models(model) # Freeze any necessary models freeze_models([vae, text_encoder, unet]) # Enable xformers if available handle_memory_attention(xformers, sdp, unet) lora_manager_spatial = LoraHandler( version="cloneofsimo", use_unet_lora=True, use_text_lora=False, save_for_webui=False, only_for_webui=False, unet_replace_modules=["Transformer2DModel"], text_encoder_replace_modules=None, lora_bias=None ) lora_manager_temporal = LoraHandler( version="cloneofsimo", use_unet_lora=True, use_text_lora=False, save_for_webui=False, only_for_webui=False, unet_replace_modules=["TransformerTemporalModel"], text_encoder_replace_modules=None, lora_bias=None ) unet_lora_params, unet_negation = lora_manager_spatial.add_lora_to_model( True, unet, lora_manager_spatial.unet_replace_modules, 0, spatial_lora_path, r=lora_rank, scale=spatial_lora_scale) unet_lora_params, unet_negation = lora_manager_temporal.add_lora_to_model( True, unet, lora_manager_temporal.unet_replace_modules, 0, temporal_lora_path, r=lora_rank, scale=temporal_lora_scale) unet.eval() text_encoder.eval() unet_and_text_g_c(unet, text_encoder, False, False) pipe = TextToVideoSDPipeline.from_pretrained( pretrained_model_name_or_path=model, scheduler=scheduler, tokenizer=tokenizer, text_encoder=text_encoder.to(device=device, dtype=torch.half), vae=vae.to(device=device, dtype=torch.half), unet=unet.to(device=device, dtype=torch.half), ) pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) return pipe def inverse_video(pipe, latents, num_steps): ddim_inv_scheduler = DDIMScheduler.from_config(pipe.scheduler.config) ddim_inv_scheduler.set_timesteps(num_steps) ddim_inv_latent = ddim_inversion( pipe, ddim_inv_scheduler, video_latent=latents.to(pipe.device), num_inv_steps=num_steps, prompt="")[-1] return ddim_inv_latent def prepare_input_latents( pipe: TextToVideoSDPipeline, batch_size: int, num_frames: int, height: int, width: int, latents_path:str, noise_prior: float ): # initialize with random gaussian noise scale = pipe.vae_scale_factor shape = (batch_size, pipe.unet.config.in_channels, num_frames, height // scale, width // scale) if noise_prior > 0.: cached_latents = torch.load(latents_path) if 'inversion_noise' not in cached_latents: latents = inverse_video(pipe, cached_latents['latents'].unsqueeze(0), 50).squeeze(0) else: latents = torch.load(latents_path)['inversion_noise'].unsqueeze(0) if latents.shape[0] != batch_size: latents = latents.repeat(batch_size, 1, 1, 1, 1) if latents.shape != shape: latents = interpolate(rearrange(latents, "b c f h w -> (b f) c h w", b=batch_size), (height // scale, width // scale), mode='bilinear') latents = rearrange(latents, "(b f) c h w -> b c f h w", b=batch_size) noise = torch.randn_like(latents, dtype=torch.half) latents = (noise_prior) ** 0.5 * latents + (1 - noise_prior) ** 0.5 * noise else: latents = torch.randn(shape, dtype=torch.half) return latents def encode(pipe: TextToVideoSDPipeline, pixels: Tensor, batch_size: int = 8): nf = pixels.shape[2] pixels = rearrange(pixels, "b c f h w -> (b f) c h w") latents = [] for idx in trange( 0, pixels.shape[0], batch_size, desc="Encoding to latents...", unit_scale=batch_size, unit="frame" ): pixels_batch = pixels[idx : idx + batch_size].to(pipe.device, dtype=torch.half) latents_batch = pipe.vae.encode(pixels_batch).latent_dist.sample() latents_batch = latents_batch.mul(pipe.vae.config.scaling_factor).cpu() latents.append(latents_batch) latents = torch.cat(latents) latents = rearrange(latents, "(b f) c h w -> b c f h w", f=nf) return latents @torch.inference_mode() def inference( model: str, prompt: str, negative_prompt: Optional[str] = None, width: int = 256, height: int = 256, num_frames: int = 24, num_steps: int = 50, guidance_scale: float = 15, device: str = "cuda", xformers: bool = False, sdp: bool = False, spatial_lora_path: str = "", temporal_lora_path: str = "", lora_rank: int = 64, spatial_lora_scale: float = 1.0, temporal_lora_scale: float = 1.0, seed: Optional[int] = None, latents_path: str="", noise_prior: float = 0., repeat_num: int = 1, ): with torch.autocast(device, dtype=torch.half): # prepare models pipe = initialize_pipeline(model, device, xformers, sdp, spatial_lora_path, temporal_lora_path, lora_rank, spatial_lora_scale, temporal_lora_scale) for i in range(repeat_num): if seed is None: random_seed = random.randint(100, 10000000) torch.manual_seed(random_seed) else: random_seed = seed torch.manual_seed(seed) # prepare input latents init_latents = prepare_input_latents( pipe=pipe, batch_size=len(prompt), num_frames=num_frames, height=height, width=width, latents_path=latents_path, noise_prior=noise_prior ) with torch.no_grad(): video_frames = pipe( prompt=prompt, negative_prompt=negative_prompt, width=width, height=height, num_frames=num_frames, num_inference_steps=num_steps, guidance_scale=guidance_scale, latents=init_latents ).frames # ========================================= # ========= write outputs to file ========= # ========================================= os.makedirs(args.output_dir, exist_ok=True) # save to mp4
export_to_video(video_frames, f"{out_name}_{random_seed}.mp4", args.fps)
0
2023-10-12 12:06:55+00:00
8k
SkunkworksAI/BakLLaVA
llava/serve/model_worker.py
[ { "identifier": "WORKER_HEART_BEAT_INTERVAL", "path": "llava/constants.py", "snippet": "WORKER_HEART_BEAT_INTERVAL = 15" }, { "identifier": "build_logger", "path": "llava/utils.py", "snippet": "def build_logger(logger_name, logger_filename):\n def __init__(self, logger, log_level=logg...
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 llava.constants import WORKER_HEART_BEAT_INTERVAL from llava.utils import (build_logger, server_error_msg, pretty_print_semaphore) from llava.model.builder import load_pretrained_model from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria from llava.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,612
""" 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): 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 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) 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:
""" 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): 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 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) 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):
8
2023-10-10 20:46:46+00:00
8k
NVlabs/curobo
src/curobo/rollout/dynamics_model/tensor_step.py
[ { "identifier": "AccelerationTensorStepIdxKernel", "path": "src/curobo/rollout/dynamics_model/integration_utils.py", "snippet": "class AccelerationTensorStepIdxKernel(torch.autograd.Function):\n @staticmethod\n def forward(\n ctx,\n u_act,\n start_position,\n start_velo...
from abc import abstractmethod from enum import Enum from typing import Optional from curobo.types.base import TensorDeviceType from curobo.types.robot import JointState from .integration_utils import ( AccelerationTensorStepIdxKernel, AccelerationTensorStepKernel, CliqueTensorStepCentralDifferenceKernel, CliqueTensorStepIdxCentralDifferenceKernel, CliqueTensorStepIdxKernel, CliqueTensorStepKernel, build_fd_matrix, build_int_matrix, build_start_state_mask, tensor_step_acc_semi_euler, tensor_step_pos, tensor_step_pos_clique, ) import torch
5,553
# # Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION, its affiliates and licensors retain all intellectual # property and proprietary rights in and to this material, related # documentation and any modifications thereto. Any use, reproduction, # disclosure or distribution of this material and related documentation # without an express license agreement from NVIDIA CORPORATION or # its affiliates is strictly prohibited. # # Standard Library # Third Party # CuRobo # Local Folder class TensorStepType(Enum): POSITION_TELEPORT = 0 POSITION_CLIQUE_KERNEL = 1 VELOCITY = 2 # Not implemented ACCELERATION_KERNEL = 3 JERK = 4 # Not implemented POSITION = 5 # deprecated POSITION_CLIQUE = 6 # deprecated ACCELERATION = 7 # deprecated class TensorStepBase: def __init__( self, tensor_args: TensorDeviceType, batch_size: int = 1, horizon: int = 1 ) -> None: self.batch_size = -1 self.horizon = -1 self.tensor_args = tensor_args self._diag_dt = None self._inv_dt_h = None self.action_horizon = horizon self.update_batch_size(batch_size, horizon) def update_dt(self, dt: float): self._dt_h[:] = dt if self._inv_dt_h is not None: self._inv_dt_h[:] = 1.0 / dt @abstractmethod def update_batch_size( self, batch_size: Optional[int] = None, horizon: Optional[int] = None, force_update: bool = False, ) -> None: self.horizon = horizon self.batch_size = batch_size @abstractmethod def forward( self, start_state: JointState, u_act: torch.Tensor, out_state_seq: JointState, start_state_idx: Optional[torch.Tensor] = None, ) -> JointState: pass class TensorStepAcceleration(TensorStepBase): def __init__( self, tensor_args: TensorDeviceType, dt_h: torch.Tensor, batch_size: int = 1, horizon: int = 1, ) -> None: super().__init__(tensor_args, batch_size=batch_size, horizon=horizon) self._dt_h = dt_h self._diag_dt_h = torch.diag(self._dt_h) self._integrate_matrix_pos = None self._integrate_matrix_vel = None def update_batch_size( self, batch_size: Optional[int] = None, horizon: Optional[int] = None, force_update: bool = False, ) -> None: if self.horizon != horizon: self._integrate_matrix_pos = ( build_int_matrix( horizon, device=self.tensor_args.device, dtype=self.tensor_args.dtype, diagonal=0, ) @ self._diag_dt_h ) self._integrate_matrix_vel = self._integrate_matrix_pos @ self._diag_dt_h return super().update_batch_size(batch_size, horizon) def forward( self, start_state: JointState, u_act: torch.Tensor, out_state_seq: JointState, start_state_idx: Optional[torch.Tensor] = None, ) -> JointState: if start_state_idx is None:
# # Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION, its affiliates and licensors retain all intellectual # property and proprietary rights in and to this material, related # documentation and any modifications thereto. Any use, reproduction, # disclosure or distribution of this material and related documentation # without an express license agreement from NVIDIA CORPORATION or # its affiliates is strictly prohibited. # # Standard Library # Third Party # CuRobo # Local Folder class TensorStepType(Enum): POSITION_TELEPORT = 0 POSITION_CLIQUE_KERNEL = 1 VELOCITY = 2 # Not implemented ACCELERATION_KERNEL = 3 JERK = 4 # Not implemented POSITION = 5 # deprecated POSITION_CLIQUE = 6 # deprecated ACCELERATION = 7 # deprecated class TensorStepBase: def __init__( self, tensor_args: TensorDeviceType, batch_size: int = 1, horizon: int = 1 ) -> None: self.batch_size = -1 self.horizon = -1 self.tensor_args = tensor_args self._diag_dt = None self._inv_dt_h = None self.action_horizon = horizon self.update_batch_size(batch_size, horizon) def update_dt(self, dt: float): self._dt_h[:] = dt if self._inv_dt_h is not None: self._inv_dt_h[:] = 1.0 / dt @abstractmethod def update_batch_size( self, batch_size: Optional[int] = None, horizon: Optional[int] = None, force_update: bool = False, ) -> None: self.horizon = horizon self.batch_size = batch_size @abstractmethod def forward( self, start_state: JointState, u_act: torch.Tensor, out_state_seq: JointState, start_state_idx: Optional[torch.Tensor] = None, ) -> JointState: pass class TensorStepAcceleration(TensorStepBase): def __init__( self, tensor_args: TensorDeviceType, dt_h: torch.Tensor, batch_size: int = 1, horizon: int = 1, ) -> None: super().__init__(tensor_args, batch_size=batch_size, horizon=horizon) self._dt_h = dt_h self._diag_dt_h = torch.diag(self._dt_h) self._integrate_matrix_pos = None self._integrate_matrix_vel = None def update_batch_size( self, batch_size: Optional[int] = None, horizon: Optional[int] = None, force_update: bool = False, ) -> None: if self.horizon != horizon: self._integrate_matrix_pos = ( build_int_matrix( horizon, device=self.tensor_args.device, dtype=self.tensor_args.dtype, diagonal=0, ) @ self._diag_dt_h ) self._integrate_matrix_vel = self._integrate_matrix_pos @ self._diag_dt_h return super().update_batch_size(batch_size, horizon) def forward( self, start_state: JointState, u_act: torch.Tensor, out_state_seq: JointState, start_state_idx: Optional[torch.Tensor] = None, ) -> JointState: if start_state_idx is None:
state_seq = tensor_step_acc_semi_euler(
9
2023-10-13 19:18:21+00:00
8k
fishaudio/fish-speech
fish_speech/models/vqgan/lit_module.py
[ { "identifier": "discriminator_loss", "path": "fish_speech/models/vqgan/losses.py", "snippet": "def discriminator_loss(\n disc_real_outputs: List[torch.Tensor], disc_generated_outputs: List[torch.Tensor]\n):\n loss = 0\n r_losses = []\n g_losses = []\n for dr, dg in zip(disc_real_outputs,...
import itertools import lightning as L import torch import torch.nn.functional as F import wandb from typing import Any, Callable, Literal from lightning.pytorch.loggers import TensorBoardLogger, WandbLogger from matplotlib import pyplot as plt from torch import nn from vector_quantize_pytorch import VectorQuantize from fish_speech.models.vqgan.losses import ( discriminator_loss, feature_loss, generator_loss, kl_loss, ) from fish_speech.models.vqgan.modules.decoder import Generator from fish_speech.models.vqgan.modules.discriminator import EnsembleDiscriminator from fish_speech.models.vqgan.modules.encoders import ( ConvDownSampler, SpeakerEncoder, TextEncoder, VQEncoder, ) from fish_speech.models.vqgan.utils import ( plot_mel, rand_slice_segments, sequence_mask, slice_segments, )
6,802
self.log( "train/generator/loss_adv", loss_adv, on_step=True, on_epoch=False, prog_bar=False, logger=True, sync_dist=True, ) self.log( "train/generator/loss_vq", loss_vq, on_step=True, on_epoch=False, prog_bar=False, logger=True, sync_dist=True, ) optim_g.zero_grad() # Only backpropagate loss_vq_all in pretrain-stage1 if self.mode == "pretrain-stage1": self.manual_backward(loss_vq_all) self.manual_backward(loss_gen_all) self.clip_gradients( optim_g, gradient_clip_val=1000.0, gradient_clip_algorithm="norm" ) optim_g.step() # Manual LR Scheduler scheduler_g, scheduler_d = self.lr_schedulers() scheduler_g.step() scheduler_d.step() def validation_step(self, batch: Any, batch_idx: int): audios, audio_lengths = batch["audios"], batch["audio_lengths"] audios = audios.float() audios = audios[:, None, :] features = gt_mels = self.mel_transform(audios, sample_rate=self.sampling_rate) if self.downsample is not None: features = self.downsample(features) mel_lengths = audio_lengths // self.hop_length feature_lengths = ( audio_lengths / self.hop_length / (self.downsample.total_strides if self.downsample is not None else 1) ).long() feature_masks = torch.unsqueeze( sequence_mask(feature_lengths, features.shape[2]), 1 ).to(gt_mels.dtype) mel_masks = torch.unsqueeze(sequence_mask(mel_lengths, gt_mels.shape[2]), 1).to( gt_mels.dtype ) # vq_features is 50 hz, need to convert to true mel size text_features = self.mel_encoder(features, feature_masks) text_features, _, _ = self.vq_encoder(text_features, feature_masks) text_features = F.interpolate( text_features, size=gt_mels.shape[2], mode="nearest" ) # Sample mels if self.decoder is not None: speaker_features = ( self.speaker_encoder(gt_mels, mel_masks) if self.speaker_encoder is not None else None ) decoded_mels = self.decoder(text_features, mel_masks, g=speaker_features) else: decoded_mels = text_features fake_audios = self.generator(decoded_mels) fake_mels = self.mel_transform(fake_audios.squeeze(1)) min_mel_length = min( decoded_mels.shape[-1], gt_mels.shape[-1], fake_mels.shape[-1] ) decoded_mels = decoded_mels[:, :, :min_mel_length] gt_mels = gt_mels[:, :, :min_mel_length] fake_mels = fake_mels[:, :, :min_mel_length] mel_loss = F.l1_loss(gt_mels * mel_masks, fake_mels * mel_masks) self.log( "val/mel_loss", mel_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True, ) for idx, ( mel, gen_mel, decode_mel, audio, gen_audio, audio_len, ) in enumerate( zip( gt_mels, fake_mels, decoded_mels, audios.detach().float(), fake_audios.detach().float(), audio_lengths, ) ): mel_len = audio_len // self.hop_length
class VQGAN(L.LightningModule): def __init__( self, optimizer: Callable, lr_scheduler: Callable, downsample: ConvDownSampler, vq_encoder: VQEncoder, mel_encoder: TextEncoder, decoder: TextEncoder, generator: Generator, discriminator: EnsembleDiscriminator, mel_transform: nn.Module, segment_size: int = 20480, hop_length: int = 640, sample_rate: int = 32000, mode: Literal["pretrain-stage1", "pretrain-stage2", "finetune"] = "finetune", speaker_encoder: SpeakerEncoder = None, ): super().__init__() # pretrain-stage1: vq use gt mel as target, hifigan use gt mel as input # pretrain-stage2: end-to-end training, use gt mel as hifi gan target # finetune: end-to-end training, use gt mel as hifi gan target but freeze vq # Model parameters self.optimizer_builder = optimizer self.lr_scheduler_builder = lr_scheduler # Generator and discriminators self.downsample = downsample self.vq_encoder = vq_encoder self.mel_encoder = mel_encoder self.speaker_encoder = speaker_encoder self.decoder = decoder self.generator = generator self.discriminator = discriminator self.mel_transform = mel_transform # Crop length for saving memory self.segment_size = segment_size self.hop_length = hop_length self.sampling_rate = sample_rate self.mode = mode # Disable automatic optimization self.automatic_optimization = False # Finetune: Train the VQ only if self.mode == "finetune": for p in self.vq_encoder.parameters(): p.requires_grad = False for p in self.mel_encoder.parameters(): p.requires_grad = False for p in self.downsample.parameters(): p.requires_grad = False def configure_optimizers(self): # Need two optimizers and two schedulers components = [] if self.mode != "finetune": components.extend( [ self.downsample.parameters(), self.vq_encoder.parameters(), self.mel_encoder.parameters(), ] ) if self.speaker_encoder is not None: components.append(self.speaker_encoder.parameters()) if self.decoder is not None: components.append(self.decoder.parameters()) components.append(self.generator.parameters()) optimizer_generator = self.optimizer_builder(itertools.chain(*components)) optimizer_discriminator = self.optimizer_builder( self.discriminator.parameters() ) lr_scheduler_generator = self.lr_scheduler_builder(optimizer_generator) lr_scheduler_discriminator = self.lr_scheduler_builder(optimizer_discriminator) return ( { "optimizer": optimizer_generator, "lr_scheduler": { "scheduler": lr_scheduler_generator, "interval": "step", "name": "optimizer/generator", }, }, { "optimizer": optimizer_discriminator, "lr_scheduler": { "scheduler": lr_scheduler_discriminator, "interval": "step", "name": "optimizer/discriminator", }, }, ) def training_step(self, batch, batch_idx): optim_g, optim_d = self.optimizers() audios, audio_lengths = batch["audios"], batch["audio_lengths"] audios = audios.float() audios = audios[:, None, :] with torch.no_grad(): features = gt_mels = self.mel_transform( audios, sample_rate=self.sampling_rate ) if self.mode == "finetune": # Disable gradient computation for VQ torch.set_grad_enabled(False) self.vq_encoder.eval() self.mel_encoder.eval() self.downsample.eval() if self.downsample is not None: features = self.downsample(features) mel_lengths = audio_lengths // self.hop_length feature_lengths = ( audio_lengths / self.hop_length / (self.downsample.total_strides if self.downsample is not None else 1) ).long() feature_masks = torch.unsqueeze( sequence_mask(feature_lengths, features.shape[2]), 1 ).to(gt_mels.dtype) mel_masks = torch.unsqueeze(sequence_mask(mel_lengths, gt_mels.shape[2]), 1).to( gt_mels.dtype ) # vq_features is 50 hz, need to convert to true mel size text_features = self.mel_encoder(features, feature_masks) text_features, _, loss_vq = self.vq_encoder(text_features, feature_masks) text_features = F.interpolate( text_features, size=gt_mels.shape[2], mode="nearest" ) if loss_vq.ndim > 1: loss_vq = loss_vq.mean() if self.mode == "finetune": # Enable gradient computation torch.set_grad_enabled(True) # Sample mels if self.decoder is not None: speaker_features = ( self.speaker_encoder(gt_mels, mel_masks) if self.speaker_encoder is not None else None ) decoded_mels = self.decoder(text_features, mel_masks, g=speaker_features) else: decoded_mels = text_features input_mels = gt_mels if self.mode == "pretrain-stage1" else decoded_mels if self.segment_size is not None: audios, ids_slice = rand_slice_segments( audios, audio_lengths, self.segment_size ) input_mels = slice_segments( input_mels, ids_slice // self.hop_length, self.segment_size // self.hop_length, ) sliced_gt_mels = slice_segments( gt_mels, ids_slice // self.hop_length, self.segment_size // self.hop_length, ) gen_mel_masks = slice_segments( mel_masks, ids_slice // self.hop_length, self.segment_size // self.hop_length, ) else: sliced_gt_mels = gt_mels gen_mel_masks = mel_masks fake_audios = self.generator(input_mels) fake_audio_mels = self.mel_transform(fake_audios.squeeze(1)) assert ( audios.shape == fake_audios.shape ), f"{audios.shape} != {fake_audios.shape}" # Discriminator y_d_hat_r, y_d_hat_g, _, _ = self.discriminator(audios, fake_audios.detach()) with torch.autocast(device_type=audios.device.type, enabled=False): loss_disc_all, _, _ = discriminator_loss(y_d_hat_r, y_d_hat_g) self.log( "train/discriminator/loss", loss_disc_all, on_step=True, on_epoch=False, prog_bar=True, logger=True, sync_dist=True, ) optim_d.zero_grad() self.manual_backward(loss_disc_all) self.clip_gradients( optim_d, gradient_clip_val=1000.0, gradient_clip_algorithm="norm" ) optim_d.step() y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = self.discriminator(audios, fake_audios) with torch.autocast(device_type=audios.device.type, enabled=False): loss_decoded_mel = F.l1_loss(gt_mels * mel_masks, decoded_mels * mel_masks) loss_mel = F.l1_loss( sliced_gt_mels * gen_mel_masks, fake_audio_mels * gen_mel_masks ) loss_adv, _ = generator_loss(y_d_hat_g) loss_fm = feature_loss(fmap_r, fmap_g) if self.mode == "pretrain-stage1": loss_vq_all = loss_decoded_mel + loss_vq loss_gen_all = loss_mel * 45 + loss_fm + loss_adv else: loss_gen_all = loss_mel * 45 + loss_vq * 45 + loss_fm + loss_adv self.log( "train/generator/loss_gen_all", loss_gen_all, on_step=True, on_epoch=False, prog_bar=True, logger=True, sync_dist=True, ) if self.mode == "pretrain-stage1": self.log( "train/generator/loss_vq_all", loss_vq_all, on_step=True, on_epoch=False, prog_bar=True, logger=True, sync_dist=True, ) self.log( "train/generator/loss_decoded_mel", loss_decoded_mel, on_step=True, on_epoch=False, prog_bar=False, logger=True, sync_dist=True, ) self.log( "train/generator/loss_mel", loss_mel, on_step=True, on_epoch=False, prog_bar=False, logger=True, sync_dist=True, ) self.log( "train/generator/loss_fm", loss_fm, on_step=True, on_epoch=False, prog_bar=False, logger=True, sync_dist=True, ) self.log( "train/generator/loss_adv", loss_adv, on_step=True, on_epoch=False, prog_bar=False, logger=True, sync_dist=True, ) self.log( "train/generator/loss_vq", loss_vq, on_step=True, on_epoch=False, prog_bar=False, logger=True, sync_dist=True, ) optim_g.zero_grad() # Only backpropagate loss_vq_all in pretrain-stage1 if self.mode == "pretrain-stage1": self.manual_backward(loss_vq_all) self.manual_backward(loss_gen_all) self.clip_gradients( optim_g, gradient_clip_val=1000.0, gradient_clip_algorithm="norm" ) optim_g.step() # Manual LR Scheduler scheduler_g, scheduler_d = self.lr_schedulers() scheduler_g.step() scheduler_d.step() def validation_step(self, batch: Any, batch_idx: int): audios, audio_lengths = batch["audios"], batch["audio_lengths"] audios = audios.float() audios = audios[:, None, :] features = gt_mels = self.mel_transform(audios, sample_rate=self.sampling_rate) if self.downsample is not None: features = self.downsample(features) mel_lengths = audio_lengths // self.hop_length feature_lengths = ( audio_lengths / self.hop_length / (self.downsample.total_strides if self.downsample is not None else 1) ).long() feature_masks = torch.unsqueeze( sequence_mask(feature_lengths, features.shape[2]), 1 ).to(gt_mels.dtype) mel_masks = torch.unsqueeze(sequence_mask(mel_lengths, gt_mels.shape[2]), 1).to( gt_mels.dtype ) # vq_features is 50 hz, need to convert to true mel size text_features = self.mel_encoder(features, feature_masks) text_features, _, _ = self.vq_encoder(text_features, feature_masks) text_features = F.interpolate( text_features, size=gt_mels.shape[2], mode="nearest" ) # Sample mels if self.decoder is not None: speaker_features = ( self.speaker_encoder(gt_mels, mel_masks) if self.speaker_encoder is not None else None ) decoded_mels = self.decoder(text_features, mel_masks, g=speaker_features) else: decoded_mels = text_features fake_audios = self.generator(decoded_mels) fake_mels = self.mel_transform(fake_audios.squeeze(1)) min_mel_length = min( decoded_mels.shape[-1], gt_mels.shape[-1], fake_mels.shape[-1] ) decoded_mels = decoded_mels[:, :, :min_mel_length] gt_mels = gt_mels[:, :, :min_mel_length] fake_mels = fake_mels[:, :, :min_mel_length] mel_loss = F.l1_loss(gt_mels * mel_masks, fake_mels * mel_masks) self.log( "val/mel_loss", mel_loss, on_step=False, on_epoch=True, prog_bar=True, logger=True, sync_dist=True, ) for idx, ( mel, gen_mel, decode_mel, audio, gen_audio, audio_len, ) in enumerate( zip( gt_mels, fake_mels, decoded_mels, audios.detach().float(), fake_audios.detach().float(), audio_lengths, ) ): mel_len = audio_len // self.hop_length
image_mels = plot_mel(
10
2023-10-10 03:16:51+00:00
8k
NVlabs/EmerNeRF
datasets/waymo_preprocess.py
[ { "identifier": "get_ground_np", "path": "datasets/utils.py", "snippet": "def get_ground_np(pts):\n \"\"\"\n This function performs ground removal on a point cloud.\n Modified from https://github.com/tusen-ai/LiDAR_SOT/blob/main/waymo_data/data_preprocessing/ground_removal.py\n\n Args:\n ...
from waymo_open_dataset import dataset_pb2 from PIL import Image from tqdm import tqdm from waymo_open_dataset import label_pb2 from waymo_open_dataset.protos import camera_segmentation_pb2 as cs_pb2 from waymo_open_dataset.utils import box_utils, range_image_utils, transform_utils from waymo_open_dataset.utils.frame_utils import parse_range_image_and_camera_projection from waymo_open_dataset.wdl_limited.camera.ops import py_camera_model_ops from datasets.utils import get_ground_np from utils.mmcv_dummy import track_parallel_progress from utils.visualization_tools import visualize_depth import json import os import numpy as np import tensorflow as tf
3,809
def __len__(self): """Length of the filename list.""" return len(self.tfrecord_pathnames) def save_interested_labels(self, frame, file_idx): """ Saves the interested labels of a given frame to a JSON file. Args: frame: A `Frame` object containing the labels to be saved. file_idx: An integer representing the index of the file to be saved. Returns: None """ frame_data = { "time_of_day": frame.context.stats.time_of_day, "location": frame.context.stats.location, "weather": frame.context.stats.weather, } object_type_name = lambda x: label_pb2.Label.Type.Name(x) object_counts = { object_type_name(x.type): x.count for x in frame.context.stats.camera_object_counts } frame_data.update(object_counts) # write as json with open( f"{self.save_dir}/{str(file_idx).zfill(3)}/frame_info.json", "w", ) as fp: json.dump(frame_data, fp) def save_image(self, frame, file_idx, frame_idx): """Parse and save the images in jpg format. Args: frame (:obj:`Frame`): Open dataset frame proto. file_idx (int): Current file index. frame_idx (int): Current frame index. """ for img in frame.images: img_path = ( f"{self.save_dir}/{str(file_idx).zfill(3)}/images/" + f"{str(frame_idx).zfill(3)}_{str(img.name - 1)}.jpg" ) with open(img_path, "wb") as fp: fp.write(img.image) def save_calib(self, frame, file_idx, frame_idx): """Parse and save the calibration data. Args: frame (:obj:`Frame`): Open dataset frame proto. file_idx (int): Current file index. frame_idx (int): Current frame index. """ # waymo front camera to kitti reference camera extrinsics = [] intrinsics = [] for camera in frame.context.camera_calibrations: # extrinsic parameters extrinsic = np.array(camera.extrinsic.transform).reshape(4, 4) intrinsic = list(camera.intrinsic) extrinsics.append(extrinsic) intrinsics.append(intrinsic) # all camera ids are saved as id-1 in the result because # camera 0 is unknown in the proto for i in range(5): np.savetxt( f"{self.save_dir}/{str(file_idx).zfill(3)}/extrinsics/" + f"{str(i)}.txt", extrinsics[i], ) np.savetxt( f"{self.save_dir}/{str(file_idx).zfill(3)}/intrinsics/" + f"{str(i)}.txt", intrinsics[i], ) def save_lidar(self, frame, file_idx, frame_idx): """Parse and save the lidar data in psd format. Args: frame (:obj:`Frame`): Open dataset frame proto. file_idx (int): Current file index. frame_idx (int): Current frame index. """ ( range_images, camera_projections, seg_labels, range_image_top_pose, ) = parse_range_image_and_camera_projection(frame) # https://github.com/waymo-research/waymo-open-dataset/blob/master/src/waymo_open_dataset/protos/segmentation.proto if range_image_top_pose is None: # the camera only split doesn't contain lidar points. return # collect first return only range_images_flow, _, _ = parse_range_image_flow_and_camera_projection(frame) ( origins, points, flows, cp_points, intensity, elongation, laser_ids, ) = convert_range_image_to_point_cloud_flow( frame, range_images, range_images_flow, camera_projections, range_image_top_pose, ri_index=0, ) origins = np.concatenate(origins, axis=0) points = np.concatenate(points, axis=0)
# Acknowledgement: # 1. https://github.com/open-mmlab/mmdetection3d/blob/main/tools/dataset_converters/waymo_converter.py # 2. https://github.com/leolyj/DCA-SRSFE/blob/main/data_preprocess/Waymo/generate_flow.py try: except ImportError: raise ImportError( 'Please run "pip install waymo-open-dataset-tf-2-6-0" ' ">1.4.5 to install the official devkit first." ) depth_visualizer = lambda frame, opacity: visualize_depth( frame, opacity, lo=None, hi=None, depth_curve_fn=lambda x: x, ) MOVEABLE_OBJECTS_IDS = [ cs_pb2.CameraSegmentation.TYPE_CAR, cs_pb2.CameraSegmentation.TYPE_TRUCK, cs_pb2.CameraSegmentation.TYPE_BUS, cs_pb2.CameraSegmentation.TYPE_OTHER_LARGE_VEHICLE, cs_pb2.CameraSegmentation.TYPE_BICYCLE, cs_pb2.CameraSegmentation.TYPE_MOTORCYCLE, cs_pb2.CameraSegmentation.TYPE_TRAILER, cs_pb2.CameraSegmentation.TYPE_PEDESTRIAN, cs_pb2.CameraSegmentation.TYPE_CYCLIST, cs_pb2.CameraSegmentation.TYPE_MOTORCYCLIST, cs_pb2.CameraSegmentation.TYPE_BIRD, cs_pb2.CameraSegmentation.TYPE_GROUND_ANIMAL, cs_pb2.CameraSegmentation.TYPE_PEDESTRIAN_OBJECT, ] def project_vehicle_to_image(vehicle_pose, calibration, points): """Projects from vehicle coordinate system to image with global shutter. Arguments: vehicle_pose: Vehicle pose transform from vehicle into world coordinate system. calibration: Camera calibration details (including intrinsics/extrinsics). points: Points to project of shape [N, 3] in vehicle coordinate system. Returns: Array of shape [N, 3], with the latter dimension composed of (u, v, ok). """ # Transform points from vehicle to world coordinate system (can be # vectorized). pose_matrix = np.array(vehicle_pose.transform).reshape(4, 4) world_points = np.zeros_like(points) for i, point in enumerate(points): cx, cy, cz, _ = np.matmul(pose_matrix, [*point, 1]) world_points[i] = (cx, cy, cz) # Populate camera image metadata. Velocity and latency stats are filled with # zeroes. extrinsic = tf.reshape( tf.constant(list(calibration.extrinsic.transform), dtype=tf.float32), [4, 4] ) intrinsic = tf.constant(list(calibration.intrinsic), dtype=tf.float32) metadata = tf.constant( [ calibration.width, calibration.height, dataset_pb2.CameraCalibration.GLOBAL_SHUTTER, ], dtype=tf.int32, ) camera_image_metadata = list(vehicle_pose.transform) + [0.0] * 10 # Perform projection and return projected image coordinates (u, v, ok). return py_camera_model_ops.world_to_image( extrinsic, intrinsic, metadata, camera_image_metadata, world_points ).numpy() def compute_range_image_cartesian( range_image_polar, extrinsic, pixel_pose=None, frame_pose=None, dtype=tf.float32, scope=None, ): """Computes range image cartesian coordinates from polar ones. Args: range_image_polar: [B, H, W, 3] float tensor. Lidar range image in polar coordinate in sensor frame. extrinsic: [B, 4, 4] float tensor. Lidar extrinsic. pixel_pose: [B, H, W, 4, 4] float tensor. If not None, it sets pose for each range image pixel. frame_pose: [B, 4, 4] float tensor. This must be set when pixel_pose is set. It decides the vehicle frame at which the cartesian points are computed. dtype: float type to use internally. This is needed as extrinsic and inclination sometimes have higher resolution than range_image. scope: the name scope. Returns: range_image_cartesian: [B, H, W, 3] cartesian coordinates. """ range_image_polar_dtype = range_image_polar.dtype range_image_polar = tf.cast(range_image_polar, dtype=dtype) extrinsic = tf.cast(extrinsic, dtype=dtype) if pixel_pose is not None: pixel_pose = tf.cast(pixel_pose, dtype=dtype) if frame_pose is not None: frame_pose = tf.cast(frame_pose, dtype=dtype) with tf.compat.v1.name_scope( scope, "ComputeRangeImageCartesian", [range_image_polar, extrinsic, pixel_pose, frame_pose], ): azimuth, inclination, range_image_range = tf.unstack(range_image_polar, axis=-1) cos_azimuth = tf.cos(azimuth) sin_azimuth = tf.sin(azimuth) cos_incl = tf.cos(inclination) sin_incl = tf.sin(inclination) # [B, H, W]. x = cos_azimuth * cos_incl * range_image_range y = sin_azimuth * cos_incl * range_image_range z = sin_incl * range_image_range # [B, H, W, 3] range_image_points = tf.stack([x, y, z], -1) range_image_origins = tf.zeros_like(range_image_points) # [B, 3, 3] rotation = extrinsic[..., 0:3, 0:3] # translation [B, 1, 3] translation = tf.expand_dims(tf.expand_dims(extrinsic[..., 0:3, 3], 1), 1) # To vehicle frame. # [B, H, W, 3] range_image_points = ( tf.einsum("bkr,bijr->bijk", rotation, range_image_points) + translation ) range_image_origins = ( tf.einsum("bkr,bijr->bijk", rotation, range_image_origins) + translation ) if pixel_pose is not None: # To global frame. # [B, H, W, 3, 3] pixel_pose_rotation = pixel_pose[..., 0:3, 0:3] # [B, H, W, 3] pixel_pose_translation = pixel_pose[..., 0:3, 3] # [B, H, W, 3] range_image_points = ( tf.einsum("bhwij,bhwj->bhwi", pixel_pose_rotation, range_image_points) + pixel_pose_translation ) range_image_origins = ( tf.einsum("bhwij,bhwj->bhwi", pixel_pose_rotation, range_image_origins) + pixel_pose_translation ) if frame_pose is None: raise ValueError("frame_pose must be set when pixel_pose is set.") # To vehicle frame corresponding to the given frame_pose # [B, 4, 4] world_to_vehicle = tf.linalg.inv(frame_pose) world_to_vehicle_rotation = world_to_vehicle[:, 0:3, 0:3] world_to_vehicle_translation = world_to_vehicle[:, 0:3, 3] # [B, H, W, 3] range_image_points = ( tf.einsum( "bij,bhwj->bhwi", world_to_vehicle_rotation, range_image_points ) + world_to_vehicle_translation[:, tf.newaxis, tf.newaxis, :] ) range_image_origins = ( tf.einsum( "bij,bhwj->bhwi", world_to_vehicle_rotation, range_image_origins ) + world_to_vehicle_translation[:, tf.newaxis, tf.newaxis, :] ) range_image_points = tf.cast(range_image_points, dtype=range_image_polar_dtype) range_image_origins = tf.cast( range_image_origins, dtype=range_image_polar_dtype ) return range_image_points, range_image_origins def extract_point_cloud_from_range_image( range_image, extrinsic, inclination, pixel_pose=None, frame_pose=None, dtype=tf.float32, scope=None, ): """Extracts point cloud from range image. Args: range_image: [B, H, W] tensor. Lidar range images. extrinsic: [B, 4, 4] tensor. Lidar extrinsic. inclination: [B, H] tensor. Inclination for each row of the range image. 0-th entry corresponds to the 0-th row of the range image. pixel_pose: [B, H, W, 4, 4] tensor. If not None, it sets pose for each range image pixel. frame_pose: [B, 4, 4] tensor. This must be set when pixel_pose is set. It decides the vehicle frame at which the cartesian points are computed. dtype: float type to use internally. This is needed as extrinsic and inclination sometimes have higher resolution than range_image. scope: the name scope. Returns: range_image_points: [B, H, W, 3] with {x, y, z} as inner dims in vehicle frame. range_image_origins: [B, H, W, 3] with {x, y, z}, the origin of the range image """ with tf.compat.v1.name_scope( scope, "ExtractPointCloudFromRangeImage", [range_image, extrinsic, inclination, pixel_pose, frame_pose], ): range_image_polar = range_image_utils.compute_range_image_polar( range_image, extrinsic, inclination, dtype=dtype ) ( range_image_points_cartesian, range_image_origins_cartesian, ) = compute_range_image_cartesian( range_image_polar, extrinsic, pixel_pose=pixel_pose, frame_pose=frame_pose, dtype=dtype, ) return range_image_origins_cartesian, range_image_points_cartesian def parse_range_image_flow_and_camera_projection(frame): range_images = {} camera_projections = {} range_image_top_pose = None for laser in frame.lasers: if ( len(laser.ri_return1.range_image_flow_compressed) > 0 ): # pylint: disable=g-explicit-length-test range_image_str_tensor = tf.io.decode_compressed( laser.ri_return1.range_image_flow_compressed, "ZLIB" ) ri = dataset_pb2.MatrixFloat() ri.ParseFromString(bytearray(range_image_str_tensor.numpy())) range_images[laser.name] = [ri] if laser.name == dataset_pb2.LaserName.TOP: range_image_top_pose_str_tensor = tf.io.decode_compressed( laser.ri_return1.range_image_pose_compressed, "ZLIB" ) range_image_top_pose = dataset_pb2.MatrixFloat() range_image_top_pose.ParseFromString( bytearray(range_image_top_pose_str_tensor.numpy()) ) camera_projection_str_tensor = tf.io.decode_compressed( laser.ri_return1.camera_projection_compressed, "ZLIB" ) cp = dataset_pb2.MatrixInt32() cp.ParseFromString(bytearray(camera_projection_str_tensor.numpy())) camera_projections[laser.name] = [cp] if ( len(laser.ri_return2.range_image_flow_compressed) > 0 ): # pylint: disable=g-explicit-length-test range_image_str_tensor = tf.io.decode_compressed( laser.ri_return2.range_image_flow_compressed, "ZLIB" ) ri = dataset_pb2.MatrixFloat() ri.ParseFromString(bytearray(range_image_str_tensor.numpy())) range_images[laser.name].append(ri) camera_projection_str_tensor = tf.io.decode_compressed( laser.ri_return2.camera_projection_compressed, "ZLIB" ) cp = dataset_pb2.MatrixInt32() cp.ParseFromString(bytearray(camera_projection_str_tensor.numpy())) camera_projections[laser.name].append(cp) return range_images, camera_projections, range_image_top_pose def convert_range_image_to_point_cloud_flow( frame, range_images, range_images_flow, camera_projections, range_image_top_pose, ri_index=0, ): """ Modified from the codes of Waymo Open Dataset. Convert range images to point cloud. Convert range images flow to scene flow. Args: frame: open dataset frame range_images: A dict of {laser_name, [range_image_first_return, range_image_second_return]}. range_imaages_flow: A dict similar to range_images. camera_projections: A dict of {laser_name, [camera_projection_from_first_return, camera_projection_from_second_return]}. range_image_top_pose: range image pixel pose for top lidar. ri_index: 0 for the first return, 1 for the second return. Returns: points: {[N, 3]} list of 3d lidar points of length 5 (number of lidars). points_flow: {[N, 3]} list of scene flow vector of each point. cp_points: {[N, 6]} list of camera projections of length 5 (number of lidars). """ calibrations = sorted(frame.context.laser_calibrations, key=lambda c: c.name) origins, points, cp_points = [], [], [] points_intensity = [] points_elongation = [] points_flow = [] laser_ids = [] frame_pose = tf.convert_to_tensor( np.reshape(np.array(frame.pose.transform), [4, 4]) ) # [H, W, 6] range_image_top_pose_tensor = tf.reshape( tf.convert_to_tensor(range_image_top_pose.data), range_image_top_pose.shape.dims ) # [H, W, 3, 3] range_image_top_pose_tensor_rotation = transform_utils.get_rotation_matrix( range_image_top_pose_tensor[..., 0], range_image_top_pose_tensor[..., 1], range_image_top_pose_tensor[..., 2], ) range_image_top_pose_tensor_translation = range_image_top_pose_tensor[..., 3:] range_image_top_pose_tensor = transform_utils.get_transform( range_image_top_pose_tensor_rotation, range_image_top_pose_tensor_translation ) for c in calibrations: range_image = range_images[c.name][ri_index] range_image_flow = range_images_flow[c.name][ri_index] if len(c.beam_inclinations) == 0: # pylint: disable=g-explicit-length-test beam_inclinations = range_image_utils.compute_inclination( tf.constant([c.beam_inclination_min, c.beam_inclination_max]), height=range_image.shape.dims[0], ) else: beam_inclinations = tf.constant(c.beam_inclinations) beam_inclinations = tf.reverse(beam_inclinations, axis=[-1]) extrinsic = np.reshape(np.array(c.extrinsic.transform), [4, 4]) range_image_tensor = tf.reshape( tf.convert_to_tensor(range_image.data), range_image.shape.dims ) range_image_flow_tensor = tf.reshape( tf.convert_to_tensor(range_image_flow.data), range_image_flow.shape.dims ) pixel_pose_local = None frame_pose_local = None if c.name == dataset_pb2.LaserName.TOP: pixel_pose_local = range_image_top_pose_tensor pixel_pose_local = tf.expand_dims(pixel_pose_local, axis=0) frame_pose_local = tf.expand_dims(frame_pose, axis=0) range_image_mask = range_image_tensor[..., 0] > 0 range_image_intensity = range_image_tensor[..., 1] range_image_elongation = range_image_tensor[..., 2] flow_x = range_image_flow_tensor[..., 0] flow_y = range_image_flow_tensor[..., 1] flow_z = range_image_flow_tensor[..., 2] flow_class = range_image_flow_tensor[..., 3] mask_index = tf.where(range_image_mask) (origins_cartesian, points_cartesian,) = extract_point_cloud_from_range_image( tf.expand_dims(range_image_tensor[..., 0], axis=0), tf.expand_dims(extrinsic, axis=0), tf.expand_dims(tf.convert_to_tensor(beam_inclinations), axis=0), pixel_pose=pixel_pose_local, frame_pose=frame_pose_local, ) origins_cartesian = tf.squeeze(origins_cartesian, axis=0) points_cartesian = tf.squeeze(points_cartesian, axis=0) origins_tensor = tf.gather_nd(origins_cartesian, mask_index) points_tensor = tf.gather_nd(points_cartesian, mask_index) points_intensity_tensor = tf.gather_nd(range_image_intensity, mask_index) points_elongation_tensor = tf.gather_nd(range_image_elongation, mask_index) points_flow_x_tensor = tf.expand_dims(tf.gather_nd(flow_x, mask_index), axis=1) points_flow_y_tensor = tf.expand_dims(tf.gather_nd(flow_y, mask_index), axis=1) points_flow_z_tensor = tf.expand_dims(tf.gather_nd(flow_z, mask_index), axis=1) points_flow_class_tensor = tf.expand_dims( tf.gather_nd(flow_class, mask_index), axis=1 ) origins.append(origins_tensor.numpy()) points.append(points_tensor.numpy()) points_intensity.append(points_intensity_tensor.numpy()) points_elongation.append(points_elongation_tensor.numpy()) laser_ids.append(np.full_like(points_intensity_tensor.numpy(), c.name - 1)) points_flow.append( tf.concat( [ points_flow_x_tensor, points_flow_y_tensor, points_flow_z_tensor, points_flow_class_tensor, ], axis=-1, ).numpy() ) return ( origins, points, points_flow, cp_points, points_intensity, points_elongation, laser_ids, ) class WaymoProcessor(object): """Process Waymo dataset. Args: load_dir (str): Directory to load waymo raw data. save_dir (str): Directory to save data in KITTI format. prefix (str): Prefix of filename. workers (int, optional): Number of workers for the parallel process. Defaults to 64. Defaults to False. save_cam_sync_labels (bool, optional): Whether to save cam sync labels. Defaults to True. """ def __init__( self, load_dir, save_dir, prefix, process_keys=[ "images", "lidar", "calib", "pose", "dynamic_masks", ], process_id_list=None, workers=64, ): self.filter_no_label_zone_points = True # Only data collected in specific locations will be converted # If set None, this filter is disabled # Available options: location_sf (main dataset) self.selected_waymo_locations = None self.save_track_id = False self.process_id_list = process_id_list self.process_keys = process_keys print("will process keys: ", self.process_keys) # turn on eager execution for older tensorflow versions if int(tf.__version__.split(".")[0]) < 2: tf.enable_eager_execution() # keep the order defined by the official protocol self.cam_list = [ "_FRONT", "_FRONT_LEFT", "_FRONT_RIGHT", "_SIDE_LEFT", "_SIDE_RIGHT", ] self.lidar_list = ["TOP", "FRONT", "SIDE_LEFT", "SIDE_RIGHT", "REAR"] self.load_dir = load_dir self.save_dir = f"{save_dir}/{prefix}" self.workers = int(workers) # a list of tfrecord pathnames training_files = open("data/waymo_train_list.txt").read().splitlines() self.tfrecord_pathnames = [ f"{self.load_dir}/{f}.tfrecord" for f in training_files ] # self.tfrecord_pathnames = sorted(glob(join(self.load_dir, "*.tfrecord"))) self.create_folder() def convert(self): """Convert action.""" print("Start converting ...") if self.process_id_list is None: id_list = range(len(self)) else: id_list = self.process_id_list track_parallel_progress(self.convert_one, id_list, self.workers) print("\nFinished ...") def convert_one(self, file_idx): """Convert action for single file. Args: file_idx (int): Index of the file to be converted. """ pathname = self.tfrecord_pathnames[file_idx] dataset = tf.data.TFRecordDataset(pathname, compression_type="") num_frames = sum(1 for _ in dataset) for frame_idx, data in enumerate( tqdm(dataset, desc=f"File {file_idx}", total=num_frames, dynamic_ncols=True) ): frame = dataset_pb2.Frame() frame.ParseFromString(bytearray(data.numpy())) if ( self.selected_waymo_locations is not None and frame.context.stats.location not in self.selected_waymo_locations ): continue if "images" in self.process_keys: self.save_image(frame, file_idx, frame_idx) if "calib" in self.process_keys: self.save_calib(frame, file_idx, frame_idx) if "lidar" in self.process_keys: self.save_lidar(frame, file_idx, frame_idx) if "pose" in self.process_keys: self.save_pose(frame, file_idx, frame_idx) if "dynamic_masks" in self.process_keys: self.save_dynamic_mask(frame, file_idx, frame_idx) if frame_idx == 0: self.save_interested_labels(frame, file_idx) def __len__(self): """Length of the filename list.""" return len(self.tfrecord_pathnames) def save_interested_labels(self, frame, file_idx): """ Saves the interested labels of a given frame to a JSON file. Args: frame: A `Frame` object containing the labels to be saved. file_idx: An integer representing the index of the file to be saved. Returns: None """ frame_data = { "time_of_day": frame.context.stats.time_of_day, "location": frame.context.stats.location, "weather": frame.context.stats.weather, } object_type_name = lambda x: label_pb2.Label.Type.Name(x) object_counts = { object_type_name(x.type): x.count for x in frame.context.stats.camera_object_counts } frame_data.update(object_counts) # write as json with open( f"{self.save_dir}/{str(file_idx).zfill(3)}/frame_info.json", "w", ) as fp: json.dump(frame_data, fp) def save_image(self, frame, file_idx, frame_idx): """Parse and save the images in jpg format. Args: frame (:obj:`Frame`): Open dataset frame proto. file_idx (int): Current file index. frame_idx (int): Current frame index. """ for img in frame.images: img_path = ( f"{self.save_dir}/{str(file_idx).zfill(3)}/images/" + f"{str(frame_idx).zfill(3)}_{str(img.name - 1)}.jpg" ) with open(img_path, "wb") as fp: fp.write(img.image) def save_calib(self, frame, file_idx, frame_idx): """Parse and save the calibration data. Args: frame (:obj:`Frame`): Open dataset frame proto. file_idx (int): Current file index. frame_idx (int): Current frame index. """ # waymo front camera to kitti reference camera extrinsics = [] intrinsics = [] for camera in frame.context.camera_calibrations: # extrinsic parameters extrinsic = np.array(camera.extrinsic.transform).reshape(4, 4) intrinsic = list(camera.intrinsic) extrinsics.append(extrinsic) intrinsics.append(intrinsic) # all camera ids are saved as id-1 in the result because # camera 0 is unknown in the proto for i in range(5): np.savetxt( f"{self.save_dir}/{str(file_idx).zfill(3)}/extrinsics/" + f"{str(i)}.txt", extrinsics[i], ) np.savetxt( f"{self.save_dir}/{str(file_idx).zfill(3)}/intrinsics/" + f"{str(i)}.txt", intrinsics[i], ) def save_lidar(self, frame, file_idx, frame_idx): """Parse and save the lidar data in psd format. Args: frame (:obj:`Frame`): Open dataset frame proto. file_idx (int): Current file index. frame_idx (int): Current frame index. """ ( range_images, camera_projections, seg_labels, range_image_top_pose, ) = parse_range_image_and_camera_projection(frame) # https://github.com/waymo-research/waymo-open-dataset/blob/master/src/waymo_open_dataset/protos/segmentation.proto if range_image_top_pose is None: # the camera only split doesn't contain lidar points. return # collect first return only range_images_flow, _, _ = parse_range_image_flow_and_camera_projection(frame) ( origins, points, flows, cp_points, intensity, elongation, laser_ids, ) = convert_range_image_to_point_cloud_flow( frame, range_images, range_images_flow, camera_projections, range_image_top_pose, ri_index=0, ) origins = np.concatenate(origins, axis=0) points = np.concatenate(points, axis=0)
ground_label = get_ground_np(points)
0
2023-10-11 20:56:27+00:00
8k
ggozad/oterm
oterm/app/oterm.py
[ { "identifier": "ModelSelection", "path": "oterm/app/model_selection.py", "snippet": "class ModelSelection(ModalScreen[str]):\n api = OllamaAPI()\n models = []\n models_info: dict[str, dict] = {}\n\n model_name: reactive[str] = reactive(\"\")\n tag: reactive[str] = reactive(\"\")\n byt...
import json from textual.app import App, ComposeResult from textual.widgets import Footer, Header, TabbedContent, TabPane from oterm.app.model_selection import ModelSelection from oterm.app.splash import SplashScreen from oterm.app.widgets.chat import ChatContainer from oterm.config import appConfig from oterm.store.store import Store
4,511
class OTerm(App): TITLE = "oTerm" SUB_TITLE = "A terminal-based Ollama client." CSS_PATH = "oterm.tcss" BINDINGS = [ ("ctrl+n", "new_chat", "new chat"), ("ctrl+t", "toggle_dark", "toggle theme"), ("ctrl+q", "quit", "quit"), ] def action_toggle_dark(self) -> None: self.dark = not self.dark appConfig.set("theme", "dark" if self.dark else "light") async def action_quit(self) -> None: return self.exit() def action_new_chat(self) -> None: async def on_model_select(model_info: str) -> None: model: dict = json.loads(model_info) tabs = self.query_one(TabbedContent) tab_count = tabs.tab_count name = f"chat #{tab_count+1} - {model['name']}" id = await self.store.save_chat( id=None, name=name, model=model["name"], context="[]", template=model["template"], system=model["system"], format=model["format"], ) pane = TabPane(name, id=f"chat-{id}") pane.compose_add_child( ChatContainer( db_id=id, chat_name=name, model=model["name"], system=model["system"], template=model["template"], format=model["format"], messages=[], ) ) tabs.add_pane(pane) tabs.active = f"chat-{id}" self.push_screen(ModelSelection(), on_model_select) async def on_mount(self) -> None:
class OTerm(App): TITLE = "oTerm" SUB_TITLE = "A terminal-based Ollama client." CSS_PATH = "oterm.tcss" BINDINGS = [ ("ctrl+n", "new_chat", "new chat"), ("ctrl+t", "toggle_dark", "toggle theme"), ("ctrl+q", "quit", "quit"), ] def action_toggle_dark(self) -> None: self.dark = not self.dark appConfig.set("theme", "dark" if self.dark else "light") async def action_quit(self) -> None: return self.exit() def action_new_chat(self) -> None: async def on_model_select(model_info: str) -> None: model: dict = json.loads(model_info) tabs = self.query_one(TabbedContent) tab_count = tabs.tab_count name = f"chat #{tab_count+1} - {model['name']}" id = await self.store.save_chat( id=None, name=name, model=model["name"], context="[]", template=model["template"], system=model["system"], format=model["format"], ) pane = TabPane(name, id=f"chat-{id}") pane.compose_add_child( ChatContainer( db_id=id, chat_name=name, model=model["name"], system=model["system"], template=model["template"], format=model["format"], messages=[], ) ) tabs.add_pane(pane) tabs.active = f"chat-{id}" self.push_screen(ModelSelection(), on_model_select) async def on_mount(self) -> None:
self.store = await Store.create()
4
2023-10-10 07:29:26+00:00
8k
OpenGVLab/PonderV2
ponder/engines/test.py
[ { "identifier": "build_dataset", "path": "ponder/datasets/builder.py", "snippet": "def build_dataset(cfg):\n \"\"\"Build datasets.\"\"\"\n return DATASETS.build(cfg)" }, { "identifier": "collate_fn", "path": "ponder/datasets/utils.py", "snippet": "def collate_fn(batch, max_point=-1...
import os import time import numpy as np import torch import torch.distributed as dist import torch.nn.functional as F import torch.utils.data import ponder.utils.comm as comm import json from collections import OrderedDict from ponder.datasets import build_dataset, collate_fn from ponder.models import build_model from ponder.utils.logger import get_root_logger from ponder.utils.misc import ( AverageMeter, intersection_and_union, intersection_and_union_gpu, make_dirs, ) from ponder.utils.registry import Registry from .defaults import create_ddp_model
5,484
test_dataset = build_dataset(self.cfg.data.test) if comm.get_world_size() > 1: test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset) else: test_sampler = None test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=self.cfg.batch_size_test_per_gpu, shuffle=False, num_workers=self.cfg.batch_size_test_per_gpu, pin_memory=True, sampler=test_sampler, collate_fn=self.__class__.collate_fn, ) return test_loader def test(self): raise NotImplementedError @staticmethod def collate_fn(batch): raise collate_fn(batch) @TESTERS.register_module() class SemSegTester(TesterBase): def test(self): assert self.test_loader.batch_size == 1 logger = get_root_logger() logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>") batch_time = AverageMeter() intersection_meter = AverageMeter() union_meter = AverageMeter() target_meter = AverageMeter() self.model.eval() save_path = os.path.join(self.cfg.save_path, "result") make_dirs(save_path) # create submit folder only on main process if ( self.cfg.data.test.type == "ScanNetDataset" or self.cfg.data.test.type == "ScanNet200Dataset" ) and comm.is_main_process(): make_dirs(os.path.join(save_path, "submit")) elif ( self.cfg.data.test.type == "SemanticKITTIDataset" and comm.is_main_process() ): make_dirs(os.path.join(save_path, "submit")) elif self.cfg.data.test.type == "NuScenesDataset" and comm.is_main_process(): make_dirs(os.path.join(save_path, "submit", "lidarseg", "test")) make_dirs(os.path.join(save_path, "submit", "test")) submission = dict( meta=dict( use_camera=False, use_lidar=True, use_radar=False, use_map=False, use_external=False, ) ) with open( os.path.join(save_path, "submit", "test", "submission.json"), "w" ) as f: json.dump(submission, f, indent=4) comm.synchronize() record = {} # fragment inference for idx, data_dict in enumerate(self.test_loader): end = time.time() data_dict = data_dict[0] # current assume batch size is 1 fragment_list = data_dict.pop("fragment_list") segment = data_dict.pop("segment") data_name = data_dict.pop("name") pred_save_path = os.path.join(save_path, "{}_pred.npy".format(data_name)) if os.path.isfile(pred_save_path): logger.info( "{}/{}: {}, loaded pred and label.".format( idx + 1, len(self.test_loader), data_name ) ) pred = np.load(pred_save_path) else: pred = torch.zeros((segment.size, self.cfg.data.num_classes)).cuda() for i in range(len(fragment_list)): fragment_batch_size = 1 s_i, e_i = i * fragment_batch_size, min( (i + 1) * fragment_batch_size, len(fragment_list) ) input_dict = collate_fn(fragment_list[s_i:e_i]) for key in input_dict.keys(): if isinstance(input_dict[key], torch.Tensor): input_dict[key] = input_dict[key].cuda(non_blocking=True) idx_part = input_dict["index"] with torch.no_grad(): pred_part = self.model(input_dict)["seg_logits"] # (n, k) pred_part = F.softmax(pred_part, -1) if self.cfg.empty_cache: torch.cuda.empty_cache() bs = 0 for be in input_dict["offset"]: pred[idx_part[bs:be], :] += pred_part[bs:be] bs = be logger.info( "Test: {}/{}-{data_name}, Batch: {batch_idx}/{batch_num}".format( idx + 1, len(self.test_loader), data_name=data_name, batch_idx=i, batch_num=len(fragment_list), ) ) pred = pred.max(1)[1].data.cpu().numpy() np.save(pred_save_path, pred) if "origin_segment" in data_dict.keys(): assert "inverse" in data_dict.keys() pred = pred[data_dict["inverse"]] segment = data_dict["origin_segment"]
""" Tester Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com) Please cite our work if the code is helpful to you. """ TESTERS = Registry("testers") class TesterBase: def __init__(self, cfg, model=None, test_loader=None, verbose=False) -> None: torch.multiprocessing.set_sharing_strategy("file_system") self.logger = get_root_logger( log_file=os.path.join(cfg.save_path, "test.log"), file_mode="a" if cfg.resume else "w", ) self.logger.info("=> Loading config ...") self.cfg = cfg self.verbose = verbose if self.verbose: self.logger.info(f"Save path: {cfg.save_path}") self.logger.info(f"Config:\n{cfg.pretty_text}") if model is None: self.logger.info("=> Building model ...") self.model = self.build_model() else: self.model = model if test_loader is None: self.logger.info("=> Building test dataset & dataloader ...") self.test_loader = self.build_test_loader() else: self.test_loader = test_loader def build_model(self): model = build_model(self.cfg.model) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) self.logger.info(f"Num params: {n_parameters}") model = create_ddp_model( model.cuda(), broadcast_buffers=False, find_unused_parameters=self.cfg.find_unused_parameters, ) if os.path.isfile(self.cfg.weight): self.logger.info(f"Loading weight at: {self.cfg.weight}") checkpoint = torch.load(self.cfg.weight) weight = OrderedDict() for key, value in checkpoint["state_dict"].items(): if key.startswith("module."): if comm.get_world_size() == 1: key = key[7:] # module.xxx.xxx -> xxx.xxx else: if comm.get_world_size() > 1: key = "module." + key # xxx.xxx -> module.xxx.xxx weight[key] = value model.load_state_dict(weight, strict=True) self.logger.info( "=> Loaded weight '{}' (epoch {})".format( self.cfg.weight, checkpoint["epoch"] ) ) else: raise RuntimeError("=> No checkpoint found at '{}'".format(self.cfg.weight)) return model def build_test_loader(self): test_dataset = build_dataset(self.cfg.data.test) if comm.get_world_size() > 1: test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset) else: test_sampler = None test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=self.cfg.batch_size_test_per_gpu, shuffle=False, num_workers=self.cfg.batch_size_test_per_gpu, pin_memory=True, sampler=test_sampler, collate_fn=self.__class__.collate_fn, ) return test_loader def test(self): raise NotImplementedError @staticmethod def collate_fn(batch): raise collate_fn(batch) @TESTERS.register_module() class SemSegTester(TesterBase): def test(self): assert self.test_loader.batch_size == 1 logger = get_root_logger() logger.info(">>>>>>>>>>>>>>>> Start Evaluation >>>>>>>>>>>>>>>>") batch_time = AverageMeter() intersection_meter = AverageMeter() union_meter = AverageMeter() target_meter = AverageMeter() self.model.eval() save_path = os.path.join(self.cfg.save_path, "result") make_dirs(save_path) # create submit folder only on main process if ( self.cfg.data.test.type == "ScanNetDataset" or self.cfg.data.test.type == "ScanNet200Dataset" ) and comm.is_main_process(): make_dirs(os.path.join(save_path, "submit")) elif ( self.cfg.data.test.type == "SemanticKITTIDataset" and comm.is_main_process() ): make_dirs(os.path.join(save_path, "submit")) elif self.cfg.data.test.type == "NuScenesDataset" and comm.is_main_process(): make_dirs(os.path.join(save_path, "submit", "lidarseg", "test")) make_dirs(os.path.join(save_path, "submit", "test")) submission = dict( meta=dict( use_camera=False, use_lidar=True, use_radar=False, use_map=False, use_external=False, ) ) with open( os.path.join(save_path, "submit", "test", "submission.json"), "w" ) as f: json.dump(submission, f, indent=4) comm.synchronize() record = {} # fragment inference for idx, data_dict in enumerate(self.test_loader): end = time.time() data_dict = data_dict[0] # current assume batch size is 1 fragment_list = data_dict.pop("fragment_list") segment = data_dict.pop("segment") data_name = data_dict.pop("name") pred_save_path = os.path.join(save_path, "{}_pred.npy".format(data_name)) if os.path.isfile(pred_save_path): logger.info( "{}/{}: {}, loaded pred and label.".format( idx + 1, len(self.test_loader), data_name ) ) pred = np.load(pred_save_path) else: pred = torch.zeros((segment.size, self.cfg.data.num_classes)).cuda() for i in range(len(fragment_list)): fragment_batch_size = 1 s_i, e_i = i * fragment_batch_size, min( (i + 1) * fragment_batch_size, len(fragment_list) ) input_dict = collate_fn(fragment_list[s_i:e_i]) for key in input_dict.keys(): if isinstance(input_dict[key], torch.Tensor): input_dict[key] = input_dict[key].cuda(non_blocking=True) idx_part = input_dict["index"] with torch.no_grad(): pred_part = self.model(input_dict)["seg_logits"] # (n, k) pred_part = F.softmax(pred_part, -1) if self.cfg.empty_cache: torch.cuda.empty_cache() bs = 0 for be in input_dict["offset"]: pred[idx_part[bs:be], :] += pred_part[bs:be] bs = be logger.info( "Test: {}/{}-{data_name}, Batch: {batch_idx}/{batch_num}".format( idx + 1, len(self.test_loader), data_name=data_name, batch_idx=i, batch_num=len(fragment_list), ) ) pred = pred.max(1)[1].data.cpu().numpy() np.save(pred_save_path, pred) if "origin_segment" in data_dict.keys(): assert "inverse" in data_dict.keys() pred = pred[data_dict["inverse"]] segment = data_dict["origin_segment"]
intersection, union, target = intersection_and_union(
5
2023-10-13 12:57:00+00:00
8k
umautobots/LONER
analysis/meshing.py
[ { "identifier": "WorldCube", "path": "src/common/pose_utils.py", "snippet": "class WorldCube:\n \"\"\"\n The WorldCube struct holds a shift and scale transformation to apply to poses \n before creating rays, such that all rays are within a unit-length cube.\n \"\"\"\n \n scale_factor: ...
import argparse import os import pathlib import pickle import re import sys import torch.multiprocessing as mp import torch import open3d as o3d import yaml from render_utils import * from src.common.pose_utils import WorldCube from src.models.losses import * from src.models.model_tcnn import Model, OccupancyGridModel from src.models.ray_sampling import OccGridRaySampler from analysis.mesher import Mesher from pathlib import Path
5,089
#!/usr/bin/env python # coding: utf-8 PROJECT_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir)) sys.path.append(PROJECT_ROOT) sys.path.append(PROJECT_ROOT + "/src") assert torch.cuda.is_available(), 'Unable to find GPU' parser = argparse.ArgumentParser(description="Render ground truth maps using trained nerf models") parser.add_argument("experiment_directory", type=str, nargs="+", help="folder in outputs with all results") parser.add_argument("configuration_path") parser.add_argument("--debug", default=False, dest="debug", action="store_true") parser.add_argument("--ckpt_id", type=str, default=None) parser.add_argument("--resolution", type=float, default=0.1, help="grid resolution (m)") parser.add_argument("--max_range", type=float, default=None) parser.add_argument("--level", type=float, default=0) parser.add_argument("--skip_step", type=int, default=15) parser.add_argument("--var_threshold", type=float, default=None) parser.add_argument("--viz", default=False, dest="viz", action="store_true") parser.add_argument("--save", default=False, dest="save", action="store_true") args = parser.parse_args() def build_mesh(exp_dir): checkpoints = os.listdir(f"{exp_dir}/checkpoints") if not (args.viz or args.save): raise RuntimeError("Either visualize or save.") with open(args.configuration_path) as config_file: config = yaml.full_load(config_file) rosbag_path = Path(os.path.expanduser(config["dataset"])) x_min, x_max = config['meshing_bounding_box']['x'] y_min, y_max = config['meshing_bounding_box']['y'] z_min, z_max = config['meshing_bounding_box']['z'] meshing_bound = [[x_min, x_max], [y_min, y_max], [z_min, z_max]] resolution = args.resolution if args.ckpt_id is None: #https://stackoverflow.com/a/2669120 convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] checkpoint = sorted(checkpoints, key = alphanum_key)[-1] args.ckpt_id = checkpoint.split('.')[0] elif args.ckpt_id=='final': checkpoint = f"final.tar" else: checkpoint = f"ckpt_{args.ckpt_id}.tar" checkpoint_path = pathlib.Path(f"{exp_dir}/checkpoints/{checkpoint}") os.makedirs(f"{exp_dir}/meshing/resolution_{resolution}/", exist_ok=True) mesh_out_file=f"{exp_dir}/meshing/resolution_{resolution}/ckpt_{args.ckpt_id}.ply" # override any params loaded from yaml with open(f"{exp_dir}/full_config.pkl", 'rb') as f: full_config = pickle.load(f) if args.debug: full_config['debug'] = True torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True _DEVICE = torch.device(full_config.mapper.device) print('_DEVICE', _DEVICE) torch.set_default_tensor_type('torch.cuda.FloatTensor') if not checkpoint_path.exists(): print(f'Checkpoint {checkpoint_path} does not exist. Quitting.') exit() occ_model_config = full_config.mapper.optimizer.model_config.model.occ_model assert isinstance(occ_model_config, dict), f"OGM enabled but model.occ_model is empty" scale_factor = full_config.world_cube.scale_factor.to(_DEVICE) shift = full_config.world_cube.shift world_cube = WorldCube(scale_factor, shift).to(_DEVICE) cfg = full_config.mapper.optimizer.model_config ray_range = cfg.data.ray_range if args.max_range is not None: ray_range = (ray_range[0], args.max_range) print(f'Loading checkpoint from: {checkpoint_path}') ckpt = torch.load(str(checkpoint_path)) model_config = full_config.mapper.optimizer.model_config.model model = Model(model_config).to(_DEVICE) model.load_state_dict(ckpt['network_state_dict'])
#!/usr/bin/env python # coding: utf-8 PROJECT_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir)) sys.path.append(PROJECT_ROOT) sys.path.append(PROJECT_ROOT + "/src") assert torch.cuda.is_available(), 'Unable to find GPU' parser = argparse.ArgumentParser(description="Render ground truth maps using trained nerf models") parser.add_argument("experiment_directory", type=str, nargs="+", help="folder in outputs with all results") parser.add_argument("configuration_path") parser.add_argument("--debug", default=False, dest="debug", action="store_true") parser.add_argument("--ckpt_id", type=str, default=None) parser.add_argument("--resolution", type=float, default=0.1, help="grid resolution (m)") parser.add_argument("--max_range", type=float, default=None) parser.add_argument("--level", type=float, default=0) parser.add_argument("--skip_step", type=int, default=15) parser.add_argument("--var_threshold", type=float, default=None) parser.add_argument("--viz", default=False, dest="viz", action="store_true") parser.add_argument("--save", default=False, dest="save", action="store_true") args = parser.parse_args() def build_mesh(exp_dir): checkpoints = os.listdir(f"{exp_dir}/checkpoints") if not (args.viz or args.save): raise RuntimeError("Either visualize or save.") with open(args.configuration_path) as config_file: config = yaml.full_load(config_file) rosbag_path = Path(os.path.expanduser(config["dataset"])) x_min, x_max = config['meshing_bounding_box']['x'] y_min, y_max = config['meshing_bounding_box']['y'] z_min, z_max = config['meshing_bounding_box']['z'] meshing_bound = [[x_min, x_max], [y_min, y_max], [z_min, z_max]] resolution = args.resolution if args.ckpt_id is None: #https://stackoverflow.com/a/2669120 convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] checkpoint = sorted(checkpoints, key = alphanum_key)[-1] args.ckpt_id = checkpoint.split('.')[0] elif args.ckpt_id=='final': checkpoint = f"final.tar" else: checkpoint = f"ckpt_{args.ckpt_id}.tar" checkpoint_path = pathlib.Path(f"{exp_dir}/checkpoints/{checkpoint}") os.makedirs(f"{exp_dir}/meshing/resolution_{resolution}/", exist_ok=True) mesh_out_file=f"{exp_dir}/meshing/resolution_{resolution}/ckpt_{args.ckpt_id}.ply" # override any params loaded from yaml with open(f"{exp_dir}/full_config.pkl", 'rb') as f: full_config = pickle.load(f) if args.debug: full_config['debug'] = True torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True _DEVICE = torch.device(full_config.mapper.device) print('_DEVICE', _DEVICE) torch.set_default_tensor_type('torch.cuda.FloatTensor') if not checkpoint_path.exists(): print(f'Checkpoint {checkpoint_path} does not exist. Quitting.') exit() occ_model_config = full_config.mapper.optimizer.model_config.model.occ_model assert isinstance(occ_model_config, dict), f"OGM enabled but model.occ_model is empty" scale_factor = full_config.world_cube.scale_factor.to(_DEVICE) shift = full_config.world_cube.shift world_cube = WorldCube(scale_factor, shift).to(_DEVICE) cfg = full_config.mapper.optimizer.model_config ray_range = cfg.data.ray_range if args.max_range is not None: ray_range = (ray_range[0], args.max_range) print(f'Loading checkpoint from: {checkpoint_path}') ckpt = torch.load(str(checkpoint_path)) model_config = full_config.mapper.optimizer.model_config.model model = Model(model_config).to(_DEVICE) model.load_state_dict(ckpt['network_state_dict'])
occ_model = OccupancyGridModel(occ_model_config).to(_DEVICE)
2
2023-10-10 16:46:35+00:00
8k
lucidrains/magvit2-pytorch
magvit2_pytorch/magvit2_pytorch.py
[ { "identifier": "Attend", "path": "magvit2_pytorch/attend.py", "snippet": "class Attend(nn.Module):\n def __init__(\n self,\n *,\n dropout = 0.,\n causal = False,\n heads = None,\n scale = None,\n flash = False,\n onnxable = False,\n sdp_...
import copy import torch import torch.nn.functional as F import torchvision import pickle from pathlib import Path from math import log2, ceil, sqrt from functools import wraps, partial from torch.cuda.amp import autocast from torch import nn, einsum, Tensor from torch.nn import Module, ModuleList from torch.autograd import grad as torch_grad from torchvision.models import VGG16_Weights from collections import namedtuple from vector_quantize_pytorch import LFQ, FSQ from einops import rearrange, repeat, reduce, pack, unpack from einops.layers.torch import Rearrange from beartype import beartype from beartype.typing import Union, Tuple, Optional, List from magvit2_pytorch.attend import Attend from magvit2_pytorch.version import __version__ from gateloop_transformer import SimpleGateLoopLayer from taylor_series_linear_attention import TaylorSeriesLinearAttn from kornia.filters import filter3d
4,053
return gates * orig_input # token shifting class TokenShift(Module): @beartype def __init__(self, fn: Module): super().__init__() self.fn = fn def forward(self, x, **kwargs): x, x_shift = x.chunk(2, dim = 1) x_shift = pad_at_dim(x_shift, (1, -1), dim = 2) # shift time dimension x = torch.cat((x, x_shift), dim = 1) return self.fn(x, **kwargs) # rmsnorm class RMSNorm(Module): def __init__( self, dim, channel_first = False, images = False, bias = False ): super().__init__() broadcastable_dims = (1, 1, 1) if not images else (1, 1) shape = (dim, *broadcastable_dims) if channel_first else (dim,) self.channel_first = channel_first self.scale = dim ** 0.5 self.gamma = nn.Parameter(torch.ones(shape)) self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0. def forward(self, x): return F.normalize(x, dim = (1 if self.channel_first else -1)) * self.scale * self.gamma + self.bias class AdaptiveRMSNorm(Module): def __init__( self, dim, *, dim_cond, channel_first = False, images = False, bias = False ): super().__init__() broadcastable_dims = (1, 1, 1) if not images else (1, 1) shape = (dim, *broadcastable_dims) if channel_first else (dim,) self.dim_cond = dim_cond self.channel_first = channel_first self.scale = dim ** 0.5 self.to_gamma = nn.Linear(dim_cond, dim) self.to_bias = nn.Linear(dim_cond, dim) if bias else None nn.init.zeros_(self.to_gamma.weight) nn.init.ones_(self.to_gamma.bias) if bias: nn.init.zeros_(self.to_bias.weight) nn.init.zeros_(self.to_bias.bias) @beartype def forward(self, x: Tensor, *, cond: Tensor): batch = x.shape[0] assert cond.shape == (batch, self.dim_cond) gamma = self.to_gamma(cond) bias = 0. if exists(self.to_bias): bias = self.to_bias(cond) if self.channel_first: gamma = append_dims(gamma, x.ndim - 2) if exists(self.to_bias): bias = append_dims(bias, x.ndim - 2) return F.normalize(x, dim = (1 if self.channel_first else -1)) * self.scale * gamma + bias # attention class Attention(Module): @beartype def __init__( self, *, dim, dim_cond: Optional[int] = None, causal = False, dim_head = 32, heads = 8, flash = False, dropout = 0., num_memory_kv = 4 ): super().__init__() dim_inner = dim_head * heads self.need_cond = exists(dim_cond) if self.need_cond: self.norm = AdaptiveRMSNorm(dim, dim_cond = dim_cond) else: self.norm = RMSNorm(dim) self.to_qkv = nn.Sequential( nn.Linear(dim, dim_inner * 3, bias = False), Rearrange('b n (qkv h d) -> qkv b h n d', qkv = 3, h = heads) ) assert num_memory_kv > 0 self.mem_kv = nn.Parameter(torch.randn(2, heads, num_memory_kv, dim_head))
# helper def exists(v): return v is not None def default(v, d): return v if exists(v) else d def safe_get_index(it, ind, default = None): if ind < len(it): return it[ind] return default def pair(t): return t if isinstance(t, tuple) else (t, t) def identity(t, *args, **kwargs): return t def divisible_by(num, den): return (num % den) == 0 def pack_one(t, pattern): return pack([t], pattern) def unpack_one(t, ps, pattern): return unpack(t, ps, pattern)[0] def append_dims(t, ndims: int): return t.reshape(*t.shape, *((1,) * ndims)) def is_odd(n): return not divisible_by(n, 2) def maybe_del_attr_(o, attr): if hasattr(o, attr): delattr(o, attr) def cast_tuple(t, length = 1): return t if isinstance(t, tuple) else ((t,) * length) # tensor helpers def l2norm(t): return F.normalize(t, dim = -1, p = 2) def pad_at_dim(t, pad, dim = -1, value = 0.): dims_from_right = (- dim - 1) if dim < 0 else (t.ndim - dim - 1) zeros = ((0, 0) * dims_from_right) return F.pad(t, (*zeros, *pad), value = value) def pick_video_frame(video, frame_indices): batch, device = video.shape[0], video.device video = rearrange(video, 'b c f ... -> b f c ...') batch_indices = torch.arange(batch, device = device) batch_indices = rearrange(batch_indices, 'b -> b 1') images = video[batch_indices, frame_indices] images = rearrange(images, 'b 1 c ... -> b c ...') return images # gan related def gradient_penalty(images, output): batch_size = images.shape[0] gradients = torch_grad( outputs = output, inputs = images, grad_outputs = torch.ones(output.size(), device = images.device), create_graph = True, retain_graph = True, only_inputs = True )[0] gradients = rearrange(gradients, 'b ... -> b (...)') return ((gradients.norm(2, dim = 1) - 1) ** 2).mean() def leaky_relu(p = 0.1): return nn.LeakyReLU(p) def hinge_discr_loss(fake, real): return (F.relu(1 + fake) + F.relu(1 - real)).mean() def hinge_gen_loss(fake): return -fake.mean() @autocast(enabled = False) @beartype def grad_layer_wrt_loss( loss: Tensor, layer: nn.Parameter ): return torch_grad( outputs = loss, inputs = layer, grad_outputs = torch.ones_like(loss), retain_graph = True )[0].detach() # helper decorators def remove_vgg(fn): @wraps(fn) def inner(self, *args, **kwargs): has_vgg = hasattr(self, 'vgg') if has_vgg: vgg = self.vgg delattr(self, 'vgg') out = fn(self, *args, **kwargs) if has_vgg: self.vgg = vgg return out return inner # helper classes def Sequential(*modules): modules = [*filter(exists, modules)] if len(modules) == 0: return nn.Identity() return nn.Sequential(*modules) class Residual(Module): @beartype def __init__(self, fn: Module): super().__init__() self.fn = fn def forward(self, x, **kwargs): return self.fn(x, **kwargs) + x # for a bunch of tensor operations to change tensor to (batch, time, feature dimension) and back class ToTimeSequence(Module): @beartype def __init__(self, fn: Module): super().__init__() self.fn = fn def forward(self, x, **kwargs): x = rearrange(x, 'b c f ... -> b ... f c') x, ps = pack_one(x, '* n c') o = self.fn(x, **kwargs) o = unpack_one(o, ps, '* n c') return rearrange(o, 'b ... f c -> b c f ...') class SqueezeExcite(Module): # global context network - attention-esque squeeze-excite variant (https://arxiv.org/abs/2012.13375) def __init__( self, dim, *, dim_out = None, dim_hidden_min = 16, init_bias = -10 ): super().__init__() dim_out = default(dim_out, dim) self.to_k = nn.Conv2d(dim, 1, 1) dim_hidden = max(dim_hidden_min, dim_out // 2) self.net = nn.Sequential( nn.Conv2d(dim, dim_hidden, 1), nn.LeakyReLU(0.1), nn.Conv2d(dim_hidden, dim_out, 1), nn.Sigmoid() ) nn.init.zeros_(self.net[-2].weight) nn.init.constant_(self.net[-2].bias, init_bias) def forward(self, x): orig_input, batch = x, x.shape[0] is_video = x.ndim == 5 if is_video: x = rearrange(x, 'b c f h w -> (b f) c h w') context = self.to_k(x) context = rearrange(context, 'b c h w -> b c (h w)').softmax(dim = -1) spatial_flattened_input = rearrange(x, 'b c h w -> b c (h w)') out = einsum('b i n, b c n -> b c i', context, spatial_flattened_input) out = rearrange(out, '... -> ... 1') gates = self.net(out) if is_video: gates = rearrange(gates, '(b f) c h w -> b c f h w', b = batch) return gates * orig_input # token shifting class TokenShift(Module): @beartype def __init__(self, fn: Module): super().__init__() self.fn = fn def forward(self, x, **kwargs): x, x_shift = x.chunk(2, dim = 1) x_shift = pad_at_dim(x_shift, (1, -1), dim = 2) # shift time dimension x = torch.cat((x, x_shift), dim = 1) return self.fn(x, **kwargs) # rmsnorm class RMSNorm(Module): def __init__( self, dim, channel_first = False, images = False, bias = False ): super().__init__() broadcastable_dims = (1, 1, 1) if not images else (1, 1) shape = (dim, *broadcastable_dims) if channel_first else (dim,) self.channel_first = channel_first self.scale = dim ** 0.5 self.gamma = nn.Parameter(torch.ones(shape)) self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0. def forward(self, x): return F.normalize(x, dim = (1 if self.channel_first else -1)) * self.scale * self.gamma + self.bias class AdaptiveRMSNorm(Module): def __init__( self, dim, *, dim_cond, channel_first = False, images = False, bias = False ): super().__init__() broadcastable_dims = (1, 1, 1) if not images else (1, 1) shape = (dim, *broadcastable_dims) if channel_first else (dim,) self.dim_cond = dim_cond self.channel_first = channel_first self.scale = dim ** 0.5 self.to_gamma = nn.Linear(dim_cond, dim) self.to_bias = nn.Linear(dim_cond, dim) if bias else None nn.init.zeros_(self.to_gamma.weight) nn.init.ones_(self.to_gamma.bias) if bias: nn.init.zeros_(self.to_bias.weight) nn.init.zeros_(self.to_bias.bias) @beartype def forward(self, x: Tensor, *, cond: Tensor): batch = x.shape[0] assert cond.shape == (batch, self.dim_cond) gamma = self.to_gamma(cond) bias = 0. if exists(self.to_bias): bias = self.to_bias(cond) if self.channel_first: gamma = append_dims(gamma, x.ndim - 2) if exists(self.to_bias): bias = append_dims(bias, x.ndim - 2) return F.normalize(x, dim = (1 if self.channel_first else -1)) * self.scale * gamma + bias # attention class Attention(Module): @beartype def __init__( self, *, dim, dim_cond: Optional[int] = None, causal = False, dim_head = 32, heads = 8, flash = False, dropout = 0., num_memory_kv = 4 ): super().__init__() dim_inner = dim_head * heads self.need_cond = exists(dim_cond) if self.need_cond: self.norm = AdaptiveRMSNorm(dim, dim_cond = dim_cond) else: self.norm = RMSNorm(dim) self.to_qkv = nn.Sequential( nn.Linear(dim, dim_inner * 3, bias = False), Rearrange('b n (qkv h d) -> qkv b h n d', qkv = 3, h = heads) ) assert num_memory_kv > 0 self.mem_kv = nn.Parameter(torch.randn(2, heads, num_memory_kv, dim_head))
self.attend = Attend(
0
2023-10-10 16:51:24+00:00
8k
alibaba-damo-academy/FunCodec
funcodec/modules/scorers/ctc.py
[ { "identifier": "CTCPrefixScore", "path": "funcodec/modules/scorers/ctc_prefix_score.py", "snippet": "class CTCPrefixScore(object):\n \"\"\"Compute CTC label sequence scores\n\n which is based on Algorithm 2 in WATANABE et al.\n \"HYBRID CTC/ATTENTION ARCHITECTURE FOR END-TO-END SPEECH RECOGNIT...
import numpy as np import torch from funcodec.modules.scorers.ctc_prefix_score import CTCPrefixScore from funcodec.modules.scorers.ctc_prefix_score import CTCPrefixScoreTH from funcodec.modules.scorers.scorer_interface import BatchPartialScorerInterface
4,752
"""ScorerInterface implementation for CTC.""" class CTCPrefixScorer(BatchPartialScorerInterface): """Decoder interface wrapper for CTCPrefixScore.""" def __init__(self, ctc: torch.nn.Module, eos: int): """Initialize class. Args: ctc (torch.nn.Module): The CTC implementation. For example, :class:`espnet.nets.pytorch_backend.ctc.CTC` eos (int): The end-of-sequence id. """ self.ctc = ctc self.eos = eos self.impl = None def init_state(self, x: torch.Tensor): """Get an initial state for decoding. Args: x (torch.Tensor): The encoded feature tensor Returns: initial state """ logp = self.ctc.log_softmax(x.unsqueeze(0)).detach().squeeze(0).cpu().numpy() # TODO(karita): use CTCPrefixScoreTH
"""ScorerInterface implementation for CTC.""" class CTCPrefixScorer(BatchPartialScorerInterface): """Decoder interface wrapper for CTCPrefixScore.""" def __init__(self, ctc: torch.nn.Module, eos: int): """Initialize class. Args: ctc (torch.nn.Module): The CTC implementation. For example, :class:`espnet.nets.pytorch_backend.ctc.CTC` eos (int): The end-of-sequence id. """ self.ctc = ctc self.eos = eos self.impl = None def init_state(self, x: torch.Tensor): """Get an initial state for decoding. Args: x (torch.Tensor): The encoded feature tensor Returns: initial state """ logp = self.ctc.log_softmax(x.unsqueeze(0)).detach().squeeze(0).cpu().numpy() # TODO(karita): use CTCPrefixScoreTH
self.impl = CTCPrefixScore(logp, 0, self.eos, np)
0
2023-10-07 02:00:40+00:00
8k
Psycoy/EasyLiterature
build/lib/easy_literature/downloads.py
[ { "identifier": "arxivInfo", "path": "build/lib/easy_literature/arxiv.py", "snippet": "class arxivInfo(object):\n def __init__(self):\n self.base_url = \"http://export.arxiv.org/api/query\"\n \n def set_proxy_handler(self, proxy):\n \"\"\"set proxy handler\n \n Aargs...
import logging import re import os import platform from .arxiv import arxivInfo from .crossref import crossrefInfo from .medbiorxiv import BMxivInfo from .GoogleScholar import GscholarInfo from .DBLP import DBLPInfo from .pdfs import pdfDownload
5,680
# log config logging.basicConfig() logger = logging.getLogger('Downloads') logger.setLevel(logging.INFO) HEADERS = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0'} def check_string(re_exp, str): res = re.match(re_exp, str) if res: return True else: return False def classify(identifier): """ Classify the type of paper_id: arxivId - arxivId doi - digital object identifier medbiorxivId - medrxiv or biorxiv id title - title """ if check_string(r'10\.(?!1101)[0-9]{4}/\.*', identifier): return 'doi' elif check_string(r'10\.1101/\.*', identifier): return "medbiorxivId" elif check_string(r'[0-9]{2}[0-1][0-9]\.[0-9]{3,}.*', identifier) or check_string(r'.*/[0-9]{2}[0-1][0-9]{4}', identifier): return 'arxivId' elif check_string(r'[a-zA-Z\d\.-/\s]*', identifier): return 'title' else: return "unrecognized" def get_paper_info_from_paperid(paper_id, proxy=None, gproxy_mode='free'): id_type = classify(paper_id) if id_type == "doi": logger.info('ID type: doi.') downloader = crossrefInfo() if proxy: downloader.set_proxy(proxy=proxy) bib_dict = downloader.get_info_by_doi(paper_id) elif id_type == "arxivId": logger.info('ID type: arixiv.')
# log config logging.basicConfig() logger = logging.getLogger('Downloads') logger.setLevel(logging.INFO) HEADERS = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0'} def check_string(re_exp, str): res = re.match(re_exp, str) if res: return True else: return False def classify(identifier): """ Classify the type of paper_id: arxivId - arxivId doi - digital object identifier medbiorxivId - medrxiv or biorxiv id title - title """ if check_string(r'10\.(?!1101)[0-9]{4}/\.*', identifier): return 'doi' elif check_string(r'10\.1101/\.*', identifier): return "medbiorxivId" elif check_string(r'[0-9]{2}[0-1][0-9]\.[0-9]{3,}.*', identifier) or check_string(r'.*/[0-9]{2}[0-1][0-9]{4}', identifier): return 'arxivId' elif check_string(r'[a-zA-Z\d\.-/\s]*', identifier): return 'title' else: return "unrecognized" def get_paper_info_from_paperid(paper_id, proxy=None, gproxy_mode='free'): id_type = classify(paper_id) if id_type == "doi": logger.info('ID type: doi.') downloader = crossrefInfo() if proxy: downloader.set_proxy(proxy=proxy) bib_dict = downloader.get_info_by_doi(paper_id) elif id_type == "arxivId": logger.info('ID type: arixiv.')
downloader = arxivInfo()
0
2023-10-09 03:45:37+00:00
8k
longzw1997/Open-GroundingDino
models/GroundingDINO/transformer.py
[ { "identifier": "inverse_sigmoid", "path": "groundingdino/util/misc.py", "snippet": "def inverse_sigmoid(x, eps=1e-3):\n x = x.clamp(min=0, max=1)\n x1 = x.clamp(min=eps)\n x2 = (1 - x).clamp(min=eps)\n return torch.log(x1 / x2)" }, { "identifier": "BiAttentionBlock", "path": "mo...
from typing import Optional from torch import Tensor, nn from groundingdino.util.misc import inverse_sigmoid from .fuse_modules import BiAttentionBlock from .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttn from .transformer_vanilla import TransformerEncoderLayer from .utils import ( MLP, _get_activation_fn, _get_clones, gen_encoder_output_proposals, gen_sineembed_for_position, get_sine_pos_embed, ) import torch import torch.utils.checkpoint as checkpoint
6,277
# ------------------------------------------------------------------------ # Grounding DINO # url: https://github.com/IDEA-Research/GroundingDINO # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR Transformer class. # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ class Transformer(nn.Module): def __init__( self, d_model=256, nhead=8, num_queries=300, num_encoder_layers=6, num_unicoder_layers=0, num_decoder_layers=6, dim_feedforward=2048, dropout=0.0, activation="relu", normalize_before=False, return_intermediate_dec=False, query_dim=4, num_patterns=0, # for deformable encoder num_feature_levels=1, enc_n_points=4, dec_n_points=4, # init query learnable_tgt_init=False, # two stage two_stage_type="no", # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1'] embed_init_tgt=False, # for text use_text_enhancer=False, use_fusion_layer=False, use_checkpoint=False, use_transformer_ckpt=False, use_text_cross_attention=False, text_dropout=0.1, fusion_dropout=0.1, fusion_droppath=0.0, ): super().__init__() self.num_feature_levels = num_feature_levels self.num_encoder_layers = num_encoder_layers self.num_unicoder_layers = num_unicoder_layers self.num_decoder_layers = num_decoder_layers self.num_queries = num_queries assert query_dim == 4 # choose encoder layer type encoder_layer = DeformableTransformerEncoderLayer( d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, enc_n_points ) if use_text_enhancer: text_enhance_layer = TransformerEncoderLayer( d_model=d_model, nhead=nhead // 2, dim_feedforward=dim_feedforward // 2, dropout=text_dropout, ) else: text_enhance_layer = None if use_fusion_layer:
# ------------------------------------------------------------------------ # Grounding DINO # url: https://github.com/IDEA-Research/GroundingDINO # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR Transformer class. # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ class Transformer(nn.Module): def __init__( self, d_model=256, nhead=8, num_queries=300, num_encoder_layers=6, num_unicoder_layers=0, num_decoder_layers=6, dim_feedforward=2048, dropout=0.0, activation="relu", normalize_before=False, return_intermediate_dec=False, query_dim=4, num_patterns=0, # for deformable encoder num_feature_levels=1, enc_n_points=4, dec_n_points=4, # init query learnable_tgt_init=False, # two stage two_stage_type="no", # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1'] embed_init_tgt=False, # for text use_text_enhancer=False, use_fusion_layer=False, use_checkpoint=False, use_transformer_ckpt=False, use_text_cross_attention=False, text_dropout=0.1, fusion_dropout=0.1, fusion_droppath=0.0, ): super().__init__() self.num_feature_levels = num_feature_levels self.num_encoder_layers = num_encoder_layers self.num_unicoder_layers = num_unicoder_layers self.num_decoder_layers = num_decoder_layers self.num_queries = num_queries assert query_dim == 4 # choose encoder layer type encoder_layer = DeformableTransformerEncoderLayer( d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, enc_n_points ) if use_text_enhancer: text_enhance_layer = TransformerEncoderLayer( d_model=d_model, nhead=nhead // 2, dim_feedforward=dim_feedforward // 2, dropout=text_dropout, ) else: text_enhance_layer = None if use_fusion_layer:
feature_fusion_layer = BiAttentionBlock(
1
2023-10-14 02:20:31+00:00
8k
patrickrchao/JailbreakingLLMs
conversers.py
[ { "identifier": "GPT", "path": "language_models.py", "snippet": "class GPT(LanguageModel):\n API_RETRY_SLEEP = 10\n API_ERROR_OUTPUT = \"$ERROR$\"\n API_QUERY_SLEEP = 0.5\n API_MAX_RETRY = 5\n API_TIMEOUT = 20\n openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\n def generate(self, c...
import common import torch from language_models import GPT, Claude, PaLM, HuggingFace from transformers import AutoModelForCausalLM, AutoTokenizer from config import VICUNA_PATH, LLAMA_PATH, ATTACK_TEMP, TARGET_TEMP, ATTACK_TOP_P, TARGET_TOP_P
3,691
temperature = self.temperature, top_p = self.top_p ) # Check for valid outputs and update the list new_indices_to_regenerate = [] for i, full_output in enumerate(outputs_list): orig_index = indices_to_regenerate[i] if "gpt" not in self.model_name: full_output = init_message + full_output attack_dict, json_str = common.extract_json(full_output) if attack_dict is not None: valid_outputs[orig_index] = attack_dict convs_list[orig_index].update_last_message(json_str) # Update the conversation with valid generation else: new_indices_to_regenerate.append(orig_index) # Update indices to regenerate for the next iteration indices_to_regenerate = new_indices_to_regenerate # If all outputs are valid, break if not indices_to_regenerate: break if any([output for output in valid_outputs if output is None]): print(f"Failed to generate output after {self.max_n_attack_attempts} attempts. Terminating.") return valid_outputs class TargetLM(): """ Base class for target language models. Generates responses for prompts using a language model. The self.model attribute contains the underlying generation model. """ def __init__(self, model_name: str, max_n_tokens: int, temperature: float, top_p: float, preloaded_model: object = None): self.model_name = model_name self.temperature = temperature self.max_n_tokens = max_n_tokens self.top_p = top_p if preloaded_model is None: self.model, self.template = load_indiv_model(model_name) else: self.model = preloaded_model _, self.template = get_model_path_and_template(model_name) def get_response(self, prompts_list): batchsize = len(prompts_list) convs_list = [common.conv_template(self.template) for _ in range(batchsize)] full_prompts = [] for conv, prompt in zip(convs_list, prompts_list): conv.append_message(conv.roles[0], prompt) if "gpt" in self.model_name: # Openai does not have separators full_prompts.append(conv.to_openai_api_messages()) elif "palm" in self.model_name: full_prompts.append(conv.messages[-1][1]) else: conv.append_message(conv.roles[1], None) full_prompts.append(conv.get_prompt()) outputs_list = self.model.batched_generate(full_prompts, max_n_tokens = self.max_n_tokens, temperature = self.temperature, top_p = self.top_p ) return outputs_list def load_indiv_model(model_name, device=None): model_path, template = get_model_path_and_template(model_name) if model_name in ["gpt-3.5-turbo", "gpt-4"]: lm = GPT(model_name) elif model_name in ["claude-2", "claude-instant-1"]: lm = Claude(model_name) elif model_name in ["palm-2"]: lm = PaLM(model_name) else: model = AutoModelForCausalLM.from_pretrained( model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True,device_map="auto").eval() tokenizer = AutoTokenizer.from_pretrained( model_path, use_fast=False ) if 'llama-2' in model_path.lower(): tokenizer.pad_token = tokenizer.unk_token tokenizer.padding_side = 'left' if 'vicuna' in model_path.lower(): tokenizer.pad_token = tokenizer.eos_token tokenizer.padding_side = 'left' if not tokenizer.pad_token: tokenizer.pad_token = tokenizer.eos_token lm = HuggingFace(model_name, model, tokenizer) return lm, template def get_model_path_and_template(model_name): full_model_dict={ "gpt-4":{ "path":"gpt-4", "template":"gpt-4" }, "gpt-3.5-turbo": { "path":"gpt-3.5-turbo", "template":"gpt-3.5-turbo" }, "vicuna":{
def load_attack_and_target_models(args): # Load attack model and tokenizer attackLM = AttackLM(model_name = args.attack_model, max_n_tokens = args.attack_max_n_tokens, max_n_attack_attempts = args.max_n_attack_attempts, temperature = ATTACK_TEMP, # init to 1 top_p = ATTACK_TOP_P, # init to 0.9 ) preloaded_model = None if args.attack_model == args.target_model: print("Using same attack and target model. Using previously loaded model.") preloaded_model = attackLM.model targetLM = TargetLM(model_name = args.target_model, max_n_tokens = args.target_max_n_tokens, temperature = TARGET_TEMP, # init to 0 top_p = TARGET_TOP_P, # init to 1 preloaded_model = preloaded_model, ) return attackLM, targetLM class AttackLM(): """ Base class for attacker language models. Generates attacks for conversations using a language model. The self.model attribute contains the underlying generation model. """ def __init__(self, model_name: str, max_n_tokens: int, max_n_attack_attempts: int, temperature: float, top_p: float): self.model_name = model_name self.temperature = temperature self.max_n_tokens = max_n_tokens self.max_n_attack_attempts = max_n_attack_attempts self.top_p = top_p self.model, self.template = load_indiv_model(model_name) if "vicuna" in model_name or "llama" in model_name: self.model.extend_eos_tokens() def get_attack(self, convs_list, prompts_list): """ Generates responses for a batch of conversations and prompts using a language model. Only valid outputs in proper JSON format are returned. If an output isn't generated successfully after max_n_attack_attempts, it's returned as None. Parameters: - convs_list: List of conversation objects. - prompts_list: List of prompts corresponding to each conversation. Returns: - List of generated outputs (dictionaries) or None for failed generations. """ assert len(convs_list) == len(prompts_list), "Mismatch between number of conversations and prompts." batchsize = len(convs_list) indices_to_regenerate = list(range(batchsize)) valid_outputs = [None] * batchsize # Initalize the attack model's generated output to match format if len(convs_list[0].messages) == 0: init_message = """{\"improvement\": \"\",\"prompt\": \"""" else: init_message = """{\"improvement\": \"""" full_prompts = [] # Add prompts and initial seeding messages to conversations (only once) for conv, prompt in zip(convs_list, prompts_list): conv.append_message(conv.roles[0], prompt) # Get prompts if "gpt" in self.model_name: full_prompts.append(conv.to_openai_api_messages()) else: conv.append_message(conv.roles[1], init_message) full_prompts.append(conv.get_prompt()[:-len(conv.sep2)]) for attempt in range(self.max_n_attack_attempts): # Subset conversations based on indices to regenerate full_prompts_subset = [full_prompts[i] for i in indices_to_regenerate] # Generate outputs outputs_list = self.model.batched_generate(full_prompts_subset, max_n_tokens = self.max_n_tokens, temperature = self.temperature, top_p = self.top_p ) # Check for valid outputs and update the list new_indices_to_regenerate = [] for i, full_output in enumerate(outputs_list): orig_index = indices_to_regenerate[i] if "gpt" not in self.model_name: full_output = init_message + full_output attack_dict, json_str = common.extract_json(full_output) if attack_dict is not None: valid_outputs[orig_index] = attack_dict convs_list[orig_index].update_last_message(json_str) # Update the conversation with valid generation else: new_indices_to_regenerate.append(orig_index) # Update indices to regenerate for the next iteration indices_to_regenerate = new_indices_to_regenerate # If all outputs are valid, break if not indices_to_regenerate: break if any([output for output in valid_outputs if output is None]): print(f"Failed to generate output after {self.max_n_attack_attempts} attempts. Terminating.") return valid_outputs class TargetLM(): """ Base class for target language models. Generates responses for prompts using a language model. The self.model attribute contains the underlying generation model. """ def __init__(self, model_name: str, max_n_tokens: int, temperature: float, top_p: float, preloaded_model: object = None): self.model_name = model_name self.temperature = temperature self.max_n_tokens = max_n_tokens self.top_p = top_p if preloaded_model is None: self.model, self.template = load_indiv_model(model_name) else: self.model = preloaded_model _, self.template = get_model_path_and_template(model_name) def get_response(self, prompts_list): batchsize = len(prompts_list) convs_list = [common.conv_template(self.template) for _ in range(batchsize)] full_prompts = [] for conv, prompt in zip(convs_list, prompts_list): conv.append_message(conv.roles[0], prompt) if "gpt" in self.model_name: # Openai does not have separators full_prompts.append(conv.to_openai_api_messages()) elif "palm" in self.model_name: full_prompts.append(conv.messages[-1][1]) else: conv.append_message(conv.roles[1], None) full_prompts.append(conv.get_prompt()) outputs_list = self.model.batched_generate(full_prompts, max_n_tokens = self.max_n_tokens, temperature = self.temperature, top_p = self.top_p ) return outputs_list def load_indiv_model(model_name, device=None): model_path, template = get_model_path_and_template(model_name) if model_name in ["gpt-3.5-turbo", "gpt-4"]: lm = GPT(model_name) elif model_name in ["claude-2", "claude-instant-1"]: lm = Claude(model_name) elif model_name in ["palm-2"]: lm = PaLM(model_name) else: model = AutoModelForCausalLM.from_pretrained( model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True,device_map="auto").eval() tokenizer = AutoTokenizer.from_pretrained( model_path, use_fast=False ) if 'llama-2' in model_path.lower(): tokenizer.pad_token = tokenizer.unk_token tokenizer.padding_side = 'left' if 'vicuna' in model_path.lower(): tokenizer.pad_token = tokenizer.eos_token tokenizer.padding_side = 'left' if not tokenizer.pad_token: tokenizer.pad_token = tokenizer.eos_token lm = HuggingFace(model_name, model, tokenizer) return lm, template def get_model_path_and_template(model_name): full_model_dict={ "gpt-4":{ "path":"gpt-4", "template":"gpt-4" }, "gpt-3.5-turbo": { "path":"gpt-3.5-turbo", "template":"gpt-3.5-turbo" }, "vicuna":{
"path":VICUNA_PATH,
4
2023-10-13 21:34:28+00:00
8k
THtianhao/ComfyUI-Portrait-Maker
portrait/nodes.py
[ { "identifier": "call_face_crop", "path": "portrait/utils/face_process_utils.py", "snippet": "def call_face_crop(retinaface_detection, image, crop_ratio, prefix=\"tmp\"):\n # retinaface detect \n retinaface_result = retinaface_detection(image)\n # get mask and keypoints\n retinaface_box, ret...
import cv2 import numpy as np from PIL import Image from modelscope.outputs import OutputKeys from .utils.face_process_utils import call_face_crop, color_transfer, Face_Skin from .utils.img_utils import img_to_tensor, tensor_to_img, tensor_to_np, np_to_tensor, np_to_mask, img_to_mask, img_to_np from .model_holder import *
4,025
@classmethod def INPUT_TYPES(s): return {"required": {"image1": ("IMAGE",), "image2": ("IMAGE",), "mask": ("MASK",), }, } RETURN_TYPES = ("IMAGE",) FUNCTION = "image_mask_merge" CATEGORY = "protrait/model" def image_mask_merge(self, image1, image2, mask, box=None): mask = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3) image1 = image1 * mask + image2 * (1 - mask) return (image1,) class ExpandMaskFaceWidthPM: @classmethod def INPUT_TYPES(s): return {"required": {"mask": ("MASK",), "box": ("BOX",), "expand_width": ("FLOAT", {"default": 0.15, "min": 0, "max": 10, "step": 0.1}) }} RETURN_TYPES = ("MASK", "BOX") FUNCTION = "expand_mask_face_width" CATEGORY = "protrait/other" def expand_mask_face_width(self, mask, box, expand_width): h, w = mask.shape[1], mask.shape[2] new_mask = mask.clone().zero_() copy_box = np.copy(np.int32(box)) face_width = copy_box[2] - copy_box[0] copy_box[0] = np.clip(np.array(copy_box[0], np.int32) - face_width * expand_width, 0, w - 1) copy_box[2] = np.clip(np.array(copy_box[2], np.int32) + face_width * expand_width, 0, w - 1) # get new input_mask new_mask[0, copy_box[1]:copy_box[3], copy_box[0]:copy_box[2]] = 255 return (new_mask, copy_box) class BoxCropImagePM: @classmethod def INPUT_TYPES(s): return {"required": {"image": ("IMAGE",), "box": ("BOX",), } } RETURN_TYPES = ("IMAGE",) RETURN_NAMES = ("crop_image",) FUNCTION = "box_crop_image" CATEGORY = "protrait/other" def box_crop_image(self, image, box): image = image[:, box[1]:box[3], box[0]:box[2], :] return (image,) class ColorTransferPM: @classmethod def INPUT_TYPES(s): return {"required": { "transfer_from": ("IMAGE",), "transfer_to": ("IMAGE",), }} RETURN_TYPES = ("IMAGE",) FUNCTION = "color_transfer" CATEGORY = "protrait/other" def color_transfer(self, transfer_from, transfer_to): transfer_result = color_transfer(tensor_to_np(transfer_from), tensor_to_np(transfer_to)) # 进行颜色迁移 return (np_to_tensor(transfer_result),) class FaceSkinPM: @classmethod def INPUT_TYPES(s): return {"required": { "image": ("IMAGE",), "blur_edge": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), "blur_threshold": ("INT", {"default": 32, "min": 0, "max": 64, "step": 1}), }, } RETURN_TYPES = ("MASK",) FUNCTION = "face_skin_mask" CATEGORY = "protrait/model" def face_skin_mask(self, image, blur_edge, blur_threshold): face_skin_img = get_face_skin()(tensor_to_img(image), get_retinaface_detection(), [[1, 2, 3, 4, 5, 10, 12, 13]])[0] face_skin_np = img_to_np(face_skin_img) if blur_edge: face_skin_np = cv2.blur(face_skin_np, (blur_threshold, blur_threshold)) return (np_to_mask(face_skin_np),) class MaskDilateErodePM: @classmethod def INPUT_TYPES(s): return {"required": {"mask": ("MASK",), } } RETURN_TYPES = ("MASK",) FUNCTION = "mask_dilate_erode" CATEGORY = "protrait/other" def mask_dilate_erode(self, mask): out_mask = Image.fromarray(np.uint8(cv2.dilate(tensor_to_np(mask), np.ones((96, 96), np.uint8), iterations=1) - cv2.erode(tensor_to_np(mask), np.ones((48, 48), np.uint8), iterations=1)))
# import pydevd_pycharm # # pydevd_pycharm.settrace('49.7.62.197', port=10090, stdoutToServer=True, stderrToServer=True) class RetinaFacePM: @classmethod def INPUT_TYPES(s): return {"required": {"image": ("IMAGE",), "multi_user_facecrop_ratio": ("FLOAT", {"default": 1, "min": 0, "max": 10, "step": 0.01}), "face_index": ("INT", {"default": 0, "min": 0, "max": 10, "step": 1}) }} RETURN_TYPES = ("IMAGE", "MASK", "BOX") RETURN_NAMES = ("crop_image", "crop_mask", "crop_box") FUNCTION = "retain_face" CATEGORY = "protrait/model" def retain_face(self, image, multi_user_facecrop_ratio, face_index): np_image = np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8) image = Image.fromarray(np_image) retinaface_boxes, retinaface_keypoints, retinaface_masks, retinaface_mask_nps = call_face_crop(get_retinaface_detection(), image, multi_user_facecrop_ratio) crop_image = image.crop(retinaface_boxes[face_index]) retinaface_mask = np_to_mask(retinaface_mask_nps[face_index]) retinaface_boxe = retinaface_boxes[face_index] return (img_to_tensor(crop_image), retinaface_mask, retinaface_boxe) class FaceFusionPM: @classmethod def INPUT_TYPES(s): return {"required": {"source_image": ("IMAGE",), "swap_image": ("IMAGE",), "mode": (["ali", "roop"],), }} RETURN_TYPES = ("IMAGE",) FUNCTION = "img_face_fusion" CATEGORY = "protrait/model" def resize(self, tensor): image = tensor_to_img(tensor) short_side = max(image.width, image.height) resize = float(short_side / 640) new_size = (int(image.width // resize), int(image.height // resize)) resize_image = image.resize(new_size, Image.Resampling.LANCZOS) return img_to_np(resize_image) def img_face_fusion(self, source_image, swap_image, mode): if mode == "ali": source_image_pil = tensor_to_img(source_image) swap_image_pil = tensor_to_img(swap_image) fusion_image = get_image_face_fusion()(dict(template=source_image_pil, user=swap_image_pil))[ OutputKeys.OUTPUT_IMG] result_image = Image.fromarray(cv2.cvtColor(fusion_image, cv2.COLOR_BGR2RGB)) return (img_to_tensor(result_image),) else: width, height = source_image.shape[2], source_image.shape[1] need_resize = False source_np = tensor_to_np(source_image) swap_np = tensor_to_np(swap_image) if source_image.shape[2] > 640 or source_image.shape[1] > 640: source_np = self.resize(source_image) need_resize = True if swap_image.shape[2] > 640 or swap_image.shape[1] > 640: swap_np = self.resize(swap_image) get_face_analysis().prepare(ctx_id=0, det_size=(640, 640)) faces = get_face_analysis().get(source_np) swap_faces = get_face_analysis().get(swap_np) if len(faces) == 0: raise RuntimeError("No face was recognized in the source image / source image 没有识别到人脸") if len(swap_faces) == 0: raise RuntimeError("No face was recognized in the swap faces / swap faces没有识别到人脸") result_image = get_roop().get(source_np, faces[0], swap_faces[0], paste_back=True) if need_resize: image = Image.fromarray(result_image) new_size = width, height result_image = image.resize(new_size, Image.Resampling.LANCZOS) result_image = img_to_np(result_image) return (np_to_tensor(result_image),) class RatioMerge2ImagePM: def __init__(self): pass @classmethod def INPUT_TYPES(s): return {"required": {"image1": ("IMAGE",), "image2": ("IMAGE",), "fusion_rate": ("FLOAT", {"default": 0.5, "min": 0, "max": 1, "step": 0.1}) }} RETURN_TYPES = ("IMAGE",) FUNCTION = "image_ratio_merge" CATEGORY = "protrait/other" def image_ratio_merge(self, image1, image2, fusion_rate): rate_fusion_image = image1 * (1 - fusion_rate) + image2 * fusion_rate return (rate_fusion_image,) class ReplaceBoxImgPM: def __init__(self): pass @classmethod def INPUT_TYPES(s): return {"required": {"origin_image": ("IMAGE",), "box_area": ("BOX",), "replace_image": ("IMAGE",), }} RETURN_TYPES = ("IMAGE",) FUNCTION = "replace_box_image" CATEGORY = "protrait/model" def replace_box_image(self, origin_image, box_area, replace_image): origin_image[:, box_area[1]:box_area[3], box_area[0]:box_area[2], :] = replace_image return (origin_image,) class MaskMerge2ImagePM: def __init__(self): pass @classmethod def INPUT_TYPES(s): return {"required": {"image1": ("IMAGE",), "image2": ("IMAGE",), "mask": ("MASK",), }, } RETURN_TYPES = ("IMAGE",) FUNCTION = "image_mask_merge" CATEGORY = "protrait/model" def image_mask_merge(self, image1, image2, mask, box=None): mask = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3) image1 = image1 * mask + image2 * (1 - mask) return (image1,) class ExpandMaskFaceWidthPM: @classmethod def INPUT_TYPES(s): return {"required": {"mask": ("MASK",), "box": ("BOX",), "expand_width": ("FLOAT", {"default": 0.15, "min": 0, "max": 10, "step": 0.1}) }} RETURN_TYPES = ("MASK", "BOX") FUNCTION = "expand_mask_face_width" CATEGORY = "protrait/other" def expand_mask_face_width(self, mask, box, expand_width): h, w = mask.shape[1], mask.shape[2] new_mask = mask.clone().zero_() copy_box = np.copy(np.int32(box)) face_width = copy_box[2] - copy_box[0] copy_box[0] = np.clip(np.array(copy_box[0], np.int32) - face_width * expand_width, 0, w - 1) copy_box[2] = np.clip(np.array(copy_box[2], np.int32) + face_width * expand_width, 0, w - 1) # get new input_mask new_mask[0, copy_box[1]:copy_box[3], copy_box[0]:copy_box[2]] = 255 return (new_mask, copy_box) class BoxCropImagePM: @classmethod def INPUT_TYPES(s): return {"required": {"image": ("IMAGE",), "box": ("BOX",), } } RETURN_TYPES = ("IMAGE",) RETURN_NAMES = ("crop_image",) FUNCTION = "box_crop_image" CATEGORY = "protrait/other" def box_crop_image(self, image, box): image = image[:, box[1]:box[3], box[0]:box[2], :] return (image,) class ColorTransferPM: @classmethod def INPUT_TYPES(s): return {"required": { "transfer_from": ("IMAGE",), "transfer_to": ("IMAGE",), }} RETURN_TYPES = ("IMAGE",) FUNCTION = "color_transfer" CATEGORY = "protrait/other" def color_transfer(self, transfer_from, transfer_to): transfer_result = color_transfer(tensor_to_np(transfer_from), tensor_to_np(transfer_to)) # 进行颜色迁移 return (np_to_tensor(transfer_result),) class FaceSkinPM: @classmethod def INPUT_TYPES(s): return {"required": { "image": ("IMAGE",), "blur_edge": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}), "blur_threshold": ("INT", {"default": 32, "min": 0, "max": 64, "step": 1}), }, } RETURN_TYPES = ("MASK",) FUNCTION = "face_skin_mask" CATEGORY = "protrait/model" def face_skin_mask(self, image, blur_edge, blur_threshold): face_skin_img = get_face_skin()(tensor_to_img(image), get_retinaface_detection(), [[1, 2, 3, 4, 5, 10, 12, 13]])[0] face_skin_np = img_to_np(face_skin_img) if blur_edge: face_skin_np = cv2.blur(face_skin_np, (blur_threshold, blur_threshold)) return (np_to_mask(face_skin_np),) class MaskDilateErodePM: @classmethod def INPUT_TYPES(s): return {"required": {"mask": ("MASK",), } } RETURN_TYPES = ("MASK",) FUNCTION = "mask_dilate_erode" CATEGORY = "protrait/other" def mask_dilate_erode(self, mask): out_mask = Image.fromarray(np.uint8(cv2.dilate(tensor_to_np(mask), np.ones((96, 96), np.uint8), iterations=1) - cv2.erode(tensor_to_np(mask), np.ones((48, 48), np.uint8), iterations=1)))
return (img_to_mask(out_mask),)
8
2023-10-08 11:40:44+00:00
8k
LehengTHU/Agent4Rec
simulation/avatar.py
[ { "identifier": "abstract_avatar", "path": "simulation/base/abstract_avatar.py", "snippet": "class abstract_avatar:\n def __init__(self, args, avatar_id):\n super().__init__()\n self.args = args\n self.avatar_id = avatar_id\n self.use_wandb = args.use_wandb\n self.m...
from simulation.base.abstract_avatar import abstract_avatar from simulation.memory import AvatarMemory from termcolor import colored, cprint from langchain.vectorstores import FAISS from langchain.embeddings import HuggingFaceEmbeddings from langchain.docstore import InMemoryDocstore from langchain.chat_models import ChatOpenAI from simulation.retriever import AvatarRetriver from langchain.embeddings import OpenAIEmbeddings import openai import os import re import numpy as np import faiss import time import datetime import torch import pandas as pd import wandb import simulation.vars as vars
6,031
class Avatar(abstract_avatar): def __init__(self, args, avatar_id, init_property, init_statistic): super().__init__(args, avatar_id) self.parse_init_property(init_property) self.parse_init_statistic(init_statistic) self.log_file = f"storage/{args.dataset}/{args.modeltype}/{args.simulation_name}/running_logs/{avatar_id}.txt" if os.path.exists(self.log_file): os.remove(self.log_file) self.init_memory() def parse_init_property(self, init_property): self.taste = init_property["taste"].split("| ") self.high_rating = init_property["high_rating"] def parse_init_statistic(self, init_statistic): """ Parse the init statistic of the avatar """ # diversity_dict activity_dict = { 1:"An Incredibly Elusive Occasional Viewer, so seldom attracted by movie recommendations that it's almost a legendary event when you do watch a movie. Your movie-watching habits are extraordinarily infrequent. And you will exit the recommender system immediately even if you just feel little unsatisfied.", 2:"An Occasional Viewer, seldom attracted by movie recommendations. Only curious about watching movies that strictly align the taste. The movie-watching habits are not very infrequent. And you tend to exit the recommender system if you have a few unsatisfied memories.", 3:"A Movie Enthusiast with an insatiable appetite for films, willing to watch nearly every movie recommended to you. Movies are a central part of your life, and movie recommendations are integral to your existence. You are tolerant of recommender system, which means you are not easy to exit recommender system even if you have some unsatisfied memory."} # conformity_dict conformity_dict = { 1:"A Dedicated Follower who gives ratings heavily relies on movie historical ratings, rarely expressing independent opinions. Usually give ratings that are same as historical ratings. ", 2:"A Balanced Evaluator who considers both historical ratings and personal preferences when giving ratings to movies. Sometimes give ratings that are different from historical rating.", 3:"A Maverick Critic who completely ignores historical ratings and evaluates movies solely based on own taste. Usually give ratings that are a lot different from historical ratings."} # activity_dict diversity_dict = { 1:"An Exceedingly Discerning Selective Viewer who watches movies with a level of selectivity that borders on exclusivity. The movie choices are meticulously curated to match personal taste, leaving no room for even a hint of variety.", 2:"A Niche Explorer who occasionally explores different genres and mostly sticks to preferred movie types.", 3:"A Cinematic Trailblazer, a relentless seeker of the unique and the obscure in the world of movies. The movie choices are so diverse and avant-garde that they defy categorization."} self.conformity_group = init_statistic["conformity"] self.activity_group = init_statistic["activity"] self.diversity_group = init_statistic["diversity"] self.conformity_dsc = conformity_dict[self.conformity_group] self.activity_dsc = activity_dict[self.activity_group] self.diversity_dsc = diversity_dict[self.diversity_group] def init_memory(self): """ Initialize the memory of the avatar """ t1 = time.time() def score_normalizer(val: float) -> float: return 1 - 1 / (1 + np.exp(val)) embeddings_model = OpenAIEmbeddings(request_timeout = 20) embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}, relevance_score_fn=score_normalizer) LLM = ChatOpenAI(max_tokens=1000, temperature=0.3, request_timeout = 30) avatar_retriever = AvatarRetriver(vectorstore=vectorstore, k=5)
class Avatar(abstract_avatar): def __init__(self, args, avatar_id, init_property, init_statistic): super().__init__(args, avatar_id) self.parse_init_property(init_property) self.parse_init_statistic(init_statistic) self.log_file = f"storage/{args.dataset}/{args.modeltype}/{args.simulation_name}/running_logs/{avatar_id}.txt" if os.path.exists(self.log_file): os.remove(self.log_file) self.init_memory() def parse_init_property(self, init_property): self.taste = init_property["taste"].split("| ") self.high_rating = init_property["high_rating"] def parse_init_statistic(self, init_statistic): """ Parse the init statistic of the avatar """ # diversity_dict activity_dict = { 1:"An Incredibly Elusive Occasional Viewer, so seldom attracted by movie recommendations that it's almost a legendary event when you do watch a movie. Your movie-watching habits are extraordinarily infrequent. And you will exit the recommender system immediately even if you just feel little unsatisfied.", 2:"An Occasional Viewer, seldom attracted by movie recommendations. Only curious about watching movies that strictly align the taste. The movie-watching habits are not very infrequent. And you tend to exit the recommender system if you have a few unsatisfied memories.", 3:"A Movie Enthusiast with an insatiable appetite for films, willing to watch nearly every movie recommended to you. Movies are a central part of your life, and movie recommendations are integral to your existence. You are tolerant of recommender system, which means you are not easy to exit recommender system even if you have some unsatisfied memory."} # conformity_dict conformity_dict = { 1:"A Dedicated Follower who gives ratings heavily relies on movie historical ratings, rarely expressing independent opinions. Usually give ratings that are same as historical ratings. ", 2:"A Balanced Evaluator who considers both historical ratings and personal preferences when giving ratings to movies. Sometimes give ratings that are different from historical rating.", 3:"A Maverick Critic who completely ignores historical ratings and evaluates movies solely based on own taste. Usually give ratings that are a lot different from historical ratings."} # activity_dict diversity_dict = { 1:"An Exceedingly Discerning Selective Viewer who watches movies with a level of selectivity that borders on exclusivity. The movie choices are meticulously curated to match personal taste, leaving no room for even a hint of variety.", 2:"A Niche Explorer who occasionally explores different genres and mostly sticks to preferred movie types.", 3:"A Cinematic Trailblazer, a relentless seeker of the unique and the obscure in the world of movies. The movie choices are so diverse and avant-garde that they defy categorization."} self.conformity_group = init_statistic["conformity"] self.activity_group = init_statistic["activity"] self.diversity_group = init_statistic["diversity"] self.conformity_dsc = conformity_dict[self.conformity_group] self.activity_dsc = activity_dict[self.activity_group] self.diversity_dsc = diversity_dict[self.diversity_group] def init_memory(self): """ Initialize the memory of the avatar """ t1 = time.time() def score_normalizer(val: float) -> float: return 1 - 1 / (1 + np.exp(val)) embeddings_model = OpenAIEmbeddings(request_timeout = 20) embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}, relevance_score_fn=score_normalizer) LLM = ChatOpenAI(max_tokens=1000, temperature=0.3, request_timeout = 30) avatar_retriever = AvatarRetriver(vectorstore=vectorstore, k=5)
self.memory = AvatarMemory(memory_retriever=avatar_retriever, llm=LLM, reflection_threshold=3, use_wandb = self.use_wandb)
1
2023-10-12 02:33:22+00:00
8k
Beckschen/3D-TransUNet
nn_transunet/networks/mask2former_modeling/transformer_decoder/mask2former_transformer_decoder3d.py
[ { "identifier": "PositionEmbeddingSine", "path": "nn_transunet/networks/mask2former_modeling/transformer_decoder/position_encoding.py", "snippet": "class PositionEmbeddingSine(nn.Module):\n \"\"\"\n This is a more standard version of the position embedding, very similar to the one\n used by the...
import logging import fvcore.nn.weight_init as weight_init import torch from typing import Optional from torch import nn, Tensor from torch.nn import functional as F from fvcore.common.registry import Registry from .position_encoding import PositionEmbeddingSine from torch.cuda.amp import autocast from nn_transunet.networks.d2util import configurable, Conv2d from nn_transunet.networks.vit_modeling import LayerScale
5,131
self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before self.ls1 = LayerScale(d_model, init_values=1e-5) if use_layer_scale else nn.Identity() self._reset_parameters() def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post(self, tgt): tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout(tgt2) tgt = self.norm(self.ls1(tgt)) return tgt def forward_pre(self, tgt): tgt2 = self.norm(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout(self.ls1(tgt2)) return tgt def forward(self, tgt): if self.normalize_before: return self.forward_pre(tgt) return self.forward_post(tgt) def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(F"activation should be relu/gelu, not {activation}.") class MLP(nn.Module): """ Very simple multi-layer perceptron (also called FFN)""" def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])) def forward(self, x): for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) return x @TRANSFORMER_DECODER_REGISTRY.register() class MultiScaleMaskedTransformerDecoder3d(nn.Module): _version = 2 def _load_from_state_dict( self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs ): version = local_metadata.get("version", None) if version is None or version < 2: # Do not warn if train from scratch scratch = True logger = logging.getLogger(__name__) for k in list(state_dict.keys()): newk = k if "static_query" in k: newk = k.replace("static_query", "query_feat") if newk != k: state_dict[newk] = state_dict[k] del state_dict[k] scratch = False if not scratch: logger.warning( f"Weight format of {self.__class__.__name__} have changed! " "Please upgrade your models. Applying automatic conversion now ..." ) @configurable def __init__( self, in_channels, mask_classification=True, *, num_classes: int, hidden_dim: int, num_queries: int, nheads: int, dim_feedforward: int, dec_layers: int, pre_norm: bool, mask_dim: int, enforce_input_project: bool, non_object: bool, num_feature_levels: int, # new is_masking: bool, # new is_masking_argmax: bool, # new is_mhsa_float32: bool, # new no_max_hw_pe: bool, # new use_layer_scale: bool, # new ): super().__init__() self.no_max_hw_pe = no_max_hw_pe self.is_masking = is_masking self.is_masking_argmax = is_masking_argmax self.num_classes = num_classes self.mask_classification = mask_classification # positional encoding N_steps = hidden_dim // 3
# 3D version of Transformer decoder; Copyright Johns Hopkins University # Modified from Mask2former TRANSFORMER_DECODER_REGISTRY = Registry("TRANSFORMER_MODULE") class SelfAttentionLayer(nn.Module): def __init__(self, d_model, nhead, dropout=0.0, activation="relu", normalize_before=False, is_mhsa_float32=False, use_layer_scale=False): super().__init__() self.is_mhsa_float32 = is_mhsa_float32 self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.norm = nn.LayerNorm(d_model) self.dropout = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before self.ls1 = LayerScale(d_model, init_values=1e-5) if use_layer_scale else nn.Identity() self._reset_parameters() def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post(self, tgt, tgt_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): q = k = self.with_pos_embed(tgt, query_pos) if self.is_mhsa_float32: with autocast(enabled=False): tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] else: tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] tgt = tgt + self.dropout(self.ls1(tgt2)) tgt = self.norm(tgt) return tgt def forward_pre(self, tgt, tgt_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): tgt2 = self.norm(tgt) q = k = self.with_pos_embed(tgt2, query_pos) if self.is_mhsa_float32: with autocast(enabled=False): tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] else: tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] tgt = tgt + self.dropout(self.ls1(tgt2)) return tgt def forward(self, tgt, tgt_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): if self.normalize_before: return self.forward_pre(tgt, tgt_mask, tgt_key_padding_mask, query_pos) return self.forward_post(tgt, tgt_mask, tgt_key_padding_mask, query_pos) class CrossAttentionLayer(nn.Module): def __init__(self, d_model, nhead, dropout=0.0, activation="relu", normalize_before=False, is_mhsa_float32=False, use_layer_scale=False): super().__init__() self.is_mhsa_float32 = is_mhsa_float32 self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.norm = nn.LayerNorm(d_model) self.dropout = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before self.ls1 = nn.Identity() self._reset_parameters() def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post(self, tgt, memory, memory_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): if self.is_mhsa_float32: with autocast(enabled=False): tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)[0] else: tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)[0] tgt = tgt + self.dropout(self.ls1(tgt2)) tgt = self.norm(tgt) return tgt def forward_pre(self, tgt, memory, memory_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): tgt2 = self.norm(tgt) if self.is_mhsa_float32: with autocast(enabled=False): tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)[0] else: tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)[0] tgt = tgt + self.dropout(self.ls1(tgt2)) return tgt def forward(self, tgt, memory, memory_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None): if self.normalize_before: return self.forward_pre(tgt, memory, memory_mask, memory_key_padding_mask, pos, query_pos) return self.forward_post(tgt, memory, memory_mask, memory_key_padding_mask, pos, query_pos) class FFNLayer(nn.Module): def __init__(self, d_model, dim_feedforward=2048, dropout=0.0, activation="relu", normalize_before=False, use_layer_scale=False): super().__init__() # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm = nn.LayerNorm(d_model) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before self.ls1 = LayerScale(d_model, init_values=1e-5) if use_layer_scale else nn.Identity() self._reset_parameters() def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos def forward_post(self, tgt): tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout(tgt2) tgt = self.norm(self.ls1(tgt)) return tgt def forward_pre(self, tgt): tgt2 = self.norm(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout(self.ls1(tgt2)) return tgt def forward(self, tgt): if self.normalize_before: return self.forward_pre(tgt) return self.forward_post(tgt) def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu raise RuntimeError(F"activation should be relu/gelu, not {activation}.") class MLP(nn.Module): """ Very simple multi-layer perceptron (also called FFN)""" def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])) def forward(self, x): for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) return x @TRANSFORMER_DECODER_REGISTRY.register() class MultiScaleMaskedTransformerDecoder3d(nn.Module): _version = 2 def _load_from_state_dict( self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs ): version = local_metadata.get("version", None) if version is None or version < 2: # Do not warn if train from scratch scratch = True logger = logging.getLogger(__name__) for k in list(state_dict.keys()): newk = k if "static_query" in k: newk = k.replace("static_query", "query_feat") if newk != k: state_dict[newk] = state_dict[k] del state_dict[k] scratch = False if not scratch: logger.warning( f"Weight format of {self.__class__.__name__} have changed! " "Please upgrade your models. Applying automatic conversion now ..." ) @configurable def __init__( self, in_channels, mask_classification=True, *, num_classes: int, hidden_dim: int, num_queries: int, nheads: int, dim_feedforward: int, dec_layers: int, pre_norm: bool, mask_dim: int, enforce_input_project: bool, non_object: bool, num_feature_levels: int, # new is_masking: bool, # new is_masking_argmax: bool, # new is_mhsa_float32: bool, # new no_max_hw_pe: bool, # new use_layer_scale: bool, # new ): super().__init__() self.no_max_hw_pe = no_max_hw_pe self.is_masking = is_masking self.is_masking_argmax = is_masking_argmax self.num_classes = num_classes self.mask_classification = mask_classification # positional encoding N_steps = hidden_dim // 3
self.pe_layer = PositionEmbeddingSine(N_steps, normalize=True)
0
2023-10-11 05:19:25+00:00
8k
AMAAI-Lab/Video2Music
train_regression.py
[ { "identifier": "create_vevo_datasets", "path": "dataset/vevo_dataset.py", "snippet": "def create_vevo_datasets(dataset_root = \"./dataset\", max_seq_chord=300, max_seq_video=300, vis_models=\"2d/clip_l14p\", emo_model=\"6c_l14p\", split_ver=\"v1\", random_seq=True, is_video=True):\n\n train_dataset ...
import os import csv import shutil import torch import torch.nn as nn from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from torch.optim import Adam from dataset.vevo_dataset import create_vevo_datasets from model.video_regression import VideoRegression from utilities.constants import * from utilities.device import get_device, use_cuda from utilities.lr_scheduling import LrStepTracker, get_lr from utilities.argument_funcs import parse_train_args, print_train_args, write_model_params from utilities.run_model_regression import train_epoch, eval_model from torch.utils.tensorboard import SummaryWriter
4,991
CSV_HEADER = ["Epoch", "Learn rate", "Avg Train loss", "Train RMSE", "Avg Eval loss", "Eval RMSE"] BASELINE_EPOCH = -1 version = VERSION split_ver = SPLIT_VER split_path = "split_" + split_ver num_epochs = 20 VIS_MODELS_ARR = [ "2d/clip_l14p" ] regModel = "gru" # lstm # bilstm # gru # bigru # main def main( vm = "" , isPrintArgs = True ): args = parse_train_args() args.epochs = num_epochs if isPrintArgs: print_train_args(args) if vm != "": args.vis_models = vm if args.is_video: vis_arr = args.vis_models.split(" ") vis_arr.sort() vis_abbr_path = "" for v in vis_arr: vis_abbr_path = vis_abbr_path + "_" + VIS_ABBR_DIC[v] vis_abbr_path = vis_abbr_path[1:] else: vis_abbr_path = "no_video" if(args.force_cpu): use_cuda(False) print("WARNING: Forced CPU usage, expect model to perform slower") print("") os.makedirs( args.output_dir, exist_ok=True) os.makedirs( os.path.join( args.output_dir, version) , exist_ok=True) ##### Output prep ##### params_file = os.path.join(args.output_dir, version, "model_params_regression.txt") write_model_params(args, params_file) weights_folder = os.path.join(args.output_dir, version, "weights_regression_" + regModel) os.makedirs(weights_folder, exist_ok=True) results_folder = os.path.join(args.output_dir, version) os.makedirs(results_folder, exist_ok=True) results_file = os.path.join(results_folder, "results_regression.csv") best_rmse_file = os.path.join(results_folder, "best_rmse_weights.pickle") best_text = os.path.join(results_folder, "best_epochs_regression.txt") ##### Tensorboard ##### if(args.no_tensorboard): tensorboard_summary = None else: tensorboad_dir = os.path.join(args.output_dir, version, "tensorboard_regression") tensorboard_summary = SummaryWriter(log_dir=tensorboad_dir)
CSV_HEADER = ["Epoch", "Learn rate", "Avg Train loss", "Train RMSE", "Avg Eval loss", "Eval RMSE"] BASELINE_EPOCH = -1 version = VERSION split_ver = SPLIT_VER split_path = "split_" + split_ver num_epochs = 20 VIS_MODELS_ARR = [ "2d/clip_l14p" ] regModel = "gru" # lstm # bilstm # gru # bigru # main def main( vm = "" , isPrintArgs = True ): args = parse_train_args() args.epochs = num_epochs if isPrintArgs: print_train_args(args) if vm != "": args.vis_models = vm if args.is_video: vis_arr = args.vis_models.split(" ") vis_arr.sort() vis_abbr_path = "" for v in vis_arr: vis_abbr_path = vis_abbr_path + "_" + VIS_ABBR_DIC[v] vis_abbr_path = vis_abbr_path[1:] else: vis_abbr_path = "no_video" if(args.force_cpu): use_cuda(False) print("WARNING: Forced CPU usage, expect model to perform slower") print("") os.makedirs( args.output_dir, exist_ok=True) os.makedirs( os.path.join( args.output_dir, version) , exist_ok=True) ##### Output prep ##### params_file = os.path.join(args.output_dir, version, "model_params_regression.txt") write_model_params(args, params_file) weights_folder = os.path.join(args.output_dir, version, "weights_regression_" + regModel) os.makedirs(weights_folder, exist_ok=True) results_folder = os.path.join(args.output_dir, version) os.makedirs(results_folder, exist_ok=True) results_file = os.path.join(results_folder, "results_regression.csv") best_rmse_file = os.path.join(results_folder, "best_rmse_weights.pickle") best_text = os.path.join(results_folder, "best_epochs_regression.txt") ##### Tensorboard ##### if(args.no_tensorboard): tensorboard_summary = None else: tensorboad_dir = os.path.join(args.output_dir, version, "tensorboard_regression") tensorboard_summary = SummaryWriter(log_dir=tensorboad_dir)
train_dataset, val_dataset, _ = create_vevo_datasets(
0
2023-10-13 09:06:24+00:00
8k
NousResearch/Obsidian
llava/serve/model_worker.py
[ { "identifier": "WORKER_HEART_BEAT_INTERVAL", "path": "llava/constants.py", "snippet": "WORKER_HEART_BEAT_INTERVAL = 15" }, { "identifier": "build_logger", "path": "llava/utils.py", "snippet": "def build_logger(logger_name, logger_filename):\n def __init__(self, logger, log_level=logg...
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 llava.constants import WORKER_HEART_BEAT_INTERVAL from llava.utils import (build_logger, server_error_msg, pretty_print_semaphore) from llava.model.builder import load_pretrained_model from llava.mm_utils import process_images, load_image_from_base64, tokenizer_image_token, KeywordsStoppingCriteria from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN from transformers import TextIteratorStreamer from threading import Thread
4,220
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): 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 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) # self.is_multimodal = 'llava' in self.model_name.lower() self.is_multimodal = True 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] print(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): 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 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) # self.is_multimodal = 'llava' in self.model_name.lower() self.is_multimodal = True 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] print(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
9
2023-10-08 01:00:06+00:00
8k
neu-vi/OmniControl
sample/generate.py
[ { "identifier": "fixseed", "path": "utils/fixseed.py", "snippet": "def fixseed(seed):\n torch.backends.cudnn.benchmark = False\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True" }, { ...
from utils.fixseed import fixseed from utils.parser_util import generate_args from utils.model_util import create_model_and_diffusion, load_model_wo_clip from utils import dist_util from model.cfg_sampler import ClassifierFreeSampleModel from data_loaders.get_data import get_dataset_loader from data_loaders.humanml.scripts.motion_process import recover_from_ric from data_loaders.humanml.utils.plot_script import plot_3d_motion from data_loaders.tensors import collate from utils.text_control_example import collate_all from os.path import join as pjoin from utils.simple_eval import simple_eval import os import numpy as np import torch import data_loaders.humanml.utils.paramUtil as paramUtil import shutil
4,002
# This code is based on https://github.com/openai/guided-diffusion """ Generate a large batch of image samples from a model and save them as a large numpy array. This can be used to produce samples for FID evaluation. """ def main(): args = generate_args() fixseed(args.seed) out_path = args.output_dir name = os.path.basename(os.path.dirname(args.model_path)) niter = os.path.basename(args.model_path).replace('model', '').replace('.pt', '') max_frames = 196 if args.dataset in ['kit', 'humanml'] else 60 fps = 12.5 if args.dataset == 'kit' else 20 n_frames = min(max_frames, int(args.motion_length*fps)) n_frames = 196 is_using_data = not any([args.text_prompt]) dist_util.setup_dist(args.device) if out_path == '': out_path = os.path.join(os.path.dirname(args.model_path), 'samples_{}_{}_seed{}'.format(name, niter, args.seed)) if args.text_prompt != '': out_path += '_' + args.text_prompt.replace(' ', '_').replace('.', '') hints = None # this block must be called BEFORE the dataset is loaded if args.text_prompt != '': if args.text_prompt == 'predefined': # generate hint and text texts, hints = collate_all(n_frames, args.dataset) args.num_samples = len(texts) if args.cond_mode == 'only_spatial': # only with spatial control signal, and the spatial control signal is defined in utils/text_control_example.py texts = ['' for i in texts] elif args.cond_mode == 'only_text': # only with text prompt, and the text prompt is defined in utils/text_control_example.py hints = None else: # otherwise we use text_prompt texts = [args.text_prompt] args.num_samples = 1 hint = None assert args.num_samples <= args.batch_size, \ f'Please either increase batch_size({args.batch_size}) or reduce num_samples({args.num_samples})' # So why do we need this check? In order to protect GPU from a memory overload in the following line. # If your GPU can handle batch size larger then default, you can specify it through --batch_size flag. # If it doesn't, and you still want to sample more prompts, run this script with different seeds # (specify through the --seed flag) args.batch_size = args.num_samples # Sampling a single batch from the testset, with exactly args.num_samples print('Loading dataset...') data = load_dataset(args, max_frames, n_frames) total_num_samples = args.num_samples * args.num_repetitions print("Creating model and diffusion...") model, diffusion = create_model_and_diffusion(args, data) print(f"Loading checkpoints from [{args.model_path}]...") state_dict = torch.load(args.model_path, map_location='cpu')
# This code is based on https://github.com/openai/guided-diffusion """ Generate a large batch of image samples from a model and save them as a large numpy array. This can be used to produce samples for FID evaluation. """ def main(): args = generate_args() fixseed(args.seed) out_path = args.output_dir name = os.path.basename(os.path.dirname(args.model_path)) niter = os.path.basename(args.model_path).replace('model', '').replace('.pt', '') max_frames = 196 if args.dataset in ['kit', 'humanml'] else 60 fps = 12.5 if args.dataset == 'kit' else 20 n_frames = min(max_frames, int(args.motion_length*fps)) n_frames = 196 is_using_data = not any([args.text_prompt]) dist_util.setup_dist(args.device) if out_path == '': out_path = os.path.join(os.path.dirname(args.model_path), 'samples_{}_{}_seed{}'.format(name, niter, args.seed)) if args.text_prompt != '': out_path += '_' + args.text_prompt.replace(' ', '_').replace('.', '') hints = None # this block must be called BEFORE the dataset is loaded if args.text_prompt != '': if args.text_prompt == 'predefined': # generate hint and text texts, hints = collate_all(n_frames, args.dataset) args.num_samples = len(texts) if args.cond_mode == 'only_spatial': # only with spatial control signal, and the spatial control signal is defined in utils/text_control_example.py texts = ['' for i in texts] elif args.cond_mode == 'only_text': # only with text prompt, and the text prompt is defined in utils/text_control_example.py hints = None else: # otherwise we use text_prompt texts = [args.text_prompt] args.num_samples = 1 hint = None assert args.num_samples <= args.batch_size, \ f'Please either increase batch_size({args.batch_size}) or reduce num_samples({args.num_samples})' # So why do we need this check? In order to protect GPU from a memory overload in the following line. # If your GPU can handle batch size larger then default, you can specify it through --batch_size flag. # If it doesn't, and you still want to sample more prompts, run this script with different seeds # (specify through the --seed flag) args.batch_size = args.num_samples # Sampling a single batch from the testset, with exactly args.num_samples print('Loading dataset...') data = load_dataset(args, max_frames, n_frames) total_num_samples = args.num_samples * args.num_repetitions print("Creating model and diffusion...") model, diffusion = create_model_and_diffusion(args, data) print(f"Loading checkpoints from [{args.model_path}]...") state_dict = torch.load(args.model_path, map_location='cpu')
load_model_wo_clip(model, state_dict)
3
2023-10-12 19:25:19+00:00
8k
eai-lab/On-NAS
task_optimizer/darts.py
[ { "identifier": "get_finite_difference", "path": "meta_optimizer/reptile.py", "snippet": "def get_finite_difference(meta_weights, task_weights):\n for layer_name, layer_weight_tensor in meta_weights:\n if layer_weight_tensor.grad is not None:\n task_weights[layer_name].data.sub_(lay...
from tqdm import tqdm from collections import OrderedDict, namedtuple from meta_optimizer.reptile import get_finite_difference from utils import utils from models.search_cnn import SearchCNNController from tqdm import tqdm import copy import time import torch import torch.nn as nn
7,131
# phase 1. child network step (w) if config.cell_phase == config.layers -1: w_optim.zero_grad() logits = model(train_X_chunk) loss = model.criterion(logits, train_y_chunk) loss_monitor = loss.item() loss.backward() nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) w_optim.step() else: w_optim.zero_grad() output_grad_sum = copy.deepcopy(config.previous_grad) pprevious_grad = copy.deepcopy(config.pprevious_grad) pprevious_grads.append(pprevious_grad) if config.residual_flag == 1: if config.cell_phase == 1: if pprevious_grads[0].shape != output_grad_sum.shape: output_grad_sum = output_grad_sum else: output_grad_sum = torch.add(pprevious_grads[0],output_grad_sum) elif config.cell_phase == 0: if pprevious_grads[1].shape != output_grad_sum.shape: output_grad_sum = output_grad_sum else: output_grad_sum = torch.add(pprevious_grads[1],output_grad_sum) latent = model(train_X_chunk) try: latent.backward(output_grad_sum) except: if output_grad_sum is not None: print("batch passed,",output_grad_sum.shape, " was the shape of grad saved") print("what we had to save was this shape, ", latent.shape ) print(f"And this was the phase.{config.cell_phase} what can be the problem here ? ") else: print("output was none. Why?") pass nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) config.cell_phase -= 1 architect.v_net.net.config.cell_phase -= 1 alpha_optim.step() w_optim.step() else: if not warm_up: # only update alphas outside warm up phase alpha_optim.zero_grad() if config.do_unrolled_architecture_steps: architect.virtual_step(train_X, train_y, lr, w_optim) # (calc w`) architect.backward(train_X, train_y, val_X, val_y, lr, w_optim) alpha_optim.step() w_optim.zero_grad() logits = model(train_X) loss = model.criterion(logits, train_y) loss.backward() nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) w_optim.step() end.record() torch.cuda.synchronize() config.computing_time += start.elapsed_time(end) config.total_steps -= 1 pprevious_grads = list() architect.pprevious_grads = list() if config.alpha_expect and config.meta_model != 'pc_adaptation': if len(config.alpha_grad_footprints) <= 5: learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()] alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha) config.alpha_grad_footprints.append(alpha_grad) else: learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()] alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha) config.alpha_grad_footprints.pop(0) config.alpha_grad_footprints.append(alpha_grad) config.alpha_sample_metrics = _exp_alpha_metric(initial_alpha,config) architect.v_net.net.config.alpha_sample_metrics = config.alpha_sample_metrics ################################################################################### task_specific_model = copy.deepcopy(model) task_specific_model = get_diff_for_const_bottom(initial_model,task_specific_model) return task_specific_model def get_diff_for_const_bottom(init_model,task_model):
""" Script for On-NAS & Two-Fold Meta-learning(TFML) & On-NAS This code have been written for a research purpose. ''' Based on https://github.com/boschresearch/metanas which is licensed under GNU Affero General Public License, ''' """ class Darts: def __init__(self, model, config, do_schedule_lr=False): self.config = config self.config.logger = None self.model = model self.do_schedule_lr = do_schedule_lr self.task_train_steps = config.task_train_steps self.test_task_train_steps = config.test_task_train_steps self.warm_up_epochs = config.warm_up_epochs self.eval_switch = 0 self.pprevious_grads = 0 # weights optimizer self.w_optim = torch.optim.Adam( self.model.weights(), lr=self.config.w_lr, betas=(0.0, 0.999), # config.w_momentum, weight_decay=self.config.w_weight_decay, ) # # architecture optimizer self.a_optim = torch.optim.Adam( model.alphas(), self.config.alpha_lr, betas=(0.0, 0.999), weight_decay=self.config.alpha_weight_decay, ) self.architect = Architect( self.model, self.config.w_momentum, self.config.w_weight_decay, self.config.use_first_order_darts, ) def step( self, task, epoch, global_progress="", test_phase=False, alpha_logger=None, sparsify_input_alphas=None, ): log_alphas = False if test_phase: top1_logger = self.config.top1_logger_test losses_logger = self.config.losses_logger_test train_steps = self.config.test_task_train_steps arch_adap_steps = int(train_steps * self.config.test_adapt_steps) if alpha_logger is not None: log_alphas = True else: top1_logger = self.config.top1_logger losses_logger = self.config.losses_logger train_steps = self.config.task_train_steps arch_adap_steps = train_steps lr = self.config.w_lr if self.config.w_task_anneal: for group in self.w_optim.param_groups: group["lr"] = self.config.w_lr w_task_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( self.w_optim, train_steps, eta_min=0.0 ) else: w_task_lr_scheduler = None if self.config.a_task_anneal: for group in self.a_optim.param_groups: group["lr"] = self.config.alpha_lr a_task_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( self.a_optim, arch_adap_steps, eta_min=0.0 ) else: a_task_lr_scheduler = None model_has_normalizer = hasattr(self.model, "normalizer") if model_has_normalizer: self.model.normalizer["params"]["curr_step"] = 0.0 self.architect.v_net.normalizer["params"]["curr_step"] = 0.0 self.model.normalizer["params"]["max_steps"] = float(arch_adap_steps) self.architect.v_net.normalizer["params"]["max_steps"] = float( arch_adap_steps ) if self.config.drop_path_prob > 0.0: if not test_phase or self.config.use_drop_path_in_meta_testing: self.model.drop_path_prob(self.config.drop_path_prob) p_bar = tqdm(range(train_steps)) self.config.total_steps = train_steps * len(task.train_loader) for train_step in p_bar: # task train_steps = epochs per task warm_up = ( epoch < self.warm_up_epochs ) # if epoch < warm_up_epochs, do warm up if ( train_step >= arch_adap_steps ): # no architecture adap after arch_adap_steps steps warm_up = 1 if w_task_lr_scheduler is not None: w_task_lr_scheduler.step() if a_task_lr_scheduler is not None: a_task_lr_scheduler.step() torch.cuda.reset_peak_memory_stats(device=0) task_specific_model = train( task, self.model, self.architect, self.w_optim, self.a_optim, lr, global_progress, self.config, warm_up, test_phase ) mem = torch.cuda.memory_stats(0)['allocated_bytes.all.peak']/(1024**2) p_bar.set_postfix({"Memory" : f"{mem : .2f}","Task average":f"{self.config.top1_logger_test.avg:.1%}"}) if train_step == 9: self.config.memory_snap = mem if ( model_has_normalizer and train_step < (arch_adap_steps - 1) and not warm_up ): self.model.normalizer["params"]["curr_step"] += 1 self.architect.v_net.normalizer["params"]["curr_step"] += 1 w_task = OrderedDict( { layer_name: copy.deepcopy(layer_weight) for layer_name, layer_weight in self.model.named_weights() # if layer_weight.grad is not None } ) a_task = OrderedDict( { layer_name: copy.deepcopy(layer_alpha) for layer_name, layer_alpha in self.model.named_alphas() # if layer_alpha.grad is not None } ) w_task_bot = OrderedDict( { layer_name: copy.deepcopy(layer_weight) for layer_name, layer_weight in task_specific_model.named_weights() } ) a_task_bot = OrderedDict( { layer_name: copy.deepcopy(layer_alpha) for layer_name, layer_alpha in task_specific_model.named_alphas() } ) # Log genotype genotype = self.model.genotype() if log_alphas: alpha_logger["normal_relaxed"].append( copy.deepcopy(self.model.alpha_normal) ) alpha_logger["reduced_relaxed"].append( copy.deepcopy(self.model.alpha_reduce) ) alpha_logger["all_alphas"].append(a_task) alpha_logger["normal_hierarchical"].append( copy.deepcopy(self.model.alpha_in_normal) ) alpha_logger["reduced_hierarchical"].append( copy.deepcopy(self.model.alpha_in_reduce) ) alpha_logger["normal_pairwise"].append( copy.deepcopy(self.model.alpha_pw_normal) ) alpha_logger["reduced_pairwise"].append( copy.deepcopy(self.model.alpha_pw_reduce) ) # for test data evaluation, turn off drop path if self.config.drop_path_prob > 0.0: self.model.drop_path_prob(0.0) little_switch = 0 if self.config.naivenaive: little_switch = 1 with torch.no_grad(): self.config.naivenaive = 1 self.config.eval_switch = 1 self.config.cell_phase = 3 for batch_idx, batch in enumerate(task.test_loader): x_test, y_test = batch x_test = x_test.to(self.config.device, non_blocking=True) y_test = y_test.to(self.config.device, non_blocking=True) if isinstance(self.model, SearchCNNController): logits = self.model( x_test, sparsify_input_alphas=sparsify_input_alphas ) else: logits = self.model(x_test) loss = self.model.criterion(logits, y_test) y_test_pred = logits.softmax(dim=1) now = time.strftime('%c', time.localtime(time.time())) prec1, prec5 = utils.accuracy(logits, y_test, self.config, topk=(1, 5)) losses_logger.update(loss.item(), 1) top1_logger.update(prec1.item(), 1) self.config.naivenaive = 0 self.config.eval_switch = 0 self.config.cell_phase = 3 if little_switch == 1: self.config.naivenaive = 1 task_info = namedtuple( "task_info", [ "genotype", "top1", "w_task", "a_task", "loss", "y_test_pred", "sparse_num_params", "w_task_bot", "a_task_bot" ], ) task_info.w_task = w_task task_info.a_task = a_task task_info.loss = loss y_test_pred = y_test_pred task_info.y_test_pred = y_test_pred task_info.genotype = genotype # task_info.top1 = top1 # task_info.sparse_num_params = self.model.get_sparse_num_params( # self.model.alpha_prune_threshold # ) task_info.w_task_bot = w_task_bot task_info.a_task_bot = a_task_bot return task_info def train( task, model, architect, w_optim, alpha_optim, lr, global_progress, config, warm_up=False, test_phase = False ): model.train() pprevious_grads = list() initial_model = copy.deepcopy(model) p_bar_monitor = (enumerate(zip(task.train_loader, task.valid_loader)))# for step, ((train_X, train_y), (val_X, val_y)) in p_bar_monitor: start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) start.record() train_X, train_y = train_X.to(config.device), train_y.to(config.device) val_X, val_y = val_X.to(config.device), val_y.to(config.device) N = train_X.size(0) initial_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()] if config.light_exp == 1: if config.meta_model != "pc_adaptation" and config.meta_model != "pure_darts" and config.dataset != "cifar10" and config.dataset != "cifar100": config.cell_phase = config.layers -1 architect.v_net.net.config.cell_phase = config.layers -1 # phase 2. architect step (alpha) prohibited_list = config.prohibited_list if config.naivenaive != 1 and config.eval_switch != 1 and config.meta_model != "pc_adaptation" and config.meta_model != "pure_darts" and config.dataset not in prohibited_list: w_optim.zero_grad() alpha_optim.zero_grad() train_X, train_y = train_X.chunk(config.split_num), train_y.chunk(config.split_num) val_X,val_y = val_X.chunk(config.split_num), val_y.chunk(config.split_num) for (train_X_chunk, train_y_chunk) ,(val_X_chunk,val_y_chunk) in zip(zip(train_X,train_y),zip(val_X,val_y)): config.cell_phase = config.layers -1 architect.v_net.net.config.cell_phase = config.layers -1 for phase in range(config.layers): if not warm_up: # only update alphas outside warm up phase if config.do_unrolled_architecture_steps: architect.virtual_step(train_X_chunk, train_y_chunk, lr, w_optim) # (calc w`) if config.cell_phase == config.layers -1: architect.v_net.net.cells[config.cell_phase].alpha_switch = 1 architect.backward(train_X_chunk, train_y_chunk, val_X_chunk, val_y_chunk, lr, w_optim) else: architect.v_net.net.cells[config.cell_phase].alpha_switch = 1 architect.partial_alpha_backward(config, train_X_chunk, train_y_chunk, val_X_chunk, val_y_chunk, lr, w_optim) model.net.alpha_switch = 0 architect.v_net.net.alpha_switch = 0 # phase 1. child network step (w) if config.cell_phase == config.layers -1: w_optim.zero_grad() logits = model(train_X_chunk) loss = model.criterion(logits, train_y_chunk) loss_monitor = loss.item() loss.backward() nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) w_optim.step() else: w_optim.zero_grad() output_grad_sum = copy.deepcopy(config.previous_grad) pprevious_grad = copy.deepcopy(config.pprevious_grad) pprevious_grads.append(pprevious_grad) if config.residual_flag == 1: if config.cell_phase == 1: if pprevious_grads[0].shape != output_grad_sum.shape: output_grad_sum = output_grad_sum else: output_grad_sum = torch.add(pprevious_grads[0],output_grad_sum) elif config.cell_phase == 0: if pprevious_grads[1].shape != output_grad_sum.shape: output_grad_sum = output_grad_sum else: output_grad_sum = torch.add(pprevious_grads[1],output_grad_sum) latent = model(train_X_chunk) try: latent.backward(output_grad_sum) except: if output_grad_sum is not None: print("batch passed,",output_grad_sum.shape, " was the shape of grad saved") print("what we had to save was this shape, ", latent.shape ) print(f"And this was the phase.{config.cell_phase} what can be the problem here ? ") else: print("output was none. Why?") pass nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) config.cell_phase -= 1 architect.v_net.net.config.cell_phase -= 1 alpha_optim.step() w_optim.step() else: if not warm_up: # only update alphas outside warm up phase alpha_optim.zero_grad() if config.do_unrolled_architecture_steps: architect.virtual_step(train_X, train_y, lr, w_optim) # (calc w`) architect.backward(train_X, train_y, val_X, val_y, lr, w_optim) alpha_optim.step() w_optim.zero_grad() logits = model(train_X) loss = model.criterion(logits, train_y) loss.backward() nn.utils.clip_grad_norm_(model.weights(), config.w_grad_clip) w_optim.step() end.record() torch.cuda.synchronize() config.computing_time += start.elapsed_time(end) config.total_steps -= 1 pprevious_grads = list() architect.pprevious_grads = list() if config.alpha_expect and config.meta_model != 'pc_adaptation': if len(config.alpha_grad_footprints) <= 5: learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()] alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha) config.alpha_grad_footprints.append(alpha_grad) else: learnt_alpha = [copy.deepcopy(x).detach().cpu() for x in model.alphas()] alpha_grad = _alpha_subtract(initial_alpha,learnt_alpha) config.alpha_grad_footprints.pop(0) config.alpha_grad_footprints.append(alpha_grad) config.alpha_sample_metrics = _exp_alpha_metric(initial_alpha,config) architect.v_net.net.config.alpha_sample_metrics = config.alpha_sample_metrics ################################################################################### task_specific_model = copy.deepcopy(model) task_specific_model = get_diff_for_const_bottom(initial_model,task_specific_model) return task_specific_model def get_diff_for_const_bottom(init_model,task_model):
get_finite_difference(init_model.named_weights(),task_model.named_weights())
0
2023-10-08 02:42:27+00:00
8k
Nightmare-n/UniPAD
projects/mmdet3d_plugin/models/backbones/mask_convnext.py
[ { "identifier": "SparseLayerNorm", "path": "projects/mmdet3d_plugin/models/utils/sparse_utils.py", "snippet": "class SparseLayerNorm(nn.LayerNorm):\n r\"\"\"LayerNorm that supports two data formats: channels_last (default) or channels_first.\n The ordering of the dimensions in the inputs. channels...
import torch import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import build_conv_layer, build_norm_layer from mmcv.runner import BaseModule from mmdet.models.builder import BACKBONES from ..utils.sparse_utils import SparseLayerNorm, SparseConvNeXtBlock from timm.models.layers import trunc_normal_, DropPath from itertools import chain from typing import Sequence from ..utils import sparse_utils
3,617
f"({set(self.arch_settings)}) or pass a dict." ) arch = self.arch_settings[arch] elif isinstance(arch, dict): assert "depths" in arch and "channels" in arch, ( f'The arch dict must have "depths" and "channels", ' f"but got {list(arch.keys())}." ) self.depths = arch["depths"] self.channels = arch["channels"] assert ( isinstance(self.depths, Sequence) and isinstance(self.channels, Sequence) and len(self.depths) == len(self.channels) ), ( f'The "depths" ({self.depths}) and "channels" ({self.channels}) ' "should be both sequence with the same length." ) self.num_stages = len(self.depths) if isinstance(out_indices, int): out_indices = [out_indices] assert isinstance(out_indices, Sequence), ( f'"out_indices" must by a sequence or int, ' f"get {type(out_indices)} instead." ) for i, index in enumerate(out_indices): if index < 0: out_indices[i] = 4 + index assert out_indices[i] >= 0, f"Invalid out_indices {index}" self.out_indices = out_indices self.norm_out = norm_out self.frozen_stages = frozen_stages # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] block_idx = 0 sparse = mae_cfg is not None # 4 downsample layers between stages, including the stem layer. self.downsample_layers = nn.ModuleList() stem = nn.Sequential( nn.Conv2d( in_channels, self.channels[0], kernel_size=stem_patch_size, stride=stem_patch_size, ), SparseLayerNorm( self.channels[0], eps=1e-6, data_format="channel_first", sparse=sparse ), ) self.downsample_layers.append(stem) # 4 feature resolution stages, each consisting of multiple residual # blocks self.stages = nn.ModuleList() for i in range(self.num_stages): depth = self.depths[i] channels = self.channels[i] if i >= 1: downsample_layer = nn.Sequential( SparseLayerNorm( self.channels[i - 1], eps=1e-6, data_format="channel_first", sparse=sparse, ), nn.Conv2d(self.channels[i - 1], channels, kernel_size=2, stride=2), ) self.downsample_layers.append(downsample_layer) stage = nn.Sequential( *[ SparseConvNeXtBlock( in_channels=channels, drop_path_rate=dpr[block_idx + j], layer_scale_init_value=layer_scale_init_value, with_cp=with_cp, sparse=sparse, ) for j in range(depth) ] ) block_idx += depth self.stages.append(stage) if i in self.out_indices and self.norm_out: norm_layer = SparseLayerNorm( channels, eps=1e-6, data_format="channel_first", sparse=sparse ) self.add_module(f"norm{i}", norm_layer) self.mae_cfg = mae_cfg if mae_cfg is not None: self.to_sparse() if mae_cfg.learnable: for i in self.out_indices: p = nn.Parameter( torch.zeros( 1, mae_cfg.downsample_dim // 2 ** (len(self.stages) - i - 1), 1, 1, ) ) trunc_normal_(p, mean=0, std=0.02, a=-0.02, b=0.02) self.register_parameter(f"mtoken{i}", p) self._freeze_stages() def to_sparse(self, verbose=False, sbn=False): for name, child in self.named_children(): self.add_module( name,
@BACKBONES.register_module() class MaskConvNeXt(BaseModule): """ConvNeXt v1&v2 backbone. A PyTorch implementation of `A ConvNet for the 2020s <https://arxiv.org/abs/2201.03545>`_ and `ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders <http://arxiv.org/abs/2301.00808>`_ Modified from the `official repo <https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py>`_ and `timm <https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/convnext.py>`_. To use ConvNeXt v2, please set ``use_grn=True`` and ``layer_scale_init_value=0.``. Args: arch (str | dict): The model's architecture. If string, it should be one of architecture in ``ConvNeXt.arch_settings``. And if dict, it should include the following two keys: - depths (list[int]): Number of blocks at each stage. - channels (list[int]): The number of channels at each stage. Defaults to 'tiny'. in_channels (int): Number of input image channels. Defaults to 3. stem_patch_size (int): The size of one patch in the stem layer. Defaults to 4. norm_cfg (dict): The config dict for norm layers. Defaults to ``dict(type='LN2d', eps=1e-6)``. act_cfg (dict): The config dict for activation between pointwise convolution. Defaults to ``dict(type='GELU')``. linear_pw_conv (bool): Whether to use linear layer to do pointwise convolution. Defaults to True. use_grn (bool): Whether to add Global Response Normalization in the blocks. Defaults to False. drop_path_rate (float): Stochastic depth rate. Defaults to 0. layer_scale_init_value (float): Init value for Layer Scale. Defaults to 1e-6. out_indices (Sequence | int): Output from which stages. Defaults to -1, means the last stage. frozen_stages (int): Stages to be frozen (all param fixed). Defaults to 0, which means not freezing any parameters. with_cp (bool): Use checkpoint or not. Using checkpoint will save some memory while slowing down the training speed. Defaults to False. init_cfg (dict, optional): Initialization config dict """ # noqa: E501 arch_settings = { "tiny": {"depths": [3, 3, 9, 3], "channels": [96, 192, 384, 768]}, "small": {"depths": [3, 3, 27, 3], "channels": [96, 192, 384, 768]}, "base": {"depths": [3, 3, 27, 3], "channels": [128, 256, 512, 1024]}, "large": {"depths": [3, 3, 27, 3], "channels": [192, 384, 768, 1536]}, } def __init__( self, arch="tiny", in_channels=3, stem_patch_size=4, drop_path_rate=0.0, layer_scale_init_value=1e-6, out_indices=-1, norm_out=False, frozen_stages=0, with_cp=False, init_cfg=[ dict(type="TruncNormal", layer=["Conv2d", "Linear"], std=0.02, bias=0.0), dict(type="Constant", layer=["LayerNorm"], val=1.0, bias=0.0), ], mae_cfg=None, ): super().__init__(init_cfg=init_cfg) if isinstance(arch, str): assert arch in self.arch_settings, ( f"Unavailable arch, please choose from " f"({set(self.arch_settings)}) or pass a dict." ) arch = self.arch_settings[arch] elif isinstance(arch, dict): assert "depths" in arch and "channels" in arch, ( f'The arch dict must have "depths" and "channels", ' f"but got {list(arch.keys())}." ) self.depths = arch["depths"] self.channels = arch["channels"] assert ( isinstance(self.depths, Sequence) and isinstance(self.channels, Sequence) and len(self.depths) == len(self.channels) ), ( f'The "depths" ({self.depths}) and "channels" ({self.channels}) ' "should be both sequence with the same length." ) self.num_stages = len(self.depths) if isinstance(out_indices, int): out_indices = [out_indices] assert isinstance(out_indices, Sequence), ( f'"out_indices" must by a sequence or int, ' f"get {type(out_indices)} instead." ) for i, index in enumerate(out_indices): if index < 0: out_indices[i] = 4 + index assert out_indices[i] >= 0, f"Invalid out_indices {index}" self.out_indices = out_indices self.norm_out = norm_out self.frozen_stages = frozen_stages # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))] block_idx = 0 sparse = mae_cfg is not None # 4 downsample layers between stages, including the stem layer. self.downsample_layers = nn.ModuleList() stem = nn.Sequential( nn.Conv2d( in_channels, self.channels[0], kernel_size=stem_patch_size, stride=stem_patch_size, ), SparseLayerNorm( self.channels[0], eps=1e-6, data_format="channel_first", sparse=sparse ), ) self.downsample_layers.append(stem) # 4 feature resolution stages, each consisting of multiple residual # blocks self.stages = nn.ModuleList() for i in range(self.num_stages): depth = self.depths[i] channels = self.channels[i] if i >= 1: downsample_layer = nn.Sequential( SparseLayerNorm( self.channels[i - 1], eps=1e-6, data_format="channel_first", sparse=sparse, ), nn.Conv2d(self.channels[i - 1], channels, kernel_size=2, stride=2), ) self.downsample_layers.append(downsample_layer) stage = nn.Sequential( *[ SparseConvNeXtBlock( in_channels=channels, drop_path_rate=dpr[block_idx + j], layer_scale_init_value=layer_scale_init_value, with_cp=with_cp, sparse=sparse, ) for j in range(depth) ] ) block_idx += depth self.stages.append(stage) if i in self.out_indices and self.norm_out: norm_layer = SparseLayerNorm( channels, eps=1e-6, data_format="channel_first", sparse=sparse ) self.add_module(f"norm{i}", norm_layer) self.mae_cfg = mae_cfg if mae_cfg is not None: self.to_sparse() if mae_cfg.learnable: for i in self.out_indices: p = nn.Parameter( torch.zeros( 1, mae_cfg.downsample_dim // 2 ** (len(self.stages) - i - 1), 1, 1, ) ) trunc_normal_(p, mean=0, std=0.02, a=-0.02, b=0.02) self.register_parameter(f"mtoken{i}", p) self._freeze_stages() def to_sparse(self, verbose=False, sbn=False): for name, child in self.named_children(): self.add_module( name,
sparse_utils.dense_model_to_sparse(
2
2023-10-13 05:52:45+00:00
8k
ximinng/VectorFusion-pytorch
libs/metric/piq/perceptual.py
[ { "identifier": "_validate_input", "path": "libs/metric/piq/utils/common.py", "snippet": "def _validate_input(\n tensors: List[torch.Tensor],\n dim_range: Tuple[int, int] = (0, -1),\n data_range: Tuple[float, float] = (0., -1.),\n # size_dim_range: Tuple[float, float] = (0., ...
from typing import List, Union, Collection from torch.nn.modules.loss import _Loss from torchvision.models import vgg16, vgg19, VGG16_Weights, VGG19_Weights from .utils import _validate_input, _reduce from .functional import similarity_map, L2Pool2d import torch import torch.nn as nn
4,359
distance: Method to compute distance between features: ``'mse'`` | ``'mae'``. reduction: Specifies the reduction type: ``'none'`` | ``'mean'`` | ``'sum'``. Default:``'mean'`` mean: List of float values used for data standardization. Default: ImageNet mean. If there is no need to normalize data, use [0., 0., 0.]. std: List of float values used for data standardization. Default: ImageNet std. If there is no need to normalize data, use [1., 1., 1.]. Examples: >>> loss = LPIPS() >>> x = torch.rand(3, 3, 256, 256, requires_grad=True) >>> y = torch.rand(3, 3, 256, 256) >>> output = loss(x, y) >>> output.backward() References: Gatys, Leon and Ecker, Alexander and Bethge, Matthias (2016). A Neural Algorithm of Artistic Style Association for Research in Vision and Ophthalmology (ARVO) https://arxiv.org/abs/1508.06576 Zhang, Richard and Isola, Phillip and Efros, et al. (2018) The Unreasonable Effectiveness of Deep Features as a Perceptual Metric IEEE/CVF Conference on Computer Vision and Pattern Recognition https://arxiv.org/abs/1801.03924 https://github.com/richzhang/PerceptualSimilarity """ _weights_url = "https://github.com/photosynthesis-team/" + \ "photosynthesis.metrics/releases/download/v0.4.0/lpips_weights.pt" def __init__(self, replace_pooling: bool = False, distance: str = "mse", reduction: str = "mean", mean: List[float] = IMAGENET_MEAN, std: List[float] = IMAGENET_STD, ) -> None: lpips_layers = ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'] lpips_weights = torch.hub.load_state_dict_from_url(self._weights_url, progress=False) super().__init__("vgg16", layers=lpips_layers, weights=lpips_weights, replace_pooling=replace_pooling, distance=distance, reduction=reduction, mean=mean, std=std, normalize_features=True) class DISTS(ContentLoss): r"""Deep Image Structure and Texture Similarity metric. By default expects input to be in range [0, 1], which is then normalized by ImageNet statistics into range [-1, 1]. If no normalisation is required, change `mean` and `std` values accordingly. Args: reduction: Specifies the reduction type: ``'none'`` | ``'mean'`` | ``'sum'``. Default:``'mean'`` mean: List of float values used for data standardization. Default: ImageNet mean. If there is no need to normalize data, use [0., 0., 0.]. std: List of float values used for data standardization. Default: ImageNet std. If there is no need to normalize data, use [1., 1., 1.]. Examples: >>> loss = DISTS() >>> x = torch.rand(3, 3, 256, 256, requires_grad=True) >>> y = torch.rand(3, 3, 256, 256) >>> output = loss(x, y) >>> output.backward() References: Keyan Ding, Kede Ma, Shiqi Wang, Eero P. Simoncelli (2020). Image Quality Assessment: Unifying Structure and Texture Similarity. https://arxiv.org/abs/2004.07728 https://github.com/dingkeyan93/DISTS """ _weights_url = "https://github.com/photosynthesis-team/piq/releases/download/v0.4.1/dists_weights.pt" def __init__(self, reduction: str = "mean", mean: List[float] = IMAGENET_MEAN, std: List[float] = IMAGENET_STD) -> None: dists_layers = ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'] channels = [3, 64, 128, 256, 512, 512] weights = torch.hub.load_state_dict_from_url(self._weights_url, progress=False) dists_weights = list(torch.split(weights['alpha'], channels, dim=1)) dists_weights.extend(torch.split(weights['beta'], channels, dim=1)) super().__init__("vgg16", layers=dists_layers, weights=dists_weights, replace_pooling=True, reduction=reduction, mean=mean, std=std, normalize_features=False, allow_layers_weights_mismatch=True) def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: r""" Args: x: An input tensor. Shape :math:`(N, C, H, W)`. y: A target tensor. Shape :math:`(N, C, H, W)`. Returns: Deep Image Structure and Texture Similarity loss, i.e. ``1-DISTS`` in range [0, 1]. """ _, _, H, W = x.shape if min(H, W) > 256: x = torch.nn.functional.interpolate( x, scale_factor=256 / min(H, W), recompute_scale_factor=False, mode='bilinear') y = torch.nn.functional.interpolate( y, scale_factor=256 / min(H, W), recompute_scale_factor=False, mode='bilinear') loss = super().forward(x, y) return 1 - loss def compute_distance(self, x_features: torch.Tensor, y_features: torch.Tensor) -> List[torch.Tensor]: r"""Compute structure similarity between feature maps Args: x_features: Features of the input tensor. y_features: Features of the target tensor. Returns: Structural similarity distance between feature maps """ structure_distance, texture_distance = [], [] # Small constant for numerical stability EPS = 1e-6 for x, y in zip(x_features, y_features): x_mean = x.mean([2, 3], keepdim=True) y_mean = y.mean([2, 3], keepdim=True)
""" Implementation of Content loss, Style loss, LPIPS and DISTS metrics References: .. [1] Gatys, Leon and Ecker, Alexander and Bethge, Matthias (2016). A Neural Algorithm of Artistic Style} Association for Research in Vision and Ophthalmology (ARVO) https://arxiv.org/abs/1508.06576 .. [2] Zhang, Richard and Isola, Phillip and Efros, et al. (2018) The Unreasonable Effectiveness of Deep Features as a Perceptual Metric 2018 IEEE/CVF Conference on Computer Vision and Pattern Recognition https://arxiv.org/abs/1801.03924 """ # Map VGG names to corresponding number in torchvision layer VGG16_LAYERS = { "conv1_1": '0', "relu1_1": '1', "conv1_2": '2', "relu1_2": '3', "pool1": '4', "conv2_1": '5', "relu2_1": '6', "conv2_2": '7', "relu2_2": '8', "pool2": '9', "conv3_1": '10', "relu3_1": '11', "conv3_2": '12', "relu3_2": '13', "conv3_3": '14', "relu3_3": '15', "pool3": '16', "conv4_1": '17', "relu4_1": '18', "conv4_2": '19', "relu4_2": '20', "conv4_3": '21', "relu4_3": '22', "pool4": '23', "conv5_1": '24', "relu5_1": '25', "conv5_2": '26', "relu5_2": '27', "conv5_3": '28', "relu5_3": '29', "pool5": '30', } VGG19_LAYERS = { "conv1_1": '0', "relu1_1": '1', "conv1_2": '2', "relu1_2": '3', "pool1": '4', "conv2_1": '5', "relu2_1": '6', "conv2_2": '7', "relu2_2": '8', "pool2": '9', "conv3_1": '10', "relu3_1": '11', "conv3_2": '12', "relu3_2": '13', "conv3_3": '14', "relu3_3": '15', "conv3_4": '16', "relu3_4": '17', "pool3": '18', "conv4_1": '19', "relu4_1": '20', "conv4_2": '21', "relu4_2": '22', "conv4_3": '23', "relu4_3": '24', "conv4_4": '25', "relu4_4": '26', "pool4": '27', "conv5_1": '28', "relu5_1": '29', "conv5_2": '30', "relu5_2": '31', "conv5_3": '32', "relu5_3": '33', "conv5_4": '34', "relu5_4": '35', "pool5": '36', } IMAGENET_MEAN = [0.485, 0.456, 0.406] IMAGENET_STD = [0.229, 0.224, 0.225] # Constant used in feature normalization to avoid zero division EPS = 1e-10 class ContentLoss(_Loss): r"""Creates Content loss that can be used for image style transfer or as a measure for image to image tasks. Uses pretrained VGG models from torchvision. Expects input to be in range [0, 1] or normalized with ImageNet statistics into range [-1, 1] Args: feature_extractor: Model to extract features or model name: ``'vgg16'`` | ``'vgg19'``. layers: List of strings with layer names. Default: ``'relu3_3'`` weights: List of float weight to balance different layers replace_pooling: Flag to replace MaxPooling layer with AveragePooling. See references for details. distance: Method to compute distance between features: ``'mse'`` | ``'mae'``. reduction: Specifies the reduction type: ``'none'`` | ``'mean'`` | ``'sum'``. Default:``'mean'`` mean: List of float values used for data standardization. Default: ImageNet mean. If there is no need to normalize data, use [0., 0., 0.]. std: List of float values used for data standardization. Default: ImageNet std. If there is no need to normalize data, use [1., 1., 1.]. normalize_features: If true, unit-normalize each feature in channel dimension before scaling and computing distance. See references for details. Examples: >>> loss = ContentLoss() >>> x = torch.rand(3, 3, 256, 256, requires_grad=True) >>> y = torch.rand(3, 3, 256, 256) >>> output = loss(x, y) >>> output.backward() References: Gatys, Leon and Ecker, Alexander and Bethge, Matthias (2016). A Neural Algorithm of Artistic Style Association for Research in Vision and Ophthalmology (ARVO) https://arxiv.org/abs/1508.06576 Zhang, Richard and Isola, Phillip and Efros, et al. (2018) The Unreasonable Effectiveness of Deep Features as a Perceptual Metric IEEE/CVF Conference on Computer Vision and Pattern Recognition https://arxiv.org/abs/1801.03924 """ def __init__(self, feature_extractor: Union[str, torch.nn.Module] = "vgg16", layers: Collection[str] = ("relu3_3",), weights: List[Union[float, torch.Tensor]] = [1.], replace_pooling: bool = False, distance: str = "mse", reduction: str = "mean", mean: List[float] = IMAGENET_MEAN, std: List[float] = IMAGENET_STD, normalize_features: bool = False, allow_layers_weights_mismatch: bool = False) -> None: assert allow_layers_weights_mismatch or len(layers) == len(weights), \ f'Lengths of provided layers and weighs mismatch ({len(weights)} weights and {len(layers)} layers), ' \ f'which will cause incorrect results. Please provide weight for each layer.' super().__init__() if callable(feature_extractor): self.model = feature_extractor self.layers = layers else: if feature_extractor == "vgg16": # self.model = vgg16(pretrained=True, progress=False).features self.model = vgg16(weights=VGG16_Weights.DEFAULT, progress=False).features self.layers = [VGG16_LAYERS[l] for l in layers] elif feature_extractor == "vgg19": # self.model = vgg19(pretrained=True, progress=False).features self.model = vgg19(weights=VGG19_Weights.DEFAULT, progress=False).features self.layers = [VGG19_LAYERS[l] for l in layers] else: raise ValueError("Unknown feature extractor") if replace_pooling: self.model = self.replace_pooling(self.model) # Disable gradients for param in self.model.parameters(): param.requires_grad_(False) self.distance = { "mse": nn.MSELoss, "mae": nn.L1Loss, }[distance](reduction='none') self.weights = [torch.tensor(w) if not isinstance(w, torch.Tensor) else w for w in weights] mean = torch.tensor(mean) std = torch.tensor(std) self.mean = mean.view(1, -1, 1, 1) self.std = std.view(1, -1, 1, 1) self.normalize_features = normalize_features self.reduction = reduction def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: r"""Computation of Content loss between feature representations of prediction :math:`x` and target :math:`y` tensors. Args: x: An input tensor. Shape :math:`(N, C, H, W)`. y: A target tensor. Shape :math:`(N, C, H, W)`. Returns: Content loss between feature representations """ _validate_input([x, y], dim_range=(4, 4), data_range=(0, -1)) self.model.to(x) x_features = self.get_features(x) y_features = self.get_features(y) distances = self.compute_distance(x_features, y_features) # Scale distances, then average in spatial dimensions, then stack and sum in channels dimension loss = torch.cat([(d * w.to(d)).mean(dim=[2, 3]) for d, w in zip(distances, self.weights)], dim=1).sum(dim=1) return _reduce(loss, self.reduction) def compute_distance(self, x_features: List[torch.Tensor], y_features: List[torch.Tensor]) -> List[torch.Tensor]: r"""Take L2 or L1 distance between feature maps depending on ``distance``. Args: x_features: Features of the input tensor. y_features: Features of the target tensor. Returns: Distance between feature maps """ return [self.distance(x, y) for x, y in zip(x_features, y_features)] def get_features(self, x: torch.Tensor) -> List[torch.Tensor]: r""" Args: x: Tensor. Shape :math:`(N, C, H, W)`. Returns: List of features extracted from intermediate layers """ # Normalize input x = (x - self.mean.to(x)) / self.std.to(x) features = [] for name, module in self.model._modules.items(): x = module(x) if name in self.layers: features.append(self.normalize(x) if self.normalize_features else x) return features @staticmethod def normalize(x: torch.Tensor) -> torch.Tensor: r"""Normalize feature maps in channel direction to unit length. Args: x: Tensor. Shape :math:`(N, C, H, W)`. Returns: Normalized input """ norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True)) return x / (norm_factor + EPS) def replace_pooling(self, module: torch.nn.Module) -> torch.nn.Module: r"""Turn All MaxPool layers into AveragePool Args: module: Module to change MaxPool int AveragePool Returns: Module with AveragePool instead MaxPool """ module_output = module if isinstance(module, torch.nn.MaxPool2d): module_output = torch.nn.AvgPool2d(kernel_size=2, stride=2, padding=0) for name, child in module.named_children(): module_output.add_module(name, self.replace_pooling(child)) return module_output class StyleLoss(ContentLoss): r"""Creates Style loss that can be used for image style transfer or as a measure in image to image tasks. Computes distance between Gram matrices of feature maps. Uses pretrained VGG models from torchvision. By default expects input to be in range [0, 1], which is then normalized by ImageNet statistics into range [-1, 1]. If no normalisation is required, change `mean` and `std` values accordingly. Args: feature_extractor: Model to extract features or model name: ``'vgg16'`` | ``'vgg19'``. layers: List of strings with layer names. Default: ``'relu3_3'`` weights: List of float weight to balance different layers replace_pooling: Flag to replace MaxPooling layer with AveragePooling. See references for details. distance: Method to compute distance between features: ``'mse'`` | ``'mae'``. reduction: Specifies the reduction type: ``'none'`` | ``'mean'`` | ``'sum'``. Default:``'mean'`` mean: List of float values used for data standardization. Default: ImageNet mean. If there is no need to normalize data, use [0., 0., 0.]. std: List of float values used for data standardization. Default: ImageNet std. If there is no need to normalize data, use [1., 1., 1.]. normalize_features: If true, unit-normalize each feature in channel dimension before scaling and computing distance. See references for details. Examples: >>> loss = StyleLoss() >>> x = torch.rand(3, 3, 256, 256, requires_grad=True) >>> y = torch.rand(3, 3, 256, 256) >>> output = loss(x, y) >>> output.backward() References: Gatys, Leon and Ecker, Alexander and Bethge, Matthias (2016). A Neural Algorithm of Artistic Style Association for Research in Vision and Ophthalmology (ARVO) https://arxiv.org/abs/1508.06576 Zhang, Richard and Isola, Phillip and Efros, et al. (2018) The Unreasonable Effectiveness of Deep Features as a Perceptual Metric IEEE/CVF Conference on Computer Vision and Pattern Recognition https://arxiv.org/abs/1801.03924 """ def compute_distance(self, x_features: torch.Tensor, y_features: torch.Tensor): r"""Take L2 or L1 distance between Gram matrices of feature maps depending on ``distance``. Args: x_features: Features of the input tensor. y_features: Features of the target tensor. Returns: Distance between Gram matrices """ x_gram = [self.gram_matrix(x) for x in x_features] y_gram = [self.gram_matrix(x) for x in y_features] return [self.distance(x, y) for x, y in zip(x_gram, y_gram)] @staticmethod def gram_matrix(x: torch.Tensor) -> torch.Tensor: r"""Compute Gram matrix for batch of features. Args: x: Tensor. Shape :math:`(N, C, H, W)`. Returns: Gram matrix for given input """ B, C, H, W = x.size() gram = [] for i in range(B): features = x[i].view(C, H * W) # Add fake channel dimension gram.append(torch.mm(features, features.t()).unsqueeze(0)) return torch.stack(gram) class LPIPS(ContentLoss): r"""Learned Perceptual Image Patch Similarity metric. Only VGG16 learned weights are supported. By default expects input to be in range [0, 1], which is then normalized by ImageNet statistics into range [-1, 1]. If no normalisation is required, change `mean` and `std` values accordingly. Args: replace_pooling: Flag to replace MaxPooling layer with AveragePooling. See references for details. distance: Method to compute distance between features: ``'mse'`` | ``'mae'``. reduction: Specifies the reduction type: ``'none'`` | ``'mean'`` | ``'sum'``. Default:``'mean'`` mean: List of float values used for data standardization. Default: ImageNet mean. If there is no need to normalize data, use [0., 0., 0.]. std: List of float values used for data standardization. Default: ImageNet std. If there is no need to normalize data, use [1., 1., 1.]. Examples: >>> loss = LPIPS() >>> x = torch.rand(3, 3, 256, 256, requires_grad=True) >>> y = torch.rand(3, 3, 256, 256) >>> output = loss(x, y) >>> output.backward() References: Gatys, Leon and Ecker, Alexander and Bethge, Matthias (2016). A Neural Algorithm of Artistic Style Association for Research in Vision and Ophthalmology (ARVO) https://arxiv.org/abs/1508.06576 Zhang, Richard and Isola, Phillip and Efros, et al. (2018) The Unreasonable Effectiveness of Deep Features as a Perceptual Metric IEEE/CVF Conference on Computer Vision and Pattern Recognition https://arxiv.org/abs/1801.03924 https://github.com/richzhang/PerceptualSimilarity """ _weights_url = "https://github.com/photosynthesis-team/" + \ "photosynthesis.metrics/releases/download/v0.4.0/lpips_weights.pt" def __init__(self, replace_pooling: bool = False, distance: str = "mse", reduction: str = "mean", mean: List[float] = IMAGENET_MEAN, std: List[float] = IMAGENET_STD, ) -> None: lpips_layers = ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'] lpips_weights = torch.hub.load_state_dict_from_url(self._weights_url, progress=False) super().__init__("vgg16", layers=lpips_layers, weights=lpips_weights, replace_pooling=replace_pooling, distance=distance, reduction=reduction, mean=mean, std=std, normalize_features=True) class DISTS(ContentLoss): r"""Deep Image Structure and Texture Similarity metric. By default expects input to be in range [0, 1], which is then normalized by ImageNet statistics into range [-1, 1]. If no normalisation is required, change `mean` and `std` values accordingly. Args: reduction: Specifies the reduction type: ``'none'`` | ``'mean'`` | ``'sum'``. Default:``'mean'`` mean: List of float values used for data standardization. Default: ImageNet mean. If there is no need to normalize data, use [0., 0., 0.]. std: List of float values used for data standardization. Default: ImageNet std. If there is no need to normalize data, use [1., 1., 1.]. Examples: >>> loss = DISTS() >>> x = torch.rand(3, 3, 256, 256, requires_grad=True) >>> y = torch.rand(3, 3, 256, 256) >>> output = loss(x, y) >>> output.backward() References: Keyan Ding, Kede Ma, Shiqi Wang, Eero P. Simoncelli (2020). Image Quality Assessment: Unifying Structure and Texture Similarity. https://arxiv.org/abs/2004.07728 https://github.com/dingkeyan93/DISTS """ _weights_url = "https://github.com/photosynthesis-team/piq/releases/download/v0.4.1/dists_weights.pt" def __init__(self, reduction: str = "mean", mean: List[float] = IMAGENET_MEAN, std: List[float] = IMAGENET_STD) -> None: dists_layers = ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'] channels = [3, 64, 128, 256, 512, 512] weights = torch.hub.load_state_dict_from_url(self._weights_url, progress=False) dists_weights = list(torch.split(weights['alpha'], channels, dim=1)) dists_weights.extend(torch.split(weights['beta'], channels, dim=1)) super().__init__("vgg16", layers=dists_layers, weights=dists_weights, replace_pooling=True, reduction=reduction, mean=mean, std=std, normalize_features=False, allow_layers_weights_mismatch=True) def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: r""" Args: x: An input tensor. Shape :math:`(N, C, H, W)`. y: A target tensor. Shape :math:`(N, C, H, W)`. Returns: Deep Image Structure and Texture Similarity loss, i.e. ``1-DISTS`` in range [0, 1]. """ _, _, H, W = x.shape if min(H, W) > 256: x = torch.nn.functional.interpolate( x, scale_factor=256 / min(H, W), recompute_scale_factor=False, mode='bilinear') y = torch.nn.functional.interpolate( y, scale_factor=256 / min(H, W), recompute_scale_factor=False, mode='bilinear') loss = super().forward(x, y) return 1 - loss def compute_distance(self, x_features: torch.Tensor, y_features: torch.Tensor) -> List[torch.Tensor]: r"""Compute structure similarity between feature maps Args: x_features: Features of the input tensor. y_features: Features of the target tensor. Returns: Structural similarity distance between feature maps """ structure_distance, texture_distance = [], [] # Small constant for numerical stability EPS = 1e-6 for x, y in zip(x_features, y_features): x_mean = x.mean([2, 3], keepdim=True) y_mean = y.mean([2, 3], keepdim=True)
structure_distance.append(similarity_map(x_mean, y_mean, constant=EPS))
2
2023-10-13 06:06:12+00:00
8k
Anonoei/klipper_auto_speed
autospeed/main.py
[ { "identifier": "calculate_graph", "path": "autospeed/funcs.py", "snippet": "def calculate_graph(velocity: float, slope: int):\n return (10000/(velocity/slope))" }, { "identifier": "calculate_accel", "path": "autospeed/funcs.py", "snippet": "def calculate_accel(veloc: float, travel: f...
import os import datetime as dt import matplotlib.pyplot as plt # this may fail if matplotlib isn't installed from time import perf_counter from .funcs import calculate_graph, calculate_accel, calculate_velocity from .move import Move, MoveX, MoveY, MoveZ, MoveDiagX, MoveDiagY from .wrappers import ResultsWrapper, AttemptWrapper
5,473
start = perf_counter() # Level the printer if it's not leveled self._level(gcmd) self._move([self.axis_limits["x"]["center"], self.axis_limits["y"]["center"], self.axis_limits["z"]["center"]], self.th_veloc) self._variance(gcmd) return perf_counter() - start def _level(self, gcmd): level = gcmd.get_int('LEVEL', 1, minval=0, maxval=1) if level == 0: return if self.level is None: return lookup = None name = None if self.level == "STA": lookup = "screw_tilt_adjust" name = "SCREWS_TILT_CALCULATE" elif self.level == "ZT": lookup = "z_tilt" name = "Z_TILT_ADJUST" elif self.level == "QGL": lookup = "quad_gantry_level" name = "QUAD_GANTRY_LEVEL" else: raise gcmd.error(f"Unknown leveling method '{self.level}'.") lm = self.printer.lookup_object(lookup) if lm.z_status.applied is False: self.gcode.respond_info(f"AUTO SPEED leveling with {name}...") self.gcode._process_commands([name], False) if lm.z_status.applied is False: raise gcmd.error(f"Failed to level printer! Please manually ensure your printer is level.") def _variance(self, gcmd): variance = gcmd.get_int('VARIANCE', 1, minval=0, maxval=1) max_missed = gcmd.get_float('MAX_MISSED', self.max_missed, above=0.0) endstop_samples = gcmd.get_int('ENDSTOP_SAMPLES', self.endstop_samples, minval=2) settling_home = gcmd.get_int("SETTLING_HOME", default=self.settling_home, minval=0, maxval=1) if variance == 0: return self.gcode.respond_info(f"AUTO SPEED checking endstop variance over {endstop_samples} samples") if settling_home: self.toolhead.wait_moves() self._home(True, True, False) axes = self._parse_axis(gcmd.get("AXIS", self._axis_to_str(self.axes))) check_x = 'x' in axes if self.isolate_xy else True check_y = 'y' in axes if self.isolate_xy else True # Check endstop variance endstops = self._endstop_variance(endstop_samples, x=check_x, y=check_y) x_max = max(endstops["x"]) if check_x else 0 y_max = max(endstops["y"]) if check_y else 0 self.gcode.respond_info(f"AUTO SPEED endstop variance:\nMissed X:{x_max:.2f} steps, Y:{y_max:.2f} steps") if x_max >= max_missed or y_max >= max_missed: raise gcmd.error(f"Please increase MAX_MISSED (currently {max_missed}), or tune your steppers/homing macro.") # ------------------------------------------------------- # # Internal Methods # # ------------------------------------------------------- def _parse_axis(self, raw_axes): raw_axes = raw_axes.lower() raw_axes = raw_axes.replace(" ", "") raw_axes = raw_axes.split(',') axes = [] for axis in raw_axes: if axis in self.valid_axes: axes.append(axis) return axes def _axis_to_str(self, raw_axes): axes = "" for axis in raw_axes: axes += f"{axis}," axes = axes[:-1] return axes def init_axis(self, aw: AttemptWrapper, axis): aw.axis = axis if axis == "diag_x": aw.move = MoveDiagX() elif axis == "diag_y": aw.move = MoveDiagY() elif axis == "x": aw.move = MoveX() elif axis == "y": aw.move = MoveY() elif axis == "z": aw.move = MoveZ() aw.move.Init(self.axis_limits, aw.margin, self.isolate_xy) def binary_search(self, aw: AttemptWrapper): aw.time_start = perf_counter() m_min = aw.min m_max = aw.max m_var = m_min + (m_max-m_min) // 3 if aw.veloc == 0.0: aw.veloc = 1.0 if aw.accel == 0.0: aw.accel = 1.0 if aw.type in ("accel", "graph"): # stat is velocity, var is accel m_stat = aw.veloc o_veloc = aw.veloc if o_veloc == 1.0:
# Find your printers max speed before losing steps # # Copyright (C) 2024 Anonoei <dev@anonoei.com> # # This file may be distributed under the terms of the MIT license. class AutoSpeed: def __init__(self, config): self.config = config self.printer = config.get_printer() self.gcode = self.printer.lookup_object('gcode') self.gcode_move = self.printer.load_object(config, 'gcode_move') self.printer_kinematics = self.config.getsection("printer").get("kinematics") self.isolate_xy = self.printer_kinematics == 'cartesian' or self.printer_kinematics == 'corexz' self.valid_axes = ["x", "y", "diag_x", "diag_y", "z"] self.axes = self._parse_axis(config.get('axis', 'x, y' if self.isolate_xy else 'diag_x, diag_y')) self.default_axes = '' for axis in self.axes: self.default_axes += f"{axis}," self.default_axes = self.default_axes[:-1] self.margin = config.getfloat( 'margin', default=20.0, above=0.0) self.settling_home = config.getboolean('settling_home', default=True) self.max_missed = config.getfloat( 'max_missed', default=1.0) self.endstop_samples = config.getint( 'endstop_samples', default=3, minval=2) self.accel_min = config.getfloat('accel_min', default=1000.0, above=1.0) self.accel_max = config.getfloat('accel_max', default=100000.0, above=self.accel_min) self.accel_accu = config.getfloat('accel_accu', default=0.05, above=0.0, below=1.0) self.veloc_min = config.getfloat('velocity_min', default=50.0, above=1.0) self.veloc_max = config.getfloat('velocity_max', default=5000.0, above=self.veloc_min) self.veloc_accu = config.getfloat('velocity_accu', default=0.05, above=0.0, below=1.0) self.derate = config.getfloat('derate', default=0.8, above=0.0, below=1.0) self.validate_margin = config.getfloat('validate_margin', default=self.margin, above=0.0) self.validate_inner_margin = config.getfloat('validate_inner_margin', default=20.0, above=0.0) self.validate_iterations = config.getint( 'validate_iterations', default=50, minval=1) for path in ( # Could be problematic if neither of these paths work os.path.dirname(self.printer.start_args['log_file']), os.path.expanduser('~/printer_data/config') ): if os.path.exists(path): results_default = path self.results_dir = config.get('results_dir',default=results_default) self.toolhead = None self.printer.register_event_handler("klippy:connect", self.handle_connect) self.printer.register_event_handler("homing:home_rails_end", self.handle_home_rails_end) self.gcode.register_command('AUTO_SPEED', self.cmd_AUTO_SPEED, desc=self.cmd_AUTO_SPEED_help) self.gcode.register_command('AUTO_SPEED_VELOCITY', self.cmd_AUTO_SPEED_VELOCITY, desc=self.cmd_AUTO_SPEED_VELOCITY_help) self.gcode.register_command('AUTO_SPEED_ACCEL', self.cmd_AUTO_SPEED_ACCEL, desc=self.cmd_AUTO_SPEED_ACCEL_help) self.gcode.register_command('AUTO_SPEED_VALIDATE', self.cmd_AUTO_SPEED_VALIDATE, desc=self.cmd_AUTO_SPEED_VALIDATE_help) self.gcode.register_command('AUTO_SPEED_GRAPH', self.cmd_AUTO_SPEED_GRAPH, desc=self.cmd_AUTO_SPEED_GRAPH_help) self.level = None self.steppers = {} self.axis_limits = {} def handle_connect(self): self.toolhead = self.printer.lookup_object('toolhead') # Reduce speed/acceleration for positioning movement self.th_accel = self.toolhead.max_accel/2 self.th_veloc = self.toolhead.max_velocity/2 # Find and define leveling method if self.printer.lookup_object("screw_tilt_adjust", None) is not None: self.level = "STA" elif self.printer.lookup_object("z_tilt", None) is not None: self.level= "ZT" elif self.printer.lookup_object("quad_gantry_level", None) is not None: self.level = "QGL" else: self.level = None def handle_home_rails_end(self, homing_state, rails): # Get axis min/max values # Get stepper microsteps if not len(self.steppers.keys()) == 3: for rail in rails: pos_min, pos_max = rail.get_range() for stepper in rail.get_steppers(): name = stepper._name # microsteps = (stepper._steps_per_rotation / full_steps / gearing) if name in ["stepper_x", "stepper_y", "stepper_z"]: config = self.printer.lookup_object('configfile').status_raw_config[name] microsteps = int(config["microsteps"]) self.steppers[name[-1]] = [pos_min, pos_max, microsteps] if self.steppers.get("x", None) is not None: self.axis_limits["x"] = { "min": self.steppers["x"][0], "max": self.steppers["x"][1], "center": (self.steppers["x"][0] + self.steppers["x"][1]) / 2, "dist": self.steppers["x"][1] - self.steppers["x"][0], "home": self.gcode_move.homing_position[0] } if self.steppers.get("y", None) is not None: self.axis_limits["y"] = { "min": self.steppers["y"][0], "max": self.steppers["y"][1], "center": (self.steppers["y"][0] + self.steppers["y"][1]) / 2, "dist": self.steppers["y"][1] - self.steppers["y"][0], "home": self.gcode_move.homing_position[1] } if self.steppers.get("z", None) is not None: self.axis_limits["z"] = { "min": self.steppers["z"][0], "max": self.steppers["z"][1], "center": (self.steppers["z"][0] + self.steppers["z"][1]) / 2, "dist": self.steppers["z"][1] - self.steppers["z"][0], "home": self.gcode_move.homing_position[2] } cmd_AUTO_SPEED_help = ("Automatically find your printer's maximum acceleration/velocity") def cmd_AUTO_SPEED(self, gcmd): if not len(self.steppers.keys()) == 3: raise gcmd.error(f"Printer must be homed first! Found {len(self.steppers.keys())} homed axes.") validate = gcmd.get_int('VALIDATE', 0, minval=0, maxval=1) self._prepare(gcmd) # Make sure the printer is level, [check endstop variance] start = perf_counter() accel_results = self.cmd_AUTO_SPEED_ACCEL(gcmd) veloc_results = self.cmd_AUTO_SPEED_VELOCITY(gcmd) respond = f"AUTO SPEED found recommended acceleration and velocity after {perf_counter() - start:.2f}s\n" for axis in self.valid_axes: aR = accel_results.vals.get(axis, None) vR = veloc_results.vals.get(axis, None) if aR is not None or vR is not None: respond += f"| {axis.replace('_', ' ').upper()} max:" if aR is not None: respond += f" a{aR:.0f}" if vR is not None: respond += f" v{vR:.0f}" respond += "\n" respond += f"Recommended accel: {accel_results.vals['rec']:.0f}\n" respond += f"Recommended velocity: {veloc_results.vals['rec']:.0f}\n" self.gcode.respond_info(respond) if validate: gcmd._params["ACCEL"] = accel_results.vals['rec'] gcmd._params["VELOCITY"] = veloc_results.vals['rec'] self.cmd_AUTO_SPEED_VALIDATE(gcmd) cmd_AUTO_SPEED_ACCEL_help = ("Automatically find your printer's maximum acceleration") def cmd_AUTO_SPEED_ACCEL(self, gcmd): if not len(self.steppers.keys()) == 3: raise gcmd.error(f"Printer must be homed first! Found {len(self.steppers.keys())} homed axes.") axes = self._parse_axis(gcmd.get("AXIS", self._axis_to_str(self.axes))) margin = gcmd.get_float("MARGIN", self.margin, above=0.0) derate = gcmd.get_float('DERATE', self.derate, above=0.0, below=1.0) max_missed = gcmd.get_float('MAX_MISSED', self.max_missed, above=0.0) accel_min = gcmd.get_float('ACCEL_MIN', self.accel_min, above=1.0) accel_max = gcmd.get_float('ACCEL_MAX', self.accel_max, above=accel_min) accel_accu = gcmd.get_float('ACCEL_ACCU', self.accel_accu, above=0.0, below=1.0) veloc = gcmd.get_float('VELOCITY', 1.0, above=1.0) respond = "AUTO SPEED finding maximum acceleration on" for axis in axes: respond += f" {axis.upper().replace('_', ' ')}," self.gcode.respond_info(respond[:-1]) rw = ResultsWrapper() start = perf_counter() for axis in axes: aw = AttemptWrapper() aw.type = "accel" aw.accuracy = accel_accu aw.max_missed = max_missed aw.margin = margin aw.min = accel_min aw.max = accel_max aw.veloc = veloc self.init_axis(aw, axis) rw.vals[aw.axis] = self.binary_search(aw) rw.duration = perf_counter() - start rw.name = "acceleration" respond = f"AUTO SPEED found maximum acceleration after {rw.duration:.2f}s\n" for axis in self.valid_axes: if rw.vals.get(axis, None) is not None: respond += f"| {axis.replace('_', ' ').upper()} max: {rw.vals[axis]:.0f}\n" respond += f"\n" rw.derate(derate) respond += f"Recommended values:\n" for axis in self.valid_axes: if rw.vals.get(axis, None) is not None: respond += f"| {axis.replace('_', ' ').upper()} max: {rw.vals[axis]:.0f}\n" respond += f"Recommended acceleration: {rw.vals['rec']:.0f}\n" self.gcode.respond_info(respond) return rw cmd_AUTO_SPEED_VELOCITY_help = ("Automatically find your printer's maximum velocity") def cmd_AUTO_SPEED_VELOCITY(self, gcmd): if not len(self.steppers.keys()) == 3: raise gcmd.error(f"Printer must be homed first! Found {len(self.steppers.keys())} homed axes.") axes = self._parse_axis(gcmd.get("AXIS", self._axis_to_str(self.axes))) margin = gcmd.get_float("MARGIN", self.margin, above=0.0) derate = gcmd.get_float('DERATE', self.derate, above=0.0, below=1.0) max_missed = gcmd.get_float('MAX_MISSED', self.max_missed, above=0.0) veloc_min = gcmd.get_float('VELOCITY_MIN', self.veloc_min, above=1.0) veloc_max = gcmd.get_float('VELOCITY_MAX', self.veloc_max, above=veloc_min) veloc_accu = gcmd.get_float('VELOCITY_ACCU', self.veloc_accu, above=0.0, below=1.0) accel = gcmd.get_float('ACCEL', 1.0, above=1.0) respond = "AUTO SPEED finding maximum velocity on" for axis in axes: respond += f" {axis.upper().replace('_', ' ')}," self.gcode.respond_info(respond[:-1]) rw = ResultsWrapper() start = perf_counter() for axis in axes: aw = AttemptWrapper() aw.type = "velocity" aw.accuracy = veloc_accu aw.max_missed = max_missed aw.margin = margin aw.min = veloc_min aw.max = veloc_max aw.accel = accel self.init_axis(aw, axis) rw.vals[aw.axis] = self.binary_search(aw) rw.duration = perf_counter() - start rw.name = "velocity" respond = f"AUTO SPEED found maximum velocity after {rw.duration:.2f}s\n" for axis in self.valid_axes: if rw.vals.get(axis, None) is not None: respond += f"| {axis.replace('_', ' ').upper()} max: {rw.vals[axis]:.0f}\n" respond += "\n" rw.derate(derate) respond += f"Recommended values\n" for axis in self.valid_axes: if rw.vals.get(axis, None) is not None: respond += f"| {axis.replace('_', ' ').upper()} max: {rw.vals[axis]:.0f}\n" respond += f"Recommended velocity: {rw.vals['rec']:.0f}\n" self.gcode.respond_info(respond) return rw cmd_AUTO_SPEED_VALIDATE_help = ("Validate your printer's acceleration/velocity don't miss steps") def cmd_AUTO_SPEED_VALIDATE(self, gcmd): if not len(self.steppers.keys()) == 3: raise gcmd.error(f"Printer must be homed first! Found {len(self.steppers.keys())} homed axes.") max_missed = gcmd.get_float('MAX_MISSED', self.max_missed, above=0.0) margin = gcmd.get_float('VALIDATE_MARGIN', default=self.validate_margin, above=0.0) small_margin = gcmd.get_float('VALIDATE_INNER_MARGIN', default=self.validate_inner_margin, above=0.0) iterations = gcmd.get_int('VALIDATE_ITERATIONS', default=self.validate_iterations, minval=1) accel = gcmd.get_float('ACCEL', default=self.toolhead.max_accel, above=0.0) veloc = gcmd.get_float('VELOCITY', default=self.toolhead.max_velocity, above=0.0) respond = f"AUTO SPEED validating over {iterations} iterations\n" respond += f"Acceleration: {accel:.0f}\n" respond += f"Velocity: {veloc:.0f}" self.gcode.respond_info(respond) self._set_velocity(veloc, accel) valid, duration, missed_x, missed_y = self._validate(veloc, iterations, margin, small_margin, max_missed) respond = f"AUTO SPEED validated results after {duration:.2f}s\n" respond += f"Valid: {valid}\n" respond += f"Missed X {missed_x:.2f}, Y {missed_y:.2f}" self.gcode.respond_info(respond) return valid cmd_AUTO_SPEED_GRAPH_help = ("Graph your printer's maximum acceleration at given velocities") def cmd_AUTO_SPEED_GRAPH(self, gcmd): if not len(self.steppers.keys()) == 3: raise gcmd.error(f"Printer must be homed first! Found {len(self.steppers.keys())} homed axes.") axes = self._parse_axis(gcmd.get("AXIS", self._axis_to_str(self.axes))) margin = gcmd.get_float("MARGIN", self.margin, above=0.0) derate = gcmd.get_float('DERATE', self.derate, above=0.0, below=1.0) max_missed = gcmd.get_float('MAX_MISSED', self.max_missed, above=0.0) veloc_min = gcmd.get_float('VELOCITY_MIN', 200.0, above=0.0) veloc_max = gcmd.get_float('VELOCITY_MAX', 700.0, above=veloc_min) veloc_div = gcmd.get_int( 'VELOCITY_DIV', 5, minval=0) accel_accu = gcmd.get_float('ACCEL_ACCU', 0.05, above=0.0, below=1.0) accel_min_slope = gcmd.get_int('ACCEL_MIN_SLOPE', 100, minval=0) accel_max_slope = gcmd.get_int('ACCEL_MAX_SLOPE', 1800, minval=accel_min_slope) veloc_step = (veloc_max - veloc_min)//(veloc_div - 1) velocs = [round((v * veloc_step) + veloc_min) for v in range(0, veloc_div)] respond = "AUTO SPEED graphing maximum accel from velocities on" for axis in axes: respond += f" {axis.upper().replace('_', ' ')}," respond = respond[:-1] + "\n" respond += f"V_MIN: {veloc_min}, V_MAX: {veloc_max}, V_STEP: {veloc_step}\n" self.gcode.respond_info(respond) aw = AttemptWrapper() aw.type = "graph" aw.accuracy = accel_accu aw.max_missed = max_missed aw.margin = margin for axis in axes: start = perf_counter() self.init_axis(aw, axis) accels = [] accel_mins = [] accel_maxs = [] for veloc in velocs: self.gcode.respond_info(f"AUTO SPEED graph {aw.axis} - v{veloc}") aw.veloc = veloc aw.min = round(calculate_graph(veloc, accel_min_slope)) aw.max = round(calculate_graph(veloc, accel_max_slope)) accel_mins.append(aw.min) accel_maxs.append(aw.max) accels.append(self.binary_search(aw)) plt.plot(velocs, accels, 'go-', label='measured') plt.plot(velocs, [a*derate for a in accels], 'g-', label='derated') plt.plot(velocs, accel_mins, 'b--', label='min') plt.plot(velocs, accel_maxs, 'r--', label='max') plt.legend(loc='upper right') plt.title(f"Max accel at velocity on {aw.axis} to {int(accel_accu*100)}% accuracy") plt.xlabel("Velocity") plt.ylabel("Acceleration") filepath = os.path.join( self.results_dir, f"AUTO_SPEED_GRAPH_{dt.datetime.now():%Y-%m-%d_%H:%M:%S}_{aw.axis}.png" ) self.gcode.respond_info(f"Velocs: {velocs}") self.gcode.respond_info(f"Accels: {accels}") self.gcode.respond_info(f"AUTO SPEED graph found max accel on {aw.axis} after {perf_counter() - start:.0f}s\nSaving graph to {filepath}") os.makedirs(self.results_dir, exist_ok=True) plt.savefig(filepath, bbox_inches='tight') plt.close() # ------------------------------------------------------- # # Internal Helpers # # ------------------------------------------------------- def _prepare(self, gcmd): if not len(self.steppers.keys()) == 3: raise gcmd.error(f"Printer must be homed first! Found {len(self.steppers.keys())} homed axes.") start = perf_counter() # Level the printer if it's not leveled self._level(gcmd) self._move([self.axis_limits["x"]["center"], self.axis_limits["y"]["center"], self.axis_limits["z"]["center"]], self.th_veloc) self._variance(gcmd) return perf_counter() - start def _level(self, gcmd): level = gcmd.get_int('LEVEL', 1, minval=0, maxval=1) if level == 0: return if self.level is None: return lookup = None name = None if self.level == "STA": lookup = "screw_tilt_adjust" name = "SCREWS_TILT_CALCULATE" elif self.level == "ZT": lookup = "z_tilt" name = "Z_TILT_ADJUST" elif self.level == "QGL": lookup = "quad_gantry_level" name = "QUAD_GANTRY_LEVEL" else: raise gcmd.error(f"Unknown leveling method '{self.level}'.") lm = self.printer.lookup_object(lookup) if lm.z_status.applied is False: self.gcode.respond_info(f"AUTO SPEED leveling with {name}...") self.gcode._process_commands([name], False) if lm.z_status.applied is False: raise gcmd.error(f"Failed to level printer! Please manually ensure your printer is level.") def _variance(self, gcmd): variance = gcmd.get_int('VARIANCE', 1, minval=0, maxval=1) max_missed = gcmd.get_float('MAX_MISSED', self.max_missed, above=0.0) endstop_samples = gcmd.get_int('ENDSTOP_SAMPLES', self.endstop_samples, minval=2) settling_home = gcmd.get_int("SETTLING_HOME", default=self.settling_home, minval=0, maxval=1) if variance == 0: return self.gcode.respond_info(f"AUTO SPEED checking endstop variance over {endstop_samples} samples") if settling_home: self.toolhead.wait_moves() self._home(True, True, False) axes = self._parse_axis(gcmd.get("AXIS", self._axis_to_str(self.axes))) check_x = 'x' in axes if self.isolate_xy else True check_y = 'y' in axes if self.isolate_xy else True # Check endstop variance endstops = self._endstop_variance(endstop_samples, x=check_x, y=check_y) x_max = max(endstops["x"]) if check_x else 0 y_max = max(endstops["y"]) if check_y else 0 self.gcode.respond_info(f"AUTO SPEED endstop variance:\nMissed X:{x_max:.2f} steps, Y:{y_max:.2f} steps") if x_max >= max_missed or y_max >= max_missed: raise gcmd.error(f"Please increase MAX_MISSED (currently {max_missed}), or tune your steppers/homing macro.") # ------------------------------------------------------- # # Internal Methods # # ------------------------------------------------------- def _parse_axis(self, raw_axes): raw_axes = raw_axes.lower() raw_axes = raw_axes.replace(" ", "") raw_axes = raw_axes.split(',') axes = [] for axis in raw_axes: if axis in self.valid_axes: axes.append(axis) return axes def _axis_to_str(self, raw_axes): axes = "" for axis in raw_axes: axes += f"{axis}," axes = axes[:-1] return axes def init_axis(self, aw: AttemptWrapper, axis): aw.axis = axis if axis == "diag_x": aw.move = MoveDiagX() elif axis == "diag_y": aw.move = MoveDiagY() elif axis == "x": aw.move = MoveX() elif axis == "y": aw.move = MoveY() elif axis == "z": aw.move = MoveZ() aw.move.Init(self.axis_limits, aw.margin, self.isolate_xy) def binary_search(self, aw: AttemptWrapper): aw.time_start = perf_counter() m_min = aw.min m_max = aw.max m_var = m_min + (m_max-m_min) // 3 if aw.veloc == 0.0: aw.veloc = 1.0 if aw.accel == 0.0: aw.accel = 1.0 if aw.type in ("accel", "graph"): # stat is velocity, var is accel m_stat = aw.veloc o_veloc = aw.veloc if o_veloc == 1.0:
aw.accel = calculate_accel(aw.veloc, aw.move.max_dist)
1
2023-10-12 03:25:56+00:00
8k
facebookresearch/SoundingBodies
evaluate.py
[ { "identifier": "build_dataset", "path": "src/datasets/builder.py", "snippet": "def build_dataset(cfg):\n return DATASETS.build(cfg)" }, { "identifier": "TrainerDp", "path": "src/trainer.py", "snippet": "class TrainerDp(Trainer):\n def __init__(self, config, model, dataset, seed, d...
import os import argparse import warnings import torchaudio as ta import datetime import copy from mmcv import Config from src.datasets import build_dataset from src.trainer import TrainerDp from src.utils import set_random_seed from src.models import build_model from src.losses import L2Loss, STFTLoss, PhaseLoss, ShiftedL2Loss
3,950
""" 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. """ warnings.filterwarnings("ignore", message="On January 1, 2023, MMCV will release v2.0.0") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, default="./config/config.py", help="path to the config file") parser.add_argument("-e", "--test_epoch", type=str, default="epoch-100", help="which checkpoint to load") parser.add_argument("-s", "--save", action="store_true", help="whether save the synthesized audio") parser.add_argument("-n", "--out_name", type=str, # default='metrics', default=datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), help="the output filename of metrics") parser.add_argument("--seed", type=int, default=1234, help="set the random seed") args = parser.parse_args() set_random_seed(seed=args.seed, deterministic=False) configs = Config.fromfile(args.config) configs.metric_filename = args.out_name configs.training.audio_outputs = f"{configs.vis_dir}_{args.test_epoch}_{args.out_name}/" configs.training.losses = [ dict(type='AmplitudeLoss', args=dict(sample_rate=48000, mask_beginning=512, mask_end=512), loss_weight=0), dict(type='SDRloss', args=dict(mask_beginning=512, mask_end=512), loss_weight=0), dict(type='PhaseLoss', args=dict(sample_rate=48000, mask_beginning=512, mask_end=512, ignore_below=0.2), loss_weight=0), ] print("Testing on: " + configs.dataset_test.data_info_file) device = 'cuda' model = build_model(configs.model) model.load(configs.output_dir, device, suffix=args.test_epoch) model.eval().to(device) # test a subset of 345 mics at a time to avoid out of memory issues dataset_chunk = configs.dataset_test dataset_chunk.NUM_FORWARD = 23 mics_all = dataset_chunk.dome_inds assert len(mics_all)/dataset_chunk.NUM_FORWARD == int(len(mics_all)/dataset_chunk.NUM_FORWARD) N = int(len(mics_all)/dataset_chunk.NUM_FORWARD) N = 1 errors = [] for mic_chunk in range(N): print('Testing mics subset: ' + str(mic_chunk+1) + '/' + str(N)) dataset_chunk.dome_inds = mics_all[mic_chunk*dataset_chunk.NUM_FORWARD:(mic_chunk+1)*dataset_chunk.NUM_FORWARD]
""" 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. """ warnings.filterwarnings("ignore", message="On January 1, 2023, MMCV will release v2.0.0") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, default="./config/config.py", help="path to the config file") parser.add_argument("-e", "--test_epoch", type=str, default="epoch-100", help="which checkpoint to load") parser.add_argument("-s", "--save", action="store_true", help="whether save the synthesized audio") parser.add_argument("-n", "--out_name", type=str, # default='metrics', default=datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), help="the output filename of metrics") parser.add_argument("--seed", type=int, default=1234, help="set the random seed") args = parser.parse_args() set_random_seed(seed=args.seed, deterministic=False) configs = Config.fromfile(args.config) configs.metric_filename = args.out_name configs.training.audio_outputs = f"{configs.vis_dir}_{args.test_epoch}_{args.out_name}/" configs.training.losses = [ dict(type='AmplitudeLoss', args=dict(sample_rate=48000, mask_beginning=512, mask_end=512), loss_weight=0), dict(type='SDRloss', args=dict(mask_beginning=512, mask_end=512), loss_weight=0), dict(type='PhaseLoss', args=dict(sample_rate=48000, mask_beginning=512, mask_end=512, ignore_below=0.2), loss_weight=0), ] print("Testing on: " + configs.dataset_test.data_info_file) device = 'cuda' model = build_model(configs.model) model.load(configs.output_dir, device, suffix=args.test_epoch) model.eval().to(device) # test a subset of 345 mics at a time to avoid out of memory issues dataset_chunk = configs.dataset_test dataset_chunk.NUM_FORWARD = 23 mics_all = dataset_chunk.dome_inds assert len(mics_all)/dataset_chunk.NUM_FORWARD == int(len(mics_all)/dataset_chunk.NUM_FORWARD) N = int(len(mics_all)/dataset_chunk.NUM_FORWARD) N = 1 errors = [] for mic_chunk in range(N): print('Testing mics subset: ' + str(mic_chunk+1) + '/' + str(N)) dataset_chunk.dome_inds = mics_all[mic_chunk*dataset_chunk.NUM_FORWARD:(mic_chunk+1)*dataset_chunk.NUM_FORWARD]
dataset_test = build_dataset(dataset_chunk)
0
2023-10-13 21:11:40+00:00
8k
LukeForeverYoung/UReader
mplug_owl/modeling_mplug_owl.py
[ { "identifier": "MplugOwlConfig", "path": "mplug_owl/configuration_mplug_owl.py", "snippet": "class MplugOwlConfig(PretrainedConfig):\n r\"\"\"\n [`MplugOwlConfig`] is the configuration class to store the configuration of a [`MplugOwlForConditionalGeneration`].\n It is used to instantiate a mPL...
import math import torch import torch.utils.checkpoint import einops from typing import Any, Optional, Tuple, Union from flash_attn.flash_attn_interface import flash_attn_unpadded_func from dataclasses import dataclass from torch import nn from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling from transformers.modeling_utils import PreTrainedModel from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer from transformers.utils import ( ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from transformers.models.auto import AutoModelForCausalLM from .configuration_mplug_owl import MplugOwlConfig, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig from pipeline.utils import get_args from torch.nn.utils.rnn import pad_sequence from transformers import GenerationConfig
6,256
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MplugOwlConfig`]): 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 [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ MPLUG_OWL_VISION_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ MPLUG_OWL_TEXT_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5 Training](./t5#training). decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ MPLUG_OWL_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for details. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be provided to serve as text prompt, which the language model can continue. Indices can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an encoder-decoder language model (like T5) is used. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. Only relevant in case an encoder-decoder language model (like T5) is used. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ class MplugOwlVisionEncoder(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`MplugOwlVisionEncoderLayer`]. Args: config (`MplugOwlVisionConfig`): The corresponding vision configuration for the `MplugOwlEncoder`. """ def __init__(self, config: MplugOwlVisionConfig): super().__init__() self.config = config
# coding=utf-8 # Copyright 2022 x-plug The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch MplugOwl model.""" try: flash_attn_func = flash_attn_unpadded_func except ImportError: flash_attn_func = None print("install flash-attn first.") logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "MAGAer13/mplug-owl-llama-7b" _CONFIG_FOR_DOC = "MplugOwlConfig" MPLUG_OWL_PRETRAINED_MODEL_ARCHIVE_LIST = [ "MAGAer13/mplug-owl-llama-7b", # See all MplugOwl models at https://huggingface.co/models?filter=mplug_owl ] @dataclass class MplugOwlForConditionalGenerationModelOutput(ModelOutput): """ Class defining the outputs of [`MPlugOwlForConditionalGeneration`]. Args: loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`): Language modeling loss from the language model. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head of the language model. vision_outputs (`BaseModelOutputWithPooling`): Outputs of the vision encoder. language_model_outputs (`CausalLMOutputWithPast` or `Seq2SeqLMOutput`): Outputs of the language model. """ loss: Optional[Tuple[torch.FloatTensor]] = None logits: Optional[Tuple[torch.FloatTensor]] = None vision_outputs: Optional[torch.FloatTensor] = None language_model_outputs: Optional[Tuple[torch.FloatTensor]] = None def to_tuple(self) -> Tuple[Any]: return tuple( self[k] if k not in ["vision_outputs", "language_model_outputs"] else getattr(self, k).to_tuple() for k in self.keys() ) def get_ltor_masks_and_position_ids_from_embeddings(data): """Build masks and position id for left to right model.""" # Extract batch size and sequence length. micro_batch_size, seq_length = data.size()[:2] # Attention mask (lower triangular). att_mask_batch = 1 attention_mask = torch.tril(torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)).view( att_mask_batch, 1, seq_length, seq_length ) # Loss mask. loss_mask = torch.ones(data.size()[:2], dtype=torch.float, device=data.device) # Position ids. position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device) position_ids = position_ids.unsqueeze(0).expand_as(data[..., 0]) # Convert attention mask to binary: attention_mask = attention_mask < 0.5 return attention_mask, loss_mask, position_ids class MplugOwlVisionEmbeddings(nn.Module): def __init__(self, config: MplugOwlVisionConfig): super().__init__() self.config = config self.hidden_size = config.hidden_size self.image_size = config.image_size self.patch_size = config.patch_size self.cls_token = nn.Parameter(torch.randn(1, 1, self.hidden_size)) self.patch_embed = nn.Conv2d( in_channels=3, out_channels=self.hidden_size, kernel_size=self.patch_size, stride=self.patch_size, bias=False, ) self.num_patches = (self.image_size // self.patch_size) ** 2 self.position_embedding = nn.Parameter(torch.randn(1, self.num_patches + 1, self.hidden_size)) self.pre_layernorm = LayerNormFp32(self.hidden_size, eps=config.layer_norm_eps) def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor: batch_size = pixel_values.size(0) image_embeds = self.patch_embed(pixel_values) image_embeds = image_embeds.flatten(2).transpose(1, 2) class_embeds = self.cls_token.expand(batch_size, 1, -1).to(image_embeds.dtype) embeddings = torch.cat([class_embeds, image_embeds], dim=1) embeddings = embeddings + self.position_embedding[:, : embeddings.size(1)].to(image_embeds.dtype) embeddings = self.pre_layernorm(embeddings) return embeddings class LayerNormFp32(nn.LayerNorm): """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back).""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def forward(self, x: torch.Tensor): output = torch.nn.functional.layer_norm( x.float(), self.normalized_shape, self.weight.float() if self.weight is not None else None, self.bias.float() if self.bias is not None else None, self.eps, ) return output.type_as(x) class MplugOwlVisionAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" 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 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} and `num_heads`:" f" {self.num_heads})." ) self.scale = self.head_dim**-0.5 self.dropout = nn.Dropout(config.attention_dropout) self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size) self.dense = nn.Linear(self.hidden_size, self.hidden_size) def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() def forward( self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: """Input shape: Batch x Time x Channel""" bsz, seq_len, embed_dim = hidden_states.size() mixed_qkv = self.query_key_value(hidden_states) mixed_qkv = mixed_qkv.reshape(bsz, seq_len, self.num_heads, 3, embed_dim // self.num_heads).permute( 3, 0, 2, 1, 4 ) # [3, b, np, sq, hn] query_states, key_states, value_states = ( mixed_qkv[0], mixed_qkv[1], mixed_qkv[2], ) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2)) attention_scores = attention_scores * self.scale # Normalize the attention scores to probabilities. attention_probs = torch.softmax(attention_scores, dim=-1) # 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_states).permute(0, 2, 1, 3) new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size,) context_layer = context_layer.reshape(new_context_layer_shape) output = self.dense(context_layer) outputs = (output, attention_probs) if output_attentions else (output, None) return outputs class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x) class MplugOwlMLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.activation_fn = QuickGELU() self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.fc1(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states = self.fc2(hidden_states) return hidden_states class MplugOwlVisionEncoderLayer(nn.Module): def __init__(self, config: MplugOwlVisionConfig): super().__init__() self.hidden_size = config.hidden_size self.self_attn = MplugOwlVisionAttention(config) self.input_layernorm = LayerNormFp32(self.hidden_size, eps=config.layer_norm_eps) self.mlp = MplugOwlMLP(config) self.post_attention_layernorm = LayerNormFp32(self.hidden_size, eps=config.layer_norm_eps) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: Optional[bool] = False, ) -> Tuple[torch.FloatTensor]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. `(config.encoder_attention_heads,)`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states hidden_states = self.input_layernorm(hidden_states) hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, head_mask=attention_mask, output_attentions=output_attentions, ) hidden_states = hidden_states + residual residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = hidden_states + residual outputs = (hidden_states,) if output_attentions: outputs += (attn_weights,) return outputs class MplugOwlPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = MplugOwlConfig base_model_prefix = "mplug_owl" supports_gradient_checkpointing = True _keys_to_ignore_on_load_missing = [ r"position_ids", r"language_model.encoder.embed_tokens.weight", r"language_model.decoder.embed_tokens.weight", r"language_model.lm_head.weight", ] _no_split_modules = [ "MplugOwlVisionEncoderLayer", "LlamaDecoderLayer", "MplugOwlVisualAbstractorLayer", "LlamaForCausalLM", "Parameter", ] _keep_in_fp32_modules = ["wo"] def _init_weights(self, module): """Initialize the weights""" factor = self.config.initializer_range if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=factor) if hasattr(module, "bias") and module.bias is not None: module.bias.data.zero_() if isinstance(module, MplugOwlVisionEmbeddings): if hasattr(self.config, "vision_config"): factor = self.config.vision_config.initializer_range nn.init.trunc_normal_(module.position_embedding, mean=0.0, std=factor) nn.init.trunc_normal_(module.cls_token, mean=0.0, std=factor) elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) elif isinstance(module, nn.Linear) and module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Parameter): raise ValueError nn.init.trunc_normal_(module.data, mean=0.0, std=factor) def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, MplugOwlVisionEncoder): module.gradient_checkpointing = value MPLUG_OWL_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MplugOwlConfig`]): 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 [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ MPLUG_OWL_VISION_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ MPLUG_OWL_TEXT_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5 Training](./t5#training). decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ MPLUG_OWL_INPUTS_DOCSTRING = r""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for details. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of input sequence tokens in the vocabulary of the language model. Input tokens can optionally be provided to serve as text prompt, which the language model can continue. Indices can be obtained using [`MplugOwlProcessor`]. See [`MplugOwlProcessor.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary of the language model. Only relevant in case an encoder-decoder language model (like T5) is used. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. Only relevant in case an encoder-decoder language model (like T5) is used. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ class MplugOwlVisionEncoder(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`MplugOwlVisionEncoderLayer`]. Args: config (`MplugOwlVisionConfig`): The corresponding vision configuration for the `MplugOwlEncoder`. """ def __init__(self, config: MplugOwlVisionConfig): super().__init__() self.config = config
args = get_args()
3
2023-10-08 06:29:02+00:00
8k
ChenyangGao/web-mount-packs
python-115-share-link-webdav/util/pan115_sharelink_dav_provider.py
[ { "identifier": "BadRequest", "path": "python-115-share-link-webdav/util/pan115.py", "snippet": "class BadRequest(ValueError):\n ..." }, { "identifier": "LoginError", "path": "python-115-share-link-webdav/util/pan115.py", "snippet": "class LoginError(Exception):\n ..." }, { ...
from hashlib import md5 from posixpath import join as joinpath, normpath from weakref import WeakValueDictionary from wsgidav.dav_error import HTTP_FORBIDDEN, DAVError # type: ignore from wsgidav.dav_provider import DAVCollection, DAVNonCollection, DAVProvider # type: ignore from wsgidav.util import get_module_logger # type: ignore from yaml import load as yaml_load, Loader as yaml_Loader # NEED: pip install types-PyYAML from .pan115 import BadRequest, LoginError, Pan115Client, Pan115ShareLinkFileSystem from .watch_links import WatchMultiFileEventHandler from os import execl from sys import executable, argv import wsgidav.wsgidav_app # type: ignore # It must be imported first!!!
7,176
def __init__( self, /, path: str, environ: dict, share_link_fs, filepath: str, ): super().__init__(path, environ) self.share_link_fs = share_link_fs self.filepath = filepath self.attr = attr = share_link_fs.attr(filepath) self.name = attr["name"] self.time = int(attr["time"].timestamp()) def get_creation_date(self): return self.time def get_display_name(self): return self.name def get_directory_info(self): return None def get_etag(self): return None def get_last_modified(self): return self.time def get_member_names(self) -> list[str]: return self.share_link_fs.listdir(self.filepath) def get_member(self, name: str) -> FileResource | FolderResource: share_link_fs = self.share_link_fs filepath = joinpath(self.filepath, name) path = joinpath(self.path, name) if share_link_fs.isdir(filepath): return FolderResource(path, self.environ, share_link_fs, filepath) else: return FileResource(path, self.environ, share_link_fs, filepath) def is_link(self, /): return False class RootResource(DAVCollection): def __init__( self, /, path: str, environ: dict, share_link_fs, ): super().__init__(path, environ) self.share_link_fs = share_link_fs self.time = None if isinstance(share_link_fs, Pan115ShareLinkFileSystem): shareinfo = share_link_fs.__dict__.get("shareinfo") if shareinfo: self.time = int(shareinfo["create_time"]) def get_creation_date(self): return self.time def get_last_modified(self): return self.time def get_member_names(self): share_link_fs = self.share_link_fs if type(share_link_fs) is dict: return list(share_link_fs) if share_link_fs is None: _logger.warn(f"{self.path!r} :: the corresponding link is not available") return [] try: share_link_fs.shareinfo except BadRequest as e: _logger.error(f"{self.path!r} :: {type(e).__qualname__}: {e}") raise DAVError(HTTP_FORBIDDEN, e) return share_link_fs.listdir("/") def get_member( self, /, name: str, ) -> None | RootResource | FileResource | FolderResource: share_link_fs = self.share_link_fs path = joinpath(self.path, name) if type(share_link_fs) is dict: if name not in share_link_fs: return None return RootResource(path, self.environ, share_link_fs[name]) if share_link_fs is None: _logger.warn(f"{self.path!r} :: the corresponding link is not available") return None try: share_link_fs.shareinfo except BadRequest as e: _logger.error(f"{self.path!r} :: {type(e).__qualname__}: {e}") raise DAVError(HTTP_FORBIDDEN, e) filepath = "/" + name if share_link_fs.isdir(filepath): return FolderResource(path, self.environ, share_link_fs, filepath) else: return FileResource(path, self.environ, share_link_fs, filepath) def is_link(self, /): return False class Pan115ShareLinkFilesystemProvider(DAVProvider): def __init__(self, /, share_link_fs): super().__init__() self.share_link_fs = share_link_fs @classmethod def from_config(cls, cookie_or_client, config_text: bytes | str, /):
#!/usr/bin/env python # coding: utf-8 from __future__ import annotations __author__ = "ChenyangGao <https://chenyanggao.github.io/>" __all__ = ["Pan115ShareLinkFilesystemProvider"] _logger = get_module_logger(__name__) class FileResource(DAVNonCollection): def __init__( self, /, path: str, environ: dict, share_link_fs, filepath: str, ): super().__init__(path, environ) self.share_link_fs = share_link_fs self.filepath = filepath self.attr = attr = share_link_fs.attr(filepath) self.name = attr["name"] self.size = attr["size"] self.time = int(attr["time"].timestamp()) def get_content_length(self): return self.size def get_creation_date(self): return self.time def get_display_name(self): return self.name def get_etag(self): return "%s-%s-%s" % ( md5(bytes(self.filepath, "utf-8")).hexdigest(), self.time, self.size, ) def get_last_modified(self): return self.time def support_etag(self): return True def support_ranges(self): return True def get_content(self): return self.share_link_fs.open(self.filepath, "rb") def is_link(self, /): return False class FolderResource(DAVCollection): def __init__( self, /, path: str, environ: dict, share_link_fs, filepath: str, ): super().__init__(path, environ) self.share_link_fs = share_link_fs self.filepath = filepath self.attr = attr = share_link_fs.attr(filepath) self.name = attr["name"] self.time = int(attr["time"].timestamp()) def get_creation_date(self): return self.time def get_display_name(self): return self.name def get_directory_info(self): return None def get_etag(self): return None def get_last_modified(self): return self.time def get_member_names(self) -> list[str]: return self.share_link_fs.listdir(self.filepath) def get_member(self, name: str) -> FileResource | FolderResource: share_link_fs = self.share_link_fs filepath = joinpath(self.filepath, name) path = joinpath(self.path, name) if share_link_fs.isdir(filepath): return FolderResource(path, self.environ, share_link_fs, filepath) else: return FileResource(path, self.environ, share_link_fs, filepath) def is_link(self, /): return False class RootResource(DAVCollection): def __init__( self, /, path: str, environ: dict, share_link_fs, ): super().__init__(path, environ) self.share_link_fs = share_link_fs self.time = None if isinstance(share_link_fs, Pan115ShareLinkFileSystem): shareinfo = share_link_fs.__dict__.get("shareinfo") if shareinfo: self.time = int(shareinfo["create_time"]) def get_creation_date(self): return self.time def get_last_modified(self): return self.time def get_member_names(self): share_link_fs = self.share_link_fs if type(share_link_fs) is dict: return list(share_link_fs) if share_link_fs is None: _logger.warn(f"{self.path!r} :: the corresponding link is not available") return [] try: share_link_fs.shareinfo except BadRequest as e: _logger.error(f"{self.path!r} :: {type(e).__qualname__}: {e}") raise DAVError(HTTP_FORBIDDEN, e) return share_link_fs.listdir("/") def get_member( self, /, name: str, ) -> None | RootResource | FileResource | FolderResource: share_link_fs = self.share_link_fs path = joinpath(self.path, name) if type(share_link_fs) is dict: if name not in share_link_fs: return None return RootResource(path, self.environ, share_link_fs[name]) if share_link_fs is None: _logger.warn(f"{self.path!r} :: the corresponding link is not available") return None try: share_link_fs.shareinfo except BadRequest as e: _logger.error(f"{self.path!r} :: {type(e).__qualname__}: {e}") raise DAVError(HTTP_FORBIDDEN, e) filepath = "/" + name if share_link_fs.isdir(filepath): return FolderResource(path, self.environ, share_link_fs, filepath) else: return FileResource(path, self.environ, share_link_fs, filepath) def is_link(self, /): return False class Pan115ShareLinkFilesystemProvider(DAVProvider): def __init__(self, /, share_link_fs): super().__init__() self.share_link_fs = share_link_fs @classmethod def from_config(cls, cookie_or_client, config_text: bytes | str, /):
def make_share_link_fs(client: Pan115Client, config):
2
2023-10-14 03:23:09+00:00
8k
hanxi/xiaomusic
xiaomusic/cli.py
[ { "identifier": "Config", "path": "xiaomusic/config.py", "snippet": "class Config:\n hardware: str = os.getenv(\"MI_HARDWARE\", \"L07A\")\n account: str = os.getenv(\"MI_USER\", \"\")\n password: str = os.getenv(\"MI_PASS\", \"\")\n mi_did: str = os.getenv(\"MI_DID\", \"\")\n mute_xiaoai:...
import argparse import asyncio from xiaomusic.config import Config from xiaomusic.xiaomusic import XiaoMusic
4,380
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--hardware", dest="hardware", help="小爱 hardware", ) parser.add_argument( "--account", dest="account", help="xiaomi account", ) parser.add_argument( "--password", dest="password", help="xiaomi password", ) parser.add_argument( "--cookie", dest="cookie", help="xiaomi cookie", ) parser.add_argument( "--use_command", dest="use_command", action="store_true", default=None, help="use command to tts", ) parser.add_argument( "--mute_xiaoai", dest="mute_xiaoai", action="store_true", default=None, help="try to mute xiaoai answer", ) parser.add_argument( "--verbose", dest="verbose", action="store_true", default=None, help="show info", ) parser.add_argument( "--config", dest="config", help="config file path", ) options = parser.parse_args() config = Config.from_options(options)
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--hardware", dest="hardware", help="小爱 hardware", ) parser.add_argument( "--account", dest="account", help="xiaomi account", ) parser.add_argument( "--password", dest="password", help="xiaomi password", ) parser.add_argument( "--cookie", dest="cookie", help="xiaomi cookie", ) parser.add_argument( "--use_command", dest="use_command", action="store_true", default=None, help="use command to tts", ) parser.add_argument( "--mute_xiaoai", dest="mute_xiaoai", action="store_true", default=None, help="try to mute xiaoai answer", ) parser.add_argument( "--verbose", dest="verbose", action="store_true", default=None, help="show info", ) parser.add_argument( "--config", dest="config", help="config file path", ) options = parser.parse_args() config = Config.from_options(options)
xiaomusic = XiaoMusic(config)
1
2023-10-14 11:39:58+00:00
8k
LeapLabTHU/Rank-DETR
projects/deta/modeling/deformable_transformer.py
[ { "identifier": "MultiScaleDeformableAttention", "path": "detrex/layers/multi_scale_deform_attn.py", "snippet": "class MultiScaleDeformableAttention(nn.Module):\n \"\"\"Multi-Scale Deformable Attention Module used in Deformable-DETR\n\n `Deformable DETR: Deformable Transformers for End-to-End Obje...
import math import torch import torch.nn as nn from detectron2.layers.nms import batched_nms from detrex.layers import ( FFN, BaseTransformerLayer, MultiheadAttention, MultiScaleDeformableAttention, TransformerLayerSequence, box_cxcywh_to_xyxy ) from detrex.utils import inverse_sigmoid
6,864
# coding=utf-8 # Copyright 2022 The IDEA Authors. 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. class DeformableDetrTransformerEncoder(TransformerLayerSequence): def __init__( self, embed_dim: int = 256, num_heads: int = 8, feedforward_dim: int = 1024, attn_dropout: float = 0.1, ffn_dropout: float = 0.1, num_layers: int = 6, post_norm: bool = False, num_feature_levels: int = 4, ): super(DeformableDetrTransformerEncoder, self).__init__(
# coding=utf-8 # Copyright 2022 The IDEA Authors. 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. class DeformableDetrTransformerEncoder(TransformerLayerSequence): def __init__( self, embed_dim: int = 256, num_heads: int = 8, feedforward_dim: int = 1024, attn_dropout: float = 0.1, ffn_dropout: float = 0.1, num_layers: int = 6, post_norm: bool = False, num_feature_levels: int = 4, ): super(DeformableDetrTransformerEncoder, self).__init__(
transformer_layers=BaseTransformerLayer(
2
2023-10-12 03:02:25+00:00
8k
SinonApp/cansleep
tools/snapshot.py
[ { "identifier": "RTSPClient", "path": "connectors/rtsp.py", "snippet": "class RTSPClient:\n __slots__ = (\n \"ip\",\n \"port\",\n \"credentials\",\n \"routes\",\n \"status\",\n \"auth_method\",\n \"last_error\",\n \"realm\",\n \"nonce\",\...
from connectors.rtsp import RTSPClient, rtsp_connect from tools.utils import escape_chars from connectors.dahua import DahuaController from connectors.hikvision import HikClient import time import os import av
4,096
def _is_video_stream(stream): return ( stream.profile is not None and stream.start_time is not None and stream.codec_context.format is not None ) def rtsp_url_parse(rtsp_url): ip, port, login, password = None, None, None, None if '@' in rtsp_url: login, password = rtsp_url.split('rtsp://')[1].split('@')[0].split(':') ip, port = rtsp_url.split('@')[1].split(':') ip, port = ip.replace('/', ''), port.replace('/', '') return (ip, port, login, password) else: ip, port = rtsp_url.split('rtsp://')[1].split(':') ip, port = ip.replace('/', ''), port.replace('/', '') return (ip, port, login, password) def rtsp_snapshoter(rtsp_url: str, snapshots_folder, logging, tries=1): MAX_SCREENSHOT_TRIES = 2 try: with av.open( rtsp_url, options={ "rtsp_transport": "tcp", "rtsp_flags": "prefer_tcp", "stimeout": "3000000", }, timeout=60.0, ) as container: stream = container.streams.video[0] if _is_video_stream(stream): file_name = escape_chars(f"{rtsp_url.lstrip('rtsp://')}.jpg") file_path = f'./{snapshots_folder}/{file_name}' stream.thread_type = "AUTO" for frame in container.decode(video=0): frame.to_image().save(file_path) break logging.info(f'[RTSP] Make snapshot from {rtsp_url}') return rtsp_url_parse(rtsp_url) else: # There's a high possibility that this video stream is broken # or something else, so we try again just to make sure. if tries < MAX_SCREENSHOT_TRIES: logging.debug(f'[RTSP] Failed make snapshoot x{tries} {rtsp_url}') container.close() tries += 1 return rtsp_snapshoter(rtsp_url, snapshots_folder, logging, tries=tries) else: return except (MemoryError, PermissionError, av.InvalidDataError) as e: # These errors occur when there's too much SCREENSHOT_THREADS. # Try one more time in hope for luck. if tries < MAX_SCREENSHOT_TRIES: logging.debug(f'[RTSP] Failed make snapshoot x{tries} {rtsp_url}') tries += 1 return rtsp_snapshoter(rtsp_url, snapshots_folder, logging, tries=tries) else: return except Exception as e: logging.debug(f'[RTSP] Failed make snapshoot {rtsp_url}') logging.debug(f'[RTSP] Error: {e}') return def dahua_snapshoter(target, snapshots_folder, logging): if not target: return False server_ip, port, login, password, dahua = target snapshots_counts = 0 try:
def _is_video_stream(stream): return ( stream.profile is not None and stream.start_time is not None and stream.codec_context.format is not None ) def rtsp_url_parse(rtsp_url): ip, port, login, password = None, None, None, None if '@' in rtsp_url: login, password = rtsp_url.split('rtsp://')[1].split('@')[0].split(':') ip, port = rtsp_url.split('@')[1].split(':') ip, port = ip.replace('/', ''), port.replace('/', '') return (ip, port, login, password) else: ip, port = rtsp_url.split('rtsp://')[1].split(':') ip, port = ip.replace('/', ''), port.replace('/', '') return (ip, port, login, password) def rtsp_snapshoter(rtsp_url: str, snapshots_folder, logging, tries=1): MAX_SCREENSHOT_TRIES = 2 try: with av.open( rtsp_url, options={ "rtsp_transport": "tcp", "rtsp_flags": "prefer_tcp", "stimeout": "3000000", }, timeout=60.0, ) as container: stream = container.streams.video[0] if _is_video_stream(stream): file_name = escape_chars(f"{rtsp_url.lstrip('rtsp://')}.jpg") file_path = f'./{snapshots_folder}/{file_name}' stream.thread_type = "AUTO" for frame in container.decode(video=0): frame.to_image().save(file_path) break logging.info(f'[RTSP] Make snapshot from {rtsp_url}') return rtsp_url_parse(rtsp_url) else: # There's a high possibility that this video stream is broken # or something else, so we try again just to make sure. if tries < MAX_SCREENSHOT_TRIES: logging.debug(f'[RTSP] Failed make snapshoot x{tries} {rtsp_url}') container.close() tries += 1 return rtsp_snapshoter(rtsp_url, snapshots_folder, logging, tries=tries) else: return except (MemoryError, PermissionError, av.InvalidDataError) as e: # These errors occur when there's too much SCREENSHOT_THREADS. # Try one more time in hope for luck. if tries < MAX_SCREENSHOT_TRIES: logging.debug(f'[RTSP] Failed make snapshoot x{tries} {rtsp_url}') tries += 1 return rtsp_snapshoter(rtsp_url, snapshots_folder, logging, tries=tries) else: return except Exception as e: logging.debug(f'[RTSP] Failed make snapshoot {rtsp_url}') logging.debug(f'[RTSP] Error: {e}') return def dahua_snapshoter(target, snapshots_folder, logging): if not target: return False server_ip, port, login, password, dahua = target snapshots_counts = 0 try:
dahua = DahuaController(server_ip, int(port), login, password)
3
2023-10-13 09:01:28+00:00
8k
ByungKwanLee/Full-Segment-Anything
modeling/sam.py
[ { "identifier": "ImageEncoderViT", "path": "modeling/image_encoder.py", "snippet": "class ImageEncoderViT(nn.Module):\n def __init__(\n self,\n img_size: int = 1024,\n patch_size: int = 16,\n in_chans: int = 3,\n embed_dim: int = 768,\n depth: int = 12,\n ...
import torch from torch import nn from torch.nn import functional as F from typing import Any, Dict, List, Tuple from .image_encoder import ImageEncoderViT from .mask_decoder import MaskDecoder from .prompt_encoder import PromptEncoder from torchvision.ops.boxes import batched_nms from utils.amg import ( MaskData, batched_mask_to_box, calculate_stability_score, is_box_near_crop_edge, uncrop_masks, )
6,328
# 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. # by LBK EDIT class Sam(nn.Module): mask_threshold: float = 0.0 image_format: str = "RGB" def __init__( self, image_encoder: ImageEncoderViT,
# 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. # by LBK EDIT class Sam(nn.Module): mask_threshold: float = 0.0 image_format: str = "RGB" def __init__( self, image_encoder: ImageEncoderViT,
prompt_encoder: PromptEncoder,
2
2023-10-13 20:07:42+00:00
8k
flow-diffusion/AVDC
flowdiffusion/guided_diffusion/guided_diffusion/unet.py
[ { "identifier": "convert_module_to_f16", "path": "flowdiffusion/guided_diffusion/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 =...
from abc import abstractmethod from einops import rearrange 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, ) from .imagen import PerceiverResampler import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F
4,044
) 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(), 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), 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 = conv_nd(1, channels, channels, 1) def forward(self, x): return checkpoint(self._forward, (x,), self.parameters(), True) def _forward(self, x): b, c, f, *spatial = x.shape x = rearrange(x, "b c f x y -> (b f) c (x y)") qkv = self.qkv(self.norm(x)) h = self.attention(qkv) h = self.proj_out(h) return rearrange((x + h), "(b f) c (x y) -> b c f x y", c=c, f=f, x=spatial[0], y=spatial[1]) 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, f, *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 * f 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, task_tokens=True, task_token_channels=512, 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.task_tokens = task_tokens self.use_checkpoint = use_checkpoint self.dtype = th.float16 if use_fp16 else th.float32 self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) if self.num_classes is not None: self.label_emb = nn.Embedding(num_classes, time_embed_dim) if task_tokens: self.task_attnpool = nn.Sequential( PerceiverResampler(dim=task_token_channels, depth=2), nn.Linear(task_token_channels, 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(), 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-09 12:03:17+00:00
8k
xt4d/CameraViewer
app.py
[ { "identifier": "CameraVisualizer", "path": "src/visualizer.py", "snippet": "class CameraVisualizer:\n\n def __init__(self, poses, legends, colors, images=None, mesh_path=None, camera_x=1.0):\n self._fig = None\n\n self._camera_x = camera_x\n \n self._poses = poses\n ...
import os, sys import argparse import numpy as np from src.visualizer import CameraVisualizer from src.loader import load_quick, load_nerf, load_colmap from src.utils import load_image
3,888
parser = argparse.ArgumentParser() parser.add_argument('--root', type=str) parser.add_argument('--format', default='quick', choices=['quick', 'nerf', 'colmap']) parser.add_argument('--type', default=None, choices=[None, 'sph', 'xyz', 'elu', 'c2w', 'w2c']) parser.add_argument('--no_images', action='store_true') parser.add_argument('--mesh_path', type=str, default=None) parser.add_argument('--image_size', type=int, default=256) parser.add_argument('--scene_size', type=int, default=5) args = parser.parse_args() root_path = args.root poses = [] legends = [] colors = [] images = None if args.format == 'quick': poses, legends, colors, image_paths = load_quick(root_path, args.type) elif args.format == 'nerf':
parser = argparse.ArgumentParser() parser.add_argument('--root', type=str) parser.add_argument('--format', default='quick', choices=['quick', 'nerf', 'colmap']) parser.add_argument('--type', default=None, choices=[None, 'sph', 'xyz', 'elu', 'c2w', 'w2c']) parser.add_argument('--no_images', action='store_true') parser.add_argument('--mesh_path', type=str, default=None) parser.add_argument('--image_size', type=int, default=256) parser.add_argument('--scene_size', type=int, default=5) args = parser.parse_args() root_path = args.root poses = [] legends = [] colors = [] images = None if args.format == 'quick': poses, legends, colors, image_paths = load_quick(root_path, args.type) elif args.format == 'nerf':
poses, legends, colors, image_paths = load_nerf(root_path)
2
2023-10-14 09:40:57+00:00
8k
sakemin/cog-musicgen-remixer
audiocraft/data/info_audio_dataset.py
[ { "identifier": "AudioDataset", "path": "audiocraft/data/audio_dataset.py", "snippet": "class AudioDataset:\n \"\"\"Base audio dataset.\n\n The dataset takes a list of AudioMeta and create a dataset composed of segments of audio\n and potentially additional information, by creating random segme...
from dataclasses import dataclass from .audio_dataset import AudioDataset, AudioMeta from ..environment import AudioCraftEnvironment from ..modules.conditioners import SegmentWithAttributes, ConditioningAttributes import logging import math import re import typing as tp import torch
6,071
# 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. """Base classes for the datasets that also provide non-audio metadata, e.g. description, text transcription etc. """ logger = logging.getLogger(__name__) def _clusterify_meta(meta: AudioMeta) -> AudioMeta: """Monkey-patch meta to match cluster specificities.""" meta.path = AudioCraftEnvironment.apply_dataset_mappers(meta.path) if meta.info_path is not None: meta.info_path.zip_path = AudioCraftEnvironment.apply_dataset_mappers(meta.info_path.zip_path) return meta def clusterify_all_meta(meta: tp.List[AudioMeta]) -> tp.List[AudioMeta]: """Monkey-patch all meta to match cluster specificities.""" return [_clusterify_meta(m) for m in meta] @dataclass class AudioInfo(SegmentWithAttributes): """Dummy SegmentInfo with empty attributes. The InfoAudioDataset is expected to return metadata that inherits from SegmentWithAttributes class and can return conditioning attributes. This basically guarantees all datasets will be compatible with current solver that contain conditioners requiring this. """ audio_tokens: tp.Optional[torch.Tensor] = None # populated when using cached batch for training a LM.
# 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. """Base classes for the datasets that also provide non-audio metadata, e.g. description, text transcription etc. """ logger = logging.getLogger(__name__) def _clusterify_meta(meta: AudioMeta) -> AudioMeta: """Monkey-patch meta to match cluster specificities.""" meta.path = AudioCraftEnvironment.apply_dataset_mappers(meta.path) if meta.info_path is not None: meta.info_path.zip_path = AudioCraftEnvironment.apply_dataset_mappers(meta.info_path.zip_path) return meta def clusterify_all_meta(meta: tp.List[AudioMeta]) -> tp.List[AudioMeta]: """Monkey-patch all meta to match cluster specificities.""" return [_clusterify_meta(m) for m in meta] @dataclass class AudioInfo(SegmentWithAttributes): """Dummy SegmentInfo with empty attributes. The InfoAudioDataset is expected to return metadata that inherits from SegmentWithAttributes class and can return conditioning attributes. This basically guarantees all datasets will be compatible with current solver that contain conditioners requiring this. """ audio_tokens: tp.Optional[torch.Tensor] = None # populated when using cached batch for training a LM.
def to_condition_attributes(self) -> ConditioningAttributes:
4
2023-10-09 09:55:24+00:00
8k
visitworld123/FedFed
algorithms_standalone/fedavg/FedAVGManager.py
[ { "identifier": "FedAVGClient", "path": "algorithms_standalone/fedavg/client.py", "snippet": "class FedAVGClient(Client):\n def __init__(self, client_index, train_ori_data, train_ori_targets,test_dataloader, train_data_num,\n test_data_num, train_cls_counts_dict, device, args, model_tr...
import copy import logging from .client import FedAVGClient from .aggregator import FedAVGAggregator from utils.data_utils import ( get_avg_num_iterations, ) from algorithms_standalone.basePS.basePSmanager import BasePSManager from model.build import create_model from trainers.build import create_trainer from model.FL_VAE import *
5,284
class FedAVGManager(BasePSManager): def __init__(self, device, args): super().__init__(device, args) self.global_epochs_per_round = self.args.global_epochs_per_round def _setup_server(self): logging.info("############_setup_server (START)#############") model = create_model(self.args, model_name=self.args.model, output_dim=self.args.model_output_dim, device=self.device, **self.other_params) init_state_kargs = {} if self.args.VAE: VAE_model = FL_CVAE_cifar(args=self.args, d=self.args.VAE_d, z=self.args.VAE_z, device=self.device)
class FedAVGManager(BasePSManager): def __init__(self, device, args): super().__init__(device, args) self.global_epochs_per_round = self.args.global_epochs_per_round def _setup_server(self): logging.info("############_setup_server (START)#############") model = create_model(self.args, model_name=self.args.model, output_dim=self.args.model_output_dim, device=self.device, **self.other_params) init_state_kargs = {} if self.args.VAE: VAE_model = FL_CVAE_cifar(args=self.args, d=self.args.VAE_d, z=self.args.VAE_z, device=self.device)
model_trainer = create_trainer(
5
2023-10-10 09:43:18+00:00
8k
zhenyuw16/Uni3DETR
projects/mmdet3d_plugin/models/dense_heads/uni3detr_head.py
[ { "identifier": "normalize_bbox", "path": "projects/mmdet3d_plugin/core/bbox/util.py", "snippet": "def normalize_bbox(bboxes, pc_range=None):\n\n cx = bboxes[..., 0:1]\n cy = bboxes[..., 1:2]\n cz = bboxes[..., 2:3]\n # align coord system with previous version\n if __mmdet3d_version__ < 1...
import copy import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import projects.mmdet3d_plugin.core.bbox.bbox_merging as bbox_merging from functools import partial from mmcv.cnn import Linear, bias_init_with_prob from mmcv.runner import force_fp32, auto_fp16 from mmdet.core import (multi_apply, multi_apply, reduce_mean) from mmdet.models.utils.transformer import inverse_sigmoid from mmdet.models import HEADS from mmdet.models.dense_heads import DETRHead from mmdet3d.core.bbox.coders import build_bbox_coder from mmdet3d.models.builder import build_loss from projects.mmdet3d_plugin.core.bbox.util import normalize_bbox, denormalize_bbox from mmdet3d.core.bbox.iou_calculators.iou3d_calculator import bbox_overlaps_3d, bbox_overlaps_nearest_3d from projects.mmdet3d_plugin.core.bbox.util import get_rdiou from mmdet3d.core.bbox import AxisAlignedBboxOverlaps3D from mmcv.ops import nms3d, nms_bev
5,444
labels = gt_bboxes.new_full((num_bboxes, ), self.num_classes, dtype=torch.long) labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds] label_weights = gt_bboxes.new_ones(num_bboxes) # bbox targets # bbox_targets = torch.zeros_like(bbox_pred)[..., :9] bbox_targets = torch.zeros_like(bbox_pred)[..., :7] ####### bbox_weights = torch.zeros_like(bbox_pred) bbox_weights[pos_inds] = 1.0 # DETR bbox_targets[pos_inds] = sampling_result.pos_gt_bboxes return (labels, label_weights, bbox_targets, bbox_weights, pos_inds, neg_inds) def get_targets(self, cls_scores_list, bbox_preds_list, gt_bboxes_list, gt_labels_list, gt_bboxes_ignore_list=None): """"Compute regression and classification targets for a batch image. Outputs from a single decoder layer of a single feature level are used. Args: cls_scores_list (list[Tensor]): Box score logits from a single decoder layer for each image with shape [num_query, cls_out_channels]. bbox_preds_list (list[Tensor]): Sigmoid outputs from a single decoder layer for each image, with normalized coordinate (cx, cy, w, h) and shape [num_query, 4]. gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels_list (list[Tensor]): Ground truth class indices for each image with shape (num_gts, ). gt_bboxes_ignore_list (list[Tensor], optional): Bounding boxes which can be ignored for each image. Default None. Returns: tuple: a tuple containing the following targets. - labels_list (list[Tensor]): Labels for all images. - label_weights_list (list[Tensor]): Label weights for all \ images. - bbox_targets_list (list[Tensor]): BBox targets for all \ images. - bbox_weights_list (list[Tensor]): BBox weights for all \ images. - num_total_pos (int): Number of positive samples in all \ images. - num_total_neg (int): Number of negative samples in all \ images. """ assert gt_bboxes_ignore_list is None, \ 'Only supports for gt_bboxes_ignore setting to None.' num_imgs = len(cls_scores_list) gt_bboxes_ignore_list = [ gt_bboxes_ignore_list for _ in range(num_imgs) ] (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, pos_inds_list, neg_inds_list) = multi_apply( self._get_target_single, cls_scores_list, bbox_preds_list, gt_labels_list, gt_bboxes_list, gt_bboxes_ignore_list) num_total_pos = sum((inds.numel() for inds in pos_inds_list)) num_total_neg = sum((inds.numel() for inds in neg_inds_list)) return (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg) def loss_single(self, cls_scores, bbox_preds, iou_preds, gt_bboxes_list, gt_labels_list, gt_bboxes_ignore_list=None): """"Loss function for outputs from a single decoder layer of a single feature level. Args: cls_scores (Tensor): Box score logits from a single decoder layer for all images. Shape [bs, num_query, cls_out_channels]. bbox_preds (Tensor): Sigmoid outputs from a single decoder layer for all images, with normalized coordinate (cx, cy, w, h) and shape [bs, num_query, 4]. gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels_list (list[Tensor]): Ground truth class indices for each image with shape (num_gts, ). gt_bboxes_ignore_list (list[Tensor], optional): Bounding boxes which can be ignored for each image. Default None. Returns: dict[str, Tensor]: A dictionary of loss components for outputs from a single decoder layer. """ num_imgs = cls_scores.size(0) cls_scores_list = [cls_scores[i] for i in range(num_imgs)] bbox_preds_list = [bbox_preds[i] for i in range(num_imgs)] cls_reg_targets = self.get_targets(cls_scores_list, bbox_preds_list, gt_bboxes_list, gt_labels_list, gt_bboxes_ignore_list) (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg) = cls_reg_targets labels = torch.cat(labels_list, 0) label_weights = torch.cat(label_weights_list, 0) bbox_targets = torch.cat(bbox_targets_list, 0) bbox_weights = torch.cat(bbox_weights_list, 0) # classification loss cls_scores = cls_scores.reshape(-1, self.cls_out_channels) # construct weighted avg_factor to match with the official DETR repo cls_avg_factor = num_total_pos * 1.0 + \ num_total_neg * self.bg_cls_weight if self.sync_cls_avg_factor: cls_avg_factor = reduce_mean( cls_scores.new_tensor([cls_avg_factor])) cls_avg_factor = max(cls_avg_factor, 1) #loss_cls = self.loss_cls(cls_scores, labels, label_weights, avg_factor=cls_avg_factor) bbox_preds = bbox_preds.reshape(-1, bbox_preds.size(-1)) normalized_bbox_targets = normalize_bbox(bbox_targets, self.pc_range)
class MLP(nn.Module): """ Very simple multi-layer perceptron (also called FFN)""" def __init__(self, input_dim, hidden_dim, output_dim, num_layers): super().__init__() self.num_layers = num_layers h = [hidden_dim] * (num_layers - 1) self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])) def forward(self, x): for i, layer in enumerate(self.layers): x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) return x class BatchNormDim1Swap(nn.BatchNorm1d): """ Used for nn.Transformer that uses a HW x N x C rep """ def forward(self, x): """ x: HW x N x C permute to N x C x HW Apply BN on C permute back """ hw, n, c = x.shape x = x.permute(1, 2, 0) x = super(BatchNormDim1Swap, self).forward(x) # x: n x c x hw -> hw x n x c x = x.permute(2, 0, 1) return x NORM_DICT = { "bn": BatchNormDim1Swap, "bn1d": nn.BatchNorm1d, "id": nn.Identity, "ln": nn.LayerNorm, } ACTIVATION_DICT = { "relu": nn.ReLU, "gelu": nn.GELU, "leakyrelu": partial(nn.LeakyReLU, negative_slope=0.1), } WEIGHT_INIT_DICT = { "xavier_uniform": nn.init.xavier_uniform_, } class GenericMLP(nn.Module): def __init__( self, input_dim, hidden_dims, output_dim, norm_fn_name=None, activation="relu", use_conv=False, dropout=None, hidden_use_bias=False, output_use_bias=True, output_use_activation=False, output_use_norm=False, weight_init_name=None, ): super().__init__() activation = ACTIVATION_DICT[activation] norm = None if norm_fn_name is not None: norm = NORM_DICT[norm_fn_name] if norm_fn_name == "ln" and use_conv: norm = lambda x: nn.GroupNorm(1, x) # easier way to use LayerNorm if dropout is not None: if not isinstance(dropout, list): dropout = [dropout for _ in range(len(hidden_dims))] layers = [] prev_dim = input_dim for idx, x in enumerate(hidden_dims): if use_conv: layer = nn.Conv1d(prev_dim, x, 1, bias=hidden_use_bias) else: layer = nn.Linear(prev_dim, x, bias=hidden_use_bias) layers.append(layer) if norm: layers.append(norm(x)) layers.append(activation()) if dropout is not None: layers.append(nn.Dropout(p=dropout[idx])) prev_dim = x if use_conv: layer = nn.Conv1d(prev_dim, output_dim, 1, bias=output_use_bias) else: layer = nn.Linear(prev_dim, output_dim, bias=output_use_bias) layers.append(layer) if output_use_norm: layers.append(norm(output_dim)) if output_use_activation: layers.append(activation()) self.layers = nn.Sequential(*layers) if weight_init_name is not None: self.do_weight_init(weight_init_name) def do_weight_init(self, weight_init_name): func = WEIGHT_INIT_DICT[weight_init_name] for (_, param) in self.named_parameters(): if param.dim() > 1: # skips batchnorm/layernorm func(param) def forward(self, x): output = self.layers(x) return output # ---------------------------------------- # Simple Point manipulations # ---------------------------------------- def shift_scale_points(pred_xyz, src_range, dst_range=None): """ pred_xyz: B x N x 3 src_range: [[B x 3], [B x 3]] - min and max XYZ coords dst_range: [[B x 3], [B x 3]] - min and max XYZ coords """ if dst_range is None: dst_range = [ torch.zeros((src_range[0].shape[0], 3), device=src_range[0].device), torch.ones((src_range[0].shape[0], 3), device=src_range[0].device), ] if pred_xyz.ndim == 4: src_range = [x[:, None] for x in src_range] dst_range = [x[:, None] for x in dst_range] assert src_range[0].shape[0] == pred_xyz.shape[0] assert dst_range[0].shape[0] == pred_xyz.shape[0] assert src_range[0].shape[-1] == pred_xyz.shape[-1] assert src_range[0].shape == src_range[1].shape assert dst_range[0].shape == dst_range[1].shape assert src_range[0].shape == dst_range[1].shape src_diff = src_range[1][:, None, :] - src_range[0][:, None, :] dst_diff = dst_range[1][:, None, :] - dst_range[0][:, None, :] prop_xyz = ( ((pred_xyz - src_range[0][:, None, :]) * dst_diff) / src_diff ) + dst_range[0][:, None, :] return prop_xyz class PositionEmbeddingCoordsSine(nn.Module): def __init__( self, temperature=10000, normalize=False, scale=None, pos_type="fourier", d_pos=None, d_in=3, gauss_scale=1.0, ): super().__init__() self.temperature = temperature self.normalize = normalize if scale is not None and normalize is False: raise ValueError("normalize should be True if scale is passed") if scale is None: scale = 2 * math.pi assert pos_type in ["sine", "fourier"] self.pos_type = pos_type self.scale = scale if pos_type == "fourier": assert d_pos is not None assert d_pos % 2 == 0 # define a gaussian matrix input_ch -> output_ch B = torch.empty((d_in, d_pos // 2)).normal_() B *= gauss_scale self.register_buffer("gauss_B", B) self.d_pos = d_pos def get_sine_embeddings(self, xyz, num_channels, input_range): # clone coords so that shift/scale operations do not affect original tensor orig_xyz = xyz xyz = orig_xyz.clone() ncoords = xyz.shape[1] if self.normalize: xyz = shift_scale_points(xyz, src_range=input_range) ndim = num_channels // xyz.shape[2] if ndim % 2 != 0: ndim -= 1 # automatically handle remainder by assiging it to the first dim rems = num_channels - (ndim * xyz.shape[2]) assert ( ndim % 2 == 0 ), f"Cannot handle odd sized ndim={ndim} where num_channels={num_channels} and xyz={xyz.shape}" final_embeds = [] prev_dim = 0 for d in range(xyz.shape[2]): cdim = ndim if rems > 0: # add remainder in increments of two to maintain even size cdim += 2 rems -= 2 if cdim != prev_dim: dim_t = torch.arange(cdim, dtype=torch.float32, device=xyz.device) dim_t = self.temperature ** (2 * (dim_t // 2) / cdim) # create batch x cdim x nccords embedding raw_pos = xyz[:, :, d] if self.scale: raw_pos *= self.scale pos = raw_pos[:, :, None] / dim_t pos = torch.stack( (pos[:, :, 0::2].sin(), pos[:, :, 1::2].cos()), dim=3 ).flatten(2) final_embeds.append(pos) prev_dim = cdim final_embeds = torch.cat(final_embeds, dim=2).permute(0, 2, 1) return final_embeds def get_fourier_embeddings(self, xyz, num_channels=None, input_range=None): # Follows - https://people.eecs.berkeley.edu/~bmild/fourfeat/index.html if num_channels is None: num_channels = self.gauss_B.shape[1] * 2 bsize, npoints = xyz.shape[0], xyz.shape[1] assert num_channels > 0 and num_channels % 2 == 0 d_in, max_d_out = self.gauss_B.shape[0], self.gauss_B.shape[1] d_out = num_channels // 2 assert d_out <= max_d_out assert d_in == xyz.shape[-1] # clone coords so that shift/scale operations do not affect original tensor orig_xyz = xyz xyz = orig_xyz.clone() ncoords = xyz.shape[1] if self.normalize: xyz = shift_scale_points(xyz, src_range=input_range) xyz *= 2 * np.pi xyz_proj = torch.mm(xyz.view(-1, d_in), self.gauss_B[:, :d_out]).view( bsize, npoints, d_out ) final_embeds = [xyz_proj.sin(), xyz_proj.cos()] # return batch x d_pos x npoints embedding final_embeds = torch.cat(final_embeds, dim=2).permute(0, 2, 1) return final_embeds def forward(self, xyz, num_channels=None, input_range=None): assert isinstance(xyz, torch.Tensor) assert xyz.ndim == 3 # xyz is batch x npoints x 3 if self.pos_type == "sine": with torch.no_grad(): return self.get_sine_embeddings(xyz, num_channels, input_range) elif self.pos_type == "fourier": with torch.no_grad(): return self.get_fourier_embeddings(xyz, num_channels, input_range) else: raise ValueError(f"Unknown {self.pos_type}") def extra_repr(self): st = f"type={self.pos_type}, scale={self.scale}, normalize={self.normalize}" if hasattr(self, "gauss_B"): st += ( f", gaussB={self.gauss_B.shape}, gaussBsum={self.gauss_B.sum().item()}" ) return st @HEADS.register_module() class Uni3DETRHead(DETRHead): """Head of UVTR. Args: with_box_refine (bool): Whether to refine the reference points in the decoder. Defaults to False. as_two_stage (bool) : Whether to generate the proposal from the outputs of encoder. transformer (obj:`ConfigDict`): ConfigDict is used for building the Encoder and Decoder. """ def __init__(self, *args, with_box_refine=False, as_two_stage=False, transformer=None, bbox_coder=None, num_cls_fcs=2, code_weights=None, loss_bbox=dict(type='RotatedIoU3DLoss', loss_weight=1.0), loss_iou=dict(type='RotatedIoU3DLoss', loss_weight=1.0), post_processing=None, gt_repeattimes=1, **kwargs): self.with_box_refine = with_box_refine self.as_two_stage = as_two_stage if self.as_two_stage: transformer['as_two_stage'] = self.as_two_stage if 'code_size' in kwargs: self.code_size = kwargs['code_size'] else: self.code_size = 10 if code_weights is not None: self.code_weights = code_weights else: self.code_weights = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.2, 0.2] self.bbox_coder = build_bbox_coder(bbox_coder) self.pc_range = self.bbox_coder.pc_range self.num_cls_fcs = num_cls_fcs - 1 super(Uni3DETRHead, self).__init__( *args, transformer=transformer, loss_bbox=loss_bbox, loss_iou=loss_iou, **kwargs) self.loss_bbox = build_loss(loss_bbox) self.loss_iou = build_loss(loss_iou) self.code_weights = nn.Parameter(torch.tensor( self.code_weights, requires_grad=False), requires_grad=False) self.fp16_enabled = False self.post_processing = post_processing self.gt_repeattimes = gt_repeattimes def _init_layers(self): """Initialize classification branch and regression branch of head.""" cls_branch = [] for _ in range(self.num_reg_fcs): cls_branch.append(Linear(self.embed_dims, self.embed_dims)) cls_branch.append(nn.LayerNorm(self.embed_dims)) cls_branch.append(nn.ReLU(inplace=True)) cls_branch.append(Linear(self.embed_dims, self.cls_out_channels)) fc_cls = nn.Sequential(*cls_branch) reg_branch = [] for _ in range(self.num_reg_fcs): reg_branch.append(Linear(self.embed_dims, self.embed_dims)) reg_branch.append(nn.ReLU()) reg_branch.append(Linear(self.embed_dims, self.code_size)) reg_branch = nn.Sequential(*reg_branch) iou_branch = [] for _ in range(self.num_reg_fcs): iou_branch.append(Linear(self.embed_dims, self.embed_dims)) iou_branch.append(nn.ReLU()) iou_branch.append(Linear(self.embed_dims, 1)) iou_branch = nn.Sequential(*iou_branch) def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) # last reg_branch is used to generate proposal from # encode feature map when as_two_stage is True. num_pred = (self.transformer.decoder.num_layers + 1) if \ self.as_two_stage else self.transformer.decoder.num_layers if self.with_box_refine: self.cls_branches = _get_clones(fc_cls, num_pred) self.reg_branches = _get_clones(reg_branch, num_pred) self.iou_branches = _get_clones(iou_branch, num_pred) else: self.cls_branches = nn.ModuleList( [fc_cls for _ in range(num_pred)]) self.reg_branches = nn.ModuleList( [reg_branch for _ in range(num_pred)]) self.iou_branches = nn.ModuleList( [iou_branch for _ in range(num_pred)]) if not self.as_two_stage: self.tgt_embed = nn.Embedding(self.num_query * 2, self.embed_dims) self.refpoint_embed = nn.Embedding(self.num_query, 3) def init_weights(self): """Initialize weights of the DeformDETR head.""" self.transformer.init_weights() if self.loss_cls.use_sigmoid: bias_init = bias_init_with_prob(0.01) for m in self.cls_branches: nn.init.constant_(m[-1].bias, bias_init) @auto_fp16(apply_to=("pts_feats",)) def forward(self, pts_feats, img_metas, fpsbpts): """Forward function. Args: mlvl_feats (tuple[Tensor]): Features from the upstream network, each is a 5D-tensor with shape (B, N, C, H, W). Returns: all_cls_scores (Tensor): Outputs from the classification head, \ shape [nb_dec, bs, num_query, cls_out_channels]. Note \ cls_out_channels should includes background. all_bbox_preds (Tensor): Sigmoid outputs from the regression \ head with normalized coordinate format (cx, cy, w, l, cz, h, theta, vx, vy). \ Shape [nb_dec, bs, num_query, 9]. """ tgt_embed = self.tgt_embed.weight # nq, 256 refanchor = self.refpoint_embed.weight # nq, 6 #query_embeds = torch.cat((tgt_embed, refanchor), dim=1) bs = fpsbpts.shape[0] if pts_feats.requires_grad: tgt_embed = torch.cat([tgt_embed[0:self.num_query], tgt_embed[self.num_query:], tgt_embed[self.num_query:]]) query_embeds = torch.cat([tgt_embed.unsqueeze(0).expand(bs, -1, -1), torch.cat([refanchor.unsqueeze(0).expand(bs, -1, -1), inverse_sigmoid(fpsbpts)], 1)], -1) else: random_point = torch.rand(fpsbpts.shape, device=fpsbpts.device)[:, :self.num_query, :] tgt_embed = torch.cat([tgt_embed[0:self.num_query], tgt_embed[self.num_query:], tgt_embed[self.num_query:], tgt_embed[self.num_query:]]) query_embeds = torch.cat([tgt_embed.unsqueeze(0).expand(bs, -1, -1), torch.cat([refanchor.unsqueeze(0).expand(bs, -1, -1), inverse_sigmoid(fpsbpts), inverse_sigmoid(random_point)], 1)], -1) # shape: (N, L, C, D, H, W) if len(pts_feats.shape) == 5: pts_feats = pts_feats.unsqueeze(1) hs, init_reference, inter_references = self.transformer( pts_feats, query_embeds, self.num_query, reg_branches=self.reg_branches if self.with_box_refine else None, img_metas=img_metas, ) hs = hs.permute(0, 2, 1, 3) outputs_classes = [] outputs_coords = [] outputs_ious = [] #for lvl in range(hs.shape[0]): for lvl in range(len(hs)): if lvl == 0: reference = init_reference else: reference = inter_references[lvl - 1] reference = inverse_sigmoid(reference) outputs_class = self.cls_branches[lvl](hs[lvl]) tmp = self.reg_branches[lvl](hs[lvl]) outputs_iou = self.iou_branches[lvl](hs[lvl]) # TODO: check the shape of reference assert reference.shape[-1] == 3 tmp[..., 0:2] += reference[..., 0:2] tmp[..., 0:2] = tmp[..., 0:2].sigmoid() tmp[..., 4:5] += reference[..., 2:3] tmp[..., 4:5] = tmp[..., 4:5].sigmoid() # transfer to lidar system tmp[..., 0:1] = (tmp[..., 0:1] * (self.pc_range[3] - self.pc_range[0]) + self.pc_range[0]) tmp[..., 1:2] = (tmp[..., 1:2] * (self.pc_range[4] - self.pc_range[1]) + self.pc_range[1]) tmp[..., 4:5] = (tmp[..., 4:5] * (self.pc_range[5] - self.pc_range[2]) + self.pc_range[2]) # TODO: check if using sigmoid outputs_coord = tmp outputs_classes.append(outputs_class) outputs_coords.append(outputs_coord) outputs_ious.append(outputs_iou) outputs_classes = torch.stack(outputs_classes) outputs_coords = torch.stack(outputs_coords) outputs_ious = torch.stack(outputs_ious) outs = { 'all_cls_scores': outputs_classes, 'all_bbox_preds': outputs_coords, 'all_iou_preds': outputs_ious } return outs def _get_target_single(self, cls_score, bbox_pred, gt_labels, gt_bboxes, gt_bboxes_ignore=None): """"Compute regression and classification targets for one image. Outputs from a single decoder layer of a single feature level are used. Args: cls_score (Tensor): Box score logits from a single decoder layer for one image. Shape [num_query, cls_out_channels]. bbox_pred (Tensor): Sigmoid outputs from a single decoder layer for one image, with normalized coordinate (cx, cy, w, h) and shape [num_query, 4]. gt_bboxes (Tensor): Ground truth bboxes for one image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels (Tensor): Ground truth class indices for one image with shape (num_gts, ). gt_bboxes_ignore (Tensor, optional): Bounding boxes which can be ignored. Default None. Returns: tuple[Tensor]: a tuple containing the following for one image. - labels (Tensor): Labels of each image. - label_weights (Tensor]): Label weights of each image. - bbox_targets (Tensor): BBox targets of each image. - bbox_weights (Tensor): BBox weights of each image. - pos_inds (Tensor): Sampled positive indices for each image. - neg_inds (Tensor): Sampled negative indices for each image. """ num_bboxes = bbox_pred.size(0) assign_result = self.assigner.assign(bbox_pred, cls_score, gt_bboxes, gt_labels, self.num_query, gt_bboxes_ignore, self.gt_repeattimes) sampling_result = self.sampler.sample(assign_result, bbox_pred, gt_bboxes) pos_inds = sampling_result.pos_inds neg_inds = sampling_result.neg_inds # label targets labels = gt_bboxes.new_full((num_bboxes, ), self.num_classes, dtype=torch.long) labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds] label_weights = gt_bboxes.new_ones(num_bboxes) # bbox targets # bbox_targets = torch.zeros_like(bbox_pred)[..., :9] bbox_targets = torch.zeros_like(bbox_pred)[..., :7] ####### bbox_weights = torch.zeros_like(bbox_pred) bbox_weights[pos_inds] = 1.0 # DETR bbox_targets[pos_inds] = sampling_result.pos_gt_bboxes return (labels, label_weights, bbox_targets, bbox_weights, pos_inds, neg_inds) def get_targets(self, cls_scores_list, bbox_preds_list, gt_bboxes_list, gt_labels_list, gt_bboxes_ignore_list=None): """"Compute regression and classification targets for a batch image. Outputs from a single decoder layer of a single feature level are used. Args: cls_scores_list (list[Tensor]): Box score logits from a single decoder layer for each image with shape [num_query, cls_out_channels]. bbox_preds_list (list[Tensor]): Sigmoid outputs from a single decoder layer for each image, with normalized coordinate (cx, cy, w, h) and shape [num_query, 4]. gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels_list (list[Tensor]): Ground truth class indices for each image with shape (num_gts, ). gt_bboxes_ignore_list (list[Tensor], optional): Bounding boxes which can be ignored for each image. Default None. Returns: tuple: a tuple containing the following targets. - labels_list (list[Tensor]): Labels for all images. - label_weights_list (list[Tensor]): Label weights for all \ images. - bbox_targets_list (list[Tensor]): BBox targets for all \ images. - bbox_weights_list (list[Tensor]): BBox weights for all \ images. - num_total_pos (int): Number of positive samples in all \ images. - num_total_neg (int): Number of negative samples in all \ images. """ assert gt_bboxes_ignore_list is None, \ 'Only supports for gt_bboxes_ignore setting to None.' num_imgs = len(cls_scores_list) gt_bboxes_ignore_list = [ gt_bboxes_ignore_list for _ in range(num_imgs) ] (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, pos_inds_list, neg_inds_list) = multi_apply( self._get_target_single, cls_scores_list, bbox_preds_list, gt_labels_list, gt_bboxes_list, gt_bboxes_ignore_list) num_total_pos = sum((inds.numel() for inds in pos_inds_list)) num_total_neg = sum((inds.numel() for inds in neg_inds_list)) return (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg) def loss_single(self, cls_scores, bbox_preds, iou_preds, gt_bboxes_list, gt_labels_list, gt_bboxes_ignore_list=None): """"Loss function for outputs from a single decoder layer of a single feature level. Args: cls_scores (Tensor): Box score logits from a single decoder layer for all images. Shape [bs, num_query, cls_out_channels]. bbox_preds (Tensor): Sigmoid outputs from a single decoder layer for all images, with normalized coordinate (cx, cy, w, h) and shape [bs, num_query, 4]. gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels_list (list[Tensor]): Ground truth class indices for each image with shape (num_gts, ). gt_bboxes_ignore_list (list[Tensor], optional): Bounding boxes which can be ignored for each image. Default None. Returns: dict[str, Tensor]: A dictionary of loss components for outputs from a single decoder layer. """ num_imgs = cls_scores.size(0) cls_scores_list = [cls_scores[i] for i in range(num_imgs)] bbox_preds_list = [bbox_preds[i] for i in range(num_imgs)] cls_reg_targets = self.get_targets(cls_scores_list, bbox_preds_list, gt_bboxes_list, gt_labels_list, gt_bboxes_ignore_list) (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg) = cls_reg_targets labels = torch.cat(labels_list, 0) label_weights = torch.cat(label_weights_list, 0) bbox_targets = torch.cat(bbox_targets_list, 0) bbox_weights = torch.cat(bbox_weights_list, 0) # classification loss cls_scores = cls_scores.reshape(-1, self.cls_out_channels) # construct weighted avg_factor to match with the official DETR repo cls_avg_factor = num_total_pos * 1.0 + \ num_total_neg * self.bg_cls_weight if self.sync_cls_avg_factor: cls_avg_factor = reduce_mean( cls_scores.new_tensor([cls_avg_factor])) cls_avg_factor = max(cls_avg_factor, 1) #loss_cls = self.loss_cls(cls_scores, labels, label_weights, avg_factor=cls_avg_factor) bbox_preds = bbox_preds.reshape(-1, bbox_preds.size(-1)) normalized_bbox_targets = normalize_bbox(bbox_targets, self.pc_range)
bboxes3d = denormalize_bbox(bbox_preds, self.pc_range)
1
2023-10-08 08:59:34+00:00
8k
awslabs/s3-connector-for-pytorch
s3torchconnector/tst/e2e/test_multiprocess_dataloading.py
[ { "identifier": "S3Reader", "path": "s3torchconnector/src/s3torchconnector/s3reader.py", "snippet": "class S3Reader(io.BufferedIOBase):\n \"\"\"A read-only, file like representation of a single object stored in S3.\"\"\"\n\n def __init__(\n self,\n bucket: str,\n key: str,\n ...
import platform import pytest import torch from collections import Counter from itertools import product from typing import Tuple, Callable, TYPE_CHECKING from torch.utils.data import DataLoader, get_worker_info from torchdata.datapipes.iter import IterableWrapper from s3torchconnector import S3IterableDataset, S3MapDataset, S3Reader from .conftest import BucketPrefixFixture
4,284
def from_objects(cls, image_directory: BucketPrefixFixture, **kwargs): return cls.from_objects( [f"s3://{image_directory.bucket}/{key}" for key in image_directory], region=image_directory.region, **kwargs, ) # Allow us to construct our datasets in tests with either from_prefix or from_objects. dataset_builders = (from_prefix, from_objects) test_args = list(product(sorted(start_methods), dataset_builders)) @pytest.mark.parametrize("start_method, dataset_builder", test_args) def test_s3iterable_dataset_multiprocess_torchdata( start_method: str, dataset_builder: Callable, image_directory: BucketPrefixFixture, ): _set_start_method(start_method) dataset = dataset_builder(S3IterableDataset, image_directory) dataset = IterableWrapper(dataset, deepcopy=False).sharding_filter().map(_read_data) batch_size = 2 num_workers = 3 dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers) total_objects = 0 uris_seen = Counter() for uris, datas in dataloader: assert len(uris) == len(datas) object_count = len(uris) assert object_count <= batch_size total_objects += object_count for uri, data in zip(uris, datas): assert isinstance(uri, str) assert isinstance(data, bytes) uris_seen[uri] += 1 # IterableWrapper has sharding enabled; we'll see each image once. assert total_objects == len(image_directory.contents) assert uris_seen == {key: 1 for key in image_directory} @pytest.mark.parametrize("start_method, dataset_builder", test_args) def test_s3iterable_dataset_multiprocess( start_method: str, dataset_builder: Callable, image_directory: BucketPrefixFixture, ): _set_start_method(start_method) dataset = dataset_builder( S3IterableDataset, image_directory, transform=_extract_object_data, ) num_workers = 3 num_epochs = 2 num_images = len(image_directory.contents) dataloader = DataLoader(dataset, num_workers=num_workers) counter = 0 for epoch in range(num_epochs): s3keys = Counter() worker_count = Counter() for ((s3key,), (contents,)), (worker_id, _num_workers) in dataloader: s3keys[s3key] += 1 counter += 1 worker_count[worker_id.item()] += 1 assert _num_workers == num_workers assert image_directory[s3key] == contents assert len(worker_count) == num_workers assert all(times_found == num_images for times_found in worker_count.values()) # Iterable dataset does not do sharding; thus we'll see each image once for each worker. assert sum(worker_count.values()) == num_images * num_workers assert dict(s3keys) == {key: num_workers for key in image_directory} @pytest.mark.parametrize("start_method, dataset_builder", test_args) def test_s3mapdataset_multiprocess( start_method: str, dataset_builder: Callable, image_directory: BucketPrefixFixture, ): _set_start_method(start_method) dataset = dataset_builder( S3MapDataset, image_directory, transform=_extract_object_data, ) num_workers = 3 num_epochs = 2 num_images = len(image_directory.contents) dataloader = DataLoader(dataset, num_workers=num_workers) for epoch in range(num_epochs): s3keys = Counter() worker_count = Counter() for ((s3key,), (contents,)), (worker_id, _num_workers) in dataloader: worker_count[worker_id.item()] += 1 s3keys[s3key] += 1 assert _num_workers == num_workers assert image_directory[s3key] == contents # Map dataset does sharding; we'll see each image once. assert sum(worker_count.values()) == num_images assert dict(s3keys) == {key: 1 for key in image_directory} assert len(dataloader) == num_images def _set_start_method(start_method: str): torch.multiprocessing.set_start_method(start_method, force=True)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # // SPDX-License-Identifier: BSD from __future__ import annotations if TYPE_CHECKING: start_methods = set(torch.multiprocessing.get_all_start_methods()) if platform.system() == "Darwin": # fork and forkserver crash on MacOS, even though it's reported as usable. # https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods # https://bugs.python.org/issue?@action=redirect&bpo=33725 start_methods -= {"fork", "forkserver"} def from_prefix(cls, image_directory: BucketPrefixFixture, **kwargs): return cls.from_prefix( s3_uri=f"s3://{image_directory.bucket}/{image_directory.prefix}", region=image_directory.region, **kwargs, ) def from_objects(cls, image_directory: BucketPrefixFixture, **kwargs): return cls.from_objects( [f"s3://{image_directory.bucket}/{key}" for key in image_directory], region=image_directory.region, **kwargs, ) # Allow us to construct our datasets in tests with either from_prefix or from_objects. dataset_builders = (from_prefix, from_objects) test_args = list(product(sorted(start_methods), dataset_builders)) @pytest.mark.parametrize("start_method, dataset_builder", test_args) def test_s3iterable_dataset_multiprocess_torchdata( start_method: str, dataset_builder: Callable, image_directory: BucketPrefixFixture, ): _set_start_method(start_method) dataset = dataset_builder(S3IterableDataset, image_directory) dataset = IterableWrapper(dataset, deepcopy=False).sharding_filter().map(_read_data) batch_size = 2 num_workers = 3 dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers) total_objects = 0 uris_seen = Counter() for uris, datas in dataloader: assert len(uris) == len(datas) object_count = len(uris) assert object_count <= batch_size total_objects += object_count for uri, data in zip(uris, datas): assert isinstance(uri, str) assert isinstance(data, bytes) uris_seen[uri] += 1 # IterableWrapper has sharding enabled; we'll see each image once. assert total_objects == len(image_directory.contents) assert uris_seen == {key: 1 for key in image_directory} @pytest.mark.parametrize("start_method, dataset_builder", test_args) def test_s3iterable_dataset_multiprocess( start_method: str, dataset_builder: Callable, image_directory: BucketPrefixFixture, ): _set_start_method(start_method) dataset = dataset_builder( S3IterableDataset, image_directory, transform=_extract_object_data, ) num_workers = 3 num_epochs = 2 num_images = len(image_directory.contents) dataloader = DataLoader(dataset, num_workers=num_workers) counter = 0 for epoch in range(num_epochs): s3keys = Counter() worker_count = Counter() for ((s3key,), (contents,)), (worker_id, _num_workers) in dataloader: s3keys[s3key] += 1 counter += 1 worker_count[worker_id.item()] += 1 assert _num_workers == num_workers assert image_directory[s3key] == contents assert len(worker_count) == num_workers assert all(times_found == num_images for times_found in worker_count.values()) # Iterable dataset does not do sharding; thus we'll see each image once for each worker. assert sum(worker_count.values()) == num_images * num_workers assert dict(s3keys) == {key: num_workers for key in image_directory} @pytest.mark.parametrize("start_method, dataset_builder", test_args) def test_s3mapdataset_multiprocess( start_method: str, dataset_builder: Callable, image_directory: BucketPrefixFixture, ): _set_start_method(start_method) dataset = dataset_builder( S3MapDataset, image_directory, transform=_extract_object_data, ) num_workers = 3 num_epochs = 2 num_images = len(image_directory.contents) dataloader = DataLoader(dataset, num_workers=num_workers) for epoch in range(num_epochs): s3keys = Counter() worker_count = Counter() for ((s3key,), (contents,)), (worker_id, _num_workers) in dataloader: worker_count[worker_id.item()] += 1 s3keys[s3key] += 1 assert _num_workers == num_workers assert image_directory[s3key] == contents # Map dataset does sharding; we'll see each image once. assert sum(worker_count.values()) == num_images assert dict(s3keys) == {key: 1 for key in image_directory} assert len(dataloader) == num_images def _set_start_method(start_method: str): torch.multiprocessing.set_start_method(start_method, force=True)
def _extract_object_data(s3reader: S3Reader) -> ((str, bytes), (int, int)):
0
2023-10-10 12:36:32+00:00
8k
test-time-training/mttt
train.py
[ { "identifier": "input_pipeline", "path": "datasets/input_pipeline.py", "snippet": "def make_for_train(\n data, preprocess_fn, batch_size,\n shuffle_buffer_size, cache_raw=False, filter_fn=None,\n num_parallel_calls=100, prefetch=2):\ndef training(input_config):\ndef make_for_inference(\n da...
import importlib import multiprocessing.pool import warnings import os.path as osp import sys import functools import ml_collections as mlc import jax.numpy as jnp import flax import optax import tensorflow as tf import torch from absl import app from absl import flags from ml_collections import config_flags from tqdm import tqdm from time import perf_counter from datasets import input_pipeline as input_pipeline from tools import utils as u, build_optax as bv_optax, evaluate from tools.helpers import * from model import Model
4,136
} ret = { "loss": l, "inner_loss_tuple_lyr": inner_loss_tuple_lyr } return carry_new, ret grad_avg = jax.tree_util.tree_map(lambda x: jnp.zeros(x.shape, x.dtype), params) carry_init = {"grad_avg": grad_avg} input_dict = {"images": images, "labels": labels} carry_new, ret = jax.lax.scan(accumulation, carry_init, input_dict, accum_time) grad_avg = jax.lax.pmean(carry_new["grad_avg"], "batch") l = jax.lax.pmean(ret["loss"].mean(), "batch") inner_loss_tuple_lyr = ret["inner_loss_tuple_lyr"] inner_loss_tuple_layers_avg = () for layer in range(layer_num): inner_loss_tuple_layer_avg = () for itr in range(itr_num): inner_loss_tuple_layer_avg += (jax.lax.pmean(inner_loss_tuple_lyr[layer][itr].mean(), "batch"),) inner_loss_tuple_layers_avg += (inner_loss_tuple_layer_avg,) updates, opt = tx.update(grad_avg, opt, params) params = optax.apply_updates(params, updates) return params, opt, rng, l, inner_loss_tuple_layers_avg return update_fn_accum def make_predict_fn(model): def predict_fn(params, image, rng): rng, rng_idx = jax.random.split(rng, 2) logits, inner_loss_tuple_layers = model.apply({"params": params}, image, rngs={"idx": rng_idx}) return logits, inner_loss_tuple_layers, rng return predict_fn def main(argv): del argv config = flags.FLAGS.config workdir = flags.FLAGS.workdir tf.random.set_seed(config.tf_seed) rng = jax.random.PRNGKey(config.get("seed", 0)) is_master = (jax.process_index() == 0) if is_master: master_mkdir(workdir) # save log.txt, training statistics master_mkdir(osp.join(workdir, "../../ckpt", workdir.split("/")[-1])) # save model checkpoint logger = open(osp.join(workdir, "log.txt"), "w") else: logger = None master_print(str(config), logger) save_ckpt_path = osp.join(workdir, "../../ckpt", workdir.split("/")[-1], "checkpoint.npz") save_stat_dict_path = osp.join(workdir, "all_stat_dict.pth") pool = multiprocessing.pool.ThreadPool() # Here we register preprocessing ops from modules listed on `pp_modules`. for m in config.get("pp_modules", ["ops_general", "ops_image"]): importlib.import_module(f"pp.{m}") master_print("Initializing...") batch_size = config.input.batch_size accum_time = config.input.accum_time if batch_size % jax.device_count() != 0: raise ValueError(f"Batch size ({batch_size}) must be divisible by device number ({jax.device_count()})") master_print( "Global batch size {} on {} hosts results in {} local batch size. With {} dev per host ({} dev total), " "that's a {} per-device batch size accumulated for {} steps.".format( batch_size, jax.process_count(), batch_size // jax.process_count(), jax.local_device_count(), jax.device_count(), batch_size // jax.device_count() // accum_time, accum_time) ) master_print("Initializing train dataset...") n_prefetch = config.get("prefetch_to_device", 1) config.input.data.data_dir = config.tfds_path config.evals.data.data_dir = config.tfds_path train_ds, ntrain_img = input_pipeline.training(config.input) train_iter = input_pipeline.start_input_pipeline(train_ds, n_prefetch) total_steps = u.steps("total", config, ntrain_img, batch_size) steps_per_epoch = total_steps // config.total_epochs master_print("Running for {} steps, that means {} epochs, {} steps per epoch".format( total_steps, total_steps * batch_size / ntrain_img, steps_per_epoch)) master_print(f"Initializing model...") model_config = config.get("model", "tiny") if config.get("benchmark", "pixel") == "pixel": patch_size = (1, 1) posemb = "learn" else: patch_size = (16, 16) posemb = "sincos2d" if model_config == "small": model_config = dict(width=384, depth=12, mlp_dim=1536, num_heads=6, patch_size=patch_size, posemb=posemb) elif model_config == "tiny": model_config = dict(width=192, depth=12, mlp_dim=768, num_heads=3, patch_size=patch_size, posemb=posemb) else: raise NotImplementedError("Model %s not implemented" % model_config) layer_num = model_config["depth"] itr_num = config.inner.TTT.inner_itr + 1 if config.inner.layer_type == 'TTT' else 2
warnings.filterwarnings("ignore") config_flags.DEFINE_config_file("config", None, "Training configuration.", lock_config=True) flags.DEFINE_string("workdir", default=None, help="Work unit directory.") jax.config.parse_flags_with_absl() def make_init_fn(model, batch_size, config): @functools.partial(jax.jit, backend="cpu") def init_fn(rng): bs = batch_size // jax.device_count() image_size = (224, 224, 3) no_image = jnp.zeros((bs,) + image_size, jnp.float32) params = flax.core.unfreeze(model.init({"params": rng, "idx": rng}, no_image))["params"] if "init_head_bias" in config: params["head"]["bias"] = jnp.full_like(params["head"]["bias"], config["init_head_bias"]) return params return init_fn def make_update_fn(model, tx, layer_num, itr_num, config): @functools.partial(jax.pmap, axis_name="batch", donate_argnums=(0, 1)) def update_fn(params, opt, rng, images, labels): if config.get("mixup") and config.mixup.p: rng, (images, labels), _ = u.mixup(rng, images, labels, **config.mixup) rng, rng_model = jax.random.split(rng, 2) rng_model_local = jax.random.fold_in(rng_model, jax.lax.axis_index("batch")) def loss_fn(params, images, labels): logits, inner_loss_tuple_layers = model.apply({"params": params}, images, rngs={"idx": rng_model_local}) return getattr(u, config.get("loss", "sigmoid_xent"))(logits=logits, labels=labels), inner_loss_tuple_layers (l, inner_loss_tuple_lyr), grads = jax.value_and_grad(loss_fn, has_aux=True)(params, images, labels) l, grads = jax.lax.pmean((l, grads), axis_name="batch") updates, opt = tx.update(grads, opt, params) params = optax.apply_updates(params, updates) inner_loss_tuple_layers_avg = () for layer in range(layer_num): inner_loss_tuple_layer_avg = () for itr in range(itr_num): inner_loss_tuple_layer_avg += (jax.lax.pmean(inner_loss_tuple_lyr[layer][itr], "batch"),) inner_loss_tuple_layers_avg += (inner_loss_tuple_layer_avg,) return params, opt, rng, l, inner_loss_tuple_layers_avg return update_fn def make_update_fn_accum(model, tx, accum_time, layer_num, itr_num, config): @functools.partial(jax.pmap, axis_name="batch", donate_argnums=(0, 1)) def update_fn_accum(params, opt, rng, images, labels): if config.get("mixup") and config.mixup.p: rng, (images, labels), _ = u.mixup(rng, images, labels, **config.mixup) images = images.reshape(accum_time, -1, *images.shape[1:]) labels = labels.reshape(accum_time, -1, *labels.shape[1:]) rng, rng_model = jax.random.split(rng, 2) rng_model_local = jax.random.fold_in(rng_model, jax.lax.axis_index("batch")) def loss_fn(params, images, labels): logits, inner_loss_tuple_layers = model.apply({"params": params}, images, rngs={"idx": rng_model_local}) return getattr(u, config.get("loss", "sigmoid_xent"))(logits=logits, labels=labels), \ inner_loss_tuple_layers grad_fn = jax.value_and_grad(loss_fn, has_aux=True, argnums=0) def accumulation(carry, input_dict): grad_avg = carry["grad_avg"] images = input_dict["images"] labels = input_dict["labels"] (l, inner_loss_tuple_lyr), grad = grad_fn(params, images, labels) grad_avg = jax.tree_util.tree_map(lambda g_avg, g: g_avg + g / accum_time, grad_avg, grad) carry_new = { "grad_avg": grad_avg } ret = { "loss": l, "inner_loss_tuple_lyr": inner_loss_tuple_lyr } return carry_new, ret grad_avg = jax.tree_util.tree_map(lambda x: jnp.zeros(x.shape, x.dtype), params) carry_init = {"grad_avg": grad_avg} input_dict = {"images": images, "labels": labels} carry_new, ret = jax.lax.scan(accumulation, carry_init, input_dict, accum_time) grad_avg = jax.lax.pmean(carry_new["grad_avg"], "batch") l = jax.lax.pmean(ret["loss"].mean(), "batch") inner_loss_tuple_lyr = ret["inner_loss_tuple_lyr"] inner_loss_tuple_layers_avg = () for layer in range(layer_num): inner_loss_tuple_layer_avg = () for itr in range(itr_num): inner_loss_tuple_layer_avg += (jax.lax.pmean(inner_loss_tuple_lyr[layer][itr].mean(), "batch"),) inner_loss_tuple_layers_avg += (inner_loss_tuple_layer_avg,) updates, opt = tx.update(grad_avg, opt, params) params = optax.apply_updates(params, updates) return params, opt, rng, l, inner_loss_tuple_layers_avg return update_fn_accum def make_predict_fn(model): def predict_fn(params, image, rng): rng, rng_idx = jax.random.split(rng, 2) logits, inner_loss_tuple_layers = model.apply({"params": params}, image, rngs={"idx": rng_idx}) return logits, inner_loss_tuple_layers, rng return predict_fn def main(argv): del argv config = flags.FLAGS.config workdir = flags.FLAGS.workdir tf.random.set_seed(config.tf_seed) rng = jax.random.PRNGKey(config.get("seed", 0)) is_master = (jax.process_index() == 0) if is_master: master_mkdir(workdir) # save log.txt, training statistics master_mkdir(osp.join(workdir, "../../ckpt", workdir.split("/")[-1])) # save model checkpoint logger = open(osp.join(workdir, "log.txt"), "w") else: logger = None master_print(str(config), logger) save_ckpt_path = osp.join(workdir, "../../ckpt", workdir.split("/")[-1], "checkpoint.npz") save_stat_dict_path = osp.join(workdir, "all_stat_dict.pth") pool = multiprocessing.pool.ThreadPool() # Here we register preprocessing ops from modules listed on `pp_modules`. for m in config.get("pp_modules", ["ops_general", "ops_image"]): importlib.import_module(f"pp.{m}") master_print("Initializing...") batch_size = config.input.batch_size accum_time = config.input.accum_time if batch_size % jax.device_count() != 0: raise ValueError(f"Batch size ({batch_size}) must be divisible by device number ({jax.device_count()})") master_print( "Global batch size {} on {} hosts results in {} local batch size. With {} dev per host ({} dev total), " "that's a {} per-device batch size accumulated for {} steps.".format( batch_size, jax.process_count(), batch_size // jax.process_count(), jax.local_device_count(), jax.device_count(), batch_size // jax.device_count() // accum_time, accum_time) ) master_print("Initializing train dataset...") n_prefetch = config.get("prefetch_to_device", 1) config.input.data.data_dir = config.tfds_path config.evals.data.data_dir = config.tfds_path train_ds, ntrain_img = input_pipeline.training(config.input) train_iter = input_pipeline.start_input_pipeline(train_ds, n_prefetch) total_steps = u.steps("total", config, ntrain_img, batch_size) steps_per_epoch = total_steps // config.total_epochs master_print("Running for {} steps, that means {} epochs, {} steps per epoch".format( total_steps, total_steps * batch_size / ntrain_img, steps_per_epoch)) master_print(f"Initializing model...") model_config = config.get("model", "tiny") if config.get("benchmark", "pixel") == "pixel": patch_size = (1, 1) posemb = "learn" else: patch_size = (16, 16) posemb = "sincos2d" if model_config == "small": model_config = dict(width=384, depth=12, mlp_dim=1536, num_heads=6, patch_size=patch_size, posemb=posemb) elif model_config == "tiny": model_config = dict(width=192, depth=12, mlp_dim=768, num_heads=3, patch_size=patch_size, posemb=posemb) else: raise NotImplementedError("Model %s not implemented" % model_config) layer_num = model_config["depth"] itr_num = config.inner.TTT.inner_itr + 1 if config.inner.layer_type == 'TTT' else 2
model = Model(num_classes=config.num_classes,
4
2023-10-14 20:52:29+00:00
8k
BAAI-DCAI/Training-Data-Synthesis
train.py
[ { "identifier": "get_dataset", "path": "data/new_load_data.py", "snippet": "def get_dataset(root, split=\"train\",subset='imagenet1k',filelist=\"file_list.txt\",transform=None):\n if subset not in ood_testset:\n root_dir = os.path.join(root,split)\n preprocess = train_preprocess if spli...
import argparse import logging import os import time import torch import torch.nn as nn import torchvision.utils import yaml import wandb from collections import OrderedDict from contextlib import suppress from datetime import datetime from functools import partial from torch.nn.parallel import DistributedDataParallel as NativeDDP from timm import utils from timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset from timm.layers import convert_splitbn_model, convert_sync_batchnorm, set_fast_norm from timm.loss import JsdCrossEntropy, SoftTargetCrossEntropy, BinaryCrossEntropy, LabelSmoothingCrossEntropy from timm.models import create_model, safe_model_name, resume_checkpoint, load_checkpoint, model_parameters from timm.optim import create_optimizer_v2, optimizer_kwargs from timm.scheduler import create_scheduler_v2, scheduler_kwargs from timm.utils import ApexScaler, NativeScaler from data.new_load_data import get_dataset, get_combined_dataset from apex import amp from apex.parallel import DistributedDataParallel as ApexDDP from apex.parallel import convert_syncbn_model from functorch.compile import memory_efficient_fusion
3,707
num_aug_splits = args.aug_splits # enable split bn (separate bn stats per batch-portion) if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2)) # move model to GPU, enable channels last layout if set model.to(device=device) if args.channels_last: model.to(memory_format=torch.channels_last) # setup synchronized BatchNorm for distributed training if args.distributed and args.sync_bn: args.dist_bn = '' # disable dist_bn when sync BN active assert not args.split_bn if has_apex and use_amp == 'apex': # Apex SyncBN used with Apex AMP # WARNING this won't currently work with models using BatchNormAct2d model = convert_syncbn_model(model) else: model = convert_sync_batchnorm(model) if utils.is_primary(args): _logger.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') if args.torchscript: assert not args.torchcompile assert not use_amp == 'apex', 'Cannot use APEX AMP with torchscripted model' assert not args.sync_bn, 'Cannot use SyncBatchNorm with torchscripted model' model = torch.jit.script(model) if not args.lr: global_batch_size = args.batch_size * args.world_size * args.grad_accum_steps batch_ratio = global_batch_size / args.lr_base_size if not args.lr_base_scale: on = args.opt.lower() args.lr_base_scale = 'sqrt' if any([o in on for o in ('ada', 'lamb')]) else 'linear' if args.lr_base_scale == 'sqrt': batch_ratio = batch_ratio ** 0.5 args.lr = args.lr_base * batch_ratio if utils.is_primary(args): _logger.info( f'Learning rate ({args.lr}) calculated from base learning rate ({args.lr_base}) ' f'and effective global batch size ({global_batch_size}) with {args.lr_base_scale} scaling.') optimizer = create_optimizer_v2( model, **optimizer_kwargs(cfg=args), **args.opt_kwargs, ) # setup automatic mixed-precision (AMP) loss scaling and op casting amp_autocast = suppress # do nothing loss_scaler = None if use_amp == 'apex': assert device.type == 'cuda' model, optimizer = amp.initialize(model, optimizer, opt_level='O1') loss_scaler = ApexScaler() if utils.is_primary(args): _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') elif use_amp == 'native': try: amp_autocast = partial(torch.autocast, device_type=device.type, dtype=amp_dtype) except (AttributeError, TypeError): # fallback to CUDA only AMP for PyTorch < 1.10 assert device.type == 'cuda' amp_autocast = torch.cuda.amp.autocast if device.type == 'cuda' and amp_dtype == torch.float16: # loss scaler only used for float16 (half) dtype, bfloat16 does not need it loss_scaler = NativeScaler() if utils.is_primary(args): _logger.info('Using native Torch AMP. Training in mixed precision.') else: if utils.is_primary(args): _logger.info('AMP not enabled. Training in float32.') # optionally resume from a checkpoint resume_epoch = None if args.resume: resume_epoch = resume_checkpoint( model, args.resume, optimizer=None if args.no_resume_opt else optimizer, loss_scaler=None if args.no_resume_opt else loss_scaler, log_info=utils.is_primary(args), ) # setup exponential moving average of model weights, SWA could be used here too model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before DDP wrapper model_ema = utils.ModelEmaV2( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else None) if args.resume: load_checkpoint(model_ema.module, args.resume, use_ema=True) # setup distributed training if args.distributed: if has_apex and use_amp == 'apex': # Apex DDP preferred unless native amp is activated if utils.is_primary(args): _logger.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if utils.is_primary(args): _logger.info("Using native Torch DistributedDataParallel.") model = NativeDDP(model, device_ids=[device], broadcast_buffers=not args.no_ddp_bb) # NOTE: EMA model does not need to be wrapped by DDP if args.torchcompile: # torch compile should be done after DDP assert has_compile, 'A version of torch w/ torch.compile() is required for --compile, possibly a nightly.' model = torch.compile(model, backend=args.torchcompile) # create the train and eval datasets if args.data and not args.data_dir: args.data_dir = args.data
#!/usr/bin/env python3 """ ImageNet Training Script This is intended to be a lean and easily modifiable ImageNet training script that reproduces ImageNet training results with some of the latest networks and training techniques. It favours canonical PyTorch and standard Python style over trying to be able to 'do it all.' That said, it offers quite a few speed and training result improvements over the usual PyTorch example scripts. Repurpose as you see fit. This script was started from an early version of the PyTorch ImageNet example (https://github.com/pytorch/examples/tree/master/imagenet) NVIDIA CUDA specific speedups adopted from NVIDIA Apex examples (https://github.com/NVIDIA/apex/tree/master/examples/imagenet) Hacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman) """ try: has_apex = True except ImportError: has_apex = False has_native_amp = False try: if getattr(torch.cuda.amp, 'autocast') is not None: has_native_amp = True except AttributeError: pass try: has_wandb = True except ImportError: has_wandb = False try: has_functorch = True except ImportError as e: has_functorch = False has_compile = hasattr(torch, 'compile') _logger = logging.getLogger('train') # The first arg parser parses out only the --config argument, this argument is used to # load a yaml file containing key-values that override the defaults for the main parser below config_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False) parser.add_argument('-c', '--config', default='', type=str, metavar='FILE', help='YAML config file specifying default arguments') parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') # Dataset parameters group = parser.add_argument_group('Dataset parameters') # Keep this argument outside the dataset group because it is positional. parser.add_argument('data', nargs='?', metavar='DIR', const=None, help='path to dataset (positional is *deprecated*, use --data-dir)') parser.add_argument('--data-dir', metavar='DIR', default="", help='path to dataset (root dir)') parser.add_argument('--imagenet_path', metavar='DIR', default="", help='path to real ImageNet') parser.add_argument('--dataset', metavar='NAME', default='', help='dataset type + name ("<type>/<name>") (default: ImageFolder or ImageTar if empty)') parser.add_argument('--use_caption', action='store_true') parser.add_argument("--guidance_scale", type=float, default=3, help="guidance scale") parser.add_argument('--comb_dataset', type=str, nargs='*', default=None, help='A list of dataset') group.add_argument('--train-split', metavar='NAME', default='train', help='dataset train split (default: train)') group.add_argument('--val-split', metavar='NAME', default='validation', help='dataset validation split (default: validation)') group.add_argument('--dataset-download', action='store_true', default=False, help='Allow download of dataset for torch/ and tfds/ datasets that support it.') group.add_argument('--class-map', default='', type=str, metavar='FILENAME', help='path to class to idx mapping file (default: "")') # Model parameters group = parser.add_argument_group('Model parameters') group.add_argument('--model', default='resnet50', type=str, metavar='MODEL', help='Name of model to train (default: "resnet50")') group.add_argument('--pretrained', action='store_true', default=False, help='Start with pretrained version of specified network (if avail)') group.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH', help='Initialize model from this checkpoint (default: none)') group.add_argument('--resume', default='', type=str, metavar='PATH', help='Resume full model and optimizer state from checkpoint (default: none)') group.add_argument('--no-resume-opt', action='store_true', default=False, help='prevent resume of optimizer state when resuming model') group.add_argument('--num-classes', type=int, default=None, metavar='N', help='number of label classes (Model default if None)') group.add_argument('--gp', default=None, type=str, metavar='POOL', help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.') group.add_argument('--img-size', type=int, default=None, metavar='N', help='Image size (default: None => model default)') group.add_argument('--in-chans', type=int, default=None, metavar='N', help='Image input channels (default: None => 3)') group.add_argument('--input-size', default=None, nargs=3, type=int, metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty') group.add_argument('--crop-pct', default=None, type=float, metavar='N', help='Input image center crop percent (for validation only)') group.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN', help='Override mean pixel value of dataset') group.add_argument('--std', type=float, nargs='+', default=None, metavar='STD', help='Override std deviation of dataset') group.add_argument('--interpolation', default='', type=str, metavar='NAME', help='Image resize interpolation type (overrides model)') group.add_argument('-b', '--batch-size', type=int, default=128, metavar='N', help='Input batch size for training (default: 128)') group.add_argument('-vb', '--validation-batch-size', type=int, default=None, metavar='N', help='Validation batch size override (default: None)') group.add_argument('--channels-last', action='store_true', default=False, help='Use channels_last memory layout') group.add_argument('--fuser', default='', type=str, help="Select jit fuser. One of ('', 'te', 'old', 'nvfuser')") group.add_argument('--grad-accum-steps', type=int, default=1, metavar='N', help='The number of steps to accumulate gradients (default: 1)') group.add_argument('--grad-checkpointing', action='store_true', default=False, help='Enable gradient checkpointing through model blocks/stages') group.add_argument('--fast-norm', default=False, action='store_true', help='enable experimental fast-norm') group.add_argument('--model-kwargs', nargs='*', default={}, action=utils.ParseKwargs) group.add_argument('--head-init-scale', default=None, type=float, help='Head initialization scale') group.add_argument('--head-init-bias', default=None, type=float, help='Head initialization bias value') # scripting / codegen scripting_group = group.add_mutually_exclusive_group() scripting_group.add_argument('--torchscript', dest='torchscript', action='store_true', help='torch.jit.script the full model') scripting_group.add_argument('--torchcompile', nargs='?', type=str, default=None, const='inductor', help="Enable compilation w/ specified backend (default: inductor).") # Optimizer parameters group = parser.add_argument_group('Optimizer parameters') group.add_argument('--opt', default='sgd', type=str, metavar='OPTIMIZER', help='Optimizer (default: "sgd")') group.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: None, use opt default)') group.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') group.add_argument('--momentum', type=float, default=0.9, metavar='M', help='Optimizer momentum (default: 0.9)') group.add_argument('--weight-decay', type=float, default=2e-5, help='weight decay (default: 2e-5)') group.add_argument('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') group.add_argument('--clip-mode', type=str, default='norm', help='Gradient clipping mode. One of ("norm", "value", "agc")') group.add_argument('--layer-decay', type=float, default=None, help='layer-wise learning rate decay (default: None)') group.add_argument('--opt-kwargs', nargs='*', default={}, action=utils.ParseKwargs) # Learning rate schedule parameters group = parser.add_argument_group('Learning rate schedule parameters') group.add_argument('--sched', type=str, default='cosine', metavar='SCHEDULER', help='LR scheduler (default: "step"') group.add_argument('--sched-on-updates', action='store_true', default=False, help='Apply LR scheduler step on update instead of epoch end.') group.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate, overrides lr-base if set (default: None)') group.add_argument('--lr-base', type=float, default=0.1, metavar='LR', help='base learning rate: lr = lr_base * global_batch_size / base_size') group.add_argument('--lr-base-size', type=int, default=256, metavar='DIV', help='base learning rate batch size (divisor, default: 256).') group.add_argument('--lr-base-scale', type=str, default='', metavar='SCALE', help='base learning rate vs batch_size scaling ("linear", "sqrt", based on opt if empty)') group.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') group.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') group.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') group.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT', help='learning rate cycle len multiplier (default: 1.0)') group.add_argument('--lr-cycle-decay', type=float, default=0.5, metavar='MULT', help='amount to decay each learning rate cycle (default: 0.5)') group.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N', help='learning rate cycle limit, cycles enabled if > 1') group.add_argument('--lr-k-decay', type=float, default=1.0, help='learning rate k-decay for cosine/poly (default: 1.0)') group.add_argument('--warmup-lr', type=float, default=1e-5, metavar='LR', help='warmup learning rate (default: 1e-5)') group.add_argument('--min-lr', type=float, default=0, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (default: 0)') group.add_argument('--epochs', type=int, default=300, metavar='N', help='number of epochs to train (default: 300)') group.add_argument('--epoch-repeats', type=float, default=0., metavar='N', help='epoch repeat multiplier (number of times to repeat dataset epoch per train epoch).') group.add_argument('--start-epoch', default=None, type=int, metavar='N', help='manual epoch number (useful on restarts)') # group.add_argument('--decay-milestones', default=[90, 180, 270], type=int, nargs='+', metavar="MILESTONES", # help='list of decay epoch indices for multistep lr. must be increasing') group.add_argument('--decay-milestones', default=[50, 100, 150], type=int, nargs='+', metavar="MILESTONES", help='list of decay epoch indices for multistep lr. must be increasing') group.add_argument('--decay-epochs', type=float, default=90, metavar='N', help='epoch interval to decay LR') group.add_argument('--warmup-epochs', type=int, default=5, metavar='N', help='epochs to warmup LR, if scheduler supports') group.add_argument('--warmup-prefix', action='store_true', default=False, help='Exclude warmup period from decay schedule.'), group.add_argument('--cooldown-epochs', type=int, default=0, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') group.add_argument('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10)') group.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)') # Augmentation & regularization parameters group = parser.add_argument_group('Augmentation and regularization parameters') group.add_argument('--no-aug', action='store_true', default=False, help='Disable all training augmentation, override other train aug args') group.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT', help='Random resize scale (default: 0.08 1.0)') group.add_argument('--ratio', type=float, nargs='+', default=[3. / 4., 4. / 3.], metavar='RATIO', help='Random resize aspect ratio (default: 0.75 1.33)') group.add_argument('--hflip', type=float, default=0.5, help='Horizontal flip training aug probability') group.add_argument('--vflip', type=float, default=0., help='Vertical flip training aug probability') group.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)') group.add_argument('--aa', type=str, default=None, metavar='NAME', help='Use AutoAugment policy. "v0" or "original". (default: None)'), group.add_argument('--aug-repeats', type=float, default=0, help='Number of augmentation repetitions (distributed training only) (default: 0)') group.add_argument('--aug-splits', type=int, default=0, help='Number of augmentation splits (default: 0, valid: 0 or >=2)') group.add_argument('--jsd-loss', action='store_true', default=False, help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.') group.add_argument('--bce-loss', action='store_true', default=False, help='Enable BCE loss w/ Mixup/CutMix use.') group.add_argument('--bce-target-thresh', type=float, default=None, help='Threshold for binarizing softened BCE targets (default: None, disabled)') group.add_argument('--reprob', type=float, default=0., metavar='PCT', help='Random erase prob (default: 0.)') group.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') group.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') group.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') group.add_argument('--mixup', type=float, default=0.0, help='mixup alpha, mixup enabled if > 0. (default: 0.)') group.add_argument('--cutmix', type=float, default=0.0, help='cutmix alpha, cutmix enabled if > 0. (default: 0.)') group.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') group.add_argument('--mixup-prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') group.add_argument('--mixup-switch-prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') group.add_argument('--mixup-mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') group.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N', help='Turn off mixup after this epoch, disabled if 0 (default: 0)') group.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') group.add_argument('--train-interpolation', type=str, default='random', help='Training interpolation (random, bilinear, bicubic default: "random")') group.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.)') group.add_argument('--drop-connect', type=float, default=None, metavar='PCT', help='Drop connect rate, DEPRECATED, use drop-path (default: None)') group.add_argument('--drop-path', type=float, default=None, metavar='PCT', help='Drop path rate (default: None)') group.add_argument('--drop-block', type=float, default=None, metavar='PCT', help='Drop block rate (default: None)') # Batch norm parameters (only works with gen_efficientnet based models currently) group = parser.add_argument_group('Batch norm parameters', 'Only works with gen_efficientnet based models currently.') group.add_argument('--bn-momentum', type=float, default=None, help='BatchNorm momentum override (if not None)') group.add_argument('--bn-eps', type=float, default=None, help='BatchNorm epsilon override (if not None)') group.add_argument('--sync-bn', action='store_true', help='Enable NVIDIA Apex or Torch synchronized BatchNorm.') group.add_argument('--dist-bn', type=str, default='reduce', help='Distribute BatchNorm stats between nodes after each epoch ("broadcast", "reduce", or "")') group.add_argument('--split-bn', action='store_true', help='Enable separate BN layers per augmentation split.') # Model Exponential Moving Average group = parser.add_argument_group('Model exponential moving average parameters') group.add_argument('--model-ema', action='store_true', default=False, help='Enable tracking moving average of model weights') group.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.') group.add_argument('--model-ema-decay', type=float, default=0.9998, help='decay factor for model weights moving average (default: 0.9998)') # Misc group = parser.add_argument_group('Miscellaneous parameters') group.add_argument('--seed', type=int, default=42, metavar='S', help='random seed (default: 42)') group.add_argument('--worker-seeding', type=str, default='all', help='worker seed mode (default: all)') group.add_argument('--log-interval', type=int, default=50, metavar='N', help='how many batches to wait before logging training status') group.add_argument('--recovery-interval', type=int, default=0, metavar='N', help='how many batches to wait before writing recovery checkpoint') group.add_argument('--checkpoint-hist', type=int, default=10, metavar='N', help='number of checkpoints to keep (default: 10)') group.add_argument('-j', '--workers', type=int, default=4, metavar='N', help='how many training processes to use (default: 4)') group.add_argument('--save-images', action='store_true', default=False, help='save images of input bathes every log interval for debugging') group.add_argument('--amp', action='store_true', default=False, help='use NVIDIA Apex AMP or Native AMP for mixed precision training') group.add_argument('--amp-dtype', default='float16', type=str, help='lower precision AMP dtype (default: float16)') group.add_argument('--amp-impl', default='native', type=str, help='AMP impl to use, "native" or "apex" (default: native)') group.add_argument('--no-ddp-bb', action='store_true', default=False, help='Force broadcast buffers for native DDP to off.') group.add_argument('--synchronize-step', action='store_true', default=False, help='torch.cuda.synchronize() end of each step') group.add_argument('--pin-mem', action='store_true', default=False, help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') group.add_argument('--no-prefetcher', action='store_true', default=False, help='disable fast prefetcher') group.add_argument('--output', default='', type=str, metavar='PATH', help='path to output folder (default: none, current dir)') group.add_argument('--experiment', default='', type=str, metavar='NAME', help='name of train experiment, name of sub-folder for output') group.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC', help='Best metric (default: "top1"') group.add_argument('--tta', type=int, default=0, metavar='N', help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)') group.add_argument("--local_rank", default=0, type=int) group.add_argument('--use-multi-epochs-loader', action='store_true', default=False, help='use the multi-epochs-loader to save time at the beginning of every epoch') group.add_argument('--log-wandb', action='store_true', default=False, help='log training and validation metrics to wandb') def _parse_args(): # Do we have a config file to parse? args_config, remaining = config_parser.parse_known_args() if args_config.config: with open(args_config.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg) # The main arg parser parses the rest of the args, the usual # defaults will have been overridden if config file specified. args = parser.parse_args(remaining) # Cache the args as a text string to save them in the output dir later args_text = yaml.safe_dump(args.__dict__, default_flow_style=False) return args, args_text def main(): utils.setup_default_logging() args, args_text = _parse_args() if torch.cuda.is_available(): torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.benchmark = True args.prefetcher = not args.no_prefetcher args.grad_accum_steps = max(1, args.grad_accum_steps) device = utils.init_distributed_device(args) if args.distributed: _logger.info( 'Training in distributed mode with multiple processes, 1 device per process.' f'Process {args.rank}, total {args.world_size}, device {args.device}.') else: _logger.info(f'Training with a single process on 1 device ({args.device}).') assert args.rank >= 0 # resolve AMP arguments based on PyTorch / Apex availability use_amp = None amp_dtype = torch.float16 if args.amp: if args.amp_impl == 'apex': assert has_apex, 'AMP impl specified as APEX but APEX is not installed.' use_amp = 'apex' assert args.amp_dtype == 'float16' else: assert has_native_amp, 'Please update PyTorch to a version with native AMP (or use APEX).' use_amp = 'native' assert args.amp_dtype in ('float16', 'bfloat16') if args.amp_dtype == 'bfloat16': amp_dtype = torch.bfloat16 utils.random_seed(args.seed, args.rank) if args.fuser: utils.set_jit_fuser(args.fuser) if args.fast_norm: set_fast_norm() in_chans = 3 if args.in_chans is not None: in_chans = args.in_chans elif args.input_size is not None: in_chans = args.input_size[0] model = create_model( args.model, pretrained=args.pretrained, in_chans=in_chans, num_classes=args.num_classes, drop_rate=args.drop, drop_path_rate=args.drop_path, drop_block_rate=args.drop_block, global_pool=args.gp, bn_momentum=args.bn_momentum, bn_eps=args.bn_eps, scriptable=args.torchscript, checkpoint_path=args.initial_checkpoint, **args.model_kwargs, ) if args.head_init_scale is not None: with torch.no_grad(): model.get_classifier().weight.mul_(args.head_init_scale) model.get_classifier().bias.mul_(args.head_init_scale) if args.head_init_bias is not None: nn.init.constant_(model.get_classifier().bias, args.head_init_bias) if args.num_classes is None: assert hasattr(model, 'num_classes'), 'Model must have `num_classes` attr if not set on cmd line/config.' args.num_classes = model.num_classes # FIXME handle model default vs config num_classes more elegantly if args.grad_checkpointing: model.set_grad_checkpointing(enable=True) if utils.is_primary(args): _logger.info( f'Model {safe_model_name(args.model)} created, param count:{sum([m.numel() for m in model.parameters()])}') data_config = resolve_data_config(vars(args), model=model, verbose=utils.is_primary(args)) # setup augmentation batch splits for contrastive loss or split bn num_aug_splits = 0 if args.aug_splits > 0: assert args.aug_splits > 1, 'A split of 1 makes no sense' num_aug_splits = args.aug_splits # enable split bn (separate bn stats per batch-portion) if args.split_bn: assert num_aug_splits > 1 or args.resplit model = convert_splitbn_model(model, max(num_aug_splits, 2)) # move model to GPU, enable channels last layout if set model.to(device=device) if args.channels_last: model.to(memory_format=torch.channels_last) # setup synchronized BatchNorm for distributed training if args.distributed and args.sync_bn: args.dist_bn = '' # disable dist_bn when sync BN active assert not args.split_bn if has_apex and use_amp == 'apex': # Apex SyncBN used with Apex AMP # WARNING this won't currently work with models using BatchNormAct2d model = convert_syncbn_model(model) else: model = convert_sync_batchnorm(model) if utils.is_primary(args): _logger.info( 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using ' 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.') if args.torchscript: assert not args.torchcompile assert not use_amp == 'apex', 'Cannot use APEX AMP with torchscripted model' assert not args.sync_bn, 'Cannot use SyncBatchNorm with torchscripted model' model = torch.jit.script(model) if not args.lr: global_batch_size = args.batch_size * args.world_size * args.grad_accum_steps batch_ratio = global_batch_size / args.lr_base_size if not args.lr_base_scale: on = args.opt.lower() args.lr_base_scale = 'sqrt' if any([o in on for o in ('ada', 'lamb')]) else 'linear' if args.lr_base_scale == 'sqrt': batch_ratio = batch_ratio ** 0.5 args.lr = args.lr_base * batch_ratio if utils.is_primary(args): _logger.info( f'Learning rate ({args.lr}) calculated from base learning rate ({args.lr_base}) ' f'and effective global batch size ({global_batch_size}) with {args.lr_base_scale} scaling.') optimizer = create_optimizer_v2( model, **optimizer_kwargs(cfg=args), **args.opt_kwargs, ) # setup automatic mixed-precision (AMP) loss scaling and op casting amp_autocast = suppress # do nothing loss_scaler = None if use_amp == 'apex': assert device.type == 'cuda' model, optimizer = amp.initialize(model, optimizer, opt_level='O1') loss_scaler = ApexScaler() if utils.is_primary(args): _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.') elif use_amp == 'native': try: amp_autocast = partial(torch.autocast, device_type=device.type, dtype=amp_dtype) except (AttributeError, TypeError): # fallback to CUDA only AMP for PyTorch < 1.10 assert device.type == 'cuda' amp_autocast = torch.cuda.amp.autocast if device.type == 'cuda' and amp_dtype == torch.float16: # loss scaler only used for float16 (half) dtype, bfloat16 does not need it loss_scaler = NativeScaler() if utils.is_primary(args): _logger.info('Using native Torch AMP. Training in mixed precision.') else: if utils.is_primary(args): _logger.info('AMP not enabled. Training in float32.') # optionally resume from a checkpoint resume_epoch = None if args.resume: resume_epoch = resume_checkpoint( model, args.resume, optimizer=None if args.no_resume_opt else optimizer, loss_scaler=None if args.no_resume_opt else loss_scaler, log_info=utils.is_primary(args), ) # setup exponential moving average of model weights, SWA could be used here too model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before DDP wrapper model_ema = utils.ModelEmaV2( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else None) if args.resume: load_checkpoint(model_ema.module, args.resume, use_ema=True) # setup distributed training if args.distributed: if has_apex and use_amp == 'apex': # Apex DDP preferred unless native amp is activated if utils.is_primary(args): _logger.info("Using NVIDIA APEX DistributedDataParallel.") model = ApexDDP(model, delay_allreduce=True) else: if utils.is_primary(args): _logger.info("Using native Torch DistributedDataParallel.") model = NativeDDP(model, device_ids=[device], broadcast_buffers=not args.no_ddp_bb) # NOTE: EMA model does not need to be wrapped by DDP if args.torchcompile: # torch compile should be done after DDP assert has_compile, 'A version of torch w/ torch.compile() is required for --compile, possibly a nightly.' model = torch.compile(model, backend=args.torchcompile) # create the train and eval datasets if args.data and not args.data_dir: args.data_dir = args.data
dataset_train = get_dataset(args.data_dir, split="train",subset=args.dataset,filelist="file_list.txt")
0
2023-10-09 14:26:22+00:00
8k
HyemiEsme/PUCA
src/datahandler/denoise_dataset.py
[ { "identifier": "rot_hflip_img", "path": "src/util/util.py", "snippet": "def rot_hflip_img(img:torch.Tensor, rot_times:int=0, hflip:int=0):\n '''\n rotate '90 x times degree' & horizontal flip image \n (shape of img: b,c,h,w or c,h,w)\n '''\n b=0 if len(img.shape)==3 else 1\n # no flip...
import random, os import cv2 import numpy as np import torch from scipy.io import savemat from torch.utils.data import Dataset from ..util.util import rot_hflip_img, tensor2np, np2tensor, mean_conv2d from ..datahandler import get_dataset_object
3,866
max_x = data['clean'].shape[2] - crop_size[0] max_y = data['clean'].shape[1] - crop_size[1] else: max_x = data['real_noisy'].shape[2] - crop_size[0] max_y = data['real_noisy'].shape[1] - crop_size[1] assert max_x >= 0 assert max_y >= 0 if rnd and max_x>0 and max_y>0: x = np.random.randint(0, max_x) y = np.random.randint(0, max_y) else: x, y = 0, 0 # crop if 'clean' in data: data['clean'] = data['clean'][:, y:y+crop_size[1], x:x+crop_size[0]] if 'real_noisy' in data: data['real_noisy'] = data['real_noisy'][:, y:y+crop_size[1], x:x+crop_size[0]] return data def normalize_data(self, data, cuda=False): # for all image for key in data: if self._is_image_tensor(data[key]): data[key] = self.normalize(data[key], cuda) return data def inverse_normalize_data(self, data, cuda=False): # for all image for key in data: # is image if self._is_image_tensor(data[key]): data[key] = self.inverse_normalize(data[key], cuda) return data def normalize(self, img, cuda=False): if img.shape[0] == 1: stds = self.gray_stds means = self.gray_means elif img.shape[0] == 3: stds = self.color_stds means = self.color_means else: raise RuntimeError('undefined image channel length : %d'%img.shape[0]) if cuda: means, stds = means.cuda(), stds.cuda() return (img-means) / stds def inverse_normalize(self, img, cuda=False): if img.shape[0] == 1: stds = self.gray_stds means = self.gray_means elif img.shape[0] == 3: stds = self.color_stds means = self.color_means else: raise RuntimeError('undefined image channel length : %d'%img.shape[0]) if cuda: means, stds = means.cuda(), stds.cuda() return (img*stds) + means def _parse_add_noise(self, add_noise_str:str): ''' noise_type-opt0:opt1:opt2-clamp ''' if add_noise_str == 'bypass': return 'bypass', None, None elif add_noise_str != None: add_noise_type = add_noise_str.split('-')[0] add_noise_opt = [float(v) for v in add_noise_str.split('-')[1].split(':')] add_noise_clamp = len(add_noise_str.split('-'))>2 and add_noise_str.split('-')[2] == 'clamp' return add_noise_type, add_noise_opt, add_noise_clamp else: return None, None, None def _add_noise(self, clean_img:torch.Tensor, add_noise_type:str, opt:list, clamp:bool=False) -> torch.Tensor: ''' add various noise to clean image. Args: clean_img (Tensor) : clean image to synthesize on add_noise_type : below types are available opt (list) : args for synthsize noise clamp (bool) : optional, clamp noisy image into [0,255] Return: synthesized_img Noise_types - bypass : bypass clean image - uni : uniform distribution noise from -opt[0] ~ opt[0] - gau : gaussian distribution noise with zero-mean & opt[0] variance - gau_blind : blind gaussian distribution with zero-mean, variance is uniformly selected from opt[0] ~ opt[1] - struc_gau : structured gaussian noise. gaussian filter is applied to above gaussian noise. opt[0] is variance of gaussian, opt[1] is window size and opt[2] is sigma of gaussian filter. - het_gau : heteroscedastic gaussian noise with indep weight:opt[0], dep weight:opt[1] ''' nlf = None if add_noise_type == 'bypass': # bypass clean image synthesized_img = clean_img elif add_noise_type == 'uni': # add uniform noise synthesized_img = clean_img + 2*opt[0] * torch.rand(clean_img.shape) - opt[0] elif add_noise_type == 'gau': # add AWGN nlf = opt[0] synthesized_img = clean_img + torch.normal(mean=0., std=nlf, size=clean_img.shape) elif add_noise_type == 'gau_blind': # add blind gaussian noise nlf = random.uniform(opt[0], opt[1]) synthesized_img = clean_img + torch.normal(mean=0., std=nlf, size=clean_img.shape) elif add_noise_type == 'struc_gau': # add structured gaussian noise (used in the paper "Noiser2Noise": https://arxiv.org/pdf/1910.11908.pdf) nlf = opt[0] gau_noise = torch.normal(mean=0., std=opt[0], size=clean_img.shape)
class DenoiseDataSet(Dataset): def __init__(self, add_noise:str=None, crop_size:list=None, aug:list=None, n_repeat:int=1, n_data:int=None, ratio_data:float=None) -> None: ''' Base denoising dataset class for various dataset. to build custom dataset class, below functions must be implemented in the inherited class. (or see other dataset class already implemented.) - self._scan(self) : scan image data & save its paths. (saved to self.img_paths) - self._load_data(self, data_idx) : load single paired data from idx as a form of dictionary. Args: add_noise (str) : configuration of additive noise to synthesize noisy image. (see _add_noise() for more details.) crop_size (list) : crop size, e.g. [W] or [H, W] and no crop if None aug (list) : list of data augmentations (see _augmentation() for more details.) n_repeat (int) : number of repeat for each data. n_data (int) : number of data to be used. (default: None = all data) ratio_data (float) : ratio of data to be used. (activated when n_data=None, default: None = all data) ''' self.dataset_dir = '../dataset' if not os.path.isdir(self.dataset_dir): raise Exception('dataset directory is not exist') # parse additive noise argument self.add_noise_type, self.add_noise_opt, self.add_noise_clamp = self._parse_add_noise(add_noise) # set parameters for dataset. self.crop_size = crop_size self.aug = aug self.n_repeat = n_repeat # scan all data and fill in self.img_paths self.img_paths = [] self._scan() if len(self.img_paths) > 0: if self.img_paths[0].__class__.__name__ in ['int', 'str', 'float']: self.img_paths.sort() # set data amount if n_data is not None: self.n_data = n_data elif ratio_data is not None: self.n_data = int(ratio_data * len(self.img_paths)) else: self.n_data = len(self.img_paths) def __len__(self): return self.n_data * self.n_repeat def __getitem__(self, idx): ''' final dictionary shape of data: {'clean', 'syn_noisy', 'real_noisy', 'noisy (any of real[first priority] and syn)', etc} ''' # calculate data index data_idx = idx % self.n_data # load data data = self._load_data(data_idx) # pre-processing (currently only crop) data = self._pre_processing(data) # synthesize additive noise if self.add_noise_type is not None: if 'clean' in data: syn_noisy_img, nlf = self._add_noise(data['clean'], self.add_noise_type, self.add_noise_opt, self.add_noise_clamp) data['syn_noisy'] = syn_noisy_img data['nlf'] = nlf elif 'real_noisy' in data: syn_noisy_img, nlf = self._add_noise(data['real_noisy'], self.add_noise_type, self.add_noise_opt, self.add_noise_clamp) data['syn_noisy'] = syn_noisy_img data['nlf'] = nlf else: raise RuntimeError('there is no clean or real image to synthesize. (synthetic noise type: %s)'%self.add_noise_type) # data augmentation if self.aug is not None: data = self._augmentation(data, self.aug) # add general label 'noisy' to use any of real_noisy or syn_noisy (real first) if 'real_noisy' in data or 'syn_noisy' in data: data['noisy'] = data['real_noisy'] if 'real_noisy' in data else data['syn_noisy'] return data def _scan(self): raise NotImplementedError # TODO fill in self.img_paths (include path from project directory) def _load_data(self, data_idx): raise NotImplementedError # TODO load possible data as dictionary # dictionary key list : # 'clean' : clean image without noise (gt or anything). # 'real_noisy' : real noisy image or already synthesized noisy image. # 'instances' : any other information of capturing situation. #----------------------------# # Image handling functions # #----------------------------# def _load_img(self, img_name, as_gray=False): img = cv2.imread(img_name, 1) assert img is not None, "failure on loading image - %s"%img_name return self._load_img_from_np(img, as_gray, RGBflip=True) def _load_img_from_np(self, img, as_gray=False, RGBflip=False): # if color if len(img.shape) != 2: if as_gray: # follows definition of sRBG in terms of the CIE 1931 linear luminance. # because calculation opencv color conversion and imread grayscale mode is a bit different. # https://en.wikipedia.org/wiki/Grayscale img = np.average(img, axis=2, weights=[0.0722, 0.7152, 0.2126]) img = np.expand_dims(img, axis=0) else: if RGBflip: img = np.flip(img, axis=2) img = np.transpose(img, (2,0,1)) # if gray else: img = np.expand_dims(img, axis=0) return torch.from_numpy(np.ascontiguousarray(img).astype(np.float32)) def _pre_processing(self, data): # get a patch from image data if self.crop_size != None: data = self._get_patch(self.crop_size, data) return data def _get_patch(self, crop_size, data, rnd=True): # check all image size is same if 'clean' in data and 'real_noisy' in data: assert data['clean'].shape[1] == data['clean'].shape[1] and data['real_noisy'].shape[2] == data['real_noisy'].shape[2], \ 'img shape should be same. (%d, %d) != (%d, %d)' % (data['clean'].shape[1], data['clean'].shape[1], data['real_noisy'].shape[2], data['real_noisy'].shape[2]) # get image shape and select random crop location if 'clean' in data: max_x = data['clean'].shape[2] - crop_size[0] max_y = data['clean'].shape[1] - crop_size[1] else: max_x = data['real_noisy'].shape[2] - crop_size[0] max_y = data['real_noisy'].shape[1] - crop_size[1] assert max_x >= 0 assert max_y >= 0 if rnd and max_x>0 and max_y>0: x = np.random.randint(0, max_x) y = np.random.randint(0, max_y) else: x, y = 0, 0 # crop if 'clean' in data: data['clean'] = data['clean'][:, y:y+crop_size[1], x:x+crop_size[0]] if 'real_noisy' in data: data['real_noisy'] = data['real_noisy'][:, y:y+crop_size[1], x:x+crop_size[0]] return data def normalize_data(self, data, cuda=False): # for all image for key in data: if self._is_image_tensor(data[key]): data[key] = self.normalize(data[key], cuda) return data def inverse_normalize_data(self, data, cuda=False): # for all image for key in data: # is image if self._is_image_tensor(data[key]): data[key] = self.inverse_normalize(data[key], cuda) return data def normalize(self, img, cuda=False): if img.shape[0] == 1: stds = self.gray_stds means = self.gray_means elif img.shape[0] == 3: stds = self.color_stds means = self.color_means else: raise RuntimeError('undefined image channel length : %d'%img.shape[0]) if cuda: means, stds = means.cuda(), stds.cuda() return (img-means) / stds def inverse_normalize(self, img, cuda=False): if img.shape[0] == 1: stds = self.gray_stds means = self.gray_means elif img.shape[0] == 3: stds = self.color_stds means = self.color_means else: raise RuntimeError('undefined image channel length : %d'%img.shape[0]) if cuda: means, stds = means.cuda(), stds.cuda() return (img*stds) + means def _parse_add_noise(self, add_noise_str:str): ''' noise_type-opt0:opt1:opt2-clamp ''' if add_noise_str == 'bypass': return 'bypass', None, None elif add_noise_str != None: add_noise_type = add_noise_str.split('-')[0] add_noise_opt = [float(v) for v in add_noise_str.split('-')[1].split(':')] add_noise_clamp = len(add_noise_str.split('-'))>2 and add_noise_str.split('-')[2] == 'clamp' return add_noise_type, add_noise_opt, add_noise_clamp else: return None, None, None def _add_noise(self, clean_img:torch.Tensor, add_noise_type:str, opt:list, clamp:bool=False) -> torch.Tensor: ''' add various noise to clean image. Args: clean_img (Tensor) : clean image to synthesize on add_noise_type : below types are available opt (list) : args for synthsize noise clamp (bool) : optional, clamp noisy image into [0,255] Return: synthesized_img Noise_types - bypass : bypass clean image - uni : uniform distribution noise from -opt[0] ~ opt[0] - gau : gaussian distribution noise with zero-mean & opt[0] variance - gau_blind : blind gaussian distribution with zero-mean, variance is uniformly selected from opt[0] ~ opt[1] - struc_gau : structured gaussian noise. gaussian filter is applied to above gaussian noise. opt[0] is variance of gaussian, opt[1] is window size and opt[2] is sigma of gaussian filter. - het_gau : heteroscedastic gaussian noise with indep weight:opt[0], dep weight:opt[1] ''' nlf = None if add_noise_type == 'bypass': # bypass clean image synthesized_img = clean_img elif add_noise_type == 'uni': # add uniform noise synthesized_img = clean_img + 2*opt[0] * torch.rand(clean_img.shape) - opt[0] elif add_noise_type == 'gau': # add AWGN nlf = opt[0] synthesized_img = clean_img + torch.normal(mean=0., std=nlf, size=clean_img.shape) elif add_noise_type == 'gau_blind': # add blind gaussian noise nlf = random.uniform(opt[0], opt[1]) synthesized_img = clean_img + torch.normal(mean=0., std=nlf, size=clean_img.shape) elif add_noise_type == 'struc_gau': # add structured gaussian noise (used in the paper "Noiser2Noise": https://arxiv.org/pdf/1910.11908.pdf) nlf = opt[0] gau_noise = torch.normal(mean=0., std=opt[0], size=clean_img.shape)
struc_gau = mean_conv2d(gau_noise, window_size=int(opt[1]), sigma=opt[2], keep_sigma=True)
3
2023-10-11 03:53:49+00:00
8k
LAION-AI/Discord-Scrapers
scrape_wuerstchen/scrape.py
[ { "identifier": "ScraperBot", "path": "scraper/scraper_bot.py", "snippet": "class ScraperBot:\n def __init__(\n self, config: ScraperBotConfig, condition_fn: Callable, parse_fn: Callable\n ) -> None:\n \"\"\"A bot that scrapes messages from a Discord channel and uploads them to the H...
import os from typing import Any, Dict, List from scraper import ScraperBot, ScraperBotConfig, HFDatasetScheme
4,607
def parse_fn(message: Dict[str, Any]) -> List[HFDatasetScheme]: """Parses a message into a list of Hugging Face Dataset Schemes. Parameters ---------- message : Dict[str, Any] The message to parse. Returns ------- List[HFDatasetScheme] A list of Hugging Face Dataset Schemes. """ prompt = message["content"].split("- <@")[0].strip().replace("**", "") image_urls = [attachment["url"] for attachment in message["attachments"]] timestamp = message["timestamp"] message_id = message["id"] return [HFDatasetScheme(caption=prompt, image=None, link=image_url, message_id=message_id, timestamp=timestamp) for image_url in image_urls] def condition_fn(message: Dict[str, Any]) -> bool: """Checks if a message meets the condition to be parsed. Parameters ---------- message : Dict[str, Any] The message to check. Returns ------- bool True if the message meets the condition, False otherwise. """ return len(message["attachments"]) > 0 if __name__ == "__main__": config_path = os.path.join(os.path.dirname(__file__), "config.json") config = ScraperBotConfig.from_json(config_path)
def parse_fn(message: Dict[str, Any]) -> List[HFDatasetScheme]: """Parses a message into a list of Hugging Face Dataset Schemes. Parameters ---------- message : Dict[str, Any] The message to parse. Returns ------- List[HFDatasetScheme] A list of Hugging Face Dataset Schemes. """ prompt = message["content"].split("- <@")[0].strip().replace("**", "") image_urls = [attachment["url"] for attachment in message["attachments"]] timestamp = message["timestamp"] message_id = message["id"] return [HFDatasetScheme(caption=prompt, image=None, link=image_url, message_id=message_id, timestamp=timestamp) for image_url in image_urls] def condition_fn(message: Dict[str, Any]) -> bool: """Checks if a message meets the condition to be parsed. Parameters ---------- message : Dict[str, Any] The message to check. Returns ------- bool True if the message meets the condition, False otherwise. """ return len(message["attachments"]) > 0 if __name__ == "__main__": config_path = os.path.join(os.path.dirname(__file__), "config.json") config = ScraperBotConfig.from_json(config_path)
bot = ScraperBot(config=config, parse_fn=parse_fn, condition_fn=condition_fn)
0
2023-10-09 15:22:15+00:00
8k
skingorz/FD-Align
modules/COSOC.py
[ { "identifier": "BaseFewShotModule", "path": "modules/base_module.py", "snippet": "class BaseFewShotModule(LightningModule):\n r\"\"\"Template for all few-shot learning models.\n \"\"\"\n def __init__(\n self,\n backbone_name: str = \"resnet12\",\n train_way: Optional[int] ...
from .base_module import BaseFewShotModule from architectures import CC_head, SOC from typing import Tuple, List, Optional, Union, Dict import torch.nn.functional as F
4,161
class COSOC(BaseFewShotModule): r"""The datamodule implementing COSOC after foreground extraction of COS. """ def __init__( self, SOC_params: Dict, num_classes: int = 64, scale_cls: float = 10., backbone_name: str = "resnet12", train_way: int = 5, val_way: int = 5, test_way: int = 5, val_shot: int = 5, test_shot: int = 5, num_query: int = 15, val_batch_size_per_gpu: int = 2, test_batch_size_per_gpu: int = 2, lr: float = 0.1, weight_decay: float = 5e-4, decay_scheduler: Optional[str] = "cosine", optim_type: str = "sgd", decay_epochs: Union[List, Tuple, None] = None, decay_power: Optional[float] = None, backbone_kwargs: Dict = {}, **kwargs ) -> None: """ Args: SOC_params: hyperparameters in the SOC algorithm. num_classes: The number of classes of the training dataset. scale_cls: The initial scale number which affects the following softmax function. backbone_name: The name of the feature extractor, which should match the correspond file name in architectures.feature_extractor train_way: The number of classes within one training task. val_way: The number of classes within one val task. test_way: The number of classes within one testing task. val_shot: The number of samples within each few-shot support class during validation. test_shot: The number of samples within each few-shot support class during testing. num_query: The number of samples within each few-shot query class. val_batch_size_per_gpu: The batch size of validation per GPU. test_batch_size_per_gpu: The batch size of testing per GPU. lr: The initial learning rate. weight_decay: The weight decay parameter. decay_scheduler: The scheduler of optimizer. "cosine" or "specified_epochs". optim_type: The optimizer type. "sgd" or "adam" decay_epochs: The list of decay epochs of decay_scheduler "specified_epochs". decay_power: The decay power of decay_scheduler "specified_epochs" at eachspeicified epoch. i.e., adjusted_lr = lr * decay_power backbone_kwargs: The parameters for creating backbone network. """ super().__init__( backbone_name=backbone_name, train_way=train_way, val_way=val_way, test_way=test_way, val_shot=val_shot, test_shot=test_shot, num_query=num_query, val_batch_size_per_gpu=val_batch_size_per_gpu, test_batch_size_per_gpu=test_batch_size_per_gpu, lr=lr, weight_decay=weight_decay, decay_scheduler=decay_scheduler, optim_type=optim_type, decay_epochs=decay_epochs, decay_power=decay_power, backbone_kwargs = backbone_kwargs )
class COSOC(BaseFewShotModule): r"""The datamodule implementing COSOC after foreground extraction of COS. """ def __init__( self, SOC_params: Dict, num_classes: int = 64, scale_cls: float = 10., backbone_name: str = "resnet12", train_way: int = 5, val_way: int = 5, test_way: int = 5, val_shot: int = 5, test_shot: int = 5, num_query: int = 15, val_batch_size_per_gpu: int = 2, test_batch_size_per_gpu: int = 2, lr: float = 0.1, weight_decay: float = 5e-4, decay_scheduler: Optional[str] = "cosine", optim_type: str = "sgd", decay_epochs: Union[List, Tuple, None] = None, decay_power: Optional[float] = None, backbone_kwargs: Dict = {}, **kwargs ) -> None: """ Args: SOC_params: hyperparameters in the SOC algorithm. num_classes: The number of classes of the training dataset. scale_cls: The initial scale number which affects the following softmax function. backbone_name: The name of the feature extractor, which should match the correspond file name in architectures.feature_extractor train_way: The number of classes within one training task. val_way: The number of classes within one val task. test_way: The number of classes within one testing task. val_shot: The number of samples within each few-shot support class during validation. test_shot: The number of samples within each few-shot support class during testing. num_query: The number of samples within each few-shot query class. val_batch_size_per_gpu: The batch size of validation per GPU. test_batch_size_per_gpu: The batch size of testing per GPU. lr: The initial learning rate. weight_decay: The weight decay parameter. decay_scheduler: The scheduler of optimizer. "cosine" or "specified_epochs". optim_type: The optimizer type. "sgd" or "adam" decay_epochs: The list of decay epochs of decay_scheduler "specified_epochs". decay_power: The decay power of decay_scheduler "specified_epochs" at eachspeicified epoch. i.e., adjusted_lr = lr * decay_power backbone_kwargs: The parameters for creating backbone network. """ super().__init__( backbone_name=backbone_name, train_way=train_way, val_way=val_way, test_way=test_way, val_shot=val_shot, test_shot=test_shot, num_query=num_query, val_batch_size_per_gpu=val_batch_size_per_gpu, test_batch_size_per_gpu=test_batch_size_per_gpu, lr=lr, weight_decay=weight_decay, decay_scheduler=decay_scheduler, optim_type=optim_type, decay_epochs=decay_epochs, decay_power=decay_power, backbone_kwargs = backbone_kwargs )
self.classifier = CC_head(self.backbone.outdim, num_classes, scale_cls)
1
2023-10-09 04:14:52+00:00
8k
Texaser/MTN
ldm/modules/encoders/modules.py
[ { "identifier": "Encoder", "path": "ldm/modules/x_transformer.py", "snippet": "class Encoder(AttentionLayers):\n def __init__(self, **kwargs):\n assert 'causal' not in kwargs, 'cannot set causality on encoder'\n super().__init__(causal=False, **kwargs)" }, { "identifier": "Trans...
import torch import torch.nn as nn import numpy as np import kornia import clip import kornia.augmentation as K import torch.nn.functional as F import random from functools import partial from ldm.modules.x_transformer import Encoder, TransformerWrapper # TODO: can we directly rely on lucidrains code and simply add this as a reuirement? --> test from ldm.util import default from transformers import BertTokenizerFast # TODO: add to reuquirements from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel from ldm.thirdp.psp.id_loss import IDFeatures from transformers import CLIPVisionModel from torchvision import transforms from ldm.util import instantiate_from_config from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.util import count_params
4,628
self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False) self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False) def preprocess(self, x): # Expects inputs in the range -1, 1 x = kornia.geometry.resize(x, (224, 224), interpolation='bicubic',align_corners=True, antialias=self.antialias) x = (x + 1.) / 2. # renormalize according to clip x = kornia.enhance.normalize(x, self.mean, self.std) return x def forward(self, x): # x is assumed to be in range [-1,1] if isinstance(x, list): # [""] denotes condition dropout for ucg device = self.model.visual.conv1.weight.device return torch.zeros(1, 768, device=device) return self.model.encode_image(self.preprocess(x)).float() def encode(self, im): return self(im).unsqueeze(1) class FrozenCLIPImageMutliEmbedder(AbstractEncoder): """ Uses the CLIP image encoder. Not actually frozen... If you want that set cond_stage_trainable=False in cfg """ def __init__( self, model='ViT-L/14', jit=False, device='cpu', antialias=True, max_crops=5, ): super().__init__() self.model, _ = clip.load(name=model, device=device, jit=jit) # We don't use the text part so delete it del self.model.transformer self.antialias = antialias self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False) self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False) self.max_crops = max_crops def preprocess(self, x): # Expects inputs in the range -1, 1 randcrop = transforms.RandomResizedCrop(224, scale=(0.085, 1.0), ratio=(1,1)) max_crops = self.max_crops patches = [] crops = [randcrop(x) for _ in range(max_crops)] patches.extend(crops) x = torch.cat(patches, dim=0) x = (x + 1.) / 2. # renormalize according to clip x = kornia.enhance.normalize(x, self.mean, self.std) return x def forward(self, x): # x is assumed to be in range [-1,1] if isinstance(x, list): # [""] denotes condition dropout for ucg device = self.model.visual.conv1.weight.device return torch.zeros(1, self.max_crops, 768, device=device) batch_tokens = [] for im in x: patches = self.preprocess(im.unsqueeze(0)) tokens = self.model.encode_image(patches).float() for t in tokens: if random.random() < 0.1: t *= 0 batch_tokens.append(tokens.unsqueeze(0)) return torch.cat(batch_tokens, dim=0) def encode(self, im): return self(im) class SpatialRescaler(nn.Module): def __init__(self, n_stages=1, method='bilinear', multiplier=0.5, in_channels=3, out_channels=None, bias=False): super().__init__() self.n_stages = n_stages assert self.n_stages >= 0 assert method in ['nearest','linear','bilinear','trilinear','bicubic','area'] self.multiplier = multiplier self.interpolator = partial(torch.nn.functional.interpolate, mode=method) self.remap_output = out_channels is not None if self.remap_output: print(f'Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing.') self.channel_mapper = nn.Conv2d(in_channels,out_channels,1,bias=bias) def forward(self,x): for stage in range(self.n_stages): x = self.interpolator(x, scale_factor=self.multiplier) if self.remap_output: x = self.channel_mapper(x) return x def encode(self, x): return self(x) class LowScaleEncoder(nn.Module): def __init__(self, model_config, linear_start, linear_end, timesteps=1000, max_noise_level=250, output_size=64, scale_factor=1.0): super().__init__() self.max_noise_level = max_noise_level
class AbstractEncoder(nn.Module): def __init__(self): super().__init__() def encode(self, *args, **kwargs): raise NotImplementedError class IdentityEncoder(AbstractEncoder): def encode(self, x): return x class FaceClipEncoder(AbstractEncoder): def __init__(self, augment=True, retreival_key=None): super().__init__() self.encoder = FrozenCLIPImageEmbedder() self.augment = augment self.retreival_key = retreival_key def forward(self, img): encodings = [] with torch.no_grad(): x_offset = 125 if self.retreival_key: # Assumes retrieved image are packed into the second half of channels face = img[:,3:,190:440,x_offset:(512-x_offset)] other = img[:,:3,...].clone() else: face = img[:,:,190:440,x_offset:(512-x_offset)] other = img.clone() if self.augment: face = K.RandomHorizontalFlip()(face) other[:,:,190:440,x_offset:(512-x_offset)] *= 0 encodings = [ self.encoder.encode(face), self.encoder.encode(other), ] return torch.cat(encodings, dim=1) def encode(self, img): if isinstance(img, list): # Uncondition return torch.zeros((1, 2, 768), device=self.encoder.model.visual.conv1.weight.device) return self(img) class FaceIdClipEncoder(AbstractEncoder): def __init__(self): super().__init__() self.encoder = FrozenCLIPImageEmbedder() for p in self.encoder.parameters(): p.requires_grad = False self.id = FrozenFaceEncoder("/home/jpinkney/code/stable-diffusion/model_ir_se50.pth", augment=True) def forward(self, img): encodings = [] with torch.no_grad(): face = kornia.geometry.resize(img, (256, 256), interpolation='bilinear', align_corners=True) other = img.clone() other[:,:,184:452,122:396] *= 0 encodings = [ self.id.encode(face), self.encoder.encode(other), ] return torch.cat(encodings, dim=1) def encode(self, img): if isinstance(img, list): # Uncondition return torch.zeros((1, 2, 768), device=self.encoder.model.visual.conv1.weight.device) return self(img) class ClassEmbedder(nn.Module): def __init__(self, embed_dim, n_classes=1000, key='class'): super().__init__() self.key = key self.embedding = nn.Embedding(n_classes, embed_dim) def forward(self, batch, key=None): if key is None: key = self.key # this is for use in crossattn c = batch[key][:, None] c = self.embedding(c) return c class TransformerEmbedder(AbstractEncoder): """Some transformer encoder layers""" def __init__(self, n_embed, n_layer, vocab_size, max_seq_len=77, device="cuda"): super().__init__() self.device = device self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len, attn_layers=Encoder(dim=n_embed, depth=n_layer)) def forward(self, tokens): tokens = tokens.to(self.device) # meh z = self.transformer(tokens, return_embeddings=True) return z def encode(self, x): return self(x) class BERTTokenizer(AbstractEncoder): """ Uses a pretrained BERT tokenizer by huggingface. Vocab size: 30522 (?)""" def __init__(self, device="cuda", vq_interface=True, max_length=77): super().__init__() self.tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased") self.device = device self.vq_interface = vq_interface self.max_length = max_length def forward(self, text): batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True, return_overflowing_tokens=False, padding="max_length", return_tensors="pt") tokens = batch_encoding["input_ids"].to(self.device) return tokens @torch.no_grad() def encode(self, text): tokens = self(text) if not self.vq_interface: return tokens return None, None, [None, None, tokens] def decode(self, text): return text class BERTEmbedder(AbstractEncoder): """Uses the BERT tokenizr model and add some transformer encoder layers""" def __init__(self, n_embed, n_layer, vocab_size=30522, max_seq_len=77, device="cuda",use_tokenizer=True, embedding_dropout=0.0): super().__init__() self.use_tknz_fn = use_tokenizer if self.use_tknz_fn: self.tknz_fn = BERTTokenizer(vq_interface=False, max_length=max_seq_len) self.device = device self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len, attn_layers=Encoder(dim=n_embed, depth=n_layer), emb_dropout=embedding_dropout) def forward(self, text): if self.use_tknz_fn: tokens = self.tknz_fn(text)#.to(self.device) else: tokens = text z = self.transformer(tokens, return_embeddings=True) return z def encode(self, text): # output of length 77 return self(text) def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self class FrozenT5Embedder(AbstractEncoder): """Uses the T5 transformer encoder for text""" def __init__(self, version="google/t5-v1_1-large", device="cuda", max_length=77): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl super().__init__() self.tokenizer = T5Tokenizer.from_pretrained(version) self.transformer = T5EncoderModel.from_pretrained(version) self.device = device self.max_length = max_length # TODO: typical value? self.freeze() def freeze(self): self.transformer = self.transformer.eval() #self.train = disabled_train for param in self.parameters(): param.requires_grad = False def forward(self, text): batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True, return_overflowing_tokens=False, padding="max_length", return_tensors="pt") tokens = batch_encoding["input_ids"].to(self.device) outputs = self.transformer(input_ids=tokens) z = outputs.last_hidden_state return z def encode(self, text): return self(text) class FrozenFaceEncoder(AbstractEncoder): def __init__(self, model_path, augment=False): super().__init__() self.loss_fn = IDFeatures(model_path) # face encoder is frozen for p in self.loss_fn.parameters(): p.requires_grad = False # Mapper is trainable self.mapper = torch.nn.Linear(512, 768) p = 0.25 if augment: self.augment = K.AugmentationSequential( K.RandomHorizontalFlip(p=0.5), K.RandomEqualize(p=p), # K.RandomPlanckianJitter(p=p), # K.RandomPlasmaBrightness(p=p), # K.RandomPlasmaContrast(p=p), # K.ColorJiggle(0.02, 0.2, 0.2, p=p), ) else: self.augment = False def forward(self, img): if isinstance(img, list): # Uncondition return torch.zeros((1, 1, 768), device=self.mapper.weight.device) if self.augment is not None: # Transforms require 0-1 img = self.augment((img + 1)/2) img = 2*img - 1 feat = self.loss_fn(img, crop=True) feat = self.mapper(feat.unsqueeze(1)) return feat def encode(self, img): return self(img) class FrozenCLIPEmbedder(AbstractEncoder): """Uses the CLIP transformer encoder for text (from huggingface)""" def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77): # clip-vit-base-patch32 super().__init__() self.tokenizer = CLIPTokenizer.from_pretrained(version) self.transformer = CLIPTextModel.from_pretrained(version) self.device = device self.max_length = max_length # TODO: typical value? self.freeze() def freeze(self): self.transformer = self.transformer.eval() #self.train = disabled_train for param in self.parameters(): param.requires_grad = False def forward(self, text): batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True, return_overflowing_tokens=False, padding="max_length", return_tensors="pt") tokens = batch_encoding["input_ids"].to(self.device) outputs = self.transformer(input_ids=tokens) z = outputs.last_hidden_state return z def encode(self, text): return self(text) class ClipImageProjector(AbstractEncoder): """ Uses the CLIP image encoder. """ def __init__(self, version="openai/clip-vit-large-patch14", max_length=77): # clip-vit-base-patch32 super().__init__() self.model = CLIPVisionModel.from_pretrained(version) self.model.train() self.max_length = max_length # TODO: typical value? self.antialias = True self.mapper = torch.nn.Linear(1024, 768) self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False) self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False) null_cond = self.get_null_cond(version, max_length) self.register_buffer('null_cond', null_cond) @torch.no_grad() def get_null_cond(self, version, max_length): device = self.mean.device embedder = FrozenCLIPEmbedder(version=version, device=device, max_length=max_length) null_cond = embedder([""]) return null_cond def preprocess(self, x): # Expects inputs in the range -1, 1 x = kornia.geometry.resize(x, (224, 224), interpolation='bicubic',align_corners=True, antialias=self.antialias) x = (x + 1.) / 2. # renormalize according to clip x = kornia.enhance.normalize(x, self.mean, self.std) return x def forward(self, x): if isinstance(x, list): return self.null_cond # x is assumed to be in range [-1,1] x = self.preprocess(x) outputs = self.model(pixel_values=x) last_hidden_state = outputs.last_hidden_state last_hidden_state = self.mapper(last_hidden_state) return F.pad(last_hidden_state, [0,0, 0,self.max_length-last_hidden_state.shape[1], 0,0]) def encode(self, im): return self(im) class ProjectedFrozenCLIPEmbedder(AbstractEncoder): def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=77): # clip-vit-base-patch32 super().__init__() self.embedder = FrozenCLIPEmbedder(version=version, device=device, max_length=max_length) self.projection = torch.nn.Linear(768, 768) def forward(self, text): z = self.embedder(text) return self.projection(z) def encode(self, text): return self(text) class FrozenCLIPImageEmbedder(AbstractEncoder): """ Uses the CLIP image encoder. Not actually frozen... If you want that set cond_stage_trainable=False in cfg """ def __init__( self, model='ViT-L/14', jit=False, device='cpu', antialias=False, ): super().__init__() self.model, _ = clip.load(name=model, device=device, jit=jit) # We don't use the text part so delete it del self.model.transformer self.antialias = antialias self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False) self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False) def preprocess(self, x): # Expects inputs in the range -1, 1 x = kornia.geometry.resize(x, (224, 224), interpolation='bicubic',align_corners=True, antialias=self.antialias) x = (x + 1.) / 2. # renormalize according to clip x = kornia.enhance.normalize(x, self.mean, self.std) return x def forward(self, x): # x is assumed to be in range [-1,1] if isinstance(x, list): # [""] denotes condition dropout for ucg device = self.model.visual.conv1.weight.device return torch.zeros(1, 768, device=device) return self.model.encode_image(self.preprocess(x)).float() def encode(self, im): return self(im).unsqueeze(1) class FrozenCLIPImageMutliEmbedder(AbstractEncoder): """ Uses the CLIP image encoder. Not actually frozen... If you want that set cond_stage_trainable=False in cfg """ def __init__( self, model='ViT-L/14', jit=False, device='cpu', antialias=True, max_crops=5, ): super().__init__() self.model, _ = clip.load(name=model, device=device, jit=jit) # We don't use the text part so delete it del self.model.transformer self.antialias = antialias self.register_buffer('mean', torch.Tensor([0.48145466, 0.4578275, 0.40821073]), persistent=False) self.register_buffer('std', torch.Tensor([0.26862954, 0.26130258, 0.27577711]), persistent=False) self.max_crops = max_crops def preprocess(self, x): # Expects inputs in the range -1, 1 randcrop = transforms.RandomResizedCrop(224, scale=(0.085, 1.0), ratio=(1,1)) max_crops = self.max_crops patches = [] crops = [randcrop(x) for _ in range(max_crops)] patches.extend(crops) x = torch.cat(patches, dim=0) x = (x + 1.) / 2. # renormalize according to clip x = kornia.enhance.normalize(x, self.mean, self.std) return x def forward(self, x): # x is assumed to be in range [-1,1] if isinstance(x, list): # [""] denotes condition dropout for ucg device = self.model.visual.conv1.weight.device return torch.zeros(1, self.max_crops, 768, device=device) batch_tokens = [] for im in x: patches = self.preprocess(im.unsqueeze(0)) tokens = self.model.encode_image(patches).float() for t in tokens: if random.random() < 0.1: t *= 0 batch_tokens.append(tokens.unsqueeze(0)) return torch.cat(batch_tokens, dim=0) def encode(self, im): return self(im) class SpatialRescaler(nn.Module): def __init__(self, n_stages=1, method='bilinear', multiplier=0.5, in_channels=3, out_channels=None, bias=False): super().__init__() self.n_stages = n_stages assert self.n_stages >= 0 assert method in ['nearest','linear','bilinear','trilinear','bicubic','area'] self.multiplier = multiplier self.interpolator = partial(torch.nn.functional.interpolate, mode=method) self.remap_output = out_channels is not None if self.remap_output: print(f'Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing.') self.channel_mapper = nn.Conv2d(in_channels,out_channels,1,bias=bias) def forward(self,x): for stage in range(self.n_stages): x = self.interpolator(x, scale_factor=self.multiplier) if self.remap_output: x = self.channel_mapper(x) return x def encode(self, x): return self(x) class LowScaleEncoder(nn.Module): def __init__(self, model_config, linear_start, linear_end, timesteps=1000, max_noise_level=250, output_size=64, scale_factor=1.0): super().__init__() self.max_noise_level = max_noise_level
self.model = instantiate_from_config(model_config)
4
2023-10-11 04:06:20+00:00
8k
zapzap-linux/zapzap
zapzap/controllers/home.py
[ { "identifier": "UserContainer", "path": "zapzap/controllers/user_container.py", "snippet": "class UserContainer(QPushButton):\n\n isSelected = False\n\n styleSheet_normal = \"\"\"\n QPushButton {\t\n qproperty-iconSize: 25px;\n }\n QToolTip {\n color: #F0F2F5;\n backgro...
import os import shutil import zapzap from PyQt6.QtWidgets import QWidget from PyQt6.QtCore import QSettings, pyqtSignal from zapzap.controllers.user_container import UserContainer from zapzap.controllers.settings import Settings from zapzap.controllers.drawer import Drawer from zapzap.model.user import UserDAO from zapzap.view.home import Ui_Home from zapzap.model.user import UserDAO from zapzap.controllers.card_user import User from zapzap.theme.builder_icon import getNewIconSVG
4,904
class Home(QWidget, Ui_Home): """ The Home Class manages the user bar and users' pages. The sidebar consists of custom qpushbutton and pages within a QSTackedwidget, both with the same position. """ list = None # personalization emitUpdateTheme = pyqtSignal(str) emitDisableTrayIcon = pyqtSignal(bool) emitNotifications = pyqtSignal() # Quit emitQuit = pyqtSignal() # New chat emitNewChatAtNumber = pyqtSignal() def __init__(self): super(Home, self).__init__() self.setupUi(self) self.settings = QSettings(zapzap.__appname__, zapzap.__appname__) self.loadUsers() self.loadActionsMenuBar() self.zapSettings = Settings() # Account self.zapSettings.emitDisableUser.connect(self.disableUserPage) self.zapSettings.emitDeleteUser.connect(self.delUserPage) self.zapSettings.emitEditUser.connect(self.editUserPage) self.zapSettings.emitNewtUser.connect(self.addNewUser) # Personalization (Atribuição inversa, pois todos os componentes já existem) self.emitUpdateTheme = self.zapSettings.emitUpdateTheme self.emitDisableTrayIcon = self.zapSettings.emitDisableTrayIcon self.emitNotifications = self.zapSettings.emitNotifications # Avanced self.zapSettings.emitHideSettingsBar.connect(self.activeSettingsBar) # Quit self.emitQuit = self.zapSettings.emitQuit self.zapSettings.emitCloseSettings.connect(self.openSettings) # Open Whatsapp Settings self.zapSettings.emitOpenSettingsWhatsapp.connect( self.openWhatsappSettings) # Drawer for Settings window self.drawer = Drawer(self) self.drawer.maximum_width = self.width() self.drawer.raise_() self.drawer.stackedWidget.insertWidget(0, self.zapSettings) # At the end, update the shortcuts self.updateShortcuts() #### Accounts #### def resizeEvent(self, event): self.drawer.setFixedHeight(self.height() - self.drawer.pos().y()) self.drawer.maximum_width = self.width() super().resizeEvent(event) def loadUsers(self): """Carries all users from the database"""
class Home(QWidget, Ui_Home): """ The Home Class manages the user bar and users' pages. The sidebar consists of custom qpushbutton and pages within a QSTackedwidget, both with the same position. """ list = None # personalization emitUpdateTheme = pyqtSignal(str) emitDisableTrayIcon = pyqtSignal(bool) emitNotifications = pyqtSignal() # Quit emitQuit = pyqtSignal() # New chat emitNewChatAtNumber = pyqtSignal() def __init__(self): super(Home, self).__init__() self.setupUi(self) self.settings = QSettings(zapzap.__appname__, zapzap.__appname__) self.loadUsers() self.loadActionsMenuBar() self.zapSettings = Settings() # Account self.zapSettings.emitDisableUser.connect(self.disableUserPage) self.zapSettings.emitDeleteUser.connect(self.delUserPage) self.zapSettings.emitEditUser.connect(self.editUserPage) self.zapSettings.emitNewtUser.connect(self.addNewUser) # Personalization (Atribuição inversa, pois todos os componentes já existem) self.emitUpdateTheme = self.zapSettings.emitUpdateTheme self.emitDisableTrayIcon = self.zapSettings.emitDisableTrayIcon self.emitNotifications = self.zapSettings.emitNotifications # Avanced self.zapSettings.emitHideSettingsBar.connect(self.activeSettingsBar) # Quit self.emitQuit = self.zapSettings.emitQuit self.zapSettings.emitCloseSettings.connect(self.openSettings) # Open Whatsapp Settings self.zapSettings.emitOpenSettingsWhatsapp.connect( self.openWhatsappSettings) # Drawer for Settings window self.drawer = Drawer(self) self.drawer.maximum_width = self.width() self.drawer.raise_() self.drawer.stackedWidget.insertWidget(0, self.zapSettings) # At the end, update the shortcuts self.updateShortcuts() #### Accounts #### def resizeEvent(self, event): self.drawer.setFixedHeight(self.height() - self.drawer.pos().y()) self.drawer.maximum_width = self.width() super().resizeEvent(event) def loadUsers(self): """Carries all users from the database"""
self.list = UserDAO.select()
3
2023-10-14 13:40:42+00:00
8k
oracle/guardian-ai
guardian_ai/fairness/metrics/dataset.py
[ { "identifier": "LazyLoader", "path": "guardian_ai/fairness/utils/lazy_loader.py", "snippet": "class LazyLoader:\n \"\"\"\n Lazy module Loader.\n This object loads a module only when we fetch attributes from it.\n It can be used to import modules in one files which are not\n present in al...
from typing import TYPE_CHECKING, Callable, List, Optional, Union from guardian_ai.fairness.utils.lazy_loader import LazyLoader from guardian_ai.fairness.metrics.utils import ( DEFAULT_DISTANCE, DEFAULT_REDUCTION, _check_subgroups, _FairnessScorer, _get_attr_idx_mappings, _get_check_array, _get_check_distance, _get_check_inputs, _get_check_reduction, _get_score_group_from_metrics, _place_space_before_capital_letters, _y_to_aifm_ds, ) from guardian_ai.utils.exception import GuardianAIValueError from aif360.metrics import BinaryLabelDatasetMetric import numpy as np import pandas as pd
6,352
values are considered as subgroups. distance_measure : str, default='diff' Determines the distance used to compare a subgroup's metric against the rest of the subgroups. Possible values are: * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed. * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``. reduction : str or None, default='mean' Determines how to reduce scores on all subgroups to a single output. Possible values are: * ``'max'``: Returns the maximal value among all subgroup metrics. * ``'mean'``: Returns the mean over all subgroup metrics. * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict. References ---------- [1] `Cynthia Dwork et al. "Fairness Through Awareness". Innovations in Theoretical Computer Science. 2012. <https://arxiv.org/abs/1104.3913>`_ Examples -------- .. code-block:: python from guardian_ai.fairness.metrics import DatasetStatisticalParityScorer scorer = DatasetStatisticalParityScorer(['race', 'sex']) scorer(X=X, y_true=y_true) scorer(None, X, y_true) """ def __init__( self, protected_attributes: Union[pd.Series, np.ndarray, List, str], distance_measure: str = DEFAULT_DISTANCE, reduction: Optional[str] = DEFAULT_REDUCTION, ): super().__init__( protected_attributes=protected_attributes, metric=dataset_statistical_parity, distance_measure=distance_measure, reduction=reduction, allow_distance_measure_none=False, ) def dataset_statistical_parity( y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame, distance_measure: str = DEFAULT_DISTANCE, reduction: str = DEFAULT_REDUCTION, ): """ Measures the statistical parity of a dataset. For more details, refer to :class:`.DatasetStatisticalParityScorer`. Parameters ---------- y_true : pandas.Series, numpy.ndarray, list Array of groundtruth labels subgroups : pandas.DataFrame Dataframe containing protected attributes for each instance. distance_measure : str, default='diff' Determines the distance used to compare a subgroup's metric against the rest of the subgroups. Possible values are: * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed. * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``. reduction : str, default='mean' Determines how to reduce scores on all subgroups to a single output. Possible values are: * ``'max'``: Returns the maximal value among all subgroup metrics. * ``'mean'``: Returns the mean over all subgroup metrics. * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict. Examples -------- .. code-block:: python from guardian_ai.fairness.metrics import dataset_statistical_parity subgroups = X[['race', 'sex']] dataset_statistical_parity(y_true, subgroups) """ return _dataset_metric( y_true, subgroups, metric="base_rate", distance_measure=distance_measure, reduction=reduction, allow_distance_measure_none=False, ) def _simple_dataset_metric( y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame, metric: str ): """ Compute engine for dataset metrics that do not require a distance measure or reduction function because they already return a float value. Parameters ---------- y_true : pandas.Series, numpy.ndarray, list Array of groundtruth labels subgroups : pandas.DataFrame Dataframe containing protected attributes for each instance. metric : str Name of the base metric to be called. Returns ------- float The computed metric value. """ y_true = _get_check_array(y_true, "y_true")
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2023 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ """Evaluating the compliance of a dataset with specific fairness metrics""" from __future__ import annotations if TYPE_CHECKING: else: pd = LazyLoader("pandas") np = LazyLoader("numpy") BinaryLabelDatasetMetric = LazyLoader( "aif360.metrics", "BinaryLabelDatasetMetric", suppress_import_warnings=True ) BinaryLabelDatasetMetric = LazyLoader( "aif360.metrics", "BinaryLabelDatasetMetric", suppress_import_warnings=True ) def _dataset_metric( y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame, metric: str, distance_measure: Optional[str], reduction: Optional[str], allow_distance_measure_none: bool, ): """ Compute engine for all dataset metrics. This computes a given metric on all subgroup pairs for a specified ``subgroups`` input. Parameters ---------- y_true : pandas.Series, numpy.ndarray, list Array of groundtruth labels subgroups : pandas.DataFrame Dataframe containing protected attributes for each instance. metric : str Name of the base metric to be called. distance_measure : str or None Determines the distance used to compare a subgroup's metric against the rest of the subgroups. Possible values are: * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed. * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``. - ``None``, to not use any distance metric. Only allowed if `allow_distance_measure_none` is set to True. reduction : str or None Determines how to reduce scores on all subgroups to a single output. Possible values are: * ``'max'``: Returns the maximal value among all subgroup metrics. * ``'mean'``: Returns the mean over all subgroup metrics. * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict. allow_distance_measure_none : bool Whether or not to allow ``distance_measure`` to be set to ``None``. Returns ------- float, dict The computed metric value, with format according to `reduction`. """ y_true = _get_check_array(y_true, "y_true") ( reduction, distance, attr_vals_to_idx, attr_idx_to_vals, subgroup_divisions, ) = _get_check_inputs( reduction, distance_measure, subgroups, allow_distance_measure_none ) ds_true = _y_to_aifm_ds(y_true, subgroups, attr_vals_to_idx) groups = [] scores = [] visited_subgroup_pairs = set() # subgroup_divisions is a list of all subgroup pairs, # e.g. [([{'sex': 0, 'race': 0}], [{'sex': 0, 'race': 1}]), ...] for unpriv_group, priv_group in subgroup_divisions: subgroup_metrics = BinaryLabelDatasetMetric(ds_true, unpriv_group, priv_group) score, group_repr = _get_score_group_from_metrics( subgroup_metrics, distance, metric, unpriv_group, priv_group, attr_idx_to_vals ) if (group_repr[1], group_repr[0]) not in visited_subgroup_pairs: scores.append(score) groups.append(group_repr) visited_subgroup_pairs.add(group_repr) return reduction(groups, scores) class _DatasetFairnessScorer(_FairnessScorer): """ Common base object for all dataset metrics. This stores settings to pass on to the ``_dataset_metric`` compute engine and does subgroups generation from a `protected_attributes` array on an input array of instances ``X``. Parameters ---------- protected_attributes: pandas.Series, numpy.ndarray, list, str Array of attributes or single attribute that should be treated as protected. If an attribute is protected, then all of its unique values are considered as subgroups. metric : str or Callable Name of the base metric to be called. distance_measure : str or None Determines the distance used to compare a subgroup's metric against the rest of the subgroups. Possible values are: * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed. * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``. - ``None``, to not use any distance metric. Only allowed if `allow_distance_measure_none` is set to True. reduction : str or None Determines how to reduce scores on all subgroups to a single output. Possible values are: * ``'max'``: Returns the maximal value among all subgroup metrics. * ``'mean'``: Returns the mean over all subgroup metrics. * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict. allow_distance_measure_none : bool Whether or not to allow ``distance_measure`` to be set to ``None``. """ def __init__( self, protected_attributes: Union[pd.Series, np.ndarray, List, str], metric: Union[str, Callable], distance_measure: Optional[str], reduction: Optional[str], allow_distance_measure_none: bool, ): super().__init__(protected_attributes, metric) self.distance_measure = _get_check_distance( distance_measure, allow_distance_measure_none ) self.reduction = _get_check_reduction(reduction) def __call__( self, model: Optional[object] = None, X: Optional[pd.DataFrame] = None, y_true: Optional[Union[pd.Series, np.ndarray, List]] = None, supplementary_features: Optional[pd.DataFrame] = None, ): """ Compute the metric on a given array of instances ``X``. Parameters ---------- model : object or None, default=None Object that implements a `predict(X)` function to collect categorical predictions. X : pandas.DataFrame or None, default=None Array of instances to compute the metric on. y_true : pandas.Series, numpy.ndarray, list or None, default=None Array of groundtruth labels. supplementary_features : pandas.DataFrame, or None, default=None Array of supplementary features for each instance. Used in case one attribute in ``self.protected_attributes`` is not contained by ``X`` (e.g. if the protected attribute is not used by the model). Raise an GuardianAIValueError if a feature is present in both ``X`` and ``supplementary_features``. Returns ------- float, dict The computed metric value, with format according to ``self.reduction``. Raises ------ GuardianAIValueError If a feature is present in both ``X`` and ``supplementary_features``. """ # We use default values of None for the unused `model` and required # ``X`` and `y_true` arguments. This way model scorers can be called with # `model_scorer(X=X, y_true=y_true)`. if X is None or y_true is None: raise GuardianAIValueError( "Value of None was received for either ``X`` or ``y_true``. " "This may be due to calling the metric using only 2 positional " "arguments. If this is the case, either call the function by " "passing ``None`` as the first argument or use named arguments " "for ``X`` and ``y_true``." ) subgroups = self._get_check_subgroups(X, supplementary_features) return self.metric(y_true, subgroups, self.distance_measure, self.reduction) @property def display_name(self): base_display_name = super().display_name fullname = " ".join( [ self.reduction.display_name, base_display_name, self.distance_measure.display_name, self._display_name_protected_attributes, ] ) fullname = " ".join(fullname.split()) return _place_space_before_capital_letters(fullname) class DatasetStatisticalParityScorer(_DatasetFairnessScorer): """ Measures the statistical parity [1] of a dataset. Statistical parity (also known as Base Rate or Disparate Impact) for a dataset states that a dataset is unbiased if the label is independent of the protected attribute. For each subgroup, statistical parity is computed as the ratio of positive labels in a subgroup. Statistical Parity (also known as Base Rate or Disparate Impact) is calculated as PL / N, where PL and N are the number of Positive Labels and total number of instances, respectively. Perfect score A perfect score for this metric means that the dataset does not have a different ratio of positive labels for a subgroup than it does for the rest of the subgroups. For example, if the protected attributes are race and sex, then a perfect statistical parity would mean that all combinations of values for race and sex have identical ratios of positive labels. Perfect values are: - 1 if using ``'ratio'`` as ``distance_measure``. - 0 if using ``'diff'`` as ``distance_measure``. Parameters ---------- protected_attributes: pandas.Series, numpy.ndarray, list, str Array of attributes or single attribute that should be treated as protected. If an attribute is protected, then all of its unique values are considered as subgroups. distance_measure : str, default='diff' Determines the distance used to compare a subgroup's metric against the rest of the subgroups. Possible values are: * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed. * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``. reduction : str or None, default='mean' Determines how to reduce scores on all subgroups to a single output. Possible values are: * ``'max'``: Returns the maximal value among all subgroup metrics. * ``'mean'``: Returns the mean over all subgroup metrics. * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict. References ---------- [1] `Cynthia Dwork et al. "Fairness Through Awareness". Innovations in Theoretical Computer Science. 2012. <https://arxiv.org/abs/1104.3913>`_ Examples -------- .. code-block:: python from guardian_ai.fairness.metrics import DatasetStatisticalParityScorer scorer = DatasetStatisticalParityScorer(['race', 'sex']) scorer(X=X, y_true=y_true) scorer(None, X, y_true) """ def __init__( self, protected_attributes: Union[pd.Series, np.ndarray, List, str], distance_measure: str = DEFAULT_DISTANCE, reduction: Optional[str] = DEFAULT_REDUCTION, ): super().__init__( protected_attributes=protected_attributes, metric=dataset_statistical_parity, distance_measure=distance_measure, reduction=reduction, allow_distance_measure_none=False, ) def dataset_statistical_parity( y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame, distance_measure: str = DEFAULT_DISTANCE, reduction: str = DEFAULT_REDUCTION, ): """ Measures the statistical parity of a dataset. For more details, refer to :class:`.DatasetStatisticalParityScorer`. Parameters ---------- y_true : pandas.Series, numpy.ndarray, list Array of groundtruth labels subgroups : pandas.DataFrame Dataframe containing protected attributes for each instance. distance_measure : str, default='diff' Determines the distance used to compare a subgroup's metric against the rest of the subgroups. Possible values are: * ``'ratio'``: Uses ``(subgroup1_val / subgroup2_val)``. Inverted to always be >= 1 if needed. * ``'diff'``: Uses ``| subgroup1_val - subgroup2_val |``. reduction : str, default='mean' Determines how to reduce scores on all subgroups to a single output. Possible values are: * ``'max'``: Returns the maximal value among all subgroup metrics. * ``'mean'``: Returns the mean over all subgroup metrics. * ``None``: Returns a ``{subgroup_pair: subgroup_pair_metric, ...}`` dict. Examples -------- .. code-block:: python from guardian_ai.fairness.metrics import dataset_statistical_parity subgroups = X[['race', 'sex']] dataset_statistical_parity(y_true, subgroups) """ return _dataset_metric( y_true, subgroups, metric="base_rate", distance_measure=distance_measure, reduction=reduction, allow_distance_measure_none=False, ) def _simple_dataset_metric( y_true: Union[pd.Series, np.ndarray, List], subgroups: pd.DataFrame, metric: str ): """ Compute engine for dataset metrics that do not require a distance measure or reduction function because they already return a float value. Parameters ---------- y_true : pandas.Series, numpy.ndarray, list Array of groundtruth labels subgroups : pandas.DataFrame Dataframe containing protected attributes for each instance. metric : str Name of the base metric to be called. Returns ------- float The computed metric value. """ y_true = _get_check_array(y_true, "y_true")
_check_subgroups(subgroups)
3
2023-10-09 09:48:50+00:00
8k
IvanZaycev0717/python_interview_assistant_rus
main.py
[ { "identifier": "YELLOW_BACKGROUND", "path": "colors.py", "snippet": "YELLOW_BACKGROUND = '#fff1c8'" }, { "identifier": "PINK_BACKGROUND", "path": "colors.py", "snippet": "PINK_BACKGROUND = '#ffcccc'" }, { "identifier": "GREEN_BACKGROUND", "path": "colors.py", "snippet": ...
import datetime import random import platform import csv import threading import tkinter as tk import sys import customtkinter as ctk import fitz import pyttsx3 from collections import deque from tkinter import ttk from tkinter import PhotoImage from typing import Optional from PIL import Image from CTkMessagebox import CTkMessagebox from colors import (YELLOW_BACKGROUND, PINK_BACKGROUND, GREEN_BACKGROUND, SWAMP_FOREGROUND, ORANGE_FOREGROUND, NEW_USER_WINDOW_FOREGROUND, PINK_FOREGROUND, CRIMSON_HOVER, BEGIN_BUTTON_FOREGROUND_COLOR, BEGIN_BUTTON_HOVER_COLOR, SOUNDS_BUTTONS_FOREGROUND, SOUNDS_BUTTONS_HOVER, POSITIVE_BUTTON_FOREGROUND, POSITIVE_BUTTON_HOVER, NEGATIVE_BUTTON_FOREGROUND, NEGATIVE_BUTTON_HOVER, ANSWER_BUTTON_FOREGROUND, ANSWER_BUTTON_HOVER, CHECKBOX_HOVER_COLOR, PROGRESS_FOREGROUND, PROGRESS_COLOR, GREEN, RED, WHITE, ERROR_COLOR, PDF_OUTPUT_COLOR) from settings import (CREATE_USER_WINDOW, HINT_WINDOW_TITLE, Theme, QuestionThreshold as qt, ValidResponse, APP_NAME, APP_RESOLUTION) from models import create_db from manage_db import (create_new_user, get_user_names, get_user_interview_duration, get_user_progress, get_last_enter_date, update_interview_duration, update_last_enter_date, update_user_progress, delete_this_user) from user_statistics import (convert_seconds_to_hours, count_interview_duration, get_right_answers_amount, get_last_enter_message) from validator import (is_name_empty, is_name_too_short, has_name_first_wrong_symbol, has_name_wrong_symbols, is_name_too_long, is_user_already_exists) from my_timers import CommandTimer, MessageTimer
5,436
"""Processes event choosing a user. It updates everything at the tab. """ self.chosen_user = self.user_var.get() self.current_user(self.chosen_user) self.set_user_progress(get_user_progress(self.chosen_user)) self.get_current_user_statistics() self.update_user_progress() self.set_color_for_user_progress() def get_current_user_statistics(self) -> None: """Gets current user statistics.""" self.last_enter_message.set( get_last_enter_message(get_last_enter_date(self.chosen_user)) ) self.interview_duration_message.set( str(convert_seconds_to_hours( get_user_interview_duration(self.chosen_user))) + ' ч.' ) messages_data = get_right_answers_amount( get_user_progress(self.chosen_user) ) self.rigth_answer_message.set(messages_data['right_answers_amount']) self.percentage_completion_message.set( messages_data['percentage_completion'] ) def author_note(self) -> None: """Shows a title of author.""" self.author_label = ctk.CTkLabel( master=self, text='github.com/IvanZaycev0717\n\nTelegram: @ivanzaycev0717' ) self.author_label.place(x=20, y=560) def create_widgets(self) -> None: """Creates widgets at the user statistics tab.""" # PINK SCREEN self.choose_user_frame = ctk.CTkFrame( self, fg_color=PINK_BACKGROUND, width=600, height=300 ) self.choose_user_frame.grid( row=0, column=0, sticky='n', padx=20, pady=20 ) # Static labels self.user_manage_label = ctk.CTkLabel( self.choose_user_frame, text='Управление пользователями', font=('Calibri', 25) ) self.user_manage_label.place(x=30, y=10) self.choose_user_label = ctk.CTkLabel( self.choose_user_frame, text='Выберите пользователя', font=('Calibri', 18)) self.choose_user_label.place(x=30, y=50) self.create_new_user_label = ctk.CTkLabel( self.choose_user_frame, text='Вы можете создать нового пользователя', font=('Calibri', 18) ) self.create_new_user_label.place(x=30, y=200) # Combobox self.combobox1 = ttk.Combobox( self.choose_user_frame, textvariable=self.user_var, state="readonly") self.combobox1.configure(values=self.users) self.combobox1.place(x=30, y=80, width=250, height=35) # Images at the buttons self.create_user_button_img = ctk.CTkImage( light_image=Image.open('images/add.png').resize((30, 30)), dark_image=Image.open('images/add.png').resize((30, 30)) ) self.delete_user_button_img = ctk.CTkImage( light_image=Image.open('images/delete.png').resize((30, 30)), dark_image=Image.open('images/delete.png').resize((30, 30)) ) # Buttons self.create_user_button = ctk.CTkButton( self.choose_user_frame, width=250, height=35, fg_color=PINK_FOREGROUND, hover_color=CRIMSON_HOVER, text='Создать пользователя', image=self.create_user_button_img, text_color='black', command=self.create_new_user) self.create_user_button.place(x=30, y=240) self.delete_user_button = ctk.CTkButton( self.choose_user_frame, width=200, height=35, fg_color=PINK_FOREGROUND, hover_color=CRIMSON_HOVER, text='Удалить пользователя', image=self.delete_user_button_img, text_color='black', command=self.delete_user) self.delete_user_button.place(x=320, y=80) # YELLOW SCREEN # frame self.global_stats_frame = ctk.CTkFrame( self,
if platform.system() == 'Windows': class Main(ctk.CTk): """Main class for the App governing vars between other classes.""" def __init__(self, title: str, size: tuple[int, int]) -> None: super().__init__() # Setup self.title(title) self.geometry(f'{size[0]}x{size[1]}') self.resizable(False, False) if platform.system() == 'Windows': self.iconbitmap(default='images/icon.ico') # Instance vars self.current_user: str = '' self.volume: float = 0.5 self.user_progress: dict = {} self.create_user_window: Optional[CreateNewUser] = None self.hint_window: Optional[HintWindow] = None # Load questions and create question bank self.question_bank = self.load_csv() # Themes dictionary self.themes: dict[int, Theme] = { 0: Theme.BASICS, 1: Theme.OOP, 2: Theme.PEP8, 3: Theme.STRUCTURES, 4: Theme.ALGHORITMS, 5: Theme.GIT, 6: Theme.SQL } # Interview mode dictionary self.interview_mode: dict[Theme | str, int] = { Theme.BASICS: 1, Theme.OOP: 0, Theme.PEP8: 0, Theme.STRUCTURES: 0, Theme.ALGHORITMS: 0, Theme.GIT: 0, Theme.SQL: 0, 'Freemode': 0, 'Random': 0 } # Notebook self.notebook = ctk.CTkTabview( self, segmented_button_fg_color='black', segmented_button_selected_color='green', segmented_button_selected_hover_color='green', text_color='white', segmented_button_unselected_color='black', segmented_button_unselected_hover_color='black') self.notebook.pack( padx=20, pady=20, side='left', fill='both', expand=True ) self.notebook.add(name='Профиль пользователей') self.notebook.add(name='Настройки собеседования') self.notebook.add(name='Пройти собеседование') self.notebook.set('Профиль пользователей') # Tabs of notebook self.userstats = UserStatisticsTab( parent=self.notebook.tab('Профиль пользователей'), create_new_user=self.create_new_user, set_current_user=self.set_current_user, set_user_progress=self.set_user_progress, set_color_for_user_progress=self.set_color_for_user_progress ) self.interview_settings = InterviewSettingsTab( parent=self.notebook.tab('Настройки собеседования'), set_interview_mode=self.set_interview_mode, get_volume=self.get_volume, set_volume=self.set_volume ) self.interview_pass = InterviewPassTab( parent=self.notebook.tab('Пройти собеседование'), themes=self.themes, database=self.question_bank, show_hint_window=self.show_hint_window, get_volume=self.get_volume, set_volume=self.set_volume, get_current_user=self.get_current_user, set_notebook_status=self.set_notebook_status, get_interview_mode=self.get_interview_mode, get_user_progress=self.get_user_progress, update_progress=self.update_progress, ) def load_csv(self) -> list[tuple[int | str]]: """Converts data.csv to list of tuples.""" with open('data.csv', encoding='utf-8', mode='r') as f: reader = csv.reader(f, delimiter=';') data = tuple(reader) return [ tuple( [int(item) if item.isdigit() else item for item in row] ) for row in data] def create_new_user(self) -> None: """Makes a new window to create a new user.""" if self.create_user_window is None or not self.create_user_window.winfo_exists(): self.create_user_window = CreateNewUser( title=CREATE_USER_WINDOW, update_combobox=self.update_combobox ) self.focus() self.create_user_window.focus() else: self.create_user_window.lift() self.create_user_window.focus() def show_hint_window(self, filepath: str, page_number: int) -> None: """Makes a new window to show the answer to the question.""" if self.hint_window is None or not self.hint_window.winfo_exists(): self.hint_window = HintWindow( HINT_WINDOW_TITLE, filepath, page_number ) self.focus() self.hint_window.focus() else: self.hint_window.lift() self.hint_window.focus() def get_volume(self) -> float: """Returns current a volume value.""" return self.volume def set_volume(self, volume: float) -> None: """Sets transferred value of volume.""" self.volume = volume if not self.volume: self.interview_pass.mute_button.configure( image=self.interview_pass.mute_button_img_OFF ) else: self.interview_pass.mute_button.configure( image=self.interview_pass.mute_button_img_ON ) hundred_volume = 100 * self.volume self.interview_settings.sound_volume.set(hundred_volume) self.interview_settings.sound_text.set( f'Громкость: {int(hundred_volume)}%' ) def update_combobox(self) -> None: """Updates user list at the user statistics tab.""" self.userstats.update_user_list() def update_progress(self) -> None: """Updates users progress bars at the user statistics tab.""" self.userstats.update_user_progress() def set_interview_mode(self, interview_mode: dict[Theme | str, int]) -> None: """Sets parametres of interview according selection at user settings tab. """ self.interview_mode = interview_mode def set_current_user(self, current_user: str) -> None: """Sets a name of user from another tabs.""" self.current_user = current_user def get_current_user(self) -> str: """Returns current user name.""" return self.current_user def set_notebook_status(self, status: str) -> None: """Sets notebook state according transferred value.""" self.notebook.configure(state=status) def get_interview_mode(self) -> dict[Theme | str, int]: """Returns the interview mode uncluding: - chosen themes - is chosen a Random mode - is chosen a Free mode. """ return self.interview_mode def set_user_progress(self, user_progress: dict) -> None: """Sets user progress according value.""" self.user_progress = user_progress def get_user_progress(self) -> None: """Returns current user progress.""" return self.user_progress def set_color_for_user_progress(self) -> None: """Updates question strings' color at the user intervew tab, according current user progress. """ self.interview_pass.set_color_for_user_progress() class UserStatisticsTab(ctk.CTkFrame): """Class for showing user statistics tab.""" def __init__(self, parent, create_new_user, set_current_user, set_user_progress, set_color_for_user_progress): # Setup super().__init__(parent) self.width = 1000 self.place(x=0, y=0) self.columnconfigure((0, 1), weight=1) self.rowconfigure((0, 1), weight=1) # Users vars self.create_new_user = create_new_user self.users = get_user_names() self.current_user = set_current_user self.set_user_progress = set_user_progress self.chosen_user = None self.set_color_for_user_progress = set_color_for_user_progress # MESSAGE VARS # pink screen self.user_var = tk.StringVar(value='Выберите пользователя...') # yellow screen self.last_enter_message = tk.StringVar() self.interview_duration_message = tk.StringVar() self.rigth_answer_message = tk.StringVar() self.percentage_completion_message = tk.StringVar() self.create_widgets() self.author_note() self.set_to_zero_progress_bars() # EVENTS self.combobox1.bind("<<ComboboxSelected>>", self.choose_user) def update_user_list(self) -> None: """Updates the list of users in Combobox.""" self.combobox1['values'] = get_user_names() def reset_settings(self) -> None: """Turns to zero any in statistics.""" self.chosen_user = None self.current_user(self.chosen_user) self.user_var.set('Выберите пользователя...') self.last_enter_message.set('') self.interview_duration_message.set('') self.rigth_answer_message.set('') self.percentage_completion_message.set('') def update_user_progress(self) -> None: """Updates everything in current user statistics.""" progress = get_right_answers_amount( get_user_progress(self.chosen_user) ) self.last_enter_message.set( get_last_enter_message( get_last_enter_date(self.chosen_user) ) ) self.interview_duration_message.set( str(convert_seconds_to_hours( get_user_interview_duration(self.chosen_user))) + ' ч.' ) self.rigth_answer_message.set(progress['right_answers_amount']) self.percentage_completion_message.set( progress['percentage_completion'] ) self.basic_progress_bar.set(progress['basic_progress']) self.oop_progress_bar.set(progress['oop_progress']) self.pep_progress_bar.set(progress['pep_progress']) self.structures_progress_bar.set(progress['structures_progress']) self.alghoritms_progress_bar.set(progress['alghorimts_progress']) self.git_progress_bar.set(progress['git_progress']) self.sql_progress_bar.set(progress['sql_progress']) def set_to_zero_progress_bars(self) -> None: """Turns to zero every progress bar.""" self.basic_progress_bar.set(0) self.oop_progress_bar.set(0) self.pep_progress_bar.set(0) self.structures_progress_bar.set(0) self.alghoritms_progress_bar.set(0) self.git_progress_bar.set(0) self.sql_progress_bar.set(0) def delete_user(self) -> None: """Deletes the chosen user from DB and screen.""" delete_this_user(self.chosen_user) self.reset_settings() self.update_user_list() self.set_to_zero_progress_bars() def choose_user(self, event) -> None: """Processes event choosing a user. It updates everything at the tab. """ self.chosen_user = self.user_var.get() self.current_user(self.chosen_user) self.set_user_progress(get_user_progress(self.chosen_user)) self.get_current_user_statistics() self.update_user_progress() self.set_color_for_user_progress() def get_current_user_statistics(self) -> None: """Gets current user statistics.""" self.last_enter_message.set( get_last_enter_message(get_last_enter_date(self.chosen_user)) ) self.interview_duration_message.set( str(convert_seconds_to_hours( get_user_interview_duration(self.chosen_user))) + ' ч.' ) messages_data = get_right_answers_amount( get_user_progress(self.chosen_user) ) self.rigth_answer_message.set(messages_data['right_answers_amount']) self.percentage_completion_message.set( messages_data['percentage_completion'] ) def author_note(self) -> None: """Shows a title of author.""" self.author_label = ctk.CTkLabel( master=self, text='github.com/IvanZaycev0717\n\nTelegram: @ivanzaycev0717' ) self.author_label.place(x=20, y=560) def create_widgets(self) -> None: """Creates widgets at the user statistics tab.""" # PINK SCREEN self.choose_user_frame = ctk.CTkFrame( self, fg_color=PINK_BACKGROUND, width=600, height=300 ) self.choose_user_frame.grid( row=0, column=0, sticky='n', padx=20, pady=20 ) # Static labels self.user_manage_label = ctk.CTkLabel( self.choose_user_frame, text='Управление пользователями', font=('Calibri', 25) ) self.user_manage_label.place(x=30, y=10) self.choose_user_label = ctk.CTkLabel( self.choose_user_frame, text='Выберите пользователя', font=('Calibri', 18)) self.choose_user_label.place(x=30, y=50) self.create_new_user_label = ctk.CTkLabel( self.choose_user_frame, text='Вы можете создать нового пользователя', font=('Calibri', 18) ) self.create_new_user_label.place(x=30, y=200) # Combobox self.combobox1 = ttk.Combobox( self.choose_user_frame, textvariable=self.user_var, state="readonly") self.combobox1.configure(values=self.users) self.combobox1.place(x=30, y=80, width=250, height=35) # Images at the buttons self.create_user_button_img = ctk.CTkImage( light_image=Image.open('images/add.png').resize((30, 30)), dark_image=Image.open('images/add.png').resize((30, 30)) ) self.delete_user_button_img = ctk.CTkImage( light_image=Image.open('images/delete.png').resize((30, 30)), dark_image=Image.open('images/delete.png').resize((30, 30)) ) # Buttons self.create_user_button = ctk.CTkButton( self.choose_user_frame, width=250, height=35, fg_color=PINK_FOREGROUND, hover_color=CRIMSON_HOVER, text='Создать пользователя', image=self.create_user_button_img, text_color='black', command=self.create_new_user) self.create_user_button.place(x=30, y=240) self.delete_user_button = ctk.CTkButton( self.choose_user_frame, width=200, height=35, fg_color=PINK_FOREGROUND, hover_color=CRIMSON_HOVER, text='Удалить пользователя', image=self.delete_user_button_img, text_color='black', command=self.delete_user) self.delete_user_button.place(x=320, y=80) # YELLOW SCREEN # frame self.global_stats_frame = ctk.CTkFrame( self,
fg_color=YELLOW_BACKGROUND,
0
2023-10-13 13:37:42+00:00
8k
microsoft/ToolTalk
src/tooltalk/apis/account.py
[ { "identifier": "APIException", "path": "src/tooltalk/apis/exceptions.py", "snippet": "class APIException(Exception):\n \"\"\"Special exception to catch when simulated APIs fail in expected ways.\"\"\"\n pass" }, { "identifier": "API", "path": "src/tooltalk/apis/api.py", "snippet":...
from abc import ABC from typing import Optional from .exceptions import APIException from .api import API, APISuite from .utils import verify_phone_format, verify_email_format
3,683
username: The username of the user. email: The email of the user. """ if username not in self.database: raise APIException("The username does not exist.") if self.database[username]["email"] != email: raise APIException("The email is incorrect.") verification_code = f"{self.random.randint(0, 999999):06d}" self.database[username]["verification_code"] = verification_code return {"status": "success"} class UpdateAccountInformation(AccountAPI): description = "Updates account information of a user." parameters = { "password": { "type": "string", "description": "The password of the user.", "required": True }, "new_email": { "type": "string", "description": "The new email of the user.", "required": False }, "new_phone_number": { "type": "string", "description": "The new phone number of the user in the format xxx-xxx-xxxx.", "required": False }, "new_name": { "type": "string", "description": "The new name of the user.", "required": False } } output = { "success": {"type": "string", "description": "success or failed."}, } is_action = True database_name = ACCOUNT_DB_NAME requires_auth = True def call( self, session_token: str, password: str, new_email: Optional[str] = None, new_phone_number: Optional[str] = None, new_name: Optional[str] = None ) -> dict: """ Updates account information of a user. Args: session_token: User's session_token. Handled by ToolExecutor. password: The password of the user. new_email: The new email of the user. new_phone_number: The new phone number of the user in the format xxx-xxx-xxxx. new_name: The new name of the user. """ user_data = self.check_session_token(session_token) username = user_data['username'] if user_data['password'] != password: raise APIException('The password is incorrect.') if new_email is None and new_phone_number is None: raise APIException("You need to provide at least one of new_email and new_phone_number.") if new_email is not None: if not verify_email_format(new_email): raise APIException("The email is invalid.") self.database[username]["email"] = new_email if new_phone_number is not None: if not verify_phone_format(new_phone_number): raise APIException("The phone number is invalid.") self.database[username]["phone"] = new_phone_number if new_name is not None: self.database[username]["name"] = new_name return {"status": "success"} class UserLogin(AccountAPI): description = 'Logs in a user returns a token.' parameters = { 'username': { 'type': "string", 'description': 'The username of the user.', 'required': True, }, 'password': { 'type': "string", 'description': 'The password of the user.', 'required': True, }, } output = { "session_token": {'type': "string", 'description': 'The token of the user.'}, } database_name = ACCOUNT_DB_NAME is_action = True def call(self, username: str, password: str) -> dict: """ Logs in a user returns a token. Args: username: The username of the user. password: The password of the user. """ if username not in self.database: raise APIException('The username does not exist.') if self.database[username]['password'] != password: raise APIException('The password is incorrect.') if self.database[username]["session_token"] is not None: raise APIException('The user is already logged in.') session_token = f"{self.random.randint(0, 0xffffffff):08x}-{self.random.randint(0, 0xffff):04x}-{self.random.randint(0, 0xffff):04x}" self.database[username]["session_token"] = session_token return {"session_token": session_token}
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. """ """ Account database schema: username: str - key password: str session_token: str # use existence to determine if user is logged in email: str phone: str name: str """ ACCOUNT_DB_NAME = "Account" class AccountAPI(API, ABC): database_name = ACCOUNT_DB_NAME def __init__( self, account_database: dict, now_timestamp: str, api_database: dict = None ) -> None: super().__init__(account_database, now_timestamp, api_database) self.database = self.account_database class ChangePassword(AccountAPI): description = 'Changes the password of an account.' parameters = { 'old_password': { 'type': "string", 'description': 'The old password of the user.', 'required': True, }, 'new_password': { 'type': "string", 'description': 'The new password of the user.', 'required': True, }, } output = { 'status': {'type': "string", 'description': 'success or failed'} } database_name = ACCOUNT_DB_NAME is_action = True requires_auth = True def call(self, session_token: str, old_password: str, new_password: str) -> dict: """ Changes the password of an account. Args: session_token: User's session_token. Handled by ToolExecutor. old_password: The old password of the user. new_password: The new password of the user. """ user_info = self.check_session_token(session_token) if user_info["password"] != old_password: raise APIException("The old password is incorrect.") user_info["password"] = new_password return {"status": "success"} class DeleteAccount(AccountAPI): description = 'Deletes a user\'s account, requires user to be logged in.' parameters = { "password": { "type": "string", "description": "The password of the user.", "required": True } } output = { "status": { "type": "string", "description": "success or failed." } } is_action = True requires_auth = True def call(self, session_token: str, password: str) -> dict: """ Deletes a user's account. Args: session_token: User's session_token. Handled by ToolExecutor. password: The password of the user. """ user_data = self.check_session_token(session_token) username = user_data['username'] if user_data['password'] != password: raise APIException('The password is incorrect.') del self.database[username] return {"status": "success"} class GetAccountInformation(AccountAPI): description = "Retrieves account information of logged in user." parameters = {} output = { "user": { "type": "object", "properties": { "username": {"type": "string"}, "email": {"type": "string"}, "phone": {"type": "string"}, "name": {"type": "string"}, }, "description": "The account information of the user." } } is_action = False requires_auth = True def call(self, session_token: str) -> dict: """ Retrieves account information of logged in user. Args: session_token: User's session_token. Handled by ToolExecutor. """ user_info = self.check_session_token(session_token) return { "user": { "username": user_info["username"], "email": user_info["email"], "phone": user_info["phone"], "name": user_info["name"], } } class LogoutUser(AccountAPI): description = "Logs user out." parameters = {} output = { "status": {"type": "string", "description": "success or failed."}, } is_action = True database_name = ACCOUNT_DB_NAME requires_auth = True def call(self, session_token: str) -> dict: """ Logs user out. Args: session_token: User's session_token. Handled by ToolExecutor. """ # check session_token will fail if user is already logged out user_data = self.check_session_token(session_token) user_data["session_token"] = None return {"status": "success"} class QueryUser(AccountAPI): description = "Finds users given a username or email." parameters = { 'username': { 'type': "string", 'description': 'The username of the user, required if email is not supplied.', "required": False }, 'email': { 'type': "string", 'description': 'The email of the user, required if username is not supplied. May match multiple users', "required": False }, } output = { "users": { "type": "array", "item": { "type": "dict", "description": "The account information of the user.", "properties": { 'username': {'type': "string", 'description': 'The username of the user.'}, 'email': {'type': "string", 'description': 'The email of the user.'}, 'phone': {'type': "string", 'description': 'The phone number of the user.'}, 'name': {'type': "string", 'description': 'The name of the user.'}, } }, "description": "Users matching the query." } } database_name = ACCOUNT_DB_NAME is_action = False requires_auth = True def call(self, session_token: str, username: Optional[str] = None, email: Optional[str] = None) -> dict: """ Finds users given a username or email. Args: session_token: User's session_token. Handled by ToolExecutor. username: The username of the user, required if email is not supplied. email: The email of the user, required if username is not supplied. May match multiple users """ self.check_session_token(session_token) if username is None and email is None: raise APIException("You need to provide at least one of username and email.") if username is None: return { "users": [ { "username": username, "email": user_data["email"], "phone": user_data["phone"], "name": user_data["name"], } for username, user_data in self.database.items() if user_data["email"] == email ] } elif username in self.database: user_info = self.database[username] return { "users": [{ "username": username, "email": user_info["email"], "phone": user_info["phone"], "name": user_info["name"], }] } else: return {"users": []} class RegisterUser(AccountAPI): description = 'Register a new user.' parameters = { 'username': { 'type': "string", 'description': 'The username of the user.', "required": True }, 'password': { 'type': "string", 'description': 'The password of the user.', "required": True }, 'email': { 'type': "string", 'description': 'The email of the user.', "required": True }, "name": { "type": "string", "description": "The name of the user.", "required": False }, "phone": { 'type': "string", 'description': 'The phone of the user in the format xxx-xxx-xxxx.', "required": False }, } output = { "session_token": {'type': "string", 'description': 'The token of the user.'}, 'user': {'type': 'dict', 'description': 'The account information of the user.'}, } database_name = ACCOUNT_DB_NAME is_action = True def call( self, username: str, password: str, email: str, name: Optional[str] = None, phone: Optional[str] = None ) -> dict: """ Register a new user. Args: username: The username of the user. password: The password of the user. email: The email of the user. name: The name of the user. phone: The phone of the user in the format xxx-xxx-xxxx. """ if username in self.database: raise APIException('The username already exists.') if not verify_email_format(email): raise APIException("The email format is invalid.") if phone is not None and not verify_phone_format(phone): raise APIException("The phone number format is invalid.") session_token = f"{self.random.randint(0, 0xffffffff):08x}-{self.random.randint(0, 0xffff):04x}-{self.random.randint(0, 0xffff):04x}" # TODO is this enough for a simulation? self.database[username] = { "username": username, 'password': password, "session_token": session_token, 'email': email, 'phone': phone, "name": name, } return { "session_token": session_token, "user": { "username": username, "email": email, "phone": phone, "name": name, } } class ResetPassword(AccountAPI): description = "Resets the password of a user using a verification code." parameters = { "username": { "type": "string", "description": "The username of the user.", "required": True }, "verification_code": { "type": "string", "description": "The 6 digit verification code sent to the user.", "required": True }, "new_password": { "type": "string", "description": "The new password of the user.", "required": True }, } output = { "status": { "type": "string", "description": "success or failed" }, } database_name = ACCOUNT_DB_NAME is_action = True def call(self, username: str, verification_code: str, new_password: str) -> dict: """ Resets the password of a user using a verification code. Parameters: - username (str): the username of the user. - verification_code (str): the verification code sent to the user. - new_password (str): the new password of the user. Returns: - status (str): success or failed """ if username not in self.database: raise APIException("The username does not exist.") if "verification_code" not in self.database[username]: raise APIException("The verification code is incorrect.") if self.database[username]["verification_code"] != verification_code: raise APIException("The verification code is incorrect.") self.database[username]["password"] = new_password return {"status": "success"} class SendVerificationCode(AccountAPI): description = "Initiates a password reset for a user by sending a verification code to a backup email." parameters = { "username": { "type": "string", "description": "The username of the user.", "required": True }, "email": { "type": "string", "description": "The email of the user.", "required": True }, } output = { "status": {"type": "string", "description": "success or failed"}, } database_name = ACCOUNT_DB_NAME is_action = True def call(self, username: str, email: str) -> dict: """ Initiates a password reset for a user by sending a verification code to a backup email. Args: username: The username of the user. email: The email of the user. """ if username not in self.database: raise APIException("The username does not exist.") if self.database[username]["email"] != email: raise APIException("The email is incorrect.") verification_code = f"{self.random.randint(0, 999999):06d}" self.database[username]["verification_code"] = verification_code return {"status": "success"} class UpdateAccountInformation(AccountAPI): description = "Updates account information of a user." parameters = { "password": { "type": "string", "description": "The password of the user.", "required": True }, "new_email": { "type": "string", "description": "The new email of the user.", "required": False }, "new_phone_number": { "type": "string", "description": "The new phone number of the user in the format xxx-xxx-xxxx.", "required": False }, "new_name": { "type": "string", "description": "The new name of the user.", "required": False } } output = { "success": {"type": "string", "description": "success or failed."}, } is_action = True database_name = ACCOUNT_DB_NAME requires_auth = True def call( self, session_token: str, password: str, new_email: Optional[str] = None, new_phone_number: Optional[str] = None, new_name: Optional[str] = None ) -> dict: """ Updates account information of a user. Args: session_token: User's session_token. Handled by ToolExecutor. password: The password of the user. new_email: The new email of the user. new_phone_number: The new phone number of the user in the format xxx-xxx-xxxx. new_name: The new name of the user. """ user_data = self.check_session_token(session_token) username = user_data['username'] if user_data['password'] != password: raise APIException('The password is incorrect.') if new_email is None and new_phone_number is None: raise APIException("You need to provide at least one of new_email and new_phone_number.") if new_email is not None: if not verify_email_format(new_email): raise APIException("The email is invalid.") self.database[username]["email"] = new_email if new_phone_number is not None: if not verify_phone_format(new_phone_number): raise APIException("The phone number is invalid.") self.database[username]["phone"] = new_phone_number if new_name is not None: self.database[username]["name"] = new_name return {"status": "success"} class UserLogin(AccountAPI): description = 'Logs in a user returns a token.' parameters = { 'username': { 'type': "string", 'description': 'The username of the user.', 'required': True, }, 'password': { 'type': "string", 'description': 'The password of the user.', 'required': True, }, } output = { "session_token": {'type': "string", 'description': 'The token of the user.'}, } database_name = ACCOUNT_DB_NAME is_action = True def call(self, username: str, password: str) -> dict: """ Logs in a user returns a token. Args: username: The username of the user. password: The password of the user. """ if username not in self.database: raise APIException('The username does not exist.') if self.database[username]['password'] != password: raise APIException('The password is incorrect.') if self.database[username]["session_token"] is not None: raise APIException('The user is already logged in.') session_token = f"{self.random.randint(0, 0xffffffff):08x}-{self.random.randint(0, 0xffff):04x}-{self.random.randint(0, 0xffff):04x}" self.database[username]["session_token"] = session_token return {"session_token": session_token}
class AccountSuite(APISuite):
2
2023-10-10 01:15:30+00:00
8k
IST-DASLab/SparseFinetuning
tests/test_training.py
[ { "identifier": "main", "path": "scripts/data_prep/convert_dataset_hf.py", "snippet": "def main(args: Namespace) -> None:\n \"\"\"Main: create C4/pile streaming dataset.\n\n Args:\n args (Namespace): Commandline arguments.\n \"\"\"\n try:\n dataset_constants = CONSTS[args.datas...
import os import shutil import sys import pytest import torch from argparse import Namespace from omegaconf import DictConfig from omegaconf import OmegaConf as om from scripts.data_prep.convert_dataset_hf import main as main_hf # noqa: E402 from scripts.train.train import main # noqa: E402
4,409
# Copyright 2022 MosaicML LLM Foundry authors # SPDX-License-Identifier: Apache-2.0 # Add repo root to path so we can import scripts and test it repo_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(repo_dir) def create_c4_dataset_xsmall(prefix: str) -> str: """Creates a small mocked version of the C4 dataset.""" c4_dir = os.path.join(os.getcwd(), f'my-copy-c4-{prefix}') shutil.rmtree(c4_dir, ignore_errors=True) downloaded_split = 'val_xsmall' # very fast to convert # Hyperparameters from https://github.com/mosaicml/llm-foundry/blob/340a56658560ebceb2a3aa69d6e37813e415acd0/README.md#L188 main_hf( Namespace( **{ 'dataset': 'c4', 'data_subset': 'en', 'splits': [downloaded_split], 'out_root': c4_dir, 'compression': None, 'concat_tokens': 2048, 'tokenizer': 'EleutherAI/gpt-neox-20b', 'bos_text': '', 'eos_text': '<|endoftext|>', 'no_wrap': False, 'num_workers': 8 })) # copy the small downloaded_split to other c4 splits for mocking purposes mocked_splits = ['train', 'val'] for mocked_split in mocked_splits: shutil.copytree(os.path.join(c4_dir, 'val_xsmall'), os.path.join(c4_dir, mocked_split)) assert os.path.exists(c4_dir) return c4_dir def gpt_tiny_cfg(dataset_name: str, device: str): """Create gpt tiny cfg.""" conf_path: str = os.path.join(repo_dir, 'scripts/train/yamls/pretrain/testing.yaml') with open(conf_path) as f: test_cfg = om.load(f) assert isinstance(test_cfg, DictConfig) test_cfg.data_local = dataset_name test_cfg.global_train_batch_size = 8 test_cfg.device_eval_batch_size = 4 test_cfg.device_train_microbatch_size = 4 test_cfg.max_duration = '4ba' test_cfg.eval_interval = '4ba' test_cfg.run_name = 'gpt-mini-integration-test' if device == 'cpu': test_cfg.model.init_device = 'cpu' test_cfg.fsdp_config = None test_cfg.model.attn_config.attn_impl = 'torch' test_cfg.model.loss_fn = 'torch_crossentropy' test_cfg.precision = 'fp32' return test_cfg @pytest.mark.parametrize('device', [ 'cpu', pytest.param('cuda', marks=pytest.mark.skipif( not torch.cuda.is_available(), reason='testing with cuda requires GPU')), ]) def test_train(device: str): """Test training run with a small dataset.""" dataset_name = create_c4_dataset_xsmall(device) test_cfg = gpt_tiny_cfg(dataset_name, device)
# Copyright 2022 MosaicML LLM Foundry authors # SPDX-License-Identifier: Apache-2.0 # Add repo root to path so we can import scripts and test it repo_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(repo_dir) def create_c4_dataset_xsmall(prefix: str) -> str: """Creates a small mocked version of the C4 dataset.""" c4_dir = os.path.join(os.getcwd(), f'my-copy-c4-{prefix}') shutil.rmtree(c4_dir, ignore_errors=True) downloaded_split = 'val_xsmall' # very fast to convert # Hyperparameters from https://github.com/mosaicml/llm-foundry/blob/340a56658560ebceb2a3aa69d6e37813e415acd0/README.md#L188 main_hf( Namespace( **{ 'dataset': 'c4', 'data_subset': 'en', 'splits': [downloaded_split], 'out_root': c4_dir, 'compression': None, 'concat_tokens': 2048, 'tokenizer': 'EleutherAI/gpt-neox-20b', 'bos_text': '', 'eos_text': '<|endoftext|>', 'no_wrap': False, 'num_workers': 8 })) # copy the small downloaded_split to other c4 splits for mocking purposes mocked_splits = ['train', 'val'] for mocked_split in mocked_splits: shutil.copytree(os.path.join(c4_dir, 'val_xsmall'), os.path.join(c4_dir, mocked_split)) assert os.path.exists(c4_dir) return c4_dir def gpt_tiny_cfg(dataset_name: str, device: str): """Create gpt tiny cfg.""" conf_path: str = os.path.join(repo_dir, 'scripts/train/yamls/pretrain/testing.yaml') with open(conf_path) as f: test_cfg = om.load(f) assert isinstance(test_cfg, DictConfig) test_cfg.data_local = dataset_name test_cfg.global_train_batch_size = 8 test_cfg.device_eval_batch_size = 4 test_cfg.device_train_microbatch_size = 4 test_cfg.max_duration = '4ba' test_cfg.eval_interval = '4ba' test_cfg.run_name = 'gpt-mini-integration-test' if device == 'cpu': test_cfg.model.init_device = 'cpu' test_cfg.fsdp_config = None test_cfg.model.attn_config.attn_impl = 'torch' test_cfg.model.loss_fn = 'torch_crossentropy' test_cfg.precision = 'fp32' return test_cfg @pytest.mark.parametrize('device', [ 'cpu', pytest.param('cuda', marks=pytest.mark.skipif( not torch.cuda.is_available(), reason='testing with cuda requires GPU')), ]) def test_train(device: str): """Test training run with a small dataset.""" dataset_name = create_c4_dataset_xsmall(device) test_cfg = gpt_tiny_cfg(dataset_name, device)
main(test_cfg)
1
2023-10-09 15:32:15+00:00
8k
jiangjiechen/auction-arena
src/bidder_base.py
[ { "identifier": "Item", "path": "src/item_base.py", "snippet": "class Item():\n def __init__(self, id: int, name: str, price: int, desc: str, true_value: int):\n self.id = id\n self.name = name\n self.price = price\n self.desc = desc\n self.true_value = true_value\n...
from typing import List from langchain.base_language import BaseLanguageModel from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) from langchain.chat_models import ( ChatAnthropic, ChatOpenAI, ChatVertexAI, ChatGooglePalm, ) from langchain.input import get_colored_text from langchain.callbacks import get_openai_callback from collections import defaultdict from pydantic import BaseModel from .item_base import Item, item_list_equal from .prompt_base import ( AUCTION_HISTORY, # INSTRUCT_OBSERVE_TEMPLATE, _LEARNING_STATEMENT, INSTRUCT_PLAN_TEMPLATE, INSTRUCT_BID_TEMPLATE, INSTRUCT_SUMMARIZE_TEMPLATE, INSTRUCT_LEARNING_TEMPLATE, INSTRUCT_REPLAN_TEMPLATE, SYSTEM_MESSAGE, ) from utils import LoadJsonL, extract_jsons_from_text, extract_numbered_list, trace_back import vertexai import queue import threading import os import random import time import ujson as json import matplotlib.pyplot as plt import sys
6,646
engagement_history = defaultdict(int) all_bidders_status = {} # track others' profit changes_of_plan = [] # not used input_box: str = None need_input = False semaphore = 0 class Config: arbitrary_types_allowed = True def __repr__(self): return self.name def __str__(self): return self.name @classmethod def create(cls, **data): instance = cls(**data) instance._post_init() return instance def _post_init(self): self.original_budget = self.budget self.system_message = SYSTEM_MESSAGE.format( name=self.name, desire_desc=DESIRE_DESC[self.desire], ) self._parse_llm() self.dialogue_history += [ SystemMessage(content=self.system_message), AIMessage(content='') ] self.budget_history.append(self.budget) self.profit_history.append(self.profit) def _parse_llm(self): if 'gpt-' in self.model_name: self.llm = ChatOpenAI(model=self.model_name, temperature=self.temperature, max_retries=30, request_timeout=1200) elif 'claude' in self.model_name: self.llm = ChatAnthropic(model=self.model_name, temperature=self.temperature, default_request_timeout=1200) elif 'bison' in self.model_name: self.llm = ChatGooglePalm(model_name=f'models/{self.model_name}', temperature=self.temperature) elif 'rule' in self.model_name or 'human' in self.model_name: self.llm = None else: raise NotImplementedError(self.model_name) # def _rotate_openai_org(self): # # use two organizations to avoid rate limit # if os.environ.get('OPENAI_ORGANIZATION_1') and os.environ.get('OPENAI_ORGANIZATION_2'): # return random.choice([os.environ.get('OPENAI_ORGANIZATION_1'), os.environ.get('OPENAI_ORGANIZATION_2')]) # else: # return None def _run_llm_standalone(self, messages: list): with get_openai_callback() as cb: for i in range(6): try: input_token_num = self.llm.get_num_tokens_from_messages(messages) if 'claude' in self.model_name: # anthropic's claude result = self.llm(messages, max_tokens_to_sample=2048) elif 'bison' in self.model_name: # google's palm-2 max_tokens = min(max(3900 - input_token_num, 192), 2048) if isinstance(self.llm, ChatVertexAI): result = self.llm(messages, max_output_tokens=max_tokens) else: result = self.llm(messages) elif 'gpt' in self.model_name: # openai if 'gpt-3.5-turbo' in self.model_name and '16k' not in self.model_name: max_tokens = max(3900 - input_token_num, 192) else: # gpt-4 # self.llm.openai_organization = self._rotate_openai_org() max_tokens = max(8000 - input_token_num, 192) result = self.llm(messages, max_tokens=max_tokens) elif 'llama' in self.model_name.lower(): raise NotImplementedError else: raise NotImplementedError break except: print(f'Retrying for {self.model_name} ({i+1}/6), wait for {2**(i+1)} sec...') time.sleep(2**(i+1)) self.openai_cost += cb.total_cost self.llm_token_count = self.llm.get_num_tokens_from_messages(messages) return result.content def _get_estimated_value(self, item): value = item.true_value * (1 + self.overestimate_percent / 100) return int(value) def _get_cur_item(self, key=None): if self.cur_item_id < len(self.items): if key is not None: return self.items[self.cur_item_id].__dict__[key] else: return self.items[self.cur_item_id] else: return 'no item left' def _get_next_item(self, key=None): if self.cur_item_id + 1 < len(self.items): if key is not None: return self.items[self.cur_item_id + 1].__dict__[key] else: return self.items[self.cur_item_id + 1] else: return 'no item left' def _get_remaining_items(self, as_str=False): remain_items = self.items[self.cur_item_id + 1:] if as_str: return ', '.join([item.name for item in remain_items]) else: return remain_items
sys.path.append('..') # DESIRE_DESC = { # 'default': "Your goal is to fully utilize your budget while actively participating in the auction", # 'maximize_profit': "Your goal is to maximize your overall profit, and fully utilize your budget while actively participating in the auction. This involves strategic bidding to win items for less than their true value, thereby ensuring the difference between the price paid and the item's value is as large as possible", # 'maximize_items': "Your goal is to win as many items as possible, and fully utilize your budget while actively participating in the auction. While keeping your budget in mind, you should aim to participate broadly across different items, striving to be the highest bidder more often than not", # } # remove period at the end of each description DESIRE_DESC = { 'maximize_profit': "Your primary objective is to secure the highest profit at the end of this auction, compared to all other bidders", 'maximize_items': "Your primary objective is to win the highest number of items at the end of this auction, compared to everyone else", } class Bidder(BaseModel): name: str model_name: str budget: int desire: str plan_strategy: str temperature: float = 0.7 overestimate_percent: int = 10 correct_belief: bool enable_learning: bool = False llm: BaseLanguageModel = None openai_cost = 0 llm_token_count = 0 verbose: bool = False auction_hash: str = '' system_message: str = '' original_budget: int = 0 # working memory profit: int = 0 cur_item_id = 0 items: list = [] dialogue_history: list = [] # for gradio UI display llm_prompt_history: list = [] # for tracking llm calling items_won = [] bid_history: list = [] # history of the bidding of a single item plan_instruct: str = '' # instruction for planning cur_plan: str = '' # current plan status_quo: dict = {} # belief of budget and profit, self and others withdraw: bool = False # state of withdraw learnings: str = '' # learnings from previous biddings. If given, then use it to guide the rest of the auction. max_bid_cnt: int = 4 # Rule Bidder: maximum number of bids on one item (K = 1 starting bid + K-1 increase bid) rule_bid_cnt: int = 0 # Rule Bidder: count of bids on one item # belief tracking failed_bid_cnt: int = 0 # count of failed bids (overspending) total_bid_cnt: int = 0 # count of total bids self_belief_error_cnt: int = 0 total_self_belief_cnt: int = 0 other_belief_error_cnt: int = 0 total_other_belief_cnt: int = 0 engagement_count: int = 0 budget_history = [] profit_history = [] budget_error_history = [] profit_error_history = [] win_bid_error_history = [] engagement_history = defaultdict(int) all_bidders_status = {} # track others' profit changes_of_plan = [] # not used input_box: str = None need_input = False semaphore = 0 class Config: arbitrary_types_allowed = True def __repr__(self): return self.name def __str__(self): return self.name @classmethod def create(cls, **data): instance = cls(**data) instance._post_init() return instance def _post_init(self): self.original_budget = self.budget self.system_message = SYSTEM_MESSAGE.format( name=self.name, desire_desc=DESIRE_DESC[self.desire], ) self._parse_llm() self.dialogue_history += [ SystemMessage(content=self.system_message), AIMessage(content='') ] self.budget_history.append(self.budget) self.profit_history.append(self.profit) def _parse_llm(self): if 'gpt-' in self.model_name: self.llm = ChatOpenAI(model=self.model_name, temperature=self.temperature, max_retries=30, request_timeout=1200) elif 'claude' in self.model_name: self.llm = ChatAnthropic(model=self.model_name, temperature=self.temperature, default_request_timeout=1200) elif 'bison' in self.model_name: self.llm = ChatGooglePalm(model_name=f'models/{self.model_name}', temperature=self.temperature) elif 'rule' in self.model_name or 'human' in self.model_name: self.llm = None else: raise NotImplementedError(self.model_name) # def _rotate_openai_org(self): # # use two organizations to avoid rate limit # if os.environ.get('OPENAI_ORGANIZATION_1') and os.environ.get('OPENAI_ORGANIZATION_2'): # return random.choice([os.environ.get('OPENAI_ORGANIZATION_1'), os.environ.get('OPENAI_ORGANIZATION_2')]) # else: # return None def _run_llm_standalone(self, messages: list): with get_openai_callback() as cb: for i in range(6): try: input_token_num = self.llm.get_num_tokens_from_messages(messages) if 'claude' in self.model_name: # anthropic's claude result = self.llm(messages, max_tokens_to_sample=2048) elif 'bison' in self.model_name: # google's palm-2 max_tokens = min(max(3900 - input_token_num, 192), 2048) if isinstance(self.llm, ChatVertexAI): result = self.llm(messages, max_output_tokens=max_tokens) else: result = self.llm(messages) elif 'gpt' in self.model_name: # openai if 'gpt-3.5-turbo' in self.model_name and '16k' not in self.model_name: max_tokens = max(3900 - input_token_num, 192) else: # gpt-4 # self.llm.openai_organization = self._rotate_openai_org() max_tokens = max(8000 - input_token_num, 192) result = self.llm(messages, max_tokens=max_tokens) elif 'llama' in self.model_name.lower(): raise NotImplementedError else: raise NotImplementedError break except: print(f'Retrying for {self.model_name} ({i+1}/6), wait for {2**(i+1)} sec...') time.sleep(2**(i+1)) self.openai_cost += cb.total_cost self.llm_token_count = self.llm.get_num_tokens_from_messages(messages) return result.content def _get_estimated_value(self, item): value = item.true_value * (1 + self.overestimate_percent / 100) return int(value) def _get_cur_item(self, key=None): if self.cur_item_id < len(self.items): if key is not None: return self.items[self.cur_item_id].__dict__[key] else: return self.items[self.cur_item_id] else: return 'no item left' def _get_next_item(self, key=None): if self.cur_item_id + 1 < len(self.items): if key is not None: return self.items[self.cur_item_id + 1].__dict__[key] else: return self.items[self.cur_item_id + 1] else: return 'no item left' def _get_remaining_items(self, as_str=False): remain_items = self.items[self.cur_item_id + 1:] if as_str: return ', '.join([item.name for item in remain_items]) else: return remain_items
def _get_items_value_str(self, items: List[Item]):
0
2023-10-08 09:30:57+00:00
8k
giangdip2410/HyperRouter
custom_layers.py
[ { "identifier": "prepare_forward", "path": "functions.py", "snippet": "def prepare_forward(gate, num_expert, world_size):\n r\"\"\"\n Prepare necessary information from gate output for MoE computation.\n\n Args:\n gate: a 1-d Long Tensor representing the target expert of each input\n ...
import tree import os import torch import torch.nn as nn from functions import prepare_forward, ensure_comm from functions import MOEScatter, MOEGather from functions import AllGather, Slice from custom_gate import HyperRouterGate from fastermoe.config import switch_from_env from .fastermoe.schedule import _fmoe_general_global_forward
3,739
r""" A general moe implementation that supports an arbitrary module as the expert. * `num_expert` stands for the number of experts on **each** worker. * `world_size` stands for the total number of workers that contains different experts. * `slice_group` can be a torch's communication group, indicating that specific model parallel is applied across the group, and workers in the group hold the same copy of input feature, and requires the same copy of the output. For each worker, FMoE only computes the output of a certain slice of the input batch, and will all-gather the outputs after computation. * `top_k` stands for the number of experts each token is going to. * `gate` is a gate class which can found in `fmoe.gates`. * `expert` can be specified as a module class, it is used to generate `num_expert` expert modules. """ def __init__( self, num_expert=32, d_model=1024, world_size=1, mp_group=None, # being deprecated slice_group=None, moe_group=None, top_k=2, gate=HyperRouterGate, expert=None, gate_hook=None, mask=None, mask_dict=None, hyper_size=None, ): super().__init__() self.num_expert = num_expert self.d_model = d_model self.world_size = world_size self.slice_group = slice_group if mp_group is not None: print("[Warning] mp_group is being deprecated") self.slice_group = mp_group if self.slice_group is None: self.slice_size = 1 self.slice_rank = 0 else: self.slice_size = self.slice_group.size() self.slice_rank = self.slice_group.rank() self.top_k = top_k if type(expert) is list: self.experts = nn.ModuleList([e(d_model) for e in expert]) self.experts_fused = False self.num_expert = num_expert = len(expert) elif expert is not None: self.experts = nn.ModuleList([expert(d_model) for _ in range(num_expert)]) self.experts_fused = False else: self.experts_fused = True if hyper_size is not None and isinstance(m.gate, HyperRouterGate): self.gate = gate(d_model, num_expert, world_size, top_k, hyper_size) else: self.gate = gate(d_model, num_expert, world_size, top_k) self.gate_hook = gate_hook self.mask = mask self.mask_dict = mask_dict self.moe_group = moe_group def expert_fn(self, inp, fwd_expert_count): r""" The default expert function which either calls the experts as a whole or as separate experts. """ if self.experts_fused: return self.experts(inp, fwd_expert_count) if isinstance(fwd_expert_count, torch.Tensor): fwd_expert_count = fwd_expert_count.cpu().numpy() outputs = [] base_idx = 0 for i in range(self.num_expert): batch_size = fwd_expert_count[i] inp_slice = inp[base_idx : base_idx + batch_size] outputs.append(self.experts[i](inp_slice)) base_idx += batch_size return torch.cat(outputs, dim=0) def mark_parallel_comm(self, expert_dp_comm="none"): r""" Automatically mark the data parallel comms of the parameters within the module. This can be typically called at the end of the __init__ function in child classes. """ if self.experts is not None: comm = expert_dp_comm if isinstance(self.experts, list): for e in self.experts: mark_module_parallel_comm(e, comm) else: mark_module_parallel_comm(self.experts, comm) mark_module_parallel_comm(self.gate, "gate") def forward(self, moe_inp): r""" The FMoE module first computes gate output, and then conduct MoE forward according to the gate. The score of the selected gate given by the expert is multiplied to the experts' output tensors as a weight. """ moe_inp_batch_size = tree.flatten( tree.map_structure(lambda tensor: tensor.shape[0], moe_inp) ) assert all( [batch_size == moe_inp_batch_size[0] for batch_size in moe_inp_batch_size] ), "MoE inputs must have the same batch size" if self.world_size > 1: def ensure_comm_func(tensor):
r""" FMoE core layer """ def mark_module_parallel_comm(module, comm): r""" Mark all parameters in `module` as doing data parallel in `comm`, where `comm` may be one of `'world', 'dp', 'none'`. """ for p in module.parameters(): setattr(p, "dp_comm", comm) def _fmoe_general_global_forward(inp, gate, expert_fn, num_expert, world_size, **kwargs): r""" A private function that performs the following steps to complete the MoE computation. * Count the number of tokens from each worker to each expert. * Send the features to their target position so that input features to each expert are contiguous in memory. * Perform the forward computation of the experts using `expert_fn` * Gather the output features of experts back, and reorder them as sentences. Intermediate results like expert counts are hidden from users by this function. """ ( pos, local_expert_count, global_expert_count, fwd_expert_count, fwd_batch_size, ) = prepare_forward(gate, num_expert, world_size) topk = 1 if len(gate.shape) == 2: topk = gate.shape[1] def scatter_func(tensor): return MOEScatter.apply( tensor, torch.div(pos, topk, rounding_mode='floor'), local_expert_count, global_expert_count, fwd_batch_size, world_size, ) x = tree.map_structure(scatter_func, inp) x = expert_fn(x, fwd_expert_count) out_batch_size = tree.flatten(inp)[0].shape[0] if len(gate.shape) == 2: out_batch_size *= gate.shape[1] def gather_func(tensor): return MOEGather.apply( tensor, pos, local_expert_count, global_expert_count, out_batch_size, world_size, ) outp = tree.map_structure(gather_func, x) return outp fmoe_faster_schedule = False if switch_from_env('FMOE_FASTER_SCHEDULE_ENABLE', False): fmoe_faster_schedule = True class FMoE(nn.Module): r""" A general moe implementation that supports an arbitrary module as the expert. * `num_expert` stands for the number of experts on **each** worker. * `world_size` stands for the total number of workers that contains different experts. * `slice_group` can be a torch's communication group, indicating that specific model parallel is applied across the group, and workers in the group hold the same copy of input feature, and requires the same copy of the output. For each worker, FMoE only computes the output of a certain slice of the input batch, and will all-gather the outputs after computation. * `top_k` stands for the number of experts each token is going to. * `gate` is a gate class which can found in `fmoe.gates`. * `expert` can be specified as a module class, it is used to generate `num_expert` expert modules. """ def __init__( self, num_expert=32, d_model=1024, world_size=1, mp_group=None, # being deprecated slice_group=None, moe_group=None, top_k=2, gate=HyperRouterGate, expert=None, gate_hook=None, mask=None, mask_dict=None, hyper_size=None, ): super().__init__() self.num_expert = num_expert self.d_model = d_model self.world_size = world_size self.slice_group = slice_group if mp_group is not None: print("[Warning] mp_group is being deprecated") self.slice_group = mp_group if self.slice_group is None: self.slice_size = 1 self.slice_rank = 0 else: self.slice_size = self.slice_group.size() self.slice_rank = self.slice_group.rank() self.top_k = top_k if type(expert) is list: self.experts = nn.ModuleList([e(d_model) for e in expert]) self.experts_fused = False self.num_expert = num_expert = len(expert) elif expert is not None: self.experts = nn.ModuleList([expert(d_model) for _ in range(num_expert)]) self.experts_fused = False else: self.experts_fused = True if hyper_size is not None and isinstance(m.gate, HyperRouterGate): self.gate = gate(d_model, num_expert, world_size, top_k, hyper_size) else: self.gate = gate(d_model, num_expert, world_size, top_k) self.gate_hook = gate_hook self.mask = mask self.mask_dict = mask_dict self.moe_group = moe_group def expert_fn(self, inp, fwd_expert_count): r""" The default expert function which either calls the experts as a whole or as separate experts. """ if self.experts_fused: return self.experts(inp, fwd_expert_count) if isinstance(fwd_expert_count, torch.Tensor): fwd_expert_count = fwd_expert_count.cpu().numpy() outputs = [] base_idx = 0 for i in range(self.num_expert): batch_size = fwd_expert_count[i] inp_slice = inp[base_idx : base_idx + batch_size] outputs.append(self.experts[i](inp_slice)) base_idx += batch_size return torch.cat(outputs, dim=0) def mark_parallel_comm(self, expert_dp_comm="none"): r""" Automatically mark the data parallel comms of the parameters within the module. This can be typically called at the end of the __init__ function in child classes. """ if self.experts is not None: comm = expert_dp_comm if isinstance(self.experts, list): for e in self.experts: mark_module_parallel_comm(e, comm) else: mark_module_parallel_comm(self.experts, comm) mark_module_parallel_comm(self.gate, "gate") def forward(self, moe_inp): r""" The FMoE module first computes gate output, and then conduct MoE forward according to the gate. The score of the selected gate given by the expert is multiplied to the experts' output tensors as a weight. """ moe_inp_batch_size = tree.flatten( tree.map_structure(lambda tensor: tensor.shape[0], moe_inp) ) assert all( [batch_size == moe_inp_batch_size[0] for batch_size in moe_inp_batch_size] ), "MoE inputs must have the same batch size" if self.world_size > 1: def ensure_comm_func(tensor):
ensure_comm(tensor, self.moe_group)
1
2023-10-09 06:35:57+00:00
8k
hyukkyukang/DBSherlock
scripts/experiments/experiment.py
[ { "identifier": "AnomalyData", "path": "src/data/anomaly_data.py", "snippet": "class AnomalyData:\n cause: str # the name of each performance anomaly\n attributes: List[str] # list of attribute names\n values: List[List[float]] # shape: (time, attribute)\n normal_regions: List[int] # lis...
import argparse import logging import os import hkkang_utils.file as file_utils import tqdm from typing import * from src.data.anomaly_data import AnomalyData, AnomalyDataset from src.data.visualize import plot_performance from src.model.dbsherlock import DBSherlock
5,079
logger = logging.getLogger("Experiment") def split_dataset( data: AnomalyDataset, cause: str, target_idx: int, exp_id: int ) -> Tuple[List[AnomalyData], List[AnomalyData]]: if exp_id == 1: # Use one training data and the rest for testing target_data = data.get_data_of_cause(cause=cause) training_data = [target_data[target_idx]] testing_data = [ data for idx, data in enumerate(target_data) if idx != target_idx ] elif exp_id in [2, 3]: # Use one testing data and the rest for training target_data = data.get_data_of_cause(cause=cause) testing_data = [target_data[target_idx]] training_data = [ data for idx, data in enumerate(target_data) if idx != target_idx ] else: ValueError(f"Invalid exp_id: {exp_id}") return training_data, testing_data def main( exp_id: int, data_path: str, output_dir: str, num_sample_per_case: int = 11, do_save_model: bool = False, ) -> None: # Load data data_in_json = file_utils.read_json_file(data_path) anomaly_dataset = AnomalyDataset.from_dict(data=data_in_json) # Check number of data assert ( len(anomaly_dataset) == len(anomaly_dataset.causes) * num_sample_per_case ), f"Number of data is not correct, {len(anomaly_dataset)} vs {len(anomaly_dataset.causes) * num_sample_per_case}" # Create DBSherlockmodel
logger = logging.getLogger("Experiment") def split_dataset( data: AnomalyDataset, cause: str, target_idx: int, exp_id: int ) -> Tuple[List[AnomalyData], List[AnomalyData]]: if exp_id == 1: # Use one training data and the rest for testing target_data = data.get_data_of_cause(cause=cause) training_data = [target_data[target_idx]] testing_data = [ data for idx, data in enumerate(target_data) if idx != target_idx ] elif exp_id in [2, 3]: # Use one testing data and the rest for training target_data = data.get_data_of_cause(cause=cause) testing_data = [target_data[target_idx]] training_data = [ data for idx, data in enumerate(target_data) if idx != target_idx ] else: ValueError(f"Invalid exp_id: {exp_id}") return training_data, testing_data def main( exp_id: int, data_path: str, output_dir: str, num_sample_per_case: int = 11, do_save_model: bool = False, ) -> None: # Load data data_in_json = file_utils.read_json_file(data_path) anomaly_dataset = AnomalyDataset.from_dict(data=data_in_json) # Check number of data assert ( len(anomaly_dataset) == len(anomaly_dataset.causes) * num_sample_per_case ), f"Number of data is not correct, {len(anomaly_dataset)} vs {len(anomaly_dataset.causes) * num_sample_per_case}" # Create DBSherlockmodel
dbsherlock = DBSherlock()
3
2023-10-11 15:47:25+00:00
8k
SH1ROd/Bert-VITS2-Integration-train-txt-infer
inference_webui_update.py
[ { "identifier": "SynthesizerTrn", "path": "models.py", "snippet": "class SynthesizerTrn(nn.Module):\n \"\"\"\n Synthesizer for Training\n \"\"\"\n\n def __init__(self,\n n_vocab,\n spec_channels,\n segment_size,\n inter_channels,\n ...
import sys, os import numpy as np import logging import torch import argparse import commons import utils import gradio as gr import webbrowser import audiotsm import audiotsm.io.wav import audiotsm.io.array from models import SynthesizerTrn from text.symbols import symbols from text import cleaned_text_to_sequence, get_bert from text.cleaner import clean_text
4,888
# 处理中文句号 tmp = tmp.replace("。", ".") # 处理中文问号 tmp = tmp.replace("?", "?") # 处理中文感叹号 tmp = tmp.replace("!", "!") with torch.no_grad(): audio = infer(tmp, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker) #分段音频的头部添加自然停顿 blank = np.zeros((int(float(stop_time) * 44100),), dtype=np.float64) # audio = np.concatenate((blank, audio), axis=None) audio = np.concatenate((blank, audio), axis=None) sum_audio = np.concatenate((sum_audio, audio), axis=None) tmp = tmp +"\n\n" print(tmp) # if index == 0: # with open("./output.txt", "w", encoding="utf-8") as f: # f.write(tmp) # else: # with open("./output.txt", "a", encoding="utf-8") as f: # f.write(tmp) current_segment = segment # 将最后一个段落加入text_seg列表中 if current_segment: tmp = current_segment + "." # with open("./output.txt", "a", encoding="utf-8") as f: # f.write(tmp) # 处理换行符 tmp = tmp.replace("\n", "") # 处理中文双引号 tmp = tmp.replace("“", "'").replace("”", "'") # 处理中文括号 tmp = tmp.replace("(", "'").replace(")", "'") # 处理英文括号 tmp = tmp.replace("(", "'").replace(")", "'") # 处理中文书名号 tmp = tmp.replace("《", "'").replace("》", "'") # 处理中文逗号 tmp = tmp.replace(",", ",") # 处理中文句号 tmp = tmp.replace("。", ".") # 处理中文问号 tmp = tmp.replace("?", "?") # 处理中文感叹号 tmp = tmp.replace("!", "!") with torch.no_grad(): audio = infer(tmp, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker) print(tmp + "\n\n") # 分段音频的头部添加自然停顿 blank = np.zeros((int(float(stop_time) * 44100),), dtype=np.float64) audio = np.concatenate((blank, audio), axis=None) sum_audio = np.concatenate((sum_audio, audio), axis=None) #变速不变调 # 可以直接读取文件 # reader = audiotsm.io.wav.WavReader("01.wav") # 也可以加载别的地方传过来的numpy.ndarray音频数据 # a, sr = sf.read("qaq.wav", dtype='float32') # a = a.reshape((1,-1)) # (1,-1):(通道数,音频长度) reader = audiotsm.io.array.ArrayReader(np.matrix(sum_audio)) # 可以直接写入文件 # writer = audiotsm.io.wav.WavWriter("02.wav", 1, 44100) # 1:单通道。 16000:采样率 # 也可以直接获得numpy.ndarray的数据 writer = audiotsm.io.array.ArrayWriter(1) wsola = audiotsm.wsola(1, speed=speed) # 1:单通道。 speed:速度 wsola.run(reader, writer) sum_audio = writer.data[0] return "Success", (hps.data.sampling_rate, sum_audio) def text_file_fn(texts_obj): data='' for file in texts_obj: with open(file.name, "r", encoding='utf-8') as f: data += '\n' + f.read() return gr.TextArea(value=data) def text_cut_change_fn(flag): return gr.Slider(visible=flag), gr.File(visible=flag) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-r", "--role", default="NaN", help="name of your role in ./model_saved") parser.add_argument("-m", "--model_dir", default="./model_saved/candace/G_2800.pth", help="path of your model") parser.add_argument("-c", "--config_dir", default="./config\config.json",help="path of your config file") parser.add_argument("-st", "--stop_time", default=1.0, help="stop time between sentences") parser.add_argument("-s", "--share", default=True, help="make link public") parser.add_argument("-d", "--debug", action="store_true", help="enable DEBUG-LEVEL log") args = parser.parse_args() if args.debug: logger.info("Enable DEBUG-LEVEL log") logging.basicConfig(level=logging.DEBUG) if args.role != "NaN": config_dir = f"./model_saved/{args.role}/config.json" args.config_dir = config_dir hps = utils.get_hparams_from_file(args.config_dir) device = "cuda:0" if torch.cuda.is_available() else "cpu" ''' device = ( "cuda:0" if torch.cuda.is_available() else ( "mps" if sys.platform == "darwin" and torch.backends.mps.is_available() else "cpu" ) ) ''' net_g = SynthesizerTrn(
if sys.platform == "darwin": os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" logging.getLogger("numba").setLevel(logging.WARNING) logging.getLogger("markdown_it").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) logging.getLogger("matplotlib").setLevel(logging.WARNING) logging.basicConfig(level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s") logger = logging.getLogger(__name__) net_g = None def get_text(text, language_str, hps): norm_text, phone, tone, word2ph = clean_text(text, language_str) phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str) if hps.data.add_blank: phone = commons.intersperse(phone, 0) tone = commons.intersperse(tone, 0) language = commons.intersperse(language, 0) for i in range(len(word2ph)): word2ph[i] = word2ph[i] * 2 word2ph[0] += 1 bert = get_bert(norm_text, word2ph, language_str) del word2ph assert bert.shape[-1] == len(phone) phone = torch.LongTensor(phone) tone = torch.LongTensor(tone) language = torch.LongTensor(language) return bert, phone, tone, language def infer(text, sdp_ratio, noise_scale, noise_scale_w, length_scale, sid): global net_g bert, phones, tones, lang_ids = get_text(text, "ZH", hps) with torch.no_grad(): x_tst=phones.to(device).unsqueeze(0) tones=tones.to(device).unsqueeze(0) lang_ids=lang_ids.to(device).unsqueeze(0) bert = bert.to(device).unsqueeze(0) x_tst_lengths = torch.LongTensor([phones.size(0)]).to(device) del phones speakers = torch.LongTensor([hps.data.spk2id[sid]]).to(device) audio = net_g.infer(x_tst, x_tst_lengths, speakers, tones, lang_ids, bert, sdp_ratio=sdp_ratio , noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale)[0][0,0].data.cpu().float().numpy() del x_tst, tones, lang_ids, bert, x_tst_lengths, speakers return audio def tts_fn(text_cut, text_cut_min_length, text, speaker, sdp_ratio, noise_scale, noise_scale_w, length_scale, speed, stop_time , seg_char): # # 处理换行符 # text = text.replace("\n", "").replace("”", "'") # # 处理中文双引号 # text = text.replace("“", "'").replace("”", "'") # # 处理中文书名号 # text = text.replace("《", "'").replace("》", "'") # # 处理中文逗号 # text = text.replace(",", ",") # # 处理中文句号 # text = text.replace("。", ".") # # 处理中文问号 # text = text.replace("?", "?") # # 处理中文感叹号 # text = text.replace("!", "!") #如果不是txt文件 if not text_cut: with torch.no_grad(): audio = infer(text, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker) return "Success", (hps.data.sampling_rate, audio) else: text_segments = text.split(seg_char) print(text_segments) # 初始化存储裁切后文字的列表 text_seg = [] # 初始化当前段落 current_segment = "" #最终合并音频 sum_audio = np.array([],dtype='float64') # 遍历每个裁切后的段落,检查长度是否满足要求,并存入text_seg列表中 for index, segment in enumerate(text_segments): # 如果当前段落加上这个segment的长度小于等于text_cut_min_length,则将这个segment加入当前段落 if len(current_segment) + len(segment) + 1 <= text_cut_min_length: if current_segment: current_segment += "." + segment else: current_segment = segment else: tmp = current_segment + "." print(tmp) # print(len(tmp)) # print(type(tmp)) # 处理换行符 tmp = tmp.replace("\n", "") # 处理中文双引号 tmp = tmp.replace("“", "'").replace("”", "'") # 处理中文括号 tmp = tmp.replace("(", "'").replace(")", "'") # 处理英文括号 tmp = tmp.replace("(", "'").replace(")", "'") # 处理中文书名号 tmp = tmp.replace("《", "'").replace("》", "'") # 处理中文逗号 tmp = tmp.replace(",", ",") # 处理中文句号 tmp = tmp.replace("。", ".") # 处理中文问号 tmp = tmp.replace("?", "?") # 处理中文感叹号 tmp = tmp.replace("!", "!") with torch.no_grad(): audio = infer(tmp, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker) #分段音频的头部添加自然停顿 blank = np.zeros((int(float(stop_time) * 44100),), dtype=np.float64) # audio = np.concatenate((blank, audio), axis=None) audio = np.concatenate((blank, audio), axis=None) sum_audio = np.concatenate((sum_audio, audio), axis=None) tmp = tmp +"\n\n" print(tmp) # if index == 0: # with open("./output.txt", "w", encoding="utf-8") as f: # f.write(tmp) # else: # with open("./output.txt", "a", encoding="utf-8") as f: # f.write(tmp) current_segment = segment # 将最后一个段落加入text_seg列表中 if current_segment: tmp = current_segment + "." # with open("./output.txt", "a", encoding="utf-8") as f: # f.write(tmp) # 处理换行符 tmp = tmp.replace("\n", "") # 处理中文双引号 tmp = tmp.replace("“", "'").replace("”", "'") # 处理中文括号 tmp = tmp.replace("(", "'").replace(")", "'") # 处理英文括号 tmp = tmp.replace("(", "'").replace(")", "'") # 处理中文书名号 tmp = tmp.replace("《", "'").replace("》", "'") # 处理中文逗号 tmp = tmp.replace(",", ",") # 处理中文句号 tmp = tmp.replace("。", ".") # 处理中文问号 tmp = tmp.replace("?", "?") # 处理中文感叹号 tmp = tmp.replace("!", "!") with torch.no_grad(): audio = infer(tmp, sdp_ratio=sdp_ratio, noise_scale=noise_scale, noise_scale_w=noise_scale_w, length_scale=length_scale, sid=speaker) print(tmp + "\n\n") # 分段音频的头部添加自然停顿 blank = np.zeros((int(float(stop_time) * 44100),), dtype=np.float64) audio = np.concatenate((blank, audio), axis=None) sum_audio = np.concatenate((sum_audio, audio), axis=None) #变速不变调 # 可以直接读取文件 # reader = audiotsm.io.wav.WavReader("01.wav") # 也可以加载别的地方传过来的numpy.ndarray音频数据 # a, sr = sf.read("qaq.wav", dtype='float32') # a = a.reshape((1,-1)) # (1,-1):(通道数,音频长度) reader = audiotsm.io.array.ArrayReader(np.matrix(sum_audio)) # 可以直接写入文件 # writer = audiotsm.io.wav.WavWriter("02.wav", 1, 44100) # 1:单通道。 16000:采样率 # 也可以直接获得numpy.ndarray的数据 writer = audiotsm.io.array.ArrayWriter(1) wsola = audiotsm.wsola(1, speed=speed) # 1:单通道。 speed:速度 wsola.run(reader, writer) sum_audio = writer.data[0] return "Success", (hps.data.sampling_rate, sum_audio) def text_file_fn(texts_obj): data='' for file in texts_obj: with open(file.name, "r", encoding='utf-8') as f: data += '\n' + f.read() return gr.TextArea(value=data) def text_cut_change_fn(flag): return gr.Slider(visible=flag), gr.File(visible=flag) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-r", "--role", default="NaN", help="name of your role in ./model_saved") parser.add_argument("-m", "--model_dir", default="./model_saved/candace/G_2800.pth", help="path of your model") parser.add_argument("-c", "--config_dir", default="./config\config.json",help="path of your config file") parser.add_argument("-st", "--stop_time", default=1.0, help="stop time between sentences") parser.add_argument("-s", "--share", default=True, help="make link public") parser.add_argument("-d", "--debug", action="store_true", help="enable DEBUG-LEVEL log") args = parser.parse_args() if args.debug: logger.info("Enable DEBUG-LEVEL log") logging.basicConfig(level=logging.DEBUG) if args.role != "NaN": config_dir = f"./model_saved/{args.role}/config.json" args.config_dir = config_dir hps = utils.get_hparams_from_file(args.config_dir) device = "cuda:0" if torch.cuda.is_available() else "cpu" ''' device = ( "cuda:0" if torch.cuda.is_available() else ( "mps" if sys.platform == "darwin" and torch.backends.mps.is_available() else "cpu" ) ) ''' net_g = SynthesizerTrn(
len(symbols),
1
2023-10-10 02:23:23+00:00
8k
sakemin/cog-musicgen-chord
audiocraft/metrics/fad.py
[ { "identifier": "audio_write", "path": "audiocraft/data/audio.py", "snippet": "def audio_write(stem_name: tp.Union[str, Path],\n wav: torch.Tensor, sample_rate: int,\n format: str = 'wav', mp3_rate: int = 320, ogg_rate: tp.Optional[int] = None,\n normalize: b...
import logging import os import subprocess import tempfile import typing as tp import flashy import torch import torchmetrics from pathlib import Path from audiocraft.data.audio import audio_write from audiocraft.data.audio_utils import convert_audio from ..environment import AudioCraftEnvironment
5,041
# e.g. instructions from: https://www.tensorflow.org/install/pip conda install -c conda-forge cudatoolkit=11.8.0 python3 -m pip install nvidia-cudnn-cu11==8.6.0.163 tensorflow==2.12.* mkdir -p $CONDA_PREFIX/etc/conda/activate.d echo 'CUDNN_PATH=$(dirname $(python -c "import nvidia.cudnn;print(nvidia.cudnn.__file__)"))' \ >> $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/:$CUDNN_PATH/lib' \ >> $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh source $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh # Verify install: on a machine with GPU device python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))" ``` Now install frechet_audio_distance required dependencies: ``` # We assume we already have TensorFlow installed from the above steps pip install apache-beam numpy scipy tf_slim ``` Finally, follow remaining library instructions to ensure you have a working frechet_audio_distance setup (you may want to specify --model_ckpt flag pointing to the model's path). 3. AudioCraft's FrechetAudioDistanceMetric requires 2 environment variables pointing to the python executable and Tensorflow library path from the above installation steps: export TF_PYTHON_EXE="<PATH_TO_THE_ENV_PYTHON_BINARY>" export TF_LIBRARY_PATH="<PATH_TO_THE_ENV_CUDNN_LIBRARY>" e.g. assuming we have installed everything in a dedicated conda env with python 3.10 that is currently active: export TF_PYTHON_EXE="$CONDA_PREFIX/bin/python" export TF_LIBRARY_PATH="$CONDA_PREFIX/lib/python3.10/site-packages/nvidia/cudnn/lib" Finally you may want to export the following variable: export TF_FORCE_GPU_ALLOW_GROWTH=true See: https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth You can save those environment variables in your training conda env, when currently active: `$CONDA_PREFIX/etc/conda/activate.d/env_vars.sh` e.g. assuming the env with TensorFlow and frechet_audio_distance install is named ac_eval, and the training conda env is named audiocraft: ``` # activate training env conda activate audiocraft # get path to all envs CONDA_ENV_DIR=$(dirname $CONDA_PREFIX) # export pointers to evaluation env for using TensorFlow in FrechetAudioDistanceMetric touch $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh echo 'export TF_PYTHON_EXE="$CONDA_ENV_DIR/ac_eval/bin/python"' >> \ $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh echo 'export TF_LIBRARY_PATH="$CONDA_ENV_DIR/ac_eval/lib/python3.10/site-packages/nvidia/cudnn/lib"' >> \ $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh # optionally: echo 'export TF_FORCE_GPU_ALLOW_GROWTH=true' >> $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh # you may need to reactivate the audiocraft env for this to take effect ``` Args: bin (Path or str): Path to installed frechet audio distance code. model_path (Path or str): Path to Tensorflow checkpoint for the model used to compute statistics over the embedding beams. format (str): Audio format used to save files. log_folder (Path or str, optional): Path where to write process logs. """ def __init__(self, bin: tp.Union[Path, str], model_path: tp.Union[Path, str], format: str = "wav", batch_size: tp.Optional[int] = None, log_folder: tp.Optional[tp.Union[Path, str]] = None): super().__init__() self.model_sample_rate = VGGISH_SAMPLE_RATE self.model_channels = VGGISH_CHANNELS self.model_path = AudioCraftEnvironment.resolve_reference_path(model_path) assert Path(self.model_path).exists(), f"Could not find provided model checkpoint path at: {self.model_path}" self.format = format self.batch_size = batch_size self.bin = bin self.tf_env = {"PYTHONPATH": str(self.bin)} self.python_path = os.environ.get('TF_PYTHON_EXE') or 'python' logger.info("Python exe for TF is %s", self.python_path) if 'TF_LIBRARY_PATH' in os.environ: self.tf_env['LD_LIBRARY_PATH'] = os.environ['TF_LIBRARY_PATH'] if 'TF_FORCE_GPU_ALLOW_GROWTH' in os.environ: self.tf_env['TF_FORCE_GPU_ALLOW_GROWTH'] = os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] logger.info("Env for TF is %r", self.tf_env) self.reset(log_folder) self.add_state("total_files", default=torch.tensor(0.), dist_reduce_fx="sum") def reset(self, log_folder: tp.Optional[tp.Union[Path, str]] = None): """Reset torchmetrics.Metrics state.""" log_folder = Path(log_folder or tempfile.mkdtemp()) self.tmp_dir = log_folder / 'fad' self.tmp_dir.mkdir(exist_ok=True) self.samples_tests_dir = self.tmp_dir / 'tests' self.samples_tests_dir.mkdir(exist_ok=True) self.samples_background_dir = self.tmp_dir / 'background' self.samples_background_dir.mkdir(exist_ok=True) self.manifest_tests = self.tmp_dir / 'files_tests.cvs' self.manifest_background = self.tmp_dir / 'files_background.cvs' self.stats_tests_dir = self.tmp_dir / 'stats_tests' self.stats_background_dir = self.tmp_dir / 'stats_background' self.counter = 0 def update(self, preds: torch.Tensor, targets: torch.Tensor, sizes: torch.Tensor, sample_rates: torch.Tensor, stems: tp.Optional[tp.List[str]] = None): """Update torchmetrics.Metrics by saving the audio and updating the manifest file.""" assert preds.shape == targets.shape, f"preds={preds.shape} != targets={targets.shape}" num_samples = preds.shape[0] assert num_samples == sizes.size(0) and num_samples == sample_rates.size(0) assert stems is None or num_samples == len(set(stems)) for i in range(num_samples): self.total_files += 1 # type: ignore self.counter += 1 wav_len = int(sizes[i].item()) sample_rate = int(sample_rates[i].item()) pred_wav = preds[i] target_wav = targets[i] pred_wav = pred_wav[..., :wav_len] target_wav = target_wav[..., :wav_len] stem_name = stems[i] if stems is not None else f'sample_{self.counter}_{flashy.distrib.rank()}' # dump audio files try:
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. logger = logging.getLogger(__name__) VGGISH_SAMPLE_RATE = 16_000 VGGISH_CHANNELS = 1 class FrechetAudioDistanceMetric(torchmetrics.Metric): """Fréchet Audio Distance computation based on official TensorFlow implementation from Google Research. From: D.C. Dowson & B.V. Landau The Fréchet distance between multivariate normal distributions https://doi.org/10.1016/0047-259X(82)90077-X The Fréchet distance between two multivariate gaussians, `X ~ N(mu_x, sigma_x)` and `Y ~ N(mu_y, sigma_y)`, is `d^2`. d^2 = (mu_x - mu_y)^2 + Tr(sigma_x + sigma_y - 2 * sqrt(sigma_x*sigma_y)) = (mu_x - mu_y)^2 + Tr(sigma_x) + Tr(sigma_y) - 2 * Tr(sqrt(sigma_x*sigma_y))) To use this FAD computation metric, you need to have the proper Frechet Audio Distance tool setup from: https://github.com/google-research/google-research/tree/master/frechet_audio_distance We provide the below instructions as reference but we do not guarantee for further support in frechet_audio_distance installation. This was tested with python 3.10, cuda 11.8, tensorflow 2.12.0. We recommend installing the frechet_audio_distance library in a dedicated env (e.g. conda). 1. Get the code and models following the repository instructions. We used the steps below: git clone git@github.com:google-research/google-research.git git clone git@github.com:tensorflow/models.git mkdir google-research/tensorflow_models touch google-research/tensorflow_models/__init__.py cp -r models/research/audioset google-research/tensorflow_models/ touch google-research/tensorflow_models/audioset/__init__.py echo "from .vggish import mel_features, vggish_params, vggish_slim" > \ google-research/tensorflow_models/audioset/__init__.py # we can now remove the tensorflow models repository # rm -r models cd google-research Follow the instructions to download the vggish checkpoint. AudioCraft base configuration assumes it is placed in the AudioCraft reference dir. Note that we operate the following changes for the code to work with TensorFlow 2.X and python 3: - Update xrange for range in: https://github.com/google-research/google-research/blob/master/frechet_audio_distance/audioset_model.py - Update `tf_record = tf.python_io.tf_record_iterator(filename).next()` to `tf_record = tf.python_io.tf_record_iterator(filename).__next__()` in https://github.com/google-research/google-research/blob/master/frechet_audio_distance/fad_utils.py - Update `import vggish_params as params` to `from . import vggish_params as params` in: https://github.com/tensorflow/models/blob/master/research/audioset/vggish/vggish_slim.py - Add flag to provide a given batch size for running the AudioSet model in: https://github.com/google-research/google-research/blob/master/frechet_audio_distance/create_embeddings_main.py ``` flags.DEFINE_integer('batch_size', 64, 'Number of samples in the batch for AudioSet model.') ``` Ensure you pass the flag to the create_embeddings_beam.create_pipeline function, adding: `batch_size=FLAGS.batch_size` to the provided parameters. 2. Follow instructions for the library installation and a valid TensorFlow installation ``` # e.g. instructions from: https://www.tensorflow.org/install/pip conda install -c conda-forge cudatoolkit=11.8.0 python3 -m pip install nvidia-cudnn-cu11==8.6.0.163 tensorflow==2.12.* mkdir -p $CONDA_PREFIX/etc/conda/activate.d echo 'CUDNN_PATH=$(dirname $(python -c "import nvidia.cudnn;print(nvidia.cudnn.__file__)"))' \ >> $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/:$CUDNN_PATH/lib' \ >> $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh source $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh # Verify install: on a machine with GPU device python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))" ``` Now install frechet_audio_distance required dependencies: ``` # We assume we already have TensorFlow installed from the above steps pip install apache-beam numpy scipy tf_slim ``` Finally, follow remaining library instructions to ensure you have a working frechet_audio_distance setup (you may want to specify --model_ckpt flag pointing to the model's path). 3. AudioCraft's FrechetAudioDistanceMetric requires 2 environment variables pointing to the python executable and Tensorflow library path from the above installation steps: export TF_PYTHON_EXE="<PATH_TO_THE_ENV_PYTHON_BINARY>" export TF_LIBRARY_PATH="<PATH_TO_THE_ENV_CUDNN_LIBRARY>" e.g. assuming we have installed everything in a dedicated conda env with python 3.10 that is currently active: export TF_PYTHON_EXE="$CONDA_PREFIX/bin/python" export TF_LIBRARY_PATH="$CONDA_PREFIX/lib/python3.10/site-packages/nvidia/cudnn/lib" Finally you may want to export the following variable: export TF_FORCE_GPU_ALLOW_GROWTH=true See: https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth You can save those environment variables in your training conda env, when currently active: `$CONDA_PREFIX/etc/conda/activate.d/env_vars.sh` e.g. assuming the env with TensorFlow and frechet_audio_distance install is named ac_eval, and the training conda env is named audiocraft: ``` # activate training env conda activate audiocraft # get path to all envs CONDA_ENV_DIR=$(dirname $CONDA_PREFIX) # export pointers to evaluation env for using TensorFlow in FrechetAudioDistanceMetric touch $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh echo 'export TF_PYTHON_EXE="$CONDA_ENV_DIR/ac_eval/bin/python"' >> \ $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh echo 'export TF_LIBRARY_PATH="$CONDA_ENV_DIR/ac_eval/lib/python3.10/site-packages/nvidia/cudnn/lib"' >> \ $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh # optionally: echo 'export TF_FORCE_GPU_ALLOW_GROWTH=true' >> $CONDA_PREFIX/etc/conda/activate.d/env_vars.sh # you may need to reactivate the audiocraft env for this to take effect ``` Args: bin (Path or str): Path to installed frechet audio distance code. model_path (Path or str): Path to Tensorflow checkpoint for the model used to compute statistics over the embedding beams. format (str): Audio format used to save files. log_folder (Path or str, optional): Path where to write process logs. """ def __init__(self, bin: tp.Union[Path, str], model_path: tp.Union[Path, str], format: str = "wav", batch_size: tp.Optional[int] = None, log_folder: tp.Optional[tp.Union[Path, str]] = None): super().__init__() self.model_sample_rate = VGGISH_SAMPLE_RATE self.model_channels = VGGISH_CHANNELS self.model_path = AudioCraftEnvironment.resolve_reference_path(model_path) assert Path(self.model_path).exists(), f"Could not find provided model checkpoint path at: {self.model_path}" self.format = format self.batch_size = batch_size self.bin = bin self.tf_env = {"PYTHONPATH": str(self.bin)} self.python_path = os.environ.get('TF_PYTHON_EXE') or 'python' logger.info("Python exe for TF is %s", self.python_path) if 'TF_LIBRARY_PATH' in os.environ: self.tf_env['LD_LIBRARY_PATH'] = os.environ['TF_LIBRARY_PATH'] if 'TF_FORCE_GPU_ALLOW_GROWTH' in os.environ: self.tf_env['TF_FORCE_GPU_ALLOW_GROWTH'] = os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] logger.info("Env for TF is %r", self.tf_env) self.reset(log_folder) self.add_state("total_files", default=torch.tensor(0.), dist_reduce_fx="sum") def reset(self, log_folder: tp.Optional[tp.Union[Path, str]] = None): """Reset torchmetrics.Metrics state.""" log_folder = Path(log_folder or tempfile.mkdtemp()) self.tmp_dir = log_folder / 'fad' self.tmp_dir.mkdir(exist_ok=True) self.samples_tests_dir = self.tmp_dir / 'tests' self.samples_tests_dir.mkdir(exist_ok=True) self.samples_background_dir = self.tmp_dir / 'background' self.samples_background_dir.mkdir(exist_ok=True) self.manifest_tests = self.tmp_dir / 'files_tests.cvs' self.manifest_background = self.tmp_dir / 'files_background.cvs' self.stats_tests_dir = self.tmp_dir / 'stats_tests' self.stats_background_dir = self.tmp_dir / 'stats_background' self.counter = 0 def update(self, preds: torch.Tensor, targets: torch.Tensor, sizes: torch.Tensor, sample_rates: torch.Tensor, stems: tp.Optional[tp.List[str]] = None): """Update torchmetrics.Metrics by saving the audio and updating the manifest file.""" assert preds.shape == targets.shape, f"preds={preds.shape} != targets={targets.shape}" num_samples = preds.shape[0] assert num_samples == sizes.size(0) and num_samples == sample_rates.size(0) assert stems is None or num_samples == len(set(stems)) for i in range(num_samples): self.total_files += 1 # type: ignore self.counter += 1 wav_len = int(sizes[i].item()) sample_rate = int(sample_rates[i].item()) pred_wav = preds[i] target_wav = targets[i] pred_wav = pred_wav[..., :wav_len] target_wav = target_wav[..., :wav_len] stem_name = stems[i] if stems is not None else f'sample_{self.counter}_{flashy.distrib.rank()}' # dump audio files try:
pred_wav = convert_audio(
1
2023-10-09 09:52:24+00:00
8k
deep-symbolic-mathematics/TPSR
nesymres/src/nesymres/architectures/bfgs.py
[ { "identifier": "Generator", "path": "nesymres/src/nesymres/dataset/generator.py", "snippet": "class Generator(object):\n SYMPY_OPERATORS = {\n # Elementary functions\n sp.Add: \"add\",\n sp.Mul: \"mul\",\n sp.Pow: \"pow\",\n sp.exp: \"exp\",\n sp.log: \"ln\"...
import os import numpy as np import random import math import types import click import marshal import copyreg import sys import ast import pdb import torch import torch.nn.functional as F import sympy as sp import time import re import numexpr as ne from scipy.optimize import minimize from torch.utils.data import DataLoader, random_split from torch import nn from dataclasses import dataclass from ..dataset.generator import Generator from . import data from typing import Tuple from ..dataset.sympy_utils import add_multiplicative_constants, add_additive_constants
7,163
class TimedFun: def __init__(self, fun, stop_after=10): self.fun_in = fun self.started = False self.stop_after = stop_after def fun(self, x, *args): if self.started is False: self.started = time.time() elif abs(time.time() - self.started) >= self.stop_after: raise ValueError("Time is over.") self.fun_value = self.fun_in(*x, *args) self.x = x return self.fun_value def bfgs(pred_str, X, y, cfg): #Check where dimensions not use, and replace them with 1 to avoid numerical issues with BFGS (i.e. absent variables placed in the denominator) y = y.squeeze() X = X.clone() bool_dim = (X==0).all(axis=1).squeeze() X[:,:,bool_dim] = 1 if (type(pred_str) != list): pred_str = pred_str[1:].tolist() else: pred_str = pred_str[1:] #pred_str = [x if x<14 else x+1 for x in pred_str] raw = data.de_tokenize(pred_str, cfg.id2word) # if "constant" in prefix: # for j,i in enumerate(list(pred_str)[:-1]): # if i == "constant": # expre[j] = 'c{}'.format(str(c)) # c=c+1 # example = "".join(list(expre)) if cfg.bfgs.add_coefficients_if_not_existing and 'constant' not in raw: print("No constants in predicted expression. Attaching them everywhere") variables = {x:sp.Symbol(x, real=True, nonzero=True) for x in cfg.total_variables} infix = Generator.prefix_to_infix(raw, coefficients=cfg.total_coefficients, variables=cfg.total_variables) s = Generator.infix_to_sympy(infix,variables, cfg.rewrite_functions) placeholder = {x:sp.Symbol(x, real=True,nonzero=True) for x in ["cm","ca"]}
class TimedFun: def __init__(self, fun, stop_after=10): self.fun_in = fun self.started = False self.stop_after = stop_after def fun(self, x, *args): if self.started is False: self.started = time.time() elif abs(time.time() - self.started) >= self.stop_after: raise ValueError("Time is over.") self.fun_value = self.fun_in(*x, *args) self.x = x return self.fun_value def bfgs(pred_str, X, y, cfg): #Check where dimensions not use, and replace them with 1 to avoid numerical issues with BFGS (i.e. absent variables placed in the denominator) y = y.squeeze() X = X.clone() bool_dim = (X==0).all(axis=1).squeeze() X[:,:,bool_dim] = 1 if (type(pred_str) != list): pred_str = pred_str[1:].tolist() else: pred_str = pred_str[1:] #pred_str = [x if x<14 else x+1 for x in pred_str] raw = data.de_tokenize(pred_str, cfg.id2word) # if "constant" in prefix: # for j,i in enumerate(list(pred_str)[:-1]): # if i == "constant": # expre[j] = 'c{}'.format(str(c)) # c=c+1 # example = "".join(list(expre)) if cfg.bfgs.add_coefficients_if_not_existing and 'constant' not in raw: print("No constants in predicted expression. Attaching them everywhere") variables = {x:sp.Symbol(x, real=True, nonzero=True) for x in cfg.total_variables} infix = Generator.prefix_to_infix(raw, coefficients=cfg.total_coefficients, variables=cfg.total_variables) s = Generator.infix_to_sympy(infix,variables, cfg.rewrite_functions) placeholder = {x:sp.Symbol(x, real=True,nonzero=True) for x in ["cm","ca"]}
s = add_multiplicative_constants(s, placeholder["cm"], unary_operators=cfg.una_ops)
1
2023-10-09 15:54:58+00:00
8k
RVC-Project/Retrieval-based-Voice-Conversion
rvc/modules/uvr5/vr.py
[ { "identifier": "nets_61968KB", "path": "rvc/lib/uvr5_pack/lib_v5/nets_61968KB.py", "snippet": "class BaseASPPNet(nn.Module):\nclass CascadedASPPNet(nn.Module):\n def __init__(self, nin, ch, dilations=(4, 8, 16)):\n def __call__(self, x):\n def __init__(self, n_fft):\n def forward(self, x, a...
import logging import os import librosa import numpy as np import soundfile as sf import torch from rvc.lib.uvr5_pack.lib_v5 import nets_61968KB as Nets from rvc.lib.uvr5_pack.lib_v5 import spec_utils from rvc.lib.uvr5_pack.lib_v5.model_param_init import ModelParameters from rvc.lib.uvr5_pack.lib_v5.nets_new import CascadedNet from rvc.lib.uvr5_pack.utils import inference
4,210
self.mp.param["reverse"], ) # pdb.set_trace() if d == bands_n and self.data["high_end_process"] != "none": input_high_end_h = (bp["n_fft"] // 2 - bp["crop_stop"]) + ( self.mp.param["pre_filter_stop"] - self.mp.param["pre_filter_start"] ) input_high_end = X_spec_s[d][ :, bp["n_fft"] // 2 - input_high_end_h : bp["n_fft"] // 2, : ] X_spec_m = spec_utils.combine_spectrograms(X_spec_s, self.mp) aggresive_set = float(self.data["agg"] / 100) aggressiveness = { "value": aggresive_set, "split_bin": self.mp.param["band"][1]["crop_stop"], } with torch.no_grad(): pred, X_mag, X_phase = inference( X_spec_m, self.device, self.model, aggressiveness, self.data ) # Postprocess if self.data["postprocess"]: pred_inv = np.clip(X_mag - pred, 0, np.inf) pred = spec_utils.mask_silence(pred, pred_inv) y_spec_m = pred * X_phase v_spec_m = X_spec_m - y_spec_m if ins_root is not None: if self.data["high_end_process"].startswith("mirroring"): input_high_end_ = spec_utils.mirroring( self.data["high_end_process"], y_spec_m, input_high_end, self.mp ) wav_instrument = spec_utils.cmb_spectrogram_to_wave( y_spec_m, self.mp, input_high_end_h, input_high_end_ ) else: wav_instrument = spec_utils.cmb_spectrogram_to_wave(y_spec_m, self.mp) logger.info("%s instruments done" % name) if is_hp3: head = "vocal_" else: head = "instrument_" if format in ["wav", "flac"]: sf.write( os.path.join( ins_root, head + f"{name}_{self.data['agg']}.{format}", ), (np.array(wav_instrument) * 32768).astype("int16"), self.mp.param["sr"], ) # else: path = os.path.join(ins_root, head + f"{name}_{self.data['agg']}.wav") sf.write( path, (np.array(wav_instrument) * 32768).astype("int16"), self.mp.param["sr"], ) if os.path.exists(path): opt_format_path = path[:-4] + ".%s" % format os.system("ffmpeg -i %s -vn %s -q:a 2 -y" % (path, opt_format_path)) if os.path.exists(opt_format_path): try: os.remove(path) except Exception: pass if vocal_root is not None: head = "instrument_" if is_hp3 else "vocal_" if self.data["high_end_process"].startswith("mirroring"): input_high_end_ = spec_utils.mirroring( self.data["high_end_process"], v_spec_m, input_high_end, self.mp ) wav_vocals = spec_utils.cmb_spectrogram_to_wave( v_spec_m, self.mp, input_high_end_h, input_high_end_ ) else: wav_vocals = spec_utils.cmb_spectrogram_to_wave(v_spec_m, self.mp) logger.info(f"{name} vocals done") if format in ["wav", "flac"]: sf.write( os.path.join( vocal_root, head + f"{name}_{self.data['agg']}.{format}", ), (np.array(wav_vocals) * 32768).astype("int16"), self.mp.param["sr"], ) else: path = os.path.join(vocal_root, head + f"{name}_{self.data['agg']}.wav") sf.write( path, (np.array(wav_vocals) * 32768).astype("int16"), self.mp.param["sr"], ) if os.path.exists(path): opt_format_path = path[:-4] + f".{format}" os.system(f"ffmpeg -i {path} -vn {opt_format_path} -q:a 2 -y") if os.path.exists(opt_format_path): try: os.remove(path) except: pass class AudioPreDeEcho: def __init__(self, agg, model_path, device, is_half, tta=False): self.model_path = model_path self.device = device self.data = { # Processing Options "postprocess": False, "tta": tta, # Constants "window_size": 512, "agg": agg, "high_end_process": "mirroring", } mp = ModelParameters("rvc/lib/uvr5_pack/lib_v5/modelparams/4band_v3.json") nout = 64 if "DeReverb" in model_path else 48
logger = logging.getLogger(__name__) class AudioPre: def __init__(self, agg, model_path, device, is_half, tta=False): self.model_path = model_path self.device = device self.data = { # Processing Options "postprocess": False, "tta": tta, # Constants "window_size": 512, "agg": agg, "high_end_process": "mirroring", } mp = ModelParameters("rvc/lib/uvr5_pack/lib_v5/modelparams/4band_v2.json") model = Nets.CascadedASPPNet(mp.param["bins"] * 2) cpk = torch.load(model_path, map_location="cpu") model.load_state_dict(cpk) model.eval() if is_half: model = model.half().to(device) else: model = model.to(device) self.mp = mp self.model = model def _path_audio_( self, music_file, ins_root=None, vocal_root=None, format="flac", is_hp3=False ): name = os.path.basename(music_file) if (ins_root and vocal_root) is None: return "No save root." else: os.makedirs(ins_root, exist_ok=True) os.makedirs(vocal_root, exist_ok=True) X_wave, y_wave, X_spec_s, y_spec_s = {}, {}, {}, {} bands_n = len(self.mp.param["band"]) # print(bands_n) for d in range(bands_n, 0, -1): bp = self.mp.param["band"][d] if d == bands_n: # high-end band # librosa loading may be buggy for some audio. ffmpeg will solve this, but it's a pain ( X_wave[d], _, ) = librosa.core.load( music_file, sr=bp["sr"], mono=False, dtype=np.float32, res_type=bp["res_type"], ) if X_wave[d].ndim == 1: X_wave[d] = np.asfortranarray([X_wave[d], X_wave[d]]) else: # lower bands X_wave[d] = librosa.core.resample( X_wave[d + 1], orig_sr=self.mp.param["band"][d + 1]["sr"], target_sr=bp["sr"], res_type=bp["res_type"], ) # Stft of wave source X_spec_s[d] = spec_utils.wave_to_spectrogram_mt( X_wave[d], bp["hl"], bp["n_fft"], self.mp.param["mid_side"], self.mp.param["mid_side_b2"], self.mp.param["reverse"], ) # pdb.set_trace() if d == bands_n and self.data["high_end_process"] != "none": input_high_end_h = (bp["n_fft"] // 2 - bp["crop_stop"]) + ( self.mp.param["pre_filter_stop"] - self.mp.param["pre_filter_start"] ) input_high_end = X_spec_s[d][ :, bp["n_fft"] // 2 - input_high_end_h : bp["n_fft"] // 2, : ] X_spec_m = spec_utils.combine_spectrograms(X_spec_s, self.mp) aggresive_set = float(self.data["agg"] / 100) aggressiveness = { "value": aggresive_set, "split_bin": self.mp.param["band"][1]["crop_stop"], } with torch.no_grad(): pred, X_mag, X_phase = inference( X_spec_m, self.device, self.model, aggressiveness, self.data ) # Postprocess if self.data["postprocess"]: pred_inv = np.clip(X_mag - pred, 0, np.inf) pred = spec_utils.mask_silence(pred, pred_inv) y_spec_m = pred * X_phase v_spec_m = X_spec_m - y_spec_m if ins_root is not None: if self.data["high_end_process"].startswith("mirroring"): input_high_end_ = spec_utils.mirroring( self.data["high_end_process"], y_spec_m, input_high_end, self.mp ) wav_instrument = spec_utils.cmb_spectrogram_to_wave( y_spec_m, self.mp, input_high_end_h, input_high_end_ ) else: wav_instrument = spec_utils.cmb_spectrogram_to_wave(y_spec_m, self.mp) logger.info("%s instruments done" % name) if is_hp3: head = "vocal_" else: head = "instrument_" if format in ["wav", "flac"]: sf.write( os.path.join( ins_root, head + f"{name}_{self.data['agg']}.{format}", ), (np.array(wav_instrument) * 32768).astype("int16"), self.mp.param["sr"], ) # else: path = os.path.join(ins_root, head + f"{name}_{self.data['agg']}.wav") sf.write( path, (np.array(wav_instrument) * 32768).astype("int16"), self.mp.param["sr"], ) if os.path.exists(path): opt_format_path = path[:-4] + ".%s" % format os.system("ffmpeg -i %s -vn %s -q:a 2 -y" % (path, opt_format_path)) if os.path.exists(opt_format_path): try: os.remove(path) except Exception: pass if vocal_root is not None: head = "instrument_" if is_hp3 else "vocal_" if self.data["high_end_process"].startswith("mirroring"): input_high_end_ = spec_utils.mirroring( self.data["high_end_process"], v_spec_m, input_high_end, self.mp ) wav_vocals = spec_utils.cmb_spectrogram_to_wave( v_spec_m, self.mp, input_high_end_h, input_high_end_ ) else: wav_vocals = spec_utils.cmb_spectrogram_to_wave(v_spec_m, self.mp) logger.info(f"{name} vocals done") if format in ["wav", "flac"]: sf.write( os.path.join( vocal_root, head + f"{name}_{self.data['agg']}.{format}", ), (np.array(wav_vocals) * 32768).astype("int16"), self.mp.param["sr"], ) else: path = os.path.join(vocal_root, head + f"{name}_{self.data['agg']}.wav") sf.write( path, (np.array(wav_vocals) * 32768).astype("int16"), self.mp.param["sr"], ) if os.path.exists(path): opt_format_path = path[:-4] + f".{format}" os.system(f"ffmpeg -i {path} -vn {opt_format_path} -q:a 2 -y") if os.path.exists(opt_format_path): try: os.remove(path) except: pass class AudioPreDeEcho: def __init__(self, agg, model_path, device, is_half, tta=False): self.model_path = model_path self.device = device self.data = { # Processing Options "postprocess": False, "tta": tta, # Constants "window_size": 512, "agg": agg, "high_end_process": "mirroring", } mp = ModelParameters("rvc/lib/uvr5_pack/lib_v5/modelparams/4band_v3.json") nout = 64 if "DeReverb" in model_path else 48
model = CascadedNet(mp.param["bins"] * 2, nout)
3
2023-10-14 09:52:31+00:00
8k
zhijie-group/LOVECon
video_diffusion/models/unet_3d_condition.py
[ { "identifier": "CrossAttnDownBlockPseudo3D", "path": "video_diffusion/models/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlockPseudo3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\...
import os import glob import json import copy import torch import torch.nn as nn import torch.utils.checkpoint from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from .unet_3d_blocks import ( CrossAttnDownBlockPseudo3D, CrossAttnUpBlockPseudo3D, DownBlockPseudo3D, UNetMidBlockPseudo3DCrossAttn, UpBlockPseudo3D, get_down_block, get_up_block, ) from .resnet import PseudoConv3d
7,092
sample: torch.FloatTensor class UNetPseudo3DConditionModel(ModelMixin, ConfigMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlockPseudo3D", "CrossAttnDownBlockPseudo3D", "CrossAttnDownBlockPseudo3D", "DownBlockPseudo3D", ), mid_block_type: str = "UNetMidBlockPseudo3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", **kwargs ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 if 'temporal_downsample' in kwargs and kwargs['temporal_downsample'] is True: kwargs['temporal_downsample_time'] = 3 self.temporal_downsample_time = kwargs.get('temporal_downsample_time', 0) # input self.conv_in = PseudoConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1), model_config=kwargs) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 kwargs_copy=copy.deepcopy(kwargs) temporal_downsample_i = ((i >= (len(down_block_types)-self.temporal_downsample_time)) and (not is_final_block)) kwargs_copy.update({'temporal_downsample': temporal_downsample_i} ) # kwargs_copy.update({'SparseCausalAttention_index': temporal_downsample_i} ) if temporal_downsample_i: print(f'Initialize model temporal downsample at layer {i}') down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, model_config=kwargs_copy ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlockPseudo3DCrossAttn":
# code mostly taken from https://github.com/huggingface/diffusers logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNetPseudo3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNetPseudo3DConditionModel(ModelMixin, ConfigMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlockPseudo3D", "CrossAttnDownBlockPseudo3D", "CrossAttnDownBlockPseudo3D", "DownBlockPseudo3D", ), mid_block_type: str = "UNetMidBlockPseudo3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", **kwargs ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 if 'temporal_downsample' in kwargs and kwargs['temporal_downsample'] is True: kwargs['temporal_downsample_time'] = 3 self.temporal_downsample_time = kwargs.get('temporal_downsample_time', 0) # input self.conv_in = PseudoConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1), model_config=kwargs) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 kwargs_copy=copy.deepcopy(kwargs) temporal_downsample_i = ((i >= (len(down_block_types)-self.temporal_downsample_time)) and (not is_final_block)) kwargs_copy.update({'temporal_downsample': temporal_downsample_i} ) # kwargs_copy.update({'SparseCausalAttention_index': temporal_downsample_i} ) if temporal_downsample_i: print(f'Initialize model temporal downsample at layer {i}') down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, model_config=kwargs_copy ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlockPseudo3DCrossAttn":
self.mid_block = UNetMidBlockPseudo3DCrossAttn(
3
2023-10-09 14:38:28+00:00
8k
UT-Austin-RPL/amago
amago/envs/amago_env.py
[ { "identifier": "ContinuousActionWrapper", "path": "amago/envs/env_utils.py", "snippet": "class ContinuousActionWrapper(gym.ActionWrapper):\n \"\"\"\n Normalize continuous action spaces [-1, 1]\n \"\"\"\n\n def __init__(self, env):\n super().__init__(env)\n self._true_action_sp...
import random import copy import numpy as np import gym as og_gym import gymnasium as gym from abc import ABC, abstractmethod from amago.envs.env_utils import ( ContinuousActionWrapper, DiscreteActionWrapper, MultiBinaryActionWrapper, space_convert, ) from amago.hindsight import Trajectory, GoalSeq, Timestep
3,619
class AMAGOEnv(gym.Wrapper, ABC): def __init__(self, env: gym.Env, horizon: int, start: int = 0): super().__init__(env) self.horizon = horizon self.start = start # action space conversion self.discrete = isinstance(space_convert(env.action_space), gym.spaces.Discrete) self.multibinary = isinstance( space_convert(env.action_space), gym.spaces.MultiBinary ) if self.discrete: self.env = DiscreteActionWrapper(self.env) self.action_size = self.action_space.n elif self.multibinary: self.env = MultiBinaryActionWrapper(self.env) self.action_size = self.action_space.n else: self.env = ContinuousActionWrapper(self.env) self.action_size = self.action_space.shape[-1] self.action_space = space_convert(self.env.action_space) # observation space conversion (defaults to dict) obs_space = self.env.observation_space if not isinstance(obs_space, gym.spaces.Dict | og_gym.spaces.Dict): obs_space = gym.spaces.Dict({"observation": space_convert(obs_space)}) self.observation_space = gym.spaces.Dict( {k: space_convert(v) for k, v in obs_space.items()} ) def render(self, *args, **kwargs): return self.env.render(*args, **kwargs) @property @abstractmethod def env_name(self): raise NotImplementedError @property @abstractmethod def achieved_goal(self) -> list[np.ndarray]: raise NotImplementedError @property @abstractmethod def kgoal_space(self) -> gym.spaces.Box: raise NotImplementedError @property @abstractmethod def goal_sequence(self) -> GoalSeq: raise NotImplementedError @property def max_goal_seq_length(self): return self.kgoal_space.shape[0] @property def blank_action(self): if self.discrete: action = [i for i in range(self.action_size)] elif self.multibinary: action = np.zeros((self.action_size,), dtype=np.int8) else: action = np.full((self.action_size,), -2.0) return action def make_action_rep(self, action) -> np.ndarray: if self.discrete: action_rep = np.zeros((self.action_size,)) action_rep[action] = 1.0 else: action_rep = action.copy() return action_rep def inner_reset(self, seed=None, options=None): return self.env.reset(seed=seed, options=options)
class AMAGOEnv(gym.Wrapper, ABC): def __init__(self, env: gym.Env, horizon: int, start: int = 0): super().__init__(env) self.horizon = horizon self.start = start # action space conversion self.discrete = isinstance(space_convert(env.action_space), gym.spaces.Discrete) self.multibinary = isinstance( space_convert(env.action_space), gym.spaces.MultiBinary ) if self.discrete: self.env = DiscreteActionWrapper(self.env) self.action_size = self.action_space.n elif self.multibinary: self.env = MultiBinaryActionWrapper(self.env) self.action_size = self.action_space.n else: self.env = ContinuousActionWrapper(self.env) self.action_size = self.action_space.shape[-1] self.action_space = space_convert(self.env.action_space) # observation space conversion (defaults to dict) obs_space = self.env.observation_space if not isinstance(obs_space, gym.spaces.Dict | og_gym.spaces.Dict): obs_space = gym.spaces.Dict({"observation": space_convert(obs_space)}) self.observation_space = gym.spaces.Dict( {k: space_convert(v) for k, v in obs_space.items()} ) def render(self, *args, **kwargs): return self.env.render(*args, **kwargs) @property @abstractmethod def env_name(self): raise NotImplementedError @property @abstractmethod def achieved_goal(self) -> list[np.ndarray]: raise NotImplementedError @property @abstractmethod def kgoal_space(self) -> gym.spaces.Box: raise NotImplementedError @property @abstractmethod def goal_sequence(self) -> GoalSeq: raise NotImplementedError @property def max_goal_seq_length(self): return self.kgoal_space.shape[0] @property def blank_action(self): if self.discrete: action = [i for i in range(self.action_size)] elif self.multibinary: action = np.zeros((self.action_size,), dtype=np.int8) else: action = np.full((self.action_size,), -2.0) return action def make_action_rep(self, action) -> np.ndarray: if self.discrete: action_rep = np.zeros((self.action_size,)) action_rep[action] = 1.0 else: action_rep = action.copy() return action_rep def inner_reset(self, seed=None, options=None): return self.env.reset(seed=seed, options=options)
def reset(self, seed=None, options=None) -> Timestep:
6
2023-10-14 19:36:06+00:00
8k
mlpc-ucsd/MaskCLIP
maskclip/model.py
[ { "identifier": "SetCriterion", "path": "maskclip/modeling/criterion.py", "snippet": "class SetCriterion(nn.Module):\n \"\"\"This class computes the loss for DETR.\n The process happens in two steps:\n 1) we compute hungarian assignment between ground truth boxes and the outputs of the mode...
from PIL import Image from typing import Tuple from torch import nn from torch.nn import functional as F from detectron2.config import configurable from detectron2.data import MetadataCatalog from detectron2.modeling import META_ARCH_REGISTRY, build_backbone, build_sem_seg_head from detectron2.modeling.backbone import Backbone from detectron2.modeling.postprocessing import sem_seg_postprocess from detectron2.structures import Boxes, ImageList, Instances, BitMasks from detectron2.utils.memory import retry_if_cuda_oom from .modeling.criterion import SetCriterion from .modeling.matcher import HungarianMatcher from .modeling.maskclip import MaskCLIP from .utils.get_vocab import get_class_names from torchvision.transforms.transforms import Compose, Resize, Normalize import torch import clip
5,204
): """ Args: backbone: a backbone module, must follow detectron2's backbone interface sem_seg_head: a module that predicts semantic segmentation from backbone features criterion: a module that defines the loss num_queries: int, number of queries object_mask_threshold: float, threshold to filter query based on classification score for panoptic segmentation inference overlap_threshold: overlap threshold used in general inference for panoptic segmentation metadata: dataset meta, get `thing` and `stuff` category names for panoptic segmentation inference size_divisibility: Some backbones require the input height and width to be divisible by a specific integer. We can use this to override such requirement. sem_seg_postprocess_before_inference: whether to resize the prediction back to original input size before semantic segmentation inference or after. For high-resolution dataset like Mapillary, resizing predictions before inference will cause OOM error. pixel_mean, pixel_std: list or tuple with #channels element, representing the per-channel mean and std to be used to normalize the input image semantic_on: bool, whether to output semantic segmentation prediction instance_on: bool, whether to output instance segmentation prediction panoptic_on: bool, whether to output panoptic segmentation prediction test_topk_per_image: int, instance segmentation parameter, keep topk instances per image """ super().__init__() self.backbone = backbone self.sem_seg_head = sem_seg_head self.criterion = criterion self.num_queries = num_queries self.overlap_threshold = overlap_threshold self.object_mask_threshold = object_mask_threshold self.metadata = metadata if size_divisibility < 0: # use backbone size_divisibility if not set size_divisibility = self.backbone.size_divisibility self.size_divisibility = size_divisibility self.sem_seg_postprocess_before_inference = sem_seg_postprocess_before_inference self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) # additional args self.semantic_on = semantic_on self.instance_on = instance_on self.panoptic_on = panoptic_on self.test_topk_per_image = test_topk_per_image if not self.semantic_on: assert self.sem_seg_postprocess_before_inference self.input_resolution = input_resolution self.txt_embed_train = txt_embed_train self.txt_embed_valid = txt_embed_valid self.maskclip = MaskCLIP( clip_model_name=clip_model_name, input_resolution=input_resolution, patch_size=patch_size, width=width, layers=layers, heads=heads, output_dim=output_dim, temperature=temperature, ) self.clip_prep = Compose([ Resize((input_resolution, input_resolution), interpolation=BICUBIC), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), ]) @classmethod def from_config(cls, cfg): backbone = build_backbone(cfg) sem_seg_head = build_sem_seg_head(cfg, backbone.output_shape()) # Loss parameters: deep_supervision = cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION no_object_weight = cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT # loss weights class_weight = cfg.MODEL.MASK_FORMER.CLASS_WEIGHT dice_weight = cfg.MODEL.MASK_FORMER.DICE_WEIGHT mask_weight = cfg.MODEL.MASK_FORMER.MASK_WEIGHT # building criterion matcher = HungarianMatcher( cost_class=class_weight, cost_mask=mask_weight, cost_dice=dice_weight, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, ) weight_dict = {"loss_ce": class_weight, "loss_mask": mask_weight, "loss_dice": dice_weight} if deep_supervision: dec_layers = cfg.MODEL.MASK_FORMER.DEC_LAYERS aux_weight_dict = {} for i in range(5): for k, v in weight_dict.items(): if k == 'loss_ce': continue aux_weight_dict.update({k + f"_{i}": v}) weight_dict.update(aux_weight_dict) losses = ["labels", "masks"] criterion = SetCriterion( sem_seg_head.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=no_object_weight, losses=losses, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, oversample_ratio=cfg.MODEL.MASK_FORMER.OVERSAMPLE_RATIO, importance_sample_ratio=cfg.MODEL.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO, ) # get category names for the dataset train_dataset_name = cfg.DATASETS.TRAIN[0] valid_dataset_name = cfg.DATASETS.TEST[0]
# Copyright (c) Facebook, Inc. and its affiliates. BICUBIC = Image.BICUBIC @META_ARCH_REGISTRY.register() class MaskFormer(nn.Module): """ Main class for mask classification semantic segmentation architectures. """ @configurable def __init__( self, *, backbone: Backbone, sem_seg_head: nn.Module, criterion: nn.Module, num_queries: int, object_mask_threshold: float, overlap_threshold: float, metadata, size_divisibility: int, sem_seg_postprocess_before_inference: bool, pixel_mean: Tuple[float], pixel_std: Tuple[float], # maskclip clip_model_name: str, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int, temperature: float, txt_embed_train, txt_embed_valid, # inference semantic_on: bool, panoptic_on: bool, instance_on: bool, test_topk_per_image: int, ): """ Args: backbone: a backbone module, must follow detectron2's backbone interface sem_seg_head: a module that predicts semantic segmentation from backbone features criterion: a module that defines the loss num_queries: int, number of queries object_mask_threshold: float, threshold to filter query based on classification score for panoptic segmentation inference overlap_threshold: overlap threshold used in general inference for panoptic segmentation metadata: dataset meta, get `thing` and `stuff` category names for panoptic segmentation inference size_divisibility: Some backbones require the input height and width to be divisible by a specific integer. We can use this to override such requirement. sem_seg_postprocess_before_inference: whether to resize the prediction back to original input size before semantic segmentation inference or after. For high-resolution dataset like Mapillary, resizing predictions before inference will cause OOM error. pixel_mean, pixel_std: list or tuple with #channels element, representing the per-channel mean and std to be used to normalize the input image semantic_on: bool, whether to output semantic segmentation prediction instance_on: bool, whether to output instance segmentation prediction panoptic_on: bool, whether to output panoptic segmentation prediction test_topk_per_image: int, instance segmentation parameter, keep topk instances per image """ super().__init__() self.backbone = backbone self.sem_seg_head = sem_seg_head self.criterion = criterion self.num_queries = num_queries self.overlap_threshold = overlap_threshold self.object_mask_threshold = object_mask_threshold self.metadata = metadata if size_divisibility < 0: # use backbone size_divisibility if not set size_divisibility = self.backbone.size_divisibility self.size_divisibility = size_divisibility self.sem_seg_postprocess_before_inference = sem_seg_postprocess_before_inference self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) # additional args self.semantic_on = semantic_on self.instance_on = instance_on self.panoptic_on = panoptic_on self.test_topk_per_image = test_topk_per_image if not self.semantic_on: assert self.sem_seg_postprocess_before_inference self.input_resolution = input_resolution self.txt_embed_train = txt_embed_train self.txt_embed_valid = txt_embed_valid self.maskclip = MaskCLIP( clip_model_name=clip_model_name, input_resolution=input_resolution, patch_size=patch_size, width=width, layers=layers, heads=heads, output_dim=output_dim, temperature=temperature, ) self.clip_prep = Compose([ Resize((input_resolution, input_resolution), interpolation=BICUBIC), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), ]) @classmethod def from_config(cls, cfg): backbone = build_backbone(cfg) sem_seg_head = build_sem_seg_head(cfg, backbone.output_shape()) # Loss parameters: deep_supervision = cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION no_object_weight = cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT # loss weights class_weight = cfg.MODEL.MASK_FORMER.CLASS_WEIGHT dice_weight = cfg.MODEL.MASK_FORMER.DICE_WEIGHT mask_weight = cfg.MODEL.MASK_FORMER.MASK_WEIGHT # building criterion matcher = HungarianMatcher( cost_class=class_weight, cost_mask=mask_weight, cost_dice=dice_weight, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, ) weight_dict = {"loss_ce": class_weight, "loss_mask": mask_weight, "loss_dice": dice_weight} if deep_supervision: dec_layers = cfg.MODEL.MASK_FORMER.DEC_LAYERS aux_weight_dict = {} for i in range(5): for k, v in weight_dict.items(): if k == 'loss_ce': continue aux_weight_dict.update({k + f"_{i}": v}) weight_dict.update(aux_weight_dict) losses = ["labels", "masks"] criterion = SetCriterion( sem_seg_head.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=no_object_weight, losses=losses, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, oversample_ratio=cfg.MODEL.MASK_FORMER.OVERSAMPLE_RATIO, importance_sample_ratio=cfg.MODEL.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO, ) # get category names for the dataset train_dataset_name = cfg.DATASETS.TRAIN[0] valid_dataset_name = cfg.DATASETS.TEST[0]
train_class_names = get_class_names(train_dataset_name)
3
2023-10-13 02:32:25+00:00
8k
jacarvalho/mpd-public
mpd/models/diffusion_models/temporal_unet.py
[ { "identifier": "GaussianFourierProjection", "path": "mpd/models/layers/layers.py", "snippet": "class GaussianFourierProjection(nn.Module):\n \"\"\"Gaussian random features for encoding time steps.\"\"\"\n\n def __init__(self, embed_dim, scale=30.):\n super().__init__()\n # Randomly ...
import einops import numpy as np import torch import torch.nn as nn from abc import ABC from einops import rearrange from torch.nn import DataParallel from mpd.models.layers.layers import GaussianFourierProjection, Downsample1d, Conv1dBlock, Upsample1d, \ ResidualTemporalBlock, TimeEncoder, MLP, group_norm_n_groups, LinearAttention, PreNorm, Residual, TemporalBlockMLP from mpd.models.layers.layers_attention import SpatialTransformer
4,991
out_dim=32, **kwargs ): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.net = nn.Identity() def forward(self, input_d): task = input_d['tasks'] task_emb = self.net(task) return task_emb class TaskModelNew(nn.Module): def __init__( self, in_dim=16, out_dim=32, **kwargs ): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.net = nn.Identity() def forward(self, task): task_emb = self.net(task) return task_emb class ContextModel(nn.Module): def __init__( self, env_model=None, task_model=None, out_dim=32, **kwargs ): super().__init__() self.env_model = env_model self.task_model = task_model self.in_dim = self.env_model.out_dim + self.task_model.out_dim # self.out_dim = out_dim # self.net = MLP(self.in_dim, self.out_dim, hidden_dim=out_dim, n_layers=1, act='mish') self.out_dim = self.in_dim self.net = nn.Identity() def forward(self, input_d=None): if input_d is None: return None env_emb = self.env_model(input_d) task_emb = self.task_model(input_d) context = torch.cat((env_emb, task_emb), dim=-1) context_emb = self.net(context) return context_emb class PointUnet(nn.Module): def __init__( self, n_support_points=None, state_dim=None, dim=32, dim_mults=(1, 2, 4), time_emb_dim=32, conditioning_embed_dim=4, conditioning_type=None, **kwargs ): super().__init__() self.dim_mults = dim_mults self.state_dim = state_dim input_dim = state_dim # Conditioning if conditioning_type is None or conditioning_type == 'None': conditioning_type = None elif conditioning_type == 'concatenate': if self.state_dim < conditioning_embed_dim // 4: # Embed the state in a latent space HxF if the conditioning embedding is much larger than the state state_emb_dim = conditioning_embed_dim // 4 self.state_encoder = MLP(state_dim, state_emb_dim, hidden_dim=state_emb_dim//2, n_layers=1, act='mish') else: state_emb_dim = state_dim self.state_encoder = nn.Identity() input_dim = state_emb_dim + conditioning_embed_dim elif conditioning_type == 'default': pass else: raise NotImplementedError self.conditioning_type = conditioning_type dims = [input_dim, *map(lambda m: dim * m, self.dim_mults)] in_out = list(zip(dims[:-1], dims[1:])) print(f'[ models/temporal ] Channel dimensions: {in_out}') # Networks self.time_mlp = TimeEncoder(32, time_emb_dim) # conditioning dimension (time + context) cond_dim = time_emb_dim + (conditioning_embed_dim if conditioning_type == 'default' else 0) # Unet self.downs = nn.ModuleList([]) self.ups = nn.ModuleList([]) for ind, (dim_in, dim_out) in enumerate(in_out): self.downs.append(nn.ModuleList([
UNET_DIM_MULTS = { 0: (1, 2, 4), 1: (1, 2, 4, 8) } class TemporalUnet(nn.Module): def __init__( self, n_support_points=None, state_dim=None, unet_input_dim=32, dim_mults=(1, 2, 4, 8), time_emb_dim=32, self_attention=False, conditioning_embed_dim=4, conditioning_type=None, attention_num_heads=2, attention_dim_head=32, **kwargs ): super().__init__() self.state_dim = state_dim input_dim = state_dim # Conditioning if conditioning_type is None or conditioning_type == 'None': conditioning_type = None elif conditioning_type == 'concatenate': if self.state_dim < conditioning_embed_dim // 4: # Embed the state in a latent space HxF if the conditioning embedding is much larger than the state state_emb_dim = conditioning_embed_dim // 4 self.state_encoder = MLP(state_dim, state_emb_dim, hidden_dim=state_emb_dim//2, n_layers=1, act='mish') else: state_emb_dim = state_dim self.state_encoder = nn.Identity() input_dim = state_emb_dim + conditioning_embed_dim elif conditioning_type == 'attention': pass elif conditioning_type == 'default': pass else: raise NotImplementedError self.conditioning_type = conditioning_type dims = [input_dim, *map(lambda m: unet_input_dim * m, dim_mults)] in_out = list(zip(dims[:-1], dims[1:])) print(f'[ models/temporal ] Channel dimensions: {in_out}') # Networks self.time_mlp = TimeEncoder(32, time_emb_dim) # conditioning dimension (time + context) cond_dim = time_emb_dim + (conditioning_embed_dim if conditioning_type == 'default' else 0) # Unet self.downs = nn.ModuleList([]) self.ups = nn.ModuleList([]) num_resolutions = len(in_out) for ind, (dim_in, dim_out) in enumerate(in_out): is_last = ind >= (num_resolutions - 1) self.downs.append(nn.ModuleList([ ResidualTemporalBlock(dim_in, dim_out, cond_dim, n_support_points=n_support_points), ResidualTemporalBlock(dim_out, dim_out, cond_dim, n_support_points=n_support_points), Residual(PreNorm(dim_out, LinearAttention(dim_out))) if self_attention else nn.Identity(), SpatialTransformer(dim_out, attention_num_heads, attention_dim_head, depth=1, context_dim=conditioning_embed_dim) if conditioning_type == 'attention' else None, Downsample1d(dim_out) if not is_last else nn.Identity() ])) if not is_last: n_support_points = n_support_points // 2 mid_dim = dims[-1] self.mid_block1 = ResidualTemporalBlock(mid_dim, mid_dim, cond_dim, n_support_points=n_support_points) self.mid_attn = Residual(PreNorm(mid_dim, LinearAttention(mid_dim))) if self_attention else nn.Identity() self.mid_attention = SpatialTransformer(mid_dim, attention_num_heads, attention_dim_head, depth=1, context_dim=conditioning_embed_dim) if conditioning_type == 'attention' else nn.Identity() self.mid_block2 = ResidualTemporalBlock(mid_dim, mid_dim, cond_dim, n_support_points=n_support_points) for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])): is_last = ind >= (num_resolutions - 1) self.ups.append(nn.ModuleList([ ResidualTemporalBlock(dim_out * 2, dim_in, cond_dim, n_support_points=n_support_points), ResidualTemporalBlock(dim_in, dim_in, cond_dim, n_support_points=n_support_points), Residual(PreNorm(dim_in, LinearAttention(dim_in))) if self_attention else nn.Identity(), SpatialTransformer(dim_in, attention_num_heads, attention_dim_head, depth=1, context_dim=conditioning_embed_dim) if conditioning_type == 'attention' else None, Upsample1d(dim_in) if not is_last else nn.Identity() ])) if not is_last: n_support_points = n_support_points * 2 self.final_conv = nn.Sequential( Conv1dBlock(unet_input_dim, unet_input_dim, kernel_size=5, n_groups=group_norm_n_groups(unet_input_dim)), nn.Conv1d(unet_input_dim, state_dim, 1), ) def forward(self, x, time, context): """ x : [ batch x horizon x state_dim ] context: [batch x context_dim] """ b, h, d = x.shape t_emb = self.time_mlp(time) c_emb = t_emb if self.conditioning_type == 'concatenate': x_emb = self.state_encoder(x) context = einops.repeat(context, 'm n -> m h n', h=h) x = torch.cat((x_emb, context), dim=-1) elif self.conditioning_type == 'attention': # reshape to keep the interface context = einops.rearrange(context, 'b d -> b 1 d') elif self.conditioning_type == 'default': c_emb = torch.cat((t_emb, context), dim=-1) # swap horizon and channels (state_dim) x = einops.rearrange(x, 'b h c -> b c h') # batch, horizon, channels (state_dim) h = [] for resnet, resnet2, attn_self, attn_conditioning, downsample in self.downs: x = resnet(x, c_emb) # if self.conditioning_type == 'attention': # x = attention1(x, context=conditioning_emb) x = resnet2(x, c_emb) x = attn_self(x) if self.conditioning_type == 'attention': x = attn_conditioning(x, context=context) h.append(x) x = downsample(x) x = self.mid_block1(x, c_emb) x = self.mid_attn(x) if self.conditioning_type == 'attention': x = self.mid_attention(x, context=context) x = self.mid_block2(x, c_emb) for resnet, resnet2, attn_self, attn_conditioning, upsample in self.ups: x = torch.cat((x, h.pop()), dim=1) x = resnet(x, c_emb) x = resnet2(x, c_emb) x = attn_self(x) if self.conditioning_type == 'attention': x = attn_conditioning(x, context=context) x = upsample(x) x = self.final_conv(x) x = einops.rearrange(x, 'b c h -> b h c') return x class EnvModel(nn.Module): def __init__( self, in_dim=16, out_dim=16, **kwargs ): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.net = nn.Identity() def forward(self, input_d): env = input_d['env'] env_emb = self.net(env) return env_emb class TaskModel(nn.Module): def __init__( self, in_dim=16, out_dim=32, **kwargs ): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.net = nn.Identity() def forward(self, input_d): task = input_d['tasks'] task_emb = self.net(task) return task_emb class TaskModelNew(nn.Module): def __init__( self, in_dim=16, out_dim=32, **kwargs ): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.net = nn.Identity() def forward(self, task): task_emb = self.net(task) return task_emb class ContextModel(nn.Module): def __init__( self, env_model=None, task_model=None, out_dim=32, **kwargs ): super().__init__() self.env_model = env_model self.task_model = task_model self.in_dim = self.env_model.out_dim + self.task_model.out_dim # self.out_dim = out_dim # self.net = MLP(self.in_dim, self.out_dim, hidden_dim=out_dim, n_layers=1, act='mish') self.out_dim = self.in_dim self.net = nn.Identity() def forward(self, input_d=None): if input_d is None: return None env_emb = self.env_model(input_d) task_emb = self.task_model(input_d) context = torch.cat((env_emb, task_emb), dim=-1) context_emb = self.net(context) return context_emb class PointUnet(nn.Module): def __init__( self, n_support_points=None, state_dim=None, dim=32, dim_mults=(1, 2, 4), time_emb_dim=32, conditioning_embed_dim=4, conditioning_type=None, **kwargs ): super().__init__() self.dim_mults = dim_mults self.state_dim = state_dim input_dim = state_dim # Conditioning if conditioning_type is None or conditioning_type == 'None': conditioning_type = None elif conditioning_type == 'concatenate': if self.state_dim < conditioning_embed_dim // 4: # Embed the state in a latent space HxF if the conditioning embedding is much larger than the state state_emb_dim = conditioning_embed_dim // 4 self.state_encoder = MLP(state_dim, state_emb_dim, hidden_dim=state_emb_dim//2, n_layers=1, act='mish') else: state_emb_dim = state_dim self.state_encoder = nn.Identity() input_dim = state_emb_dim + conditioning_embed_dim elif conditioning_type == 'default': pass else: raise NotImplementedError self.conditioning_type = conditioning_type dims = [input_dim, *map(lambda m: dim * m, self.dim_mults)] in_out = list(zip(dims[:-1], dims[1:])) print(f'[ models/temporal ] Channel dimensions: {in_out}') # Networks self.time_mlp = TimeEncoder(32, time_emb_dim) # conditioning dimension (time + context) cond_dim = time_emb_dim + (conditioning_embed_dim if conditioning_type == 'default' else 0) # Unet self.downs = nn.ModuleList([]) self.ups = nn.ModuleList([]) for ind, (dim_in, dim_out) in enumerate(in_out): self.downs.append(nn.ModuleList([
TemporalBlockMLP(dim_in, dim_out, cond_dim)
11
2023-10-11 11:06:35+00:00
8k
Yuri-YuzuChaN/nonebot-plugin-maimaidx
nonebot_plugin_maimaidx/libraries/maimaidx_best_50.py
[ { "identifier": "DrawText", "path": "nonebot_plugin_maimaidx/libraries/image.py", "snippet": "class DrawText:\n\n def __init__(self, image: ImageDraw.ImageDraw, font: str) -> None:\n self._img = image\n self._font = str(font)\n\n def get_box(self, text: str, size: int):\n retu...
import math import traceback import httpx from io import BytesIO from typing import List, Optional, Tuple, Union from nonebot.adapters.onebot.v11 import MessageSegment from PIL import Image, ImageDraw from pydantic import BaseModel from ..config import * from .image import DrawText, image_to_bytesio from .maimaidx_api_data import maiApi from .maimaidx_error import * from .maimaidx_music import download_music_pictrue, mai
3,853
elif self.Rating < 10000: num = '05' elif self.Rating < 12000: num = '06' elif self.Rating < 13000: num = '07' elif self.Rating < 14000: num = '08' elif self.Rating < 14500: num = '09' elif self.Rating < 15000: num = '10' else: num = '11' return f'UI_CMN_DXRating_{num}.png' def _findMatchLevel(self) -> str: if self.addRating <= 10: num = f'{self.addRating:02d}' else: num = f'{self.addRating + 1:02d}' return f'UI_DNM_DaniPlate_{num}.png' async def whiledraw(self, data: List[ChartInfo], type: bool) -> Image.Image: # y为第一排纵向坐标,dy为各排间距 y = 430 if type else 1670 dy = 170 TEXT_COLOR = [(255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (103, 20, 141, 255)] DXSTAR_DEST = [0, 330, 320, 310, 300, 290] for num, info in enumerate(data): if num % 5 == 0: x = 70 y += dy if num != 0 else 0 else: x += 416 cover = Image.open(await download_music_pictrue(info.song_id)).resize((135, 135)) version = Image.open(maimaidir / f'UI_RSL_MBase_Parts_{info.type}.png').resize((55, 19)) rate = Image.open(maimaidir / f'UI_TTR_Rank_{score_Rank[info.rate]}.png').resize((95, 44)) self._im.alpha_composite(self._diff[info.level_index], (x, y)) self._im.alpha_composite(cover, (x + 5, y + 5)) self._im.alpha_composite(version, (x + 80, y + 141)) self._im.alpha_composite(rate, (x + 150, y + 98)) if info.fc: fc = Image.open(maimaidir / f'UI_MSS_MBase_Icon_{fcl[info.fc]}.png').resize((45, 45)) self._im.alpha_composite(fc, (x + 260, y + 98)) if info.fs: fs = Image.open(maimaidir / f'UI_MSS_MBase_Icon_{fsl[info.fs]}.png').resize((45, 45)) self._im.alpha_composite(fs, (x + 315, y + 98)) dxscore = sum(mai.total_list.by_id(str(info.song_id)).charts[info.level_index].notes) * 3 diff_sum_dx = info.dxScore / dxscore * 100 dxtype, dxnum = dxScore(diff_sum_dx) for _ in range(dxnum): self._im.alpha_composite(self.dxstar[dxtype], (x + DXSTAR_DEST[dxnum] + 20 * _, y + 74)) self._tb.draw(x + 40, y + 148, 20, info.song_id, anchor='mm') title = info.title if coloumWidth(title) > 18: title = changeColumnWidth(title, 17) + '...' self._siyuan.draw(x + 155, y + 20, 20, title, TEXT_COLOR[info.level_index], anchor='lm') p, s = f'{info.achievements:.4f}'.split('.') r = self._tb.get_box(p, 32) self._tb.draw(x + 155, y + 70, 32, p, TEXT_COLOR[info.level_index], anchor='ld') self._tb.draw(x + 155 + r[2], y + 68, 22, f'.{s}%', TEXT_COLOR[info.level_index], anchor='ld') self._tb.draw(x + 340, y + 60, 18, f'{info.dxScore}/{dxscore}', TEXT_COLOR[info.level_index], anchor='mm') self._tb.draw(x + 155, y + 80, 22, f'{info.ds} -> {info.ra}', TEXT_COLOR[info.level_index], anchor='lm') async def draw(self): basic = Image.open(maimaidir / 'b40_score_basic.png') advanced = Image.open(maimaidir / 'b40_score_advanced.png') expert = Image.open(maimaidir / 'b40_score_expert.png') master = Image.open(maimaidir / 'b40_score_master.png') remaster = Image.open(maimaidir / 'b40_score_remaster.png') logo = Image.open(maimaidir / 'logo.png').resize((378, 172)) dx_rating = Image.open(maimaidir / self._findRaPic()).resize((300, 59)) Name = Image.open(maimaidir / 'Name.png') MatchLevel = Image.open(maimaidir / self._findMatchLevel()).resize((134, 55)) ClassLevel = Image.open(maimaidir / 'UI_FBR_Class_00.png').resize((144, 87)) rating = Image.open(maimaidir / 'UI_CMN_Shougou_Rainbow.png').resize((454, 50)) self._diff = [basic, advanced, expert, master, remaster] self.dxstar = [Image.open(maimaidir / f'UI_RSL_DXScore_Star_0{_ + 1}.png').resize((20, 20)) for _ in range(3)] # 作图 self._im = Image.open(maimaidir / 'b40_bg.png').convert('RGBA') self._im.alpha_composite(logo, (5, 130)) if self.plate: plate = Image.open(maimaidir / f'{self.plate}.png').resize((1420, 230)) else: plate = Image.open(maimaidir / 'UI_Plate_300101.png').resize((1420, 230)) self._im.alpha_composite(plate, (390, 100)) icon = Image.open(maimaidir / 'UI_Icon_309503.png').resize((214, 214)) self._im.alpha_composite(icon, (398, 108)) if self.qqId: try: async with httpx.AsyncClient() as client: res = await client.get(f'http://q1.qlogo.cn/g?b=qq&nk={self.qqId}&s=100') qqLogo = Image.open(BytesIO(res.content)) self._im.alpha_composite(Image.new('RGBA', (203, 203), (255, 255, 255, 255)), (404, 114)) self._im.alpha_composite(qqLogo.convert('RGBA').resize((201, 201)), (405, 115)) except Exception: pass self._im.alpha_composite(dx_rating, (620, 122)) Rating = f'{self.Rating:05d}' for n, i in enumerate(Rating): self._im.alpha_composite(Image.open(maimaidir / f'UI_NUM_Drating_{i}.png').resize((28, 34)), (760 + 23 * n, 137)) self._im.alpha_composite(Name, (620, 200)) self._im.alpha_composite(MatchLevel, (935, 205)) self._im.alpha_composite(ClassLevel, (926, 105)) self._im.alpha_composite(rating, (620, 275)) text_im = ImageDraw.Draw(self._im)
class ChartInfo(BaseModel): achievements: float ds: float dxScore: int fc: Optional[str] = '' fs: Optional[str] = '' level: str level_index: int level_label: str ra: int rate: str song_id: int title: str type: str class Data(BaseModel): sd: Optional[List[ChartInfo]] = None dx: Optional[List[ChartInfo]] = None class UserInfo(BaseModel): additional_rating: Optional[int] charts: Optional[Data] nickname: Optional[str] plate: Optional[str] = None rating: Optional[int] username: Optional[str] class DrawBest: def __init__(self, UserInfo: UserInfo, qqId: Optional[Union[int, str]] = None) -> None: self.userName = UserInfo.nickname self.plate = UserInfo.plate self.addRating = UserInfo.additional_rating self.Rating = UserInfo.rating self.sdBest = UserInfo.charts.sd self.dxBest = UserInfo.charts.dx self.qqId = qqId def _findRaPic(self) -> str: if self.Rating < 1000: num = '01' elif self.Rating < 2000: num = '02' elif self.Rating < 4000: num = '03' elif self.Rating < 7000: num = '04' elif self.Rating < 10000: num = '05' elif self.Rating < 12000: num = '06' elif self.Rating < 13000: num = '07' elif self.Rating < 14000: num = '08' elif self.Rating < 14500: num = '09' elif self.Rating < 15000: num = '10' else: num = '11' return f'UI_CMN_DXRating_{num}.png' def _findMatchLevel(self) -> str: if self.addRating <= 10: num = f'{self.addRating:02d}' else: num = f'{self.addRating + 1:02d}' return f'UI_DNM_DaniPlate_{num}.png' async def whiledraw(self, data: List[ChartInfo], type: bool) -> Image.Image: # y为第一排纵向坐标,dy为各排间距 y = 430 if type else 1670 dy = 170 TEXT_COLOR = [(255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (255, 255, 255, 255), (103, 20, 141, 255)] DXSTAR_DEST = [0, 330, 320, 310, 300, 290] for num, info in enumerate(data): if num % 5 == 0: x = 70 y += dy if num != 0 else 0 else: x += 416 cover = Image.open(await download_music_pictrue(info.song_id)).resize((135, 135)) version = Image.open(maimaidir / f'UI_RSL_MBase_Parts_{info.type}.png').resize((55, 19)) rate = Image.open(maimaidir / f'UI_TTR_Rank_{score_Rank[info.rate]}.png').resize((95, 44)) self._im.alpha_composite(self._diff[info.level_index], (x, y)) self._im.alpha_composite(cover, (x + 5, y + 5)) self._im.alpha_composite(version, (x + 80, y + 141)) self._im.alpha_composite(rate, (x + 150, y + 98)) if info.fc: fc = Image.open(maimaidir / f'UI_MSS_MBase_Icon_{fcl[info.fc]}.png').resize((45, 45)) self._im.alpha_composite(fc, (x + 260, y + 98)) if info.fs: fs = Image.open(maimaidir / f'UI_MSS_MBase_Icon_{fsl[info.fs]}.png').resize((45, 45)) self._im.alpha_composite(fs, (x + 315, y + 98)) dxscore = sum(mai.total_list.by_id(str(info.song_id)).charts[info.level_index].notes) * 3 diff_sum_dx = info.dxScore / dxscore * 100 dxtype, dxnum = dxScore(diff_sum_dx) for _ in range(dxnum): self._im.alpha_composite(self.dxstar[dxtype], (x + DXSTAR_DEST[dxnum] + 20 * _, y + 74)) self._tb.draw(x + 40, y + 148, 20, info.song_id, anchor='mm') title = info.title if coloumWidth(title) > 18: title = changeColumnWidth(title, 17) + '...' self._siyuan.draw(x + 155, y + 20, 20, title, TEXT_COLOR[info.level_index], anchor='lm') p, s = f'{info.achievements:.4f}'.split('.') r = self._tb.get_box(p, 32) self._tb.draw(x + 155, y + 70, 32, p, TEXT_COLOR[info.level_index], anchor='ld') self._tb.draw(x + 155 + r[2], y + 68, 22, f'.{s}%', TEXT_COLOR[info.level_index], anchor='ld') self._tb.draw(x + 340, y + 60, 18, f'{info.dxScore}/{dxscore}', TEXT_COLOR[info.level_index], anchor='mm') self._tb.draw(x + 155, y + 80, 22, f'{info.ds} -> {info.ra}', TEXT_COLOR[info.level_index], anchor='lm') async def draw(self): basic = Image.open(maimaidir / 'b40_score_basic.png') advanced = Image.open(maimaidir / 'b40_score_advanced.png') expert = Image.open(maimaidir / 'b40_score_expert.png') master = Image.open(maimaidir / 'b40_score_master.png') remaster = Image.open(maimaidir / 'b40_score_remaster.png') logo = Image.open(maimaidir / 'logo.png').resize((378, 172)) dx_rating = Image.open(maimaidir / self._findRaPic()).resize((300, 59)) Name = Image.open(maimaidir / 'Name.png') MatchLevel = Image.open(maimaidir / self._findMatchLevel()).resize((134, 55)) ClassLevel = Image.open(maimaidir / 'UI_FBR_Class_00.png').resize((144, 87)) rating = Image.open(maimaidir / 'UI_CMN_Shougou_Rainbow.png').resize((454, 50)) self._diff = [basic, advanced, expert, master, remaster] self.dxstar = [Image.open(maimaidir / f'UI_RSL_DXScore_Star_0{_ + 1}.png').resize((20, 20)) for _ in range(3)] # 作图 self._im = Image.open(maimaidir / 'b40_bg.png').convert('RGBA') self._im.alpha_composite(logo, (5, 130)) if self.plate: plate = Image.open(maimaidir / f'{self.plate}.png').resize((1420, 230)) else: plate = Image.open(maimaidir / 'UI_Plate_300101.png').resize((1420, 230)) self._im.alpha_composite(plate, (390, 100)) icon = Image.open(maimaidir / 'UI_Icon_309503.png').resize((214, 214)) self._im.alpha_composite(icon, (398, 108)) if self.qqId: try: async with httpx.AsyncClient() as client: res = await client.get(f'http://q1.qlogo.cn/g?b=qq&nk={self.qqId}&s=100') qqLogo = Image.open(BytesIO(res.content)) self._im.alpha_composite(Image.new('RGBA', (203, 203), (255, 255, 255, 255)), (404, 114)) self._im.alpha_composite(qqLogo.convert('RGBA').resize((201, 201)), (405, 115)) except Exception: pass self._im.alpha_composite(dx_rating, (620, 122)) Rating = f'{self.Rating:05d}' for n, i in enumerate(Rating): self._im.alpha_composite(Image.open(maimaidir / f'UI_NUM_Drating_{i}.png').resize((28, 34)), (760 + 23 * n, 137)) self._im.alpha_composite(Name, (620, 200)) self._im.alpha_composite(MatchLevel, (935, 205)) self._im.alpha_composite(ClassLevel, (926, 105)) self._im.alpha_composite(rating, (620, 275)) text_im = ImageDraw.Draw(self._im)
self._meiryo = DrawText(text_im, MEIRYO)
0
2023-10-13 13:38:42+00:00
8k
NVlabs/Optimus
optimus/algo/bc.py
[ { "identifier": "TransformerActorNetwork", "path": "optimus/models/transformer.py", "snippet": "class TransformerActorNetwork(MIMO_Transformer):\n \"\"\"\n An Transformer policy network that predicts actions from observation sequences (assumed to be frame stacked\n from previous observations) a...
import copy import numpy as np import robomimic.models.base_nets as BaseNets import robomimic.models.policy_nets as PolicyNets import robomimic.utils.loss_utils as LossUtils import robomimic.utils.obs_utils as ObsUtils import robomimic.utils.tensor_utils as TensorUtils import robomimic.utils.torch_utils as TorchUtils import torch import torch.distributions as D import torch.nn as nn from collections import OrderedDict from robomimic.algo import PolicyAlgo, register_algo_factory_func from robomimic.algo.bc import BC, BC_GMM, BC_RNN, BC_RNN_GMM, BC_VAE, BC_Gaussian from optimus.models.transformer import TransformerActorNetwork, TransformerGMMActorNetwork
5,893
# only supervise final timestep predictions["actions"] = predictions["actions"][:, -1, :] return predictions def get_action(self, obs_dict, goal_dict=None): """ Get policy action outputs. Args: obs_dict (dict): current observation goal_dict (dict): (optional) goal Returns: action (torch.Tensor): action tensor """ assert not self.nets.training TensorUtils.assert_size_at_dim( obs_dict, size=(self.context_length), dim=1, msg="Error: expect temporal dimension of obs batch to match transformer context length {}".format( self.context_length ), ) actions = obs_dict["actions"] del obs_dict["actions"] out = self.nets["policy"](obs_dict, actions=actions, goal_dict=goal_dict) action = out[:, -1, :] return action def _train_step(self, losses, epoch): """ Internal helper function for BC algo class. Perform backpropagation on the loss tensors in @losses to update networks. Args: losses (dict): dictionary of losses computed over the batch, from @_compute_losses """ # gradient step info = OrderedDict() optim = self.optimizers["policy"] loss = losses["action_loss"] net = self.nets["policy"] max_grad_norm = None # backprop optim.zero_grad(set_to_none=True) loss.backward() # gradient clipping if max_grad_norm is not None: torch.nn.utils.clip_grad_norm_(net.parameters(), max_grad_norm) # compute grad norms grad_norms = 0.0 for p in net.parameters(): # only clip gradients for parameters for which requires_grad is True if p.grad is not None: grad_norms += p.grad.data.norm(2).pow(2).item() # step for pg in optim.param_groups: if epoch <= 100: pg["lr"] = (-0.009 * float(epoch) + 1) * self.optim_params["policy"][ "learning_rate" ]["initial"] else: pg["lr"] = 1e-5 optim.step() info["policy_grad_norms"] = grad_norms return info def _compute_losses(self, predictions, batch): """ Internal helper function for BC algo class. Compute losses based on network outputs in @predictions dict, using reference labels in @batch. Args: predictions (dict): dictionary containing network outputs, from @_forward_training batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training Returns: losses (dict): dictionary of losses computed over the batch """ losses = OrderedDict() a_target = batch["actions"] actions = predictions["actions"] losses["l2_loss"] = nn.MSELoss()(actions, a_target) losses["l1_loss"] = nn.SmoothL1Loss()(actions, a_target) # cosine direction loss on eef delta position losses["cos_loss"] = LossUtils.cosine_loss(actions[..., :3], a_target[..., :3]) action_losses = [ # self.algo_config.loss.l2_weight * losses["l2_loss"], losses["l2_loss"], # self.algo_config.loss.l1_weight * losses["l1_loss"], # self.algo_config.loss.cos_weight * losses["cos_loss"], ] action_loss = sum(action_losses) losses["action_loss"] = action_loss return losses class BC_Transformer_GMM(BC_Transformer): """ BC training with a Transformer GMM policy. """ def _create_networks(self): """ Creates networks and places them into @self.nets. """ assert self.algo_config.gmm.enabled assert self.algo_config.transformer.enabled self.nets = nn.ModuleDict()
# Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the NVIDIA Source Code License [see LICENSE for details]. """ Implementation of Behavioral Cloning (BC). Adapted from Ajay Mandlekar's private version of robomimic. """ @register_algo_factory_func("bc") def algo_config_to_class(algo_config): """ Maps algo config to the BC algo class to instantiate, along with additional algo kwargs. Args: algo_config (Config instance): algo config Returns: algo_class: subclass of Algo algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm """ # note: we need the check below because some configs import BCConfig and exclude # some of these options gaussian_enabled = "gaussian" in algo_config and algo_config.gaussian.enabled gmm_enabled = "gmm" in algo_config and algo_config.gmm.enabled vae_enabled = "vae" in algo_config and algo_config.vae.enabled rnn_enabled = "rnn" in algo_config and algo_config.rnn.enabled transformer_enabled = "transformer" in algo_config and algo_config.transformer.enabled # enforce options don't conflict assert sum([gaussian_enabled, gmm_enabled, vae_enabled]) <= 1 assert sum([rnn_enabled, transformer_enabled]) <= 1 if rnn_enabled: if gmm_enabled: return BC_RNN_GMM, {} return BC_RNN, {} if transformer_enabled: if gmm_enabled: return BC_Transformer_GMM, {} return BC_Transformer, {} if gaussian_enabled: return BC_Gaussian, {} if gmm_enabled: return BC_GMM, {} if vae_enabled: return BC_VAE, {} return BC, {} def transformer_args_from_config(transformer_config): """ Takes a Config object corresponding to transformer settings (for example `config.algo.transformer` in BCConfig) and extracts transformer kwargs for instantiating transformer networks. """ return dict( transformer_num_layers=transformer_config.num_layers, transformer_context_length=transformer_config.context_length, transformer_embed_dim=transformer_config.embed_dim, transformer_num_heads=transformer_config.num_heads, transformer_embedding_dropout=transformer_config.embedding_dropout, transformer_block_attention_dropout=transformer_config.block_attention_dropout, transformer_block_output_dropout=transformer_config.block_output_dropout, layer_dims=transformer_config.layer_dims, ) class BC(PolicyAlgo): """ Normal BC training. """ def _create_networks(self): """ Creates networks and places them into @self.nets. """ self.nets = nn.ModuleDict() self.nets["policy"] = PolicyNets.ActorNetwork( obs_shapes=self.obs_shapes, goal_shapes=self.goal_shapes, ac_dim=self.ac_dim, mlp_layer_dims=self.algo_config.actor_layer_dims, encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), ) def process_batch_for_training(self, batch): """ Processes input batch from a data loader to filter out relevant information and prepare the batch for training. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader Returns: input_batch (dict): processed and filtered batch that will be used for training """ input_batch = dict() input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present input_batch["actions"] = batch["actions"][:, 0, :] return TensorUtils.to_float(input_batch) def train_on_batch(self, batch, epoch, validate=False): """ Training on a single batch of data. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training epoch (int): epoch number - required by some Algos that need to perform staged training and early stopping validate (bool): if True, don't perform any learning updates. Returns: info (dict): dictionary of relevant inputs, outputs, and losses that might be relevant for logging """ with TorchUtils.maybe_no_grad(no_grad=validate): info = super(BC, self).train_on_batch(batch, epoch, validate=validate) predictions = self._forward_training(batch) losses = self._compute_losses(predictions, batch) info["predictions"] = TensorUtils.detach(predictions) info["losses"] = TensorUtils.detach(losses) if not validate: step_info = self._train_step(losses) info.update(step_info) return info def _forward_training(self, batch): """ Internal helper function for BC algo class. Compute forward pass and return network outputs in @predictions dict. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training Returns: predictions (dict): dictionary containing network outputs """ predictions = OrderedDict() actions = self.nets["policy"](obs_dict=batch["obs"], goal_dict=batch["goal_obs"]) predictions["actions"] = actions return predictions def _compute_losses(self, predictions, batch): """ Internal helper function for BC algo class. Compute losses based on network outputs in @predictions dict, using reference labels in @batch. Args: predictions (dict): dictionary containing network outputs, from @_forward_training batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training Returns: losses (dict): dictionary of losses computed over the batch """ losses = OrderedDict() a_target = batch["actions"] actions = predictions["actions"] losses["l2_loss"] = nn.MSELoss()(actions, a_target) losses["l1_loss"] = nn.SmoothL1Loss()(actions, a_target) # cosine direction loss on eef delta position losses["cos_loss"] = LossUtils.cosine_loss(actions[..., :3], a_target[..., :3]) losses["l2_loss_eef"] = nn.MSELoss()(actions[..., :3], a_target[..., :3]) losses["l2_loss_ori"] = nn.MSELoss()(actions[..., 3:6], a_target[..., 3:6]) losses["l2_loss_is_gripper"] = nn.MSELoss()(actions[..., 6], a_target[..., 6]) losses["l2_loss_grasp"] = nn.MSELoss()(actions[..., 7], a_target[..., 7]) action_losses = [ self.algo_config.loss.l2_weight * losses["l2_loss"], self.algo_config.loss.l1_weight * losses["l1_loss"], self.algo_config.loss.cos_weight * losses["cos_loss"], ] action_loss = sum(action_losses) losses["action_loss"] = action_loss return losses def _train_step(self, losses): """ Internal helper function for BC algo class. Perform backpropagation on the loss tensors in @losses to update networks. Args: losses (dict): dictionary of losses computed over the batch, from @_compute_losses """ # gradient step info = OrderedDict() policy_grad_norms = TorchUtils.backprop_for_loss( net=self.nets["policy"], optim=self.optimizers["policy"], loss=losses["action_loss"], ) info["policy_grad_norms"] = policy_grad_norms return info def log_info(self, info): """ Process info dictionary from @train_on_batch to summarize information to pass to tensorboard for logging. Args: info (dict): dictionary of info Returns: loss_log (dict): name -> summary statistic """ log = super(BC, self).log_info(info) log["Loss"] = info["losses"]["action_loss"].item() if "l2_loss" in info["losses"]: log["L2_Loss"] = info["losses"]["l2_loss"].item() if "l1_loss" in info["losses"]: log["L1_Loss"] = info["losses"]["l1_loss"].item() if "cos_loss" in info["losses"]: log["Cosine_Loss"] = info["losses"]["cos_loss"].item() if "policy_grad_norms" in info: log["Policy_Grad_Norms"] = info["policy_grad_norms"] if "l2_loss_eef" in info["losses"]: log["L2_Loss_EEF"] = info["losses"]["l2_loss_eef"].item() if "l2_loss_ori" in info["losses"]: log["L2_Loss_Ori"] = info["losses"]["l2_loss_ori"].item() if "l2_loss_is_gripper" in info["losses"]: log["L2_Loss_Is_Gripper"] = info["losses"]["l2_loss_is_gripper"].item() if "l2_loss_grasp" in info["losses"]: log["L2_Loss_Grasp"] = info["losses"]["l2_loss_grasp"].item() return log def get_action(self, obs_dict, goal_dict=None): """ Get policy action outputs. Args: obs_dict (dict): current observation goal_dict (dict): (optional) goal Returns: action (torch.Tensor): action tensor """ assert not self.nets.training return self.nets["policy"](obs_dict, goal_dict=goal_dict) class BC_Gaussian(BC): """ BC training with a Gaussian policy. """ def _create_networks(self): """ Creates networks and places them into @self.nets. """ assert self.algo_config.gaussian.enabled self.nets = nn.ModuleDict() self.nets["policy"] = PolicyNets.GaussianActorNetwork( obs_shapes=self.obs_shapes, goal_shapes=self.goal_shapes, ac_dim=self.ac_dim, mlp_layer_dims=self.algo_config.actor_layer_dims, fixed_std=self.algo_config.gaussian.fixed_std, init_std=self.algo_config.gaussian.init_std, std_limits=(self.algo_config.gaussian.min_std, 7.5), std_activation=self.algo_config.gaussian.std_activation, low_noise_eval=self.algo_config.gaussian.low_noise_eval, encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), ) def _forward_training(self, batch): """ Internal helper function for BC algo class. Compute forward pass and return network outputs in @predictions dict. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training Returns: predictions (dict): dictionary containing network outputs """ dists = self.nets["policy"].forward_train( obs_dict=batch["obs"], goal_dict=batch["goal_obs"], ) # make sure that this is a batch of multivariate action distributions, so that # the log probability computation will be correct assert len(dists.batch_shape) == 1 log_probs = dists.log_prob(batch["actions"]) predictions = OrderedDict( log_probs=log_probs, actions=dists.mean, ) return predictions def _compute_losses(self, predictions, batch): """ Internal helper function for BC algo class. Compute losses based on network outputs in @predictions dict, using reference labels in @batch. Args: predictions (dict): dictionary containing network outputs, from @_forward_training batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training Returns: losses (dict): dictionary of losses computed over the batch """ a_target = batch["actions"] actions = predictions["actions"] # loss is just negative log-likelihood of action targets action_loss = -predictions["log_probs"].mean() losses = OrderedDict( log_probs=-action_loss, action_loss=action_loss, ) losses["l2_loss_eef"] = nn.MSELoss()(actions[..., :3], a_target[..., :3]) losses["l2_loss_ori"] = nn.MSELoss()(actions[..., 3:6], a_target[..., 3:6]) losses["l2_loss_is_gripper"] = nn.MSELoss()(actions[..., 6], a_target[..., 6]) # losses["l2_loss_grasp"] = nn.MSELoss()(actions[..., 7], a_target[..., 7]) # this is hardcoded for 7dof ee-ctrl actions return losses def log_info(self, info): """ Process info dictionary from @train_on_batch to summarize information to pass to tensorboard for logging. Args: info (dict): dictionary of info Returns: loss_log (dict): name -> summary statistic """ log = PolicyAlgo.log_info(self, info) log["Loss"] = info["losses"]["action_loss"].item() log["Log_Likelihood"] = info["losses"]["log_probs"].item() if "policy_grad_norms" in info: log["Policy_Grad_Norms"] = info["policy_grad_norms"] if "l2_loss_eef" in info["losses"]: log["L2_Loss_EEF"] = info["losses"]["l2_loss_eef"].item() if "l2_loss_ori" in info["losses"]: log["L2_Loss_Ori"] = info["losses"]["l2_loss_ori"].item() if "l2_loss_is_gripper" in info["losses"]: log["L2_Loss_Is_Gripper"] = info["losses"]["l2_loss_is_gripper"].item() if "l2_loss_grasp" in info["losses"]: log["L2_Loss_Grasp"] = info["losses"]["l2_loss_grasp"].item() return log class BC_GMM(BC_Gaussian): """ BC training with a Gaussian Mixture Model policy. """ def _create_networks(self): """ Creates networks and places them into @self.nets. """ assert self.algo_config.gmm.enabled self.nets = nn.ModuleDict() self.nets["policy"] = PolicyNets.GMMActorNetwork( obs_shapes=self.obs_shapes, goal_shapes=self.goal_shapes, ac_dim=self.ac_dim, mlp_layer_dims=self.algo_config.actor_layer_dims, num_modes=self.algo_config.gmm.num_modes, min_std=self.algo_config.gmm.min_std, std_activation=self.algo_config.gmm.std_activation, low_noise_eval=self.algo_config.gmm.low_noise_eval, encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), ) self.epoch_every_n_steps = self.global_config.experiment.epoch_every_n_steps self.num_epochs = self.global_config.train.num_epochs class BC_RNN(BC_RNN): def _create_networks(self): """ Creates networks and places them into @self.nets. """ self.nets = nn.ModuleDict() self.nets["policy"] = PolicyNets.RNNActorNetwork( obs_shapes=self.obs_shapes, goal_shapes=self.goal_shapes, ac_dim=self.ac_dim, mlp_layer_dims=self.algo_config.actor_layer_dims, encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), **BaseNets.rnn_args_from_config(self.algo_config.rnn), ) self._rnn_hidden_state = None self._rnn_horizon = self.algo_config.rnn.horizon self._rnn_counter = 0 self._rnn_is_open_loop = self.algo_config.rnn.get("open_loop", False) self.lr_warmup = False def process_batch_for_training(self, batch): """ Processes input batch from a data loader to filter out relevant information and prepare the batch for training. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader Returns: input_batch (dict): processed and filtered batch that will be used for training """ input_batch = dict() input_batch["obs"] = batch["obs"] input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present input_batch["actions"] = batch["actions"] if self._rnn_is_open_loop: # replace the observation sequence with one that only consists of the first observation. # This way, all actions are predicted "open-loop" after the first observation, based # on the rnn hidden state. n_steps = batch["actions"].shape[1] obs_seq_start = TensorUtils.index_at_time(batch["obs"], ind=0) input_batch["obs"] = TensorUtils.unsqueeze_expand_at(obs_seq_start, size=n_steps, dim=1) return input_batch def get_action(self, obs_dict, goal_dict=None): """ Get policy action outputs. Args: obs_dict (dict): current observation goal_dict (dict): (optional) goal Returns: action (torch.Tensor): action tensor """ assert not self.nets.training if self._rnn_hidden_state is None or self._rnn_counter % self._rnn_horizon == 0: batch_size = list(obs_dict.values())[0].shape[0] self._rnn_hidden_state = self.nets["policy"].get_rnn_init_state( batch_size=batch_size, device=list(obs_dict.values())[0].device ) if self._rnn_is_open_loop: # remember the initial observation, and use it instead of the current observation # for open-loop action sequence prediction self._open_loop_obs = TensorUtils.clone(TensorUtils.detach(obs_dict)) obs_to_use = obs_dict if self._rnn_is_open_loop: # replace current obs with last recorded obs obs_to_use = self._open_loop_obs self._rnn_counter += 1 action, self._rnn_hidden_state = self.nets["policy"].forward_step( obs_to_use, goal_dict=goal_dict, rnn_state=self._rnn_hidden_state ) return action class BC_RNN_GMM(BC_RNN_GMM): """ BC training with an RNN GMM policy. """ def _create_networks(self): """ Creates networks and places them into @self.nets. """ assert self.algo_config.gmm.enabled assert self.algo_config.rnn.enabled self.nets = nn.ModuleDict() self.nets["policy"] = PolicyNets.RNNGMMActorNetwork( obs_shapes=self.obs_shapes, goal_shapes=self.goal_shapes, ac_dim=self.ac_dim, mlp_layer_dims=self.algo_config.actor_layer_dims, num_modes=self.algo_config.gmm.num_modes, min_std=self.algo_config.gmm.min_std, std_activation=self.algo_config.gmm.std_activation, low_noise_eval=self.algo_config.gmm.low_noise_eval, encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), **BaseNets.rnn_args_from_config(self.algo_config.rnn), ) self._rnn_hidden_state = None self._rnn_horizon = self.algo_config.rnn.horizon self._rnn_counter = 0 self._rnn_is_open_loop = self.algo_config.rnn.get("open_loop", False) self.lr_warmup = False self.epoch_every_n_steps = self.global_config.experiment.epoch_every_n_steps self.num_epochs = self.global_config.train.num_epochs def process_batch_for_training(self, batch): """ Processes input batch from a data loader to filter out relevant information and prepare the batch for training. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader Returns: input_batch (dict): processed and filtered batch that will be used for training """ input_batch = dict() input_batch["obs"] = batch["obs"] input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present input_batch["actions"] = batch["actions"] if self._rnn_is_open_loop: # replace the observation sequence with one that only consists of the first observation. # This way, all actions are predicted "open-loop" after the first observation, based # on the rnn hidden state. n_steps = batch["actions"].shape[1] obs_seq_start = TensorUtils.index_at_time(batch["obs"], ind=0) input_batch["obs"] = TensorUtils.unsqueeze_expand_at(obs_seq_start, size=n_steps, dim=1) return input_batch def get_action(self, obs_dict, goal_dict=None): """ Get policy action outputs. Args: obs_dict (dict): current observation goal_dict (dict): (optional) goal Returns: action (torch.Tensor): action tensor """ assert not self.nets.training if self._rnn_hidden_state is None or self._rnn_counter % self._rnn_horizon == 0: batch_size = list(obs_dict.values())[0].shape[0] self._rnn_hidden_state = self.nets["policy"].get_rnn_init_state( batch_size=batch_size, device=list(obs_dict.values())[0].device ) if self._rnn_is_open_loop: # remember the initial observation, and use it instead of the current observation # for open-loop action sequence prediction self._open_loop_obs = TensorUtils.clone(TensorUtils.detach(obs_dict)) obs_to_use = obs_dict if self._rnn_is_open_loop: # replace current obs with last recorded obs obs_to_use = self._open_loop_obs self._rnn_counter += 1 action, self._rnn_hidden_state = self.nets["policy"].forward_step( obs_to_use, goal_dict=goal_dict, rnn_state=self._rnn_hidden_state ) return action class BC_Transformer(BC): """ BC training with a Transformer policy. """ def set_params_from_config(self): # read specific config variables we need for training / eval self.context_length = self.algo_config.transformer.context_length self.optimizer_type = self.algo_config.transformer.optimizer_type self.lr_scheduler_type = self.algo_config.transformer.lr_scheduler_type self.lr_warmup = self.algo_config.transformer.lr_warmup self.num_open_loop_actions_to_execute = ( self.algo_config.transformer.num_open_loop_actions_to_execute ) self.epoch_every_n_steps = self.global_config.experiment.epoch_every_n_steps self.num_epochs = self.global_config.train.num_epochs def _create_networks(self): """ Creates networks and places them into @self.nets. """ assert self.algo_config.transformer.enabled self.nets = nn.ModuleDict() self.nets["policy"] = TransformerActorNetwork( obs_shapes=self.obs_shapes, goal_shapes=self.goal_shapes, ac_dim=self.ac_dim, encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), **transformer_args_from_config(self.algo_config.transformer), ) self.set_params_from_config() self.algo_config = None self.obs_config = None self.global_config = None def linear_schedule_by_factor_10_over_100(self, step): # scales down learning rate by 10^-1 after 100 epochs epoch = step // self.epoch_every_n_steps if epoch < 100: return (-0.009) * float(epoch) + 1 else: return (-0.009) * float(100) + 1 def _create_optimizers(self): """ Creates optimizers using @self.optim_params and places them into @self.optimizers. """ self.optimizers = dict() self.lr_schedulers = dict() if self.optimizer_type == "adamw": self.optimizers["policy"] = torch.optim.AdamW( self.nets.parameters(), lr=self.optim_params["policy"]["learning_rate"]["initial"], betas=self.optim_params["policy"]["learning_rate"]["betas"], weight_decay=self.optim_params["policy"]["learning_rate"]["decay_factor"], ) elif self.optimizer_type == "adam": self.optimizers["policy"] = torch.optim.AdamW( self.nets.parameters(), lr=self.optim_params["policy"]["learning_rate"]["initial"], betas=self.optim_params["policy"]["learning_rate"]["betas"], ) if self.lr_scheduler_type == "cosine": self.lr_schedulers["policy"] = torch.optim.lr_scheduler.CosineAnnealingLR( self.optimizers["policy"], T_max=int(1e6), eta_min=self.optim_params["policy"]["learning_rate"]["initial"] * 1 / 10, ) elif self.lr_scheduler_type == "linear": self.lr_schedulers["policy"] = torch.optim.lr_scheduler.LambdaLR( self.optimizers["policy"], self.linear_schedule_by_factor_10_over_100 ) elif self.lr_scheduler_type == "none": self.lr_schedulers["policy"] = None elif self.lr_scheduler_type == "linear_to_0": self.lr_schedulers["policy"] = torch.optim.lr_scheduler.LinearLR( self.optimizers["policy"], start_factor=1.0, end_factor=0.0, total_iters=self.num_epochs * self.epoch_every_n_steps, ) def train_on_batch(self, batch, epoch, validate=False): """ Training on a single batch of data. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training epoch (int): epoch number - required by some Algos that need to perform staged training and early stopping validate (bool): if True, don't perform any learning updates. Returns: info (dict): dictionary of relevant inputs, outputs, and losses that might be relevant for logging """ with TorchUtils.maybe_no_grad(no_grad=validate): # because of PL: cast to device here: batch = TensorUtils.to_device(TensorUtils.to_float(batch), self.device) info = PolicyAlgo.train_on_batch(self, batch, epoch, validate=validate) predictions = self._forward_training(batch) losses = self._compute_losses(predictions, batch) info["predictions"] = TensorUtils.detach(predictions) info["losses"] = TensorUtils.detach(losses) if not validate: step_info = self._train_step(losses, epoch) info.update(step_info) return info def process_batch_for_training(self, batch): """ Processes input batch from a data loader to filter out relevant information and prepare the batch for training. Args: batch (dict): dictionary with torch.Tensors sampled from a data loader Returns: input_batch (dict): processed and filtered batch that will be used for training """ input_batch = dict() input_batch["obs"] = batch["obs"] input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present # just use final timestep input_batch["actions"] = batch["actions"][:, -1, :] return input_batch def _forward_training(self, batch): """ Modify from super class to handle different inputs and outputs (e.g. conditioning on actions). """ # ensure that transformer context length is consistent with temporal dimension of observations TensorUtils.assert_size_at_dim( batch["obs"], size=(self.context_length), dim=1, msg="Error: expect temporal dimension of obs batch to match transformer context length {}".format( self.context_length ), ) predictions = OrderedDict() masked_obs, masked_actions = batch["obs"], batch["actions"] predictions["actions"] = self.nets["policy"]( obs_dict=masked_obs, actions=masked_actions, goal_dict=batch["goal_obs"] ) # only supervise final timestep predictions["actions"] = predictions["actions"][:, -1, :] return predictions def get_action(self, obs_dict, goal_dict=None): """ Get policy action outputs. Args: obs_dict (dict): current observation goal_dict (dict): (optional) goal Returns: action (torch.Tensor): action tensor """ assert not self.nets.training TensorUtils.assert_size_at_dim( obs_dict, size=(self.context_length), dim=1, msg="Error: expect temporal dimension of obs batch to match transformer context length {}".format( self.context_length ), ) actions = obs_dict["actions"] del obs_dict["actions"] out = self.nets["policy"](obs_dict, actions=actions, goal_dict=goal_dict) action = out[:, -1, :] return action def _train_step(self, losses, epoch): """ Internal helper function for BC algo class. Perform backpropagation on the loss tensors in @losses to update networks. Args: losses (dict): dictionary of losses computed over the batch, from @_compute_losses """ # gradient step info = OrderedDict() optim = self.optimizers["policy"] loss = losses["action_loss"] net = self.nets["policy"] max_grad_norm = None # backprop optim.zero_grad(set_to_none=True) loss.backward() # gradient clipping if max_grad_norm is not None: torch.nn.utils.clip_grad_norm_(net.parameters(), max_grad_norm) # compute grad norms grad_norms = 0.0 for p in net.parameters(): # only clip gradients for parameters for which requires_grad is True if p.grad is not None: grad_norms += p.grad.data.norm(2).pow(2).item() # step for pg in optim.param_groups: if epoch <= 100: pg["lr"] = (-0.009 * float(epoch) + 1) * self.optim_params["policy"][ "learning_rate" ]["initial"] else: pg["lr"] = 1e-5 optim.step() info["policy_grad_norms"] = grad_norms return info def _compute_losses(self, predictions, batch): """ Internal helper function for BC algo class. Compute losses based on network outputs in @predictions dict, using reference labels in @batch. Args: predictions (dict): dictionary containing network outputs, from @_forward_training batch (dict): dictionary with torch.Tensors sampled from a data loader and filtered by @process_batch_for_training Returns: losses (dict): dictionary of losses computed over the batch """ losses = OrderedDict() a_target = batch["actions"] actions = predictions["actions"] losses["l2_loss"] = nn.MSELoss()(actions, a_target) losses["l1_loss"] = nn.SmoothL1Loss()(actions, a_target) # cosine direction loss on eef delta position losses["cos_loss"] = LossUtils.cosine_loss(actions[..., :3], a_target[..., :3]) action_losses = [ # self.algo_config.loss.l2_weight * losses["l2_loss"], losses["l2_loss"], # self.algo_config.loss.l1_weight * losses["l1_loss"], # self.algo_config.loss.cos_weight * losses["cos_loss"], ] action_loss = sum(action_losses) losses["action_loss"] = action_loss return losses class BC_Transformer_GMM(BC_Transformer): """ BC training with a Transformer GMM policy. """ def _create_networks(self): """ Creates networks and places them into @self.nets. """ assert self.algo_config.gmm.enabled assert self.algo_config.transformer.enabled self.nets = nn.ModuleDict()
self.nets["policy"] = TransformerGMMActorNetwork(
1
2023-10-10 00:48:42+00:00
8k
jutanke/hik
hik/eval/longterm.py
[ { "identifier": "PersonSequence", "path": "hik/data/person_sequence.py", "snippet": "class PersonSequence:\n def __init__(self, data, dataset: str, pid: int):\n \"\"\"\n :param data: {\n \"transforms\": {n x 6}\n \"smpl\": {n x 21 x 3}\n \"poses3d\": {n ...
from ndms.database import Data from hik.data.person_sequence import PersonSequence from hik.data.smpl import Body from typing import List from einops import repeat from hik.transforms.transforms import normalize from os.path import join, isfile from einops import rearrange import numpy as np
4,038
# you can define a transform function that is called for each motion word # to for example normalize the data: def transform(motion_word): """ :param {kernel_size x dim*3} """ motion_word = rearrange(motion_word, "t (j d) -> t j d", d=3) motion_word = normalize( motion_word, frame=0, zero_z=False, check_shape=False, allow_zero_z=True, # noqa E501 ) # noqa E501 return rearrange(motion_word, "t j d -> t (j d)") class NDMSData(Data): def __init__(
# you can define a transform function that is called for each motion word # to for example normalize the data: def transform(motion_word): """ :param {kernel_size x dim*3} """ motion_word = rearrange(motion_word, "t (j d) -> t j d", d=3) motion_word = normalize( motion_word, frame=0, zero_z=False, check_shape=False, allow_zero_z=True, # noqa E501 ) # noqa E501 return rearrange(motion_word, "t j d -> t (j d)") class NDMSData(Data): def __init__(
self, seqs: List[PersonSequence], pid: int, body: Body, cache_dir=None
0
2023-10-14 07:10:03+00:00
8k
mlpc-ucsd/MasQCLIP
masqclip/mask_distill.py
[ { "identifier": "SetCriterion", "path": "masqclip/modeling/criterion.py", "snippet": "class SetCriterion(nn.Module):\n \"\"\"This class computes the loss for DETR.\n The process happens in two steps:\n 1) we compute hungarian assignment between ground truth boxes and the outputs of the mode...
from typing import Tuple from torch import nn from torch.nn import functional as F from detectron2.config import configurable from detectron2.data import MetadataCatalog from detectron2.modeling import META_ARCH_REGISTRY, build_backbone, build_sem_seg_head from detectron2.modeling.backbone import Backbone from detectron2.modeling.postprocessing import sem_seg_postprocess from detectron2.structures import Boxes, ImageList, Instances, BitMasks from detectron2.utils.memory import retry_if_cuda_oom from detectron2.projects.point_rend.point_features import point_sample from .modeling.criterion import SetCriterion from .modeling.matcher import HungarianMatcher import torch
5,495
if masks.shape[0] == 0: return masks idx = torch.argsort(scores, descending=True) masks = masks[idx] # sort point_coords = torch.rand(1, self.num_points, 2, device=masks.device) sample_masks = point_sample(masks[:, None], point_coords.repeat(masks.shape[0], 1, 1), align_corners=False).squeeze(1) new_masks = [] new_sample_masks = [] for mask, sample_mask in zip(masks, sample_masks): if len(new_masks) == 0: new_masks.append(mask) new_sample_masks.append(sample_mask) continue # dice sample_masks_array = torch.stack(new_sample_masks, dim=0) dice = self.batch_dice(sample_mask[None], sample_masks_array) max_dice = dice.max(dim=1)[0].item() if max_dice < self.dice_threshold: new_masks.append(mask) new_sample_masks.append(sample_mask) new_masks = torch.stack(new_masks, dim=0) return new_masks @META_ARCH_REGISTRY.register() class MaskFormer(nn.Module): """ Main class for Mask2Former. """ @configurable def __init__( self, *, backbone: Backbone, sem_seg_head: nn.Module, criterion: nn.Module, num_queries: int, object_mask_threshold: float, overlap_threshold: float, metadata, size_divisibility: int, sem_seg_postprocess_before_inference: bool, pixel_mean: Tuple[float], pixel_std: Tuple[float], # inference semantic_on: bool, panoptic_on: bool, instance_on: bool, test_topk_per_image: int, ): """ Args: backbone: a backbone module, must follow detectron2's backbone interface sem_seg_head: a module that predicts semantic segmentation from backbone features criterion: a module that defines the loss num_queries: int, number of queries object_mask_threshold: float, threshold to filter query based on classification score for panoptic segmentation inference overlap_threshold: overlap threshold used in general inference for panoptic segmentation metadata: dataset meta, get `thing` and `stuff` category names for panoptic segmentation inference size_divisibility: Some backbones require the input height and width to be divisible by a specific integer. We can use this to override such requirement. sem_seg_postprocess_before_inference: whether to resize the prediction back to original input size before semantic segmentation inference or after. For high-resolution dataset like Mapillary, resizing predictions before inference will cause OOM error. pixel_mean, pixel_std: list or tuple with #channels element, representing the per-channel mean and std to be used to normalize the input image semantic_on: bool, whether to output semantic segmentation prediction instance_on: bool, whether to output instance segmentation prediction panoptic_on: bool, whether to output panoptic segmentation prediction test_topk_per_image: int, instance segmentation parameter, keep topk instances per image """ super().__init__() self.backbone = backbone self.sem_seg_head = sem_seg_head self.criterion = criterion self.num_queries = num_queries self.overlap_threshold = overlap_threshold self.object_mask_threshold = object_mask_threshold self.metadata = metadata if size_divisibility < 0: # use backbone size_divisibility if not set size_divisibility = self.backbone.size_divisibility self.size_divisibility = size_divisibility self.sem_seg_postprocess_before_inference = sem_seg_postprocess_before_inference self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) # additional args self.semantic_on = semantic_on self.instance_on = instance_on self.panoptic_on = panoptic_on self.test_topk_per_image = test_topk_per_image if not self.semantic_on: assert self.sem_seg_postprocess_before_inference @classmethod def from_config(cls, cfg): backbone = build_backbone(cfg) sem_seg_head = build_sem_seg_head(cfg, backbone.output_shape()) # Loss parameters: deep_supervision = cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION no_object_weight = cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT # loss weights class_weight = cfg.MODEL.MASK_FORMER.CLASS_WEIGHT dice_weight = cfg.MODEL.MASK_FORMER.DICE_WEIGHT mask_weight = cfg.MODEL.MASK_FORMER.MASK_WEIGHT # building criterion
# Copyright (c) Facebook, Inc. and its affiliates. @META_ARCH_REGISTRY.register() class MaskDistill(nn.Module): def __init__(self, cfg): super().__init__() self.score_threshold = cfg.MODEL.MASQ_CLIP.SCORE_THRESHOLD self.dice_threshold = cfg.MODEL.MASQ_CLIP.NMS_THRESHOLD self.num_points = cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS self.teacher_model = MaskFormer(cfg) self.student_model = MaskFormer(cfg) # load weights teacher_weights = torch.load(cfg.MODEL.WEIGHTS) self.teacher_model.load_state_dict(teacher_weights["model"]) for para in self.teacher_model.parameters(): para.requires_grad = False for para in self.student_model.parameters(): para.requires_grad = True def load_state_dict(self, state_dict, strict): return self.student_model.load_state_dict(state_dict, strict) def state_dict(self): return self.student_model.state_dict() @property def device(self): return self.student_model.device def forward(self, batched_inputs): if self.training: assert "instances" in batched_inputs[0] self.teacher_model.eval() self.student_model.train() with torch.no_grad(): predictions = self.teacher_model(batched_inputs) batched_inputs_revise = self.revise_input(batched_inputs, predictions) losses = self.student_model(batched_inputs_revise) return losses else: # inference self.student_model.eval() with torch.no_grad(): predictions = self.student_model(batched_inputs) return predictions def revise_input(self, batched_inputs, predictions): new_batched_inputs = [] for input_per_image, pred_per_image in zip(batched_inputs, predictions): gt_ins = input_per_image["instances"] pred_ins = pred_per_image["instances"] # high scores valid_masks = (pred_ins.scores > self.score_threshold) pred_scores = pred_ins.scores[valid_masks] pred_masks = pred_ins.pred_masks[valid_masks] # binary gt_masks = gt_ins.gt_masks.float().to(pred_masks.device) # new masks pred_sample, gt_sample = pred_masks[:, None], gt_masks[:, None] point_coords = torch.rand(1, self.num_points, 2, device=pred_masks.device) # sampling pred_sample = point_sample(pred_sample, point_coords.repeat(pred_masks.shape[0], 1, 1), align_corners=False).squeeze(1) gt_sample = point_sample(gt_sample, point_coords.repeat(gt_masks.shape[0], 1, 1), align_corners=False).squeeze(1) batch_dice = self.batch_dice(pred_sample, gt_sample) if batch_dice.shape[1] > 0: valid_masks = (batch_dice.max(dim=1)[0] < self.dice_threshold) append_scores = pred_scores[valid_masks] append_masks = pred_masks[valid_masks] else: append_scores = pred_scores append_masks = pred_masks # NMS append_masks = self.NMS(append_scores, append_masks) # new targets new_instances = Instances(input_per_image["image"].shape[1:]) new_instances.gt_classes = torch.concat([ torch.zeros_like(gt_ins.gt_classes).to(self.device), torch.zeros((append_masks.shape[0]), dtype=gt_ins.gt_classes.dtype).to(self.device), ], dim=0) new_instances.gt_masks = torch.concat([ gt_ins.gt_masks.to(self.device), append_masks.to(self.device), ], dim=0) input_per_image["instances"] = new_instances new_batched_inputs.append(input_per_image) return new_batched_inputs def batch_dice(self, inputs, targets): inputs = inputs.flatten(1) targets = targets.flatten(1) # 0-1 numerator = 2 * torch.einsum("nc,mc->nm", inputs, targets) denominator = inputs.sum(-1)[:, None] + targets.sum(-1)[None, :] dice = (numerator + 1) / (denominator + 1) return dice def NMS(self, scores, masks): if masks.shape[0] == 0: return masks idx = torch.argsort(scores, descending=True) masks = masks[idx] # sort point_coords = torch.rand(1, self.num_points, 2, device=masks.device) sample_masks = point_sample(masks[:, None], point_coords.repeat(masks.shape[0], 1, 1), align_corners=False).squeeze(1) new_masks = [] new_sample_masks = [] for mask, sample_mask in zip(masks, sample_masks): if len(new_masks) == 0: new_masks.append(mask) new_sample_masks.append(sample_mask) continue # dice sample_masks_array = torch.stack(new_sample_masks, dim=0) dice = self.batch_dice(sample_mask[None], sample_masks_array) max_dice = dice.max(dim=1)[0].item() if max_dice < self.dice_threshold: new_masks.append(mask) new_sample_masks.append(sample_mask) new_masks = torch.stack(new_masks, dim=0) return new_masks @META_ARCH_REGISTRY.register() class MaskFormer(nn.Module): """ Main class for Mask2Former. """ @configurable def __init__( self, *, backbone: Backbone, sem_seg_head: nn.Module, criterion: nn.Module, num_queries: int, object_mask_threshold: float, overlap_threshold: float, metadata, size_divisibility: int, sem_seg_postprocess_before_inference: bool, pixel_mean: Tuple[float], pixel_std: Tuple[float], # inference semantic_on: bool, panoptic_on: bool, instance_on: bool, test_topk_per_image: int, ): """ Args: backbone: a backbone module, must follow detectron2's backbone interface sem_seg_head: a module that predicts semantic segmentation from backbone features criterion: a module that defines the loss num_queries: int, number of queries object_mask_threshold: float, threshold to filter query based on classification score for panoptic segmentation inference overlap_threshold: overlap threshold used in general inference for panoptic segmentation metadata: dataset meta, get `thing` and `stuff` category names for panoptic segmentation inference size_divisibility: Some backbones require the input height and width to be divisible by a specific integer. We can use this to override such requirement. sem_seg_postprocess_before_inference: whether to resize the prediction back to original input size before semantic segmentation inference or after. For high-resolution dataset like Mapillary, resizing predictions before inference will cause OOM error. pixel_mean, pixel_std: list or tuple with #channels element, representing the per-channel mean and std to be used to normalize the input image semantic_on: bool, whether to output semantic segmentation prediction instance_on: bool, whether to output instance segmentation prediction panoptic_on: bool, whether to output panoptic segmentation prediction test_topk_per_image: int, instance segmentation parameter, keep topk instances per image """ super().__init__() self.backbone = backbone self.sem_seg_head = sem_seg_head self.criterion = criterion self.num_queries = num_queries self.overlap_threshold = overlap_threshold self.object_mask_threshold = object_mask_threshold self.metadata = metadata if size_divisibility < 0: # use backbone size_divisibility if not set size_divisibility = self.backbone.size_divisibility self.size_divisibility = size_divisibility self.sem_seg_postprocess_before_inference = sem_seg_postprocess_before_inference self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) # additional args self.semantic_on = semantic_on self.instance_on = instance_on self.panoptic_on = panoptic_on self.test_topk_per_image = test_topk_per_image if not self.semantic_on: assert self.sem_seg_postprocess_before_inference @classmethod def from_config(cls, cfg): backbone = build_backbone(cfg) sem_seg_head = build_sem_seg_head(cfg, backbone.output_shape()) # Loss parameters: deep_supervision = cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION no_object_weight = cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT # loss weights class_weight = cfg.MODEL.MASK_FORMER.CLASS_WEIGHT dice_weight = cfg.MODEL.MASK_FORMER.DICE_WEIGHT mask_weight = cfg.MODEL.MASK_FORMER.MASK_WEIGHT # building criterion
matcher = HungarianMatcher(
1
2023-10-13 02:43:53+00:00
8k
Ravi-Teja-konda/OSGPT
myenv/Lib/site-packages/quart/testing/client.py
[ { "identifier": "TestHTTPConnection", "path": "myenv/Lib/site-packages/quart/testing/connections.py", "snippet": "class TestHTTPConnection:\n def __init__(self, app: Quart, scope: HTTPScope, _preserve_context: bool = False) -> None:\n self.app = app\n self.headers: Optional[Headers] = N...
from contextlib import asynccontextmanager from datetime import datetime, timedelta from http.cookiejar import CookieJar from types import TracebackType from typing import ( Any, AnyStr, AsyncGenerator, Dict, List, Optional, Tuple, Type, TYPE_CHECKING, Union, ) from urllib.request import Request as U2Request from werkzeug.datastructures import Authorization, Headers from werkzeug.http import dump_cookie from .connections import TestHTTPConnection, TestWebsocketConnection from .utils import ( make_test_body_with_headers, make_test_headers_path_and_query_string, make_test_scope, sentinel, ) from ..datastructures import FileStorage from ..globals import _cv_request from ..sessions import SessionMixin from ..typing import TestHTTPConnectionProtocol, TestWebsocketConnectionProtocol from ..wrappers import Response from ..app import Quart # noqa
5,134
if TYPE_CHECKING: class _TestWrapper: def __init__(self, headers: Headers) -> None: self.headers = headers def get_all(self, name: str, default: Optional[Any] = None) -> List[str]: name = name.lower() result = [] for key, value in self.headers: if key.lower() == name: result.append(value) return result or default or [] class _TestCookieJarResponse: def __init__(self, headers: Headers) -> None: self.headers = headers def info(self) -> _TestWrapper: return _TestWrapper(self.headers) class QuartClient: http_connection_class: Type[TestHTTPConnectionProtocol] websocket_connection_class: Type[TestWebsocketConnectionProtocol] http_connection_class = TestHTTPConnection websocket_connection_class = TestWebsocketConnection def __init__(self, app: "Quart", use_cookies: bool = True) -> None: self.app = app self.cookie_jar: Optional[CookieJar] if use_cookies: self.cookie_jar = CookieJar() else: self.cookie_jar = None self.preserve_context = False self.push_promises: List[Tuple[str, Headers]] = [] async def open( self, path: str, *, method: str = "GET", headers: Optional[Union[dict, Headers]] = None, data: Optional[AnyStr] = None, form: Optional[dict] = None, files: Optional[Dict[str, FileStorage]] = None, query_string: Optional[dict] = None, json: Any = sentinel, scheme: str = "http", follow_redirects: bool = False, root_path: str = "", http_version: str = "1.1", scope_base: Optional[dict] = None, auth: Optional[Union[Authorization, Tuple[str, str]]] = None, subdomain: Optional[str] = None, ) -> Response: self.push_promises = [] response = await self._make_request( path, method, headers, data, form, files, query_string, json, scheme, root_path, http_version, scope_base, auth, subdomain, ) if follow_redirects: while response.status_code >= 300 and response.status_code <= 399: # Most browsers respond to an HTTP 302 with a GET request to the new location, # despite what the HTTP spec says. HTTP 303 should always be responded to with # a GET request. if response.status_code == 302 or response.status_code == 303: method = "GET" response = await self._make_request( response.location, method, headers, data, form, files, query_string, json, scheme, root_path, http_version, scope_base, auth, subdomain, ) if self.preserve_context: _cv_request.set(self.app._preserved_context) # type: ignore return response def request( self, path: str, *, method: str = "GET", headers: Optional[Union[dict, Headers]] = None, query_string: Optional[dict] = None, scheme: str = "http", root_path: str = "", http_version: str = "1.1", scope_base: Optional[dict] = None, auth: Optional[Union[Authorization, Tuple[str, str]]] = None, subdomain: Optional[str] = None, ) -> TestHTTPConnectionProtocol:
from __future__ import annotations if TYPE_CHECKING: class _TestWrapper: def __init__(self, headers: Headers) -> None: self.headers = headers def get_all(self, name: str, default: Optional[Any] = None) -> List[str]: name = name.lower() result = [] for key, value in self.headers: if key.lower() == name: result.append(value) return result or default or [] class _TestCookieJarResponse: def __init__(self, headers: Headers) -> None: self.headers = headers def info(self) -> _TestWrapper: return _TestWrapper(self.headers) class QuartClient: http_connection_class: Type[TestHTTPConnectionProtocol] websocket_connection_class: Type[TestWebsocketConnectionProtocol] http_connection_class = TestHTTPConnection websocket_connection_class = TestWebsocketConnection def __init__(self, app: "Quart", use_cookies: bool = True) -> None: self.app = app self.cookie_jar: Optional[CookieJar] if use_cookies: self.cookie_jar = CookieJar() else: self.cookie_jar = None self.preserve_context = False self.push_promises: List[Tuple[str, Headers]] = [] async def open( self, path: str, *, method: str = "GET", headers: Optional[Union[dict, Headers]] = None, data: Optional[AnyStr] = None, form: Optional[dict] = None, files: Optional[Dict[str, FileStorage]] = None, query_string: Optional[dict] = None, json: Any = sentinel, scheme: str = "http", follow_redirects: bool = False, root_path: str = "", http_version: str = "1.1", scope_base: Optional[dict] = None, auth: Optional[Union[Authorization, Tuple[str, str]]] = None, subdomain: Optional[str] = None, ) -> Response: self.push_promises = [] response = await self._make_request( path, method, headers, data, form, files, query_string, json, scheme, root_path, http_version, scope_base, auth, subdomain, ) if follow_redirects: while response.status_code >= 300 and response.status_code <= 399: # Most browsers respond to an HTTP 302 with a GET request to the new location, # despite what the HTTP spec says. HTTP 303 should always be responded to with # a GET request. if response.status_code == 302 or response.status_code == 303: method = "GET" response = await self._make_request( response.location, method, headers, data, form, files, query_string, json, scheme, root_path, http_version, scope_base, auth, subdomain, ) if self.preserve_context: _cv_request.set(self.app._preserved_context) # type: ignore return response def request( self, path: str, *, method: str = "GET", headers: Optional[Union[dict, Headers]] = None, query_string: Optional[dict] = None, scheme: str = "http", root_path: str = "", http_version: str = "1.1", scope_base: Optional[dict] = None, auth: Optional[Union[Authorization, Tuple[str, str]]] = None, subdomain: Optional[str] = None, ) -> TestHTTPConnectionProtocol:
headers, path, query_string_bytes = make_test_headers_path_and_query_string(
2
2023-10-14 12:02:59+00:00
8k
snu-mllab/DPPO
train.py
[ { "identifier": "evaluate", "path": "evaluation.py", "snippet": "def evaluate(agent: nn.Module, env: gym.Env,\n num_episodes: int) -> Dict[str, float]:\n stats = {'return': [], 'length': [], 'success': []}\n\n # for _ in trange(num_episodes, desc='evaluation', leave=False):\n for _ ...
import datetime import os import pickle import gym import numpy as np import absl import wrappers from typing import Tuple from evaluation import evaluate from learner import Learner from viskit.logging import logger, setup_logger from JaxPref.utils import WandBLogger, define_flags_with_default, get_user_flags, \ set_random_seed, Timer, prefix_metrics from JaxPref.dataset_utils import PrefD4RLDataset from JaxPref.PrefTransformer import PrefTransformer
6,531
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '.50' FLAGS_DEF = define_flags_with_default( env_name='halfcheetah-medium-v2', seed=42, tqdm=True, eval_episodes=10, log_interval=1000, eval_interval=5000, batch_size=256, max_steps=int(1e6), model_type="PrefTransformer", comment="base", seq_len=100, min_seq_len=0, dropout=0.0, lambd=1.0, dist_temperature=0.1,
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '.50' FLAGS_DEF = define_flags_with_default( env_name='halfcheetah-medium-v2', seed=42, tqdm=True, eval_episodes=10, log_interval=1000, eval_interval=5000, batch_size=256, max_steps=int(1e6), model_type="PrefTransformer", comment="base", seq_len=100, min_seq_len=0, dropout=0.0, lambd=1.0, dist_temperature=0.1,
logging=WandBLogger.get_default_config(),
3
2023-10-08 13:41:43+00:00
8k
amazon-science/tabsyn
baselines/great/models/great.py
[ { "identifier": "GReaTDataset", "path": "baselines/great/models/great_dataset.py", "snippet": "class GReaTDataset(Dataset):\n \"\"\" GReaT Dataset\n\n The GReaTDataset overwrites the _getitem function of the HuggingFace Dataset Class to include the permutation step.\n\n Attributes:\n tok...
import os import warnings import json import typing as tp import logging import numpy as np import pandas as pd import torch from tqdm import tqdm from transformers import (AutoTokenizer, AutoModelForCausalLM, TrainingArguments) from baselines.great.models.great_dataset import GReaTDataset, GReaTDataCollator from baselines.great.models.great_start import GReaTStart, CategoricalStart, ContinuousStart, RandomStart from baselines.great.models.great_trainer import GReaTTrainer from baselines.great.models.great_utils import _array_to_dataframe, _get_column_distribution, _convert_tokens_to_text, \ _convert_text_to_tabular_data, bcolors from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, TaskType
4,924
self.llm = llm self.tokenizer = AutoTokenizer.from_pretrained(self.llm) self.tokenizer.pad_token = self.tokenizer.eos_token self.model = AutoModelForCausalLM.from_pretrained(self.llm) if self.efficient_finetuning == 'lora': # Define LoRA Config lora_config = LoraConfig( r=16, # only training 0.16% of the parameters of the model lora_alpha=32, target_modules=["c_attn"], # this is specific for gpt2 model, to be adapted lora_dropout=0.05, bias="none", task_type=TaskType.CAUSAL_LM # this is specific for gpt2 model, to be adapted ) # prepare int-8 model for training self.model = prepare_model_for_int8_training(self.model) # add LoRA adaptor self.model = get_peft_model(self.model, lora_config) self.model.print_trainable_parameters() # Set the training hyperparameters self.experiment_dir = experiment_dir self.epochs = epochs self.batch_size = batch_size self.train_hyperparameters = train_kwargs # Needed for the sampling process self.columns = None self.num_cols = None self.conditional_col = None self.conditional_col_dist = None def fit(self, data: tp.Union[pd.DataFrame, np.ndarray], column_names: tp.Optional[tp.List[str]] = None, conditional_col: tp.Optional[str] = None, resume_from_checkpoint: tp.Union[bool, str] = False) \ -> GReaTTrainer: """ Fine-tune GReaT using tabular data. Args: data: Pandas DataFrame or Numpy Array that contains the tabular data column_names: If data is Numpy Array, the feature names have to be defined. If data is Pandas DataFrame, the value is ignored conditional_col: If given, the distribution of this column is saved and used as a starting point for the generation process later. If None, the last column is considered as conditional feature resume_from_checkpoint: If True, resumes training from the latest checkpoint in the experiment_dir. If path, resumes the training from the given checkpoint (has to be a valid HuggingFace checkpoint!) Returns: GReaTTrainer used for the fine-tuning process """ df = _array_to_dataframe(data, columns=column_names) self._update_column_information(df) self._update_conditional_information(df, conditional_col) # Convert DataFrame into HuggingFace dataset object logging.info("Convert data into HuggingFace dataset object...") great_ds = GReaTDataset.from_pandas(df) great_ds.set_tokenizer(self.tokenizer) # Set training hyperparameters logging.info("Create GReaT Trainer...") training_args = TrainingArguments(self.experiment_dir, num_train_epochs=self.epochs, per_device_train_batch_size=self.batch_size, **self.train_hyperparameters) great_trainer = GReaTTrainer(self.model, training_args, train_dataset=great_ds, tokenizer=self.tokenizer, data_collator=GReaTDataCollator(self.tokenizer)) # Start training logging.info("Start training...") great_trainer.train(resume_from_checkpoint=resume_from_checkpoint) return great_trainer def sample(self, n_samples: int, start_col: tp.Optional[str] = "", start_col_dist: tp.Optional[tp.Union[dict, list]] = None, temperature: float = 0.7, k: int = 100, max_length: int = 500, device: str = "cuda") -> pd.DataFrame: """ Generate synthetic tabular data samples Args: n_samples: Number of synthetic samples to generate start_col: Feature to use as starting point for the generation process. If not given, the target learned during the fitting is used as starting point start_col_dist: Feature distribution of the starting feature. Should have the format "{F1: p1, F2: p2, ...}" for discrete columns or be a list of possible values for continuous columns. If not given, the target distribution learned during the fitting is used as starting point temperature: The generation samples each token from the probability distribution given by a softmax function. The temperature parameter controls the softmax function. A low temperature makes it sharper (0 equals greedy search), a high temperature brings more diversity but also uncertainty into the output. See this blog article (https://huggingface.co/blog/how-to-generate) to read more about the generation process k: Sampling Batch Size. Set as high as possible. Speeds up the generation process significantly max_length: Maximal number of tokens to generate - has to be long enough to not cut any information! device: Set to "cpu" if the GPU should not be used. You can also specify the concrete GPU Returns: Pandas DataFrame with n_samples rows of generated data """ great_start = self._get_start_sampler(start_col, start_col_dist) # Move model to device self.model.to(device) # Init empty DataFrame for the generated samples df_gen = pd.DataFrame(columns=self.columns) # Start generation process with tqdm(total=n_samples) as pbar: already_generated = 0 _cnt = 0 # try: while n_samples > df_gen.shape[0]: start_tokens = great_start.get_start_tokens(k) start_tokens = torch.tensor(start_tokens).to(device) # Generate tokens tokens = self.model.generate(input_ids=start_tokens, max_length=max_length, do_sample=True, temperature=temperature, pad_token_id=50256) # Convert tokens back to tabular data
class GReaT: """ GReaT Class The GReaT class handles the whole generation flow. It is used to fine-tune a large language model for tabular data, and to sample synthetic tabular data. Attributes: llm (str): HuggingFace checkpoint of a pretrained large language model, used a basis of our model tokenizer (AutoTokenizer): Tokenizer, automatically downloaded from llm-checkpoint model (AutoModelForCausalLM): Large language model, automatically downloaded from llm-checkpoint experiment_dir (str): Directory, where the training checkpoints will be saved epochs (int): Number of epochs to fine-tune the model batch_size (int): Batch size used for fine-tuning train_hyperparameters (dict): Additional hyperparameters added to the TrainingArguments used by the HuggingFaceLibrary, see here the full list of all possible values https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments columns (list): List of all features/columns of the tabular dataset num_cols (list): List of all numerical features/columns of the tabular dataset conditional_col (str): Name of a feature/column on which the sampling can be conditioned conditional_col_dist (dict | list): Distribution of the feature/column specified by condtional_col """ def __init__(self, llm: str, experiment_dir: str = "trainer_great", epochs: int = 100, batch_size: int = 8, efficient_finetuning: str = "", **train_kwargs): """ Initializes GReaT. Args: llm: HuggingFace checkpoint of a pretrained large language model, used a basis of our model experiment_dir: Directory, where the training checkpoints will be saved epochs: Number of epochs to fine-tune the model batch_size: Batch size used for fine-tuning efficient_finetuning: Indication of fune-tuning method train_kwargs: Additional hyperparameters added to the TrainingArguments used by the HuggingFaceLibrary, see here the full list of all possible values https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments """ # Load Model and Tokenizer from HuggingFace self.efficient_finetuning = efficient_finetuning self.llm = llm self.tokenizer = AutoTokenizer.from_pretrained(self.llm) self.tokenizer.pad_token = self.tokenizer.eos_token self.model = AutoModelForCausalLM.from_pretrained(self.llm) if self.efficient_finetuning == 'lora': # Define LoRA Config lora_config = LoraConfig( r=16, # only training 0.16% of the parameters of the model lora_alpha=32, target_modules=["c_attn"], # this is specific for gpt2 model, to be adapted lora_dropout=0.05, bias="none", task_type=TaskType.CAUSAL_LM # this is specific for gpt2 model, to be adapted ) # prepare int-8 model for training self.model = prepare_model_for_int8_training(self.model) # add LoRA adaptor self.model = get_peft_model(self.model, lora_config) self.model.print_trainable_parameters() # Set the training hyperparameters self.experiment_dir = experiment_dir self.epochs = epochs self.batch_size = batch_size self.train_hyperparameters = train_kwargs # Needed for the sampling process self.columns = None self.num_cols = None self.conditional_col = None self.conditional_col_dist = None def fit(self, data: tp.Union[pd.DataFrame, np.ndarray], column_names: tp.Optional[tp.List[str]] = None, conditional_col: tp.Optional[str] = None, resume_from_checkpoint: tp.Union[bool, str] = False) \ -> GReaTTrainer: """ Fine-tune GReaT using tabular data. Args: data: Pandas DataFrame or Numpy Array that contains the tabular data column_names: If data is Numpy Array, the feature names have to be defined. If data is Pandas DataFrame, the value is ignored conditional_col: If given, the distribution of this column is saved and used as a starting point for the generation process later. If None, the last column is considered as conditional feature resume_from_checkpoint: If True, resumes training from the latest checkpoint in the experiment_dir. If path, resumes the training from the given checkpoint (has to be a valid HuggingFace checkpoint!) Returns: GReaTTrainer used for the fine-tuning process """ df = _array_to_dataframe(data, columns=column_names) self._update_column_information(df) self._update_conditional_information(df, conditional_col) # Convert DataFrame into HuggingFace dataset object logging.info("Convert data into HuggingFace dataset object...") great_ds = GReaTDataset.from_pandas(df) great_ds.set_tokenizer(self.tokenizer) # Set training hyperparameters logging.info("Create GReaT Trainer...") training_args = TrainingArguments(self.experiment_dir, num_train_epochs=self.epochs, per_device_train_batch_size=self.batch_size, **self.train_hyperparameters) great_trainer = GReaTTrainer(self.model, training_args, train_dataset=great_ds, tokenizer=self.tokenizer, data_collator=GReaTDataCollator(self.tokenizer)) # Start training logging.info("Start training...") great_trainer.train(resume_from_checkpoint=resume_from_checkpoint) return great_trainer def sample(self, n_samples: int, start_col: tp.Optional[str] = "", start_col_dist: tp.Optional[tp.Union[dict, list]] = None, temperature: float = 0.7, k: int = 100, max_length: int = 500, device: str = "cuda") -> pd.DataFrame: """ Generate synthetic tabular data samples Args: n_samples: Number of synthetic samples to generate start_col: Feature to use as starting point for the generation process. If not given, the target learned during the fitting is used as starting point start_col_dist: Feature distribution of the starting feature. Should have the format "{F1: p1, F2: p2, ...}" for discrete columns or be a list of possible values for continuous columns. If not given, the target distribution learned during the fitting is used as starting point temperature: The generation samples each token from the probability distribution given by a softmax function. The temperature parameter controls the softmax function. A low temperature makes it sharper (0 equals greedy search), a high temperature brings more diversity but also uncertainty into the output. See this blog article (https://huggingface.co/blog/how-to-generate) to read more about the generation process k: Sampling Batch Size. Set as high as possible. Speeds up the generation process significantly max_length: Maximal number of tokens to generate - has to be long enough to not cut any information! device: Set to "cpu" if the GPU should not be used. You can also specify the concrete GPU Returns: Pandas DataFrame with n_samples rows of generated data """ great_start = self._get_start_sampler(start_col, start_col_dist) # Move model to device self.model.to(device) # Init empty DataFrame for the generated samples df_gen = pd.DataFrame(columns=self.columns) # Start generation process with tqdm(total=n_samples) as pbar: already_generated = 0 _cnt = 0 # try: while n_samples > df_gen.shape[0]: start_tokens = great_start.get_start_tokens(k) start_tokens = torch.tensor(start_tokens).to(device) # Generate tokens tokens = self.model.generate(input_ids=start_tokens, max_length=max_length, do_sample=True, temperature=temperature, pad_token_id=50256) # Convert tokens back to tabular data
text_data = _convert_tokens_to_text(tokens, self.tokenizer)
9
2023-10-10 18:06:31+00:00
8k
xtudbxk/TMP
basicsr/data/reds_dataset.py
[ { "identifier": "augment", "path": "basicsr/data/transforms.py", "snippet": "def augment(imgs, hflip=True, rotation=True, flows=None, return_status=False):\n \"\"\"Augment: horizontal flips OR rotate (0, 90, 180, 270 degrees).\n\n We use vertical flip and transpose for rotation implementation.\n ...
import os import numpy as np import random import torch from pathlib import Path from torch.utils import data as data from basicsr.data.transforms import augment, paired_random_crop from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor from basicsr.utils.flow_util import dequantize_flow from basicsr.utils.registry import DATASET_REGISTRY
5,347
self.io_backend_opt['db_paths'] = [self.lq_root, self.gt_root, self.flow_root] self.io_backend_opt['client_keys'] = ['lq', 'gt', 'flow'] else: self.io_backend_opt['db_paths'] = [self.lq_root, self.gt_root] self.io_backend_opt['client_keys'] = ['lq', 'gt'] elif self.io_backend_opt['type'] == 'sharedict': self.is_sharedict = True self.io_backend_opt['imgdirs'] = [self.lq_root, self.gt_root] elif self.io_backend_opt['type'] == 'sharememory': self.is_sharememory = True self.io_backend_opt['imgdirs'] = [self.lq_root, self.gt_root] self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt) # temporal augmentation configs self.interval_list = opt['interval_list'] self.random_reverse = opt['random_reverse'] interval_str = ','.join(str(x) for x in opt['interval_list']) logger = get_root_logger() logger.info(f'Temporal augmentation interval list: [{interval_str}]; ' f'random reverse is {self.random_reverse}.') def __getitem__(self, index): scale = self.opt['scale'] gt_size = self.opt['gt_size'] key = self.keys[index] clip_name, frame_name = key.split('/') # key example: 000/00000000 center_frame_idx = int(frame_name) # determine the neighboring frames interval = random.choice(self.interval_list) # ensure not exceeding the borders start_frame_idx = center_frame_idx - self.num_half_frames * interval end_frame_idx = center_frame_idx + self.num_half_frames * interval # each clip has 100 frames starting from 0 to 99 while (start_frame_idx < 0) or (end_frame_idx > 99): center_frame_idx = random.randint(0, 99) start_frame_idx = (center_frame_idx - self.num_half_frames * interval) end_frame_idx = center_frame_idx + self.num_half_frames * interval frame_name = f'{center_frame_idx:08d}' neighbor_list = list(range(start_frame_idx, end_frame_idx + 1, interval)) # random reverse if self.random_reverse and random.random() < 0.5: neighbor_list.reverse() assert len(neighbor_list) == self.num_frame, (f'Wrong length of neighbor list: {len(neighbor_list)}') # get the GT frame (as the center frame) if self.is_lmdb: img_gt_path = f'{clip_name}/{frame_name}' else: img_gt_path = os.path.join(self.gt_root, clip_name, f'{frame_name}.png') img_bytes = self.file_client.get(img_gt_path, 'gt') if self.io_backend_opt.get('store_undecoded', True): img_gt = imfrombytes(img_bytes, float32=True) else: img_gt = img_bytes.astype(np.float32) / 255. # get the neighboring LQ frames img_lqs = [] for neighbor in neighbor_list: if self.is_lmdb: img_lq_path = f'{clip_name}/{neighbor:08d}' else: img_lq_path = self.lq_root / clip_name / f'{neighbor:08d}.png' img_bytes = self.file_client.get(img_lq_path, 'lq') if self.io_backend_opt.get('store_undecoded', True): img_lq = imfrombytes(img_bytes, float32=True) else: img_lq = img_bytes.astype(np.float32) / 255. img_lqs.append(img_lq) # get flows if self.flow_root is not None: img_flows = [] # read previous flows for i in range(self.num_half_frames, 0, -1): if self.is_lmdb: flow_path = f'{clip_name}/{frame_name}_p{i}' else: flow_path = (self.flow_root / clip_name / f'{frame_name}_p{i}.png') img_bytes = self.file_client.get(flow_path, 'flow') if self.io_backend_opt.get('store_undecoded', True): cat_flow = imfrombytes(img_bytes, flag='grayscale', float32=False) # uint8, [0, 255] else: cat_flow = img_bytes dx, dy = np.split(cat_flow, 2, axis=0) flow = dequantize_flow(dx, dy, max_val=20, denorm=False) # we use max_val 20 here. img_flows.append(flow) # read next flows for i in range(1, self.num_half_frames + 1): if self.is_lmdb: flow_path = f'{clip_name}/{frame_name}_n{i}' else: flow_path = (self.flow_root / clip_name / f'{frame_name}_n{i}.png') img_bytes = self.file_client.get(flow_path, 'flow') if self.io_backend_opt.get('store_undecoded', True): cat_flow = imfrombytes(img_bytes, flag='grayscale', float32=False) # uint8, [0, 255] else: cat_flow = img_bytes dx, dy = np.split(cat_flow, 2, axis=0) flow = dequantize_flow(dx, dy, max_val=20, denorm=False) # we use max_val 20 here. img_flows.append(flow) # for random crop, here, img_flows and img_lqs have the same # spatial size img_lqs.extend(img_flows) # randomly crop img_gt, img_lqs = paired_random_crop(img_gt, img_lqs, gt_size, scale, img_gt_path) if self.flow_root is not None: img_lqs, img_flows = img_lqs[:self.num_frame], img_lqs[self.num_frame:] # augmentation - flip, rotate img_lqs.append(img_gt) if self.flow_root is not None: img_results, img_flows = augment(img_lqs, self.opt['use_hflip'], self.opt['use_rot'], img_flows) else: img_results = augment(img_lqs, self.opt['use_hflip'], self.opt['use_rot'])
@DATASET_REGISTRY.register() class REDSDataset(data.Dataset): """REDS dataset for training. The keys are generated from a meta info txt file. basicsr/data/meta_info/meta_info_REDS_GT.txt Each line contains: 1. subfolder (clip) name; 2. frame number; 3. image shape, separated by a white space. Examples: 000 100 (720,1280,3) 001 100 (720,1280,3) ... Key examples: "000/00000000" GT (gt): Ground-Truth; LQ (lq): Low-Quality, e.g., low-resolution/blurry/noisy/compressed frames. Args: opt (dict): Config for train dataset. It contains the following keys: dataroot_gt (str): Data root path for gt. dataroot_lq (str): Data root path for lq. dataroot_flow (str, optional): Data root path for flow. meta_info_file (str): Path for meta information file. val_partition (str): Validation partition types. 'REDS4' or 'official'. io_backend (dict): IO backend type and other kwarg. num_frame (int): Window size for input frames. gt_size (int): Cropped patched size for gt patches. interval_list (list): Interval list for temporal augmentation. random_reverse (bool): Random reverse input frames. use_hflip (bool): Use horizontal flips. use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation). scale (bool): Scale, which will be added automatically. """ def __init__(self, opt): super(REDSDataset, self).__init__() self.opt = opt self.gt_root, self.lq_root = Path(opt['dataroot_gt']), Path(opt['dataroot_lq']) self.flow_root = Path(opt['dataroot_flow']) if opt['dataroot_flow'] is not None else None assert opt['num_frame'] % 2 == 1, (f'num_frame should be odd number, but got {opt["num_frame"]}') self.num_frame = opt['num_frame'] self.num_half_frames = opt['num_frame'] // 2 self.keys = [] with open(opt['meta_info_file'], 'r') as fin: for line in fin: folder, frame_num, _ = line.split(' ') self.keys.extend([f'{folder}/{i:08d}' for i in range(int(frame_num))]) # remove the video clips used in validation if opt['val_partition'] == 'REDS4': val_partition = ['000', '011', '015', '020'] elif opt['val_partition'] == 'official': val_partition = [f'{v:03d}' for v in range(240, 270)] else: raise ValueError(f'Wrong validation partition {opt["val_partition"]}.' f"Supported ones are ['official', 'REDS4'].") self.keys = [v for v in self.keys if v.split('/')[0] not in val_partition] # file client (io backend) self.file_client = None self.io_backend_opt = opt['io_backend'] self.is_lmdb = False if self.io_backend_opt['type'] == 'lmdb': self.is_lmdb = True if self.flow_root is not None: self.io_backend_opt['db_paths'] = [self.lq_root, self.gt_root, self.flow_root] self.io_backend_opt['client_keys'] = ['lq', 'gt', 'flow'] else: self.io_backend_opt['db_paths'] = [self.lq_root, self.gt_root] self.io_backend_opt['client_keys'] = ['lq', 'gt'] elif self.io_backend_opt['type'] == 'sharedict': self.is_sharedict = True self.io_backend_opt['imgdirs'] = [self.lq_root, self.gt_root] elif self.io_backend_opt['type'] == 'sharememory': self.is_sharememory = True self.io_backend_opt['imgdirs'] = [self.lq_root, self.gt_root] self.file_client = FileClient(self.io_backend_opt.pop('type'), **self.io_backend_opt) # temporal augmentation configs self.interval_list = opt['interval_list'] self.random_reverse = opt['random_reverse'] interval_str = ','.join(str(x) for x in opt['interval_list']) logger = get_root_logger() logger.info(f'Temporal augmentation interval list: [{interval_str}]; ' f'random reverse is {self.random_reverse}.') def __getitem__(self, index): scale = self.opt['scale'] gt_size = self.opt['gt_size'] key = self.keys[index] clip_name, frame_name = key.split('/') # key example: 000/00000000 center_frame_idx = int(frame_name) # determine the neighboring frames interval = random.choice(self.interval_list) # ensure not exceeding the borders start_frame_idx = center_frame_idx - self.num_half_frames * interval end_frame_idx = center_frame_idx + self.num_half_frames * interval # each clip has 100 frames starting from 0 to 99 while (start_frame_idx < 0) or (end_frame_idx > 99): center_frame_idx = random.randint(0, 99) start_frame_idx = (center_frame_idx - self.num_half_frames * interval) end_frame_idx = center_frame_idx + self.num_half_frames * interval frame_name = f'{center_frame_idx:08d}' neighbor_list = list(range(start_frame_idx, end_frame_idx + 1, interval)) # random reverse if self.random_reverse and random.random() < 0.5: neighbor_list.reverse() assert len(neighbor_list) == self.num_frame, (f'Wrong length of neighbor list: {len(neighbor_list)}') # get the GT frame (as the center frame) if self.is_lmdb: img_gt_path = f'{clip_name}/{frame_name}' else: img_gt_path = os.path.join(self.gt_root, clip_name, f'{frame_name}.png') img_bytes = self.file_client.get(img_gt_path, 'gt') if self.io_backend_opt.get('store_undecoded', True): img_gt = imfrombytes(img_bytes, float32=True) else: img_gt = img_bytes.astype(np.float32) / 255. # get the neighboring LQ frames img_lqs = [] for neighbor in neighbor_list: if self.is_lmdb: img_lq_path = f'{clip_name}/{neighbor:08d}' else: img_lq_path = self.lq_root / clip_name / f'{neighbor:08d}.png' img_bytes = self.file_client.get(img_lq_path, 'lq') if self.io_backend_opt.get('store_undecoded', True): img_lq = imfrombytes(img_bytes, float32=True) else: img_lq = img_bytes.astype(np.float32) / 255. img_lqs.append(img_lq) # get flows if self.flow_root is not None: img_flows = [] # read previous flows for i in range(self.num_half_frames, 0, -1): if self.is_lmdb: flow_path = f'{clip_name}/{frame_name}_p{i}' else: flow_path = (self.flow_root / clip_name / f'{frame_name}_p{i}.png') img_bytes = self.file_client.get(flow_path, 'flow') if self.io_backend_opt.get('store_undecoded', True): cat_flow = imfrombytes(img_bytes, flag='grayscale', float32=False) # uint8, [0, 255] else: cat_flow = img_bytes dx, dy = np.split(cat_flow, 2, axis=0) flow = dequantize_flow(dx, dy, max_val=20, denorm=False) # we use max_val 20 here. img_flows.append(flow) # read next flows for i in range(1, self.num_half_frames + 1): if self.is_lmdb: flow_path = f'{clip_name}/{frame_name}_n{i}' else: flow_path = (self.flow_root / clip_name / f'{frame_name}_n{i}.png') img_bytes = self.file_client.get(flow_path, 'flow') if self.io_backend_opt.get('store_undecoded', True): cat_flow = imfrombytes(img_bytes, flag='grayscale', float32=False) # uint8, [0, 255] else: cat_flow = img_bytes dx, dy = np.split(cat_flow, 2, axis=0) flow = dequantize_flow(dx, dy, max_val=20, denorm=False) # we use max_val 20 here. img_flows.append(flow) # for random crop, here, img_flows and img_lqs have the same # spatial size img_lqs.extend(img_flows) # randomly crop img_gt, img_lqs = paired_random_crop(img_gt, img_lqs, gt_size, scale, img_gt_path) if self.flow_root is not None: img_lqs, img_flows = img_lqs[:self.num_frame], img_lqs[self.num_frame:] # augmentation - flip, rotate img_lqs.append(img_gt) if self.flow_root is not None: img_results, img_flows = augment(img_lqs, self.opt['use_hflip'], self.opt['use_rot'], img_flows) else: img_results = augment(img_lqs, self.opt['use_hflip'], self.opt['use_rot'])
img_results = img2tensor(img_results)
4
2023-10-13 06:53:09+00:00
8k
ykwang20/Guardians_as_You_Fall
legged_gym/envs/go1/go1_stand_config.py
[ { "identifier": "LeggedRobotCfg", "path": "legged_gym/envs/base/legged_robot_config.py", "snippet": "class LeggedRobotCfg(BaseConfig):\n class env:\n num_envs = 4096\n num_observations = 235\n num_privileged_obs = None # if not None a priviledge_obs_buf will be returned by step()...
from legged_gym.envs.base.legged_robot_config import LeggedRobotCfg, LeggedRobotCfgPPO
5,631
'4_RL_thigh_joint': 4.04, # [rad] '1_FR_thigh_joint': 3.7, # [rad] '3_RR_thigh_joint': 4.04, # [rad] '2_FL_calf_joint': -1.5, # [rad] '4_RL_calf_joint': -1.8, # [rad] '1_FR_calf_joint': -1.5, # [rad] '3_RR_calf_joint': -1.8, # [rad] } class noise: add_noise = True#False noise_level = 1.0 # scales other values class noise_scales: dof_pos = 0.03 dof_vel = 1.5 lin_vel = 0.1 ang_vel = 0.3 gravity = 0.05 height_measurements = 0.1 class commands: curriculum = False max_curriculum = 1. num_commands = 4 # default: lin_vel_x, lin_vel_y, ang_vel_yaw, heading (in heading mode ang_vel_yaw is recomputed from heading error) resampling_time = 10. # time before command are changed[s] heading_command = True # if true: compute ang vel command from heading error goal=[5,0] class ranges: lin_vel_x = [-1.0, 1.0] # min max [m/s] lin_vel_y = [-1.0, 1.0] # min max [m/s] ang_vel_yaw = [-1, 1] # min max [rad/s] heading = [-3.14, 3.14] class manip_ranges: T=[1.5,1.5] H=[0.1,0.1]#[0.06,0.2] px=[0.1,0.35] py=[0,0.1] manip=False class terrain( LeggedRobotCfg.terrain ): mesh_type = 'plane' measure_heights = False class sim(LeggedRobotCfg.sim): dt = 0.005 class normalization(LeggedRobotCfg.normalization): #clip_actions_hi=[0.6,1.2,1.2]#[2.4,4.8,4.8]# # [hip, thigh, calf] clip_actions_hi=[0.6,3.6,1.2]#[2.4,4.8,4.8]# for back_stand clip_actions_lo=[-0.6,-1.2,-1.2]# class domain_rand(LeggedRobotCfg.terrain): randomize_friction = True friction_range =[0.5, 2] #[0.5, 1.25] randomize_base_mass =True# False added_mass_range = [-1., 1.] push_robots = True push_interval_s = 3#15 max_push_vel_xy = 1. randomize_gains = True#False stiffness_multiplier_range = [0.9, 1.1] damping_multiplier_range = [0.9, 1.1] class control( LeggedRobotCfg.control ): # PD Drive parameters: control_type = 'P' stiffness ={'joint': 20.}# {'joint': 60.} # [N*m/rad] damping = {'joint': 0.5}#{'joint': 3.} # [N*m*s/rad] # action scale: target angle = actionScale * action + defaultAngle action_scale = 1# for stand#0.25 # decimation: Number of control action updates @ sim DT per policy DT decimation = 4 class asset( LeggedRobotCfg.asset ): file = '/home/yikai/Fall_Recovery_control/legged_gym/resources/robots/go1/urdf/go1.urdf' ball_file= '/home/yikai/Fall_Recovery_control/legged_gym/resources/robots/ball.urdf' num_balls_row=0#3 num_balls_col=0#3 foot_name = "foot" penalize_contacts_on = ["thigh", "calf"] terminate_after_contacts_on = [ "base","RL_hip","RR_hip"] #terminate_after_contacts_on = [ "base"] self_collisions = 0 # 1 to disable, 0 to enable...bitwise filter class rewards( LeggedRobotCfg.rewards ): soft_dof_pos_limit = 0.975 base_height_target = 0.25 class scales( LeggedRobotCfg.rewards.scales ): termination = 0.0 tracking_lin_vel = 0#1.5 * 1. / (.005 * 6) tracking_ang_vel = 0#0.5 * 1. / (.005 * 6) lin_vel_z =0# -1 ang_vel_xy = 0.0 orientation = 0.0 torques =0#-0.00001# -0.00005 dof_vel =0# -0.15 #for stand dof_acc =-5e-8# -1e-7#-2.5e-7 base_height = 0.0 feet_air_time = 0.0 collision = 0.0 feet_stumble = 0.0 action_rate_exp =0#3 #for stand action_rate=-2.5e-3 #TODO: check if this is the right value actions_before? actions out of bound? hip_pos=-0.01#-0.1 stand_still = 0.0 dof_pos_limits = 0.0 upright=1.0 #for stand max_height=1. #for stand work=0#-0.003 traj_tracking=0#2 regularization=0#-0.5 regular_pose=0#-0.5 pursue_goal=0#1 hang=0#-2 front_legs=0#-1 action_limit=-2 only_positive_rewards = True # if true negative total rewards are clipped at zero (avoids early termination problems)
# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Copyright (c) 2021 ETH Zurich, Nikita Rudin class Go1StandCfg( LeggedRobotCfg ): class env( LeggedRobotCfg.env ): num_envs = 5480 include_history_steps = 3 # Number of steps of history to include.#3 for stand num_observations =46#42#39#43#46#48 #for stand#42 num_privileged_obs = 49#45#49#48 episode_length_s =4 reference_state_initialization = False # reference_state_initialization_prob = 0.85 # amp_motion_files = MOTION_FILES class init_state( LeggedRobotCfg.init_state ): pos = [0.0, 0.0, 0.278] # x,y,z [m] rot = [0., -1.0, 0.0, 0.0] # x,y,z,w [quat] #rot = [0., 0., 0.0, 1.0] # x,y,z,w [quat] default_joint_angles = { # = target angles [rad] when action = 0.0 '2_FL_hip_joint': 0., # [rad] '4_RL_hip_joint': 0., # [rad] '1_FR_hip_joint': 0. , # [rad] '3_RR_hip_joint': 0., # [rad] '2_FL_thigh_joint': 0.9, # [rad] '4_RL_thigh_joint': 0.9, # [rad] '1_FR_thigh_joint': 0.9, # [rad] '3_RR_thigh_joint': 0.9, # [rad] '2_FL_calf_joint': -1.8, # [rad] '4_RL_calf_joint': -1.8, # [rad] '1_FR_calf_joint': -1.8, # [rad] '3_RR_calf_joint': -1.8, # [rad] } # default_joint_angles={ # '2_FL_hip_joint': 0., # [rad] # '4_RL_hip_joint': 0., # [rad] # '1_FR_hip_joint': 0. , # [rad] # '3_RR_hip_joint': 0., # [rad] # '2_FL_thigh_joint': 1.3, # [rad] # '4_RL_thigh_joint': 2.2, # [rad] # '1_FR_thigh_joint': 1.3, # [rad] # '3_RR_thigh_joint': 2.2, # [rad] # '2_FL_calf_joint': -2.2, # [rad] # '4_RL_calf_joint': -1.0, # [rad] # '1_FR_calf_joint': -2.2, # [rad] # '3_RR_calf_joint': -1.0, # [rad] # } # init_joint_angles = { # = target angles [rad] when action = 0.0 # '2_FL_hip_joint': 0., # [rad] # '4_RL_hip_joint': 0., # [rad] # '1_FR_hip_joint': 0. , # [rad] # '3_RR_hip_joint': 0., # [rad] # '2_FL_thigh_joint': 0.9, # [rad] # '4_RL_thigh_joint': 0.9, # [rad] # '1_FR_thigh_joint': 0.9, # [rad] # '3_RR_thigh_joint': 0.9, # [rad] # '2_FL_calf_joint': -1.8, # [rad] # '4_RL_calf_joint': -1.8, # [rad] # '1_FR_calf_joint': -1.8, # [rad] # '3_RR_calf_joint': -1.8, # [rad] # } init_joint_angles={ '2_FL_hip_joint': 0., # [rad] '4_RL_hip_joint': 0., # [rad] '1_FR_hip_joint': 0. , # [rad] '3_RR_hip_joint': 0., # [rad] '2_FL_thigh_joint': 3.7, # [rad] '4_RL_thigh_joint': 4.04, # [rad] '1_FR_thigh_joint': 3.7, # [rad] '3_RR_thigh_joint': 4.04, # [rad] '2_FL_calf_joint': -1.5, # [rad] '4_RL_calf_joint': -1.8, # [rad] '1_FR_calf_joint': -1.5, # [rad] '3_RR_calf_joint': -1.8, # [rad] } class noise: add_noise = True#False noise_level = 1.0 # scales other values class noise_scales: dof_pos = 0.03 dof_vel = 1.5 lin_vel = 0.1 ang_vel = 0.3 gravity = 0.05 height_measurements = 0.1 class commands: curriculum = False max_curriculum = 1. num_commands = 4 # default: lin_vel_x, lin_vel_y, ang_vel_yaw, heading (in heading mode ang_vel_yaw is recomputed from heading error) resampling_time = 10. # time before command are changed[s] heading_command = True # if true: compute ang vel command from heading error goal=[5,0] class ranges: lin_vel_x = [-1.0, 1.0] # min max [m/s] lin_vel_y = [-1.0, 1.0] # min max [m/s] ang_vel_yaw = [-1, 1] # min max [rad/s] heading = [-3.14, 3.14] class manip_ranges: T=[1.5,1.5] H=[0.1,0.1]#[0.06,0.2] px=[0.1,0.35] py=[0,0.1] manip=False class terrain( LeggedRobotCfg.terrain ): mesh_type = 'plane' measure_heights = False class sim(LeggedRobotCfg.sim): dt = 0.005 class normalization(LeggedRobotCfg.normalization): #clip_actions_hi=[0.6,1.2,1.2]#[2.4,4.8,4.8]# # [hip, thigh, calf] clip_actions_hi=[0.6,3.6,1.2]#[2.4,4.8,4.8]# for back_stand clip_actions_lo=[-0.6,-1.2,-1.2]# class domain_rand(LeggedRobotCfg.terrain): randomize_friction = True friction_range =[0.5, 2] #[0.5, 1.25] randomize_base_mass =True# False added_mass_range = [-1., 1.] push_robots = True push_interval_s = 3#15 max_push_vel_xy = 1. randomize_gains = True#False stiffness_multiplier_range = [0.9, 1.1] damping_multiplier_range = [0.9, 1.1] class control( LeggedRobotCfg.control ): # PD Drive parameters: control_type = 'P' stiffness ={'joint': 20.}# {'joint': 60.} # [N*m/rad] damping = {'joint': 0.5}#{'joint': 3.} # [N*m*s/rad] # action scale: target angle = actionScale * action + defaultAngle action_scale = 1# for stand#0.25 # decimation: Number of control action updates @ sim DT per policy DT decimation = 4 class asset( LeggedRobotCfg.asset ): file = '/home/yikai/Fall_Recovery_control/legged_gym/resources/robots/go1/urdf/go1.urdf' ball_file= '/home/yikai/Fall_Recovery_control/legged_gym/resources/robots/ball.urdf' num_balls_row=0#3 num_balls_col=0#3 foot_name = "foot" penalize_contacts_on = ["thigh", "calf"] terminate_after_contacts_on = [ "base","RL_hip","RR_hip"] #terminate_after_contacts_on = [ "base"] self_collisions = 0 # 1 to disable, 0 to enable...bitwise filter class rewards( LeggedRobotCfg.rewards ): soft_dof_pos_limit = 0.975 base_height_target = 0.25 class scales( LeggedRobotCfg.rewards.scales ): termination = 0.0 tracking_lin_vel = 0#1.5 * 1. / (.005 * 6) tracking_ang_vel = 0#0.5 * 1. / (.005 * 6) lin_vel_z =0# -1 ang_vel_xy = 0.0 orientation = 0.0 torques =0#-0.00001# -0.00005 dof_vel =0# -0.15 #for stand dof_acc =-5e-8# -1e-7#-2.5e-7 base_height = 0.0 feet_air_time = 0.0 collision = 0.0 feet_stumble = 0.0 action_rate_exp =0#3 #for stand action_rate=-2.5e-3 #TODO: check if this is the right value actions_before? actions out of bound? hip_pos=-0.01#-0.1 stand_still = 0.0 dof_pos_limits = 0.0 upright=1.0 #for stand max_height=1. #for stand work=0#-0.003 traj_tracking=0#2 regularization=0#-0.5 regular_pose=0#-0.5 pursue_goal=0#1 hang=0#-2 front_legs=0#-1 action_limit=-2 only_positive_rewards = True # if true negative total rewards are clipped at zero (avoids early termination problems)
class Go1StandCfgPPO( LeggedRobotCfgPPO ):
1
2023-10-07 17:03:35+00:00
8k
bloomberg/blazingmq-sdk-python
src/blazingmq/_callbacks.py
[ { "identifier": "AckStatus", "path": "src/blazingmq/_enums.py", "snippet": "class AckStatus(Enum):\n \"\"\"An enum representing the status of an Ack message\n\n An `AckStatus` is a status of a received `Ack` message\n which is the result of an attempted put to some particular queue.\n Anythi...
import os import sys import weakref import faulthandler from typing import Any from typing import Callable from typing import Dict from typing import Iterable from typing import Mapping from typing import Optional from typing import TYPE_CHECKING from typing import Tuple from typing import Type from typing import Union from ._enums import AckStatus from ._enums import PropertyType from ._messages import Ack from ._messages import Message from ._messages import MessageHandle from ._messages import create_ack from ._messages import create_message from ._messages import create_message_handle from .session_events import InterfaceError from .session_events import QueueEvent from .session_events import QueueReopenFailed from .session_events import QueueReopened from .session_events import QueueResumeFailed from .session_events import QueueResumed from .session_events import QueueSuspendFailed from .session_events import QueueSuspended from .session_events import SessionEvent from . import _ext # pragma: no cover
4,185
# Copyright 2019-2023 Bloomberg Finance L.P. # 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. from __future__ import annotations if TYPE_CHECKING: # Safely perform circular references only during static type analysis def on_session_event( user_callback: Callable[[SessionEvent], None], event_type_mapping: Dict[int, Type[SessionEvent]], error_description: bytes, sdk_event: Optional[Tuple[int, bytes, int, bytes, str]] = None, ) -> None: if sdk_event is None: # This is a synthetically generated InterfaceError being produced in # response to input from the SDK that we can't handle. return user_callback(InterfaceError(error_description.decode())) # Otherwise, we're passing a bmqa::SessionEvent we've received to our user event_type, event_name, status_code, status_name, queue_uri = sdk_event event_cls = event_type_mapping.get(event_type, InterfaceError) # Prepare event message if event_cls is InterfaceError: msg = "Unexpected event type: %s" % event_name.decode() elif status_code != 0: msg = "%s%s%s (%d)" % ( error_description.decode(), ": " if error_description else "", status_name.decode(), status_code, ) else: msg = None # Create event if issubclass(event_cls, QueueEvent): failure_class_by_success_class = { QueueReopened: QueueReopenFailed, QueueResumed: QueueResumeFailed, QueueSuspended: QueueSuspendFailed, } if status_code != 0: event_cls = failure_class_by_success_class[event_cls] assert queue_uri event: SessionEvent = event_cls(queue_uri, msg) else: event = event_cls(msg) # Invoke user callback user_callback(event) PropertiesAndTypesDictsType = Tuple[Dict[str, Union[int, bytes]], Dict[str, int]] def on_message( user_callback: Callable[[Message, MessageHandle], None], ext_session_wr: weakref.ref[_ext.Session], property_type_to_py: Mapping[int, PropertyType], messages: Iterable[Tuple[bytes, bytes, bytes, PropertiesAndTypesDictsType]], ) -> None: ext_session = ext_session_wr() assert ext_session is not None, "ext.Session has been deleted" for data, guid, queue_uri, properties_tuple in messages: properties, property_types = properties_tuple property_types_py = { k: property_type_to_py[v] for k, v in property_types.items() } message = create_message( data, guid, queue_uri.decode(), properties, property_types_py ) message_handle = create_message_handle(message, ext_session) user_callback(message, message_handle) del message_handle # The message handle holds a reference to the extension session. if sys.getrefcount(ext_session) == 2: # covered in a subprocess # pragma: no cover # Dropping our reference to the extension session will drop its reference count # to 0, calling __dealloc__ and stop() from its own background thread. print( "Deadlock detected by blazingmq after calling %s; aborting process." % user_callback, file=sys.stderr, ) try: faulthandler.dump_traceback() finally: # `faulthandler` only exists on 3; abort even if it doesn't exist or fails. sys.stderr.flush() os.abort() def on_ack(
# Copyright 2019-2023 Bloomberg Finance L.P. # 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. from __future__ import annotations if TYPE_CHECKING: # Safely perform circular references only during static type analysis def on_session_event( user_callback: Callable[[SessionEvent], None], event_type_mapping: Dict[int, Type[SessionEvent]], error_description: bytes, sdk_event: Optional[Tuple[int, bytes, int, bytes, str]] = None, ) -> None: if sdk_event is None: # This is a synthetically generated InterfaceError being produced in # response to input from the SDK that we can't handle. return user_callback(InterfaceError(error_description.decode())) # Otherwise, we're passing a bmqa::SessionEvent we've received to our user event_type, event_name, status_code, status_name, queue_uri = sdk_event event_cls = event_type_mapping.get(event_type, InterfaceError) # Prepare event message if event_cls is InterfaceError: msg = "Unexpected event type: %s" % event_name.decode() elif status_code != 0: msg = "%s%s%s (%d)" % ( error_description.decode(), ": " if error_description else "", status_name.decode(), status_code, ) else: msg = None # Create event if issubclass(event_cls, QueueEvent): failure_class_by_success_class = { QueueReopened: QueueReopenFailed, QueueResumed: QueueResumeFailed, QueueSuspended: QueueSuspendFailed, } if status_code != 0: event_cls = failure_class_by_success_class[event_cls] assert queue_uri event: SessionEvent = event_cls(queue_uri, msg) else: event = event_cls(msg) # Invoke user callback user_callback(event) PropertiesAndTypesDictsType = Tuple[Dict[str, Union[int, bytes]], Dict[str, int]] def on_message( user_callback: Callable[[Message, MessageHandle], None], ext_session_wr: weakref.ref[_ext.Session], property_type_to_py: Mapping[int, PropertyType], messages: Iterable[Tuple[bytes, bytes, bytes, PropertiesAndTypesDictsType]], ) -> None: ext_session = ext_session_wr() assert ext_session is not None, "ext.Session has been deleted" for data, guid, queue_uri, properties_tuple in messages: properties, property_types = properties_tuple property_types_py = { k: property_type_to_py[v] for k, v in property_types.items() } message = create_message( data, guid, queue_uri.decode(), properties, property_types_py ) message_handle = create_message_handle(message, ext_session) user_callback(message, message_handle) del message_handle # The message handle holds a reference to the extension session. if sys.getrefcount(ext_session) == 2: # covered in a subprocess # pragma: no cover # Dropping our reference to the extension session will drop its reference count # to 0, calling __dealloc__ and stop() from its own background thread. print( "Deadlock detected by blazingmq after calling %s; aborting process." % user_callback, file=sys.stderr, ) try: faulthandler.dump_traceback() finally: # `faulthandler` only exists on 3; abort even if it doesn't exist or fails. sys.stderr.flush() os.abort() def on_ack(
ack_status_mapping: Dict[int, AckStatus],
0
2023-10-10 14:47:32+00:00
8k