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
DLYuanGod/TinyGPT-V
minigpt4/datasets/builders/image_text_pair_builder.py
[ { "identifier": "registry", "path": "minigpt4/common/registry.py", "snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_task(cls, name):\n def wrap(task_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def ...
import os import logging import warnings from minigpt4.common.registry import registry from minigpt4.datasets.builders.base_dataset_builder import BaseDatasetBuilder from minigpt4.datasets.datasets.laion_dataset import LaionDataset from minigpt4.datasets.datasets.cc_sbu_dataset import CCSBUDataset, CCSBUAlignDataset from minigpt4.datasets.datasets.text_caps import TextCapDataset from minigpt4.datasets.datasets.llava_dataset import LlavaDetailDataset, LlavaReasonDataset, LlavaConversationDataset from minigpt4.datasets.datasets.unnatural_instruction import UnnaturalDataset from minigpt4.datasets.datasets.multitask_conversation import MultiTaskConversationDataset from minigpt4.datasets.datasets.flickr import GroundedDetailDataset,CaptionToObjectDataset,PhraseToObjectDataset from minigpt4.datasets.datasets.vg_dataset import ReferVisualGenomeDataset from minigpt4.datasets.datasets.coco_dataset import ReferCOCODataset, InvReferCOCODataset from minigpt4.datasets.datasets.gqa_datasets import GQADataset from minigpt4.datasets.datasets.aok_vqa_datasets import AOKVQADataset from minigpt4.datasets.datasets.coco_vqa_datasets import COCOVQADataset from minigpt4.datasets.datasets.ocrvqa_dataset import OCRVQADataset from minigpt4.datasets.datasets.coco_caption import COCOCapDataset
11,868
def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets class DocumentVQABuilder(BaseDatasetBuilder): def _download_ann(self): pass def _download_vis(self): pass def build(self): self.build_processors() build_info = self.config.build_info datasets = dict() split = "train" dataset_cls = self.train_dataset_cls datasets[split] = dataset_cls( vis_processor=self.vis_processors[split], text_processor=self.text_processors[split], vis_root=build_info.image_path, ann_path=build_info.ann_path ) return datasets @registry.register_builder("ocrvqa") class OCRVQABuilder(DocumentVQABuilder): train_dataset_cls = OCRVQADataset DATASET_CONFIG_DICT = {"default": "configs/datasets/ocrvqa/ocrvqa.yaml"} @registry.register_builder("cc_sbu") class CCSBUBuilder(BaseDatasetBuilder): train_dataset_cls = CCSBUDataset DATASET_CONFIG_DICT = {"default": "configs/datasets/cc_sbu/defaults.yaml"} def _download_ann(self): pass def _download_vis(self): pass def build(self): self.build_processors() build_info = self.config.build_info datasets = dict() split = "train" # create datasets # [NOTE] return inner_datasets (wds.DataPipeline) dataset_cls = self.train_dataset_cls datasets[split] = dataset_cls( vis_processor=self.vis_processors[split], text_processor=self.text_processors[split], location=build_info.storage, ).inner_dataset return datasets @registry.register_builder("laion") class LaionBuilder(BaseDatasetBuilder): train_dataset_cls = LaionDataset DATASET_CONFIG_DICT = {"default": "configs/datasets/laion/defaults.yaml"} def _download_ann(self): pass def _download_vis(self): pass def build(self): self.build_processors() build_info = self.config.build_info datasets = dict() split = "train" # create datasets # [NOTE] return inner_datasets (wds.DataPipeline) dataset_cls = self.train_dataset_cls datasets[split] = dataset_cls( vis_processor=self.vis_processors[split], text_processor=self.text_processors[split], location=build_info.storage, ).inner_dataset return datasets @registry.register_builder("coco_caption") class COCOCapBuilder(BaseDatasetBuilder):
@registry.register_builder("multitask_conversation") class MultitaskConversationBuilder(BaseDatasetBuilder): train_dataset_cls = MultiTaskConversationDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/multitask_conversation/default.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("unnatural_instruction") class UnnaturalInstructionBuilder(BaseDatasetBuilder): train_dataset_cls = UnnaturalDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/nlp/unnatural_instruction.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( text_processor=self.text_processors["train"], ann_path=build_info.ann_path, ) return datasets @registry.register_builder("llava_detail") class LlavaDetailBuilder(BaseDatasetBuilder): train_dataset_cls = LlavaDetailDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/llava/detail.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("llava_reason") class LlavaReasonBuilder(BaseDatasetBuilder): train_dataset_cls = LlavaReasonDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/llava/reason.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("llava_conversation") class LlavaReasonBuilder(BaseDatasetBuilder): train_dataset_cls = LlavaConversationDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/llava/conversation.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets class AllRefCOCOBuilder(BaseDatasetBuilder): def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info image_path = build_info.image_path ann_path = build_info.ann_path datasets = dict() if not os.path.exists(image_path): warnings.warn("image path {} does not exist.".format(image_path)) if not os.path.exists(ann_path): warnings.warn("ann path {} does not exist.".format(ann_path)) # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=ann_path, vis_root=image_path, dataset=build_info.dataset, splitBy=build_info.splitBy ) return datasets @registry.register_builder("refcoco") class RefCOCOBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcoco.yaml", } @registry.register_builder("refcocop") class RefCOCOPBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcocop.yaml", } @registry.register_builder("refcocog") class RefCOCOGBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcocog.yaml", } @registry.register_builder("invrefcoco") class RefCOCOBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcoco.yaml", } @registry.register_builder("invrefcocop") class RefCOCOPBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcocop.yaml", } @registry.register_builder("invrefcocog") class RefCOCOGBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcocog.yaml", } @registry.register_builder("refvg") class RefVisualGenomeBuilder(BaseDatasetBuilder): train_dataset_cls = ReferVisualGenomeDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/vg/ref.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info data_dir = build_info.data_dir datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], data_dir=data_dir, ) return datasets @registry.register_builder("textcaps_caption") class TextcapCaptionBuilder(BaseDatasetBuilder): train_dataset_cls = TextCapDataset DATASET_CONFIG_DICT = {"default": "configs/datasets/textcaps/caption.yaml"} def _download_ann(self): pass def _download_vis(self): pass def build(self): self.build_processors() build_info = self.config.build_info datasets = dict() split = "train" # create datasets # [NOTE] return inner_datasets (wds.DataPipeline) dataset_cls = self.train_dataset_cls datasets[split] = dataset_cls( vis_processor=self.vis_processors[split], text_processor=self.text_processors[split], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("coco_vqa") class COCOVQABuilder(BaseDatasetBuilder): train_dataset_cls = COCOVQADataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco/defaults_vqa.yaml", } @registry.register_builder("ok_vqa") class OKVQABuilder(COCOVQABuilder): DATASET_CONFIG_DICT = { "default": "configs/datasets/okvqa/defaults.yaml", } @registry.register_builder("aok_vqa") class AOKVQABuilder(BaseDatasetBuilder): train_dataset_cls = AOKVQADataset DATASET_CONFIG_DICT = {"default": "configs/datasets/aokvqa/defaults.yaml"} @registry.register_builder("gqa") class GQABuilder(BaseDatasetBuilder): train_dataset_cls = GQADataset DATASET_CONFIG_DICT = { "default": "configs/datasets/gqa/balanced_val.yaml", } @registry.register_builder("flickr_grounded_caption") class GroundedCaptionBuilder(BaseDatasetBuilder): train_dataset_cls = GroundedDetailDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/flickr/default.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("flickr_CaptionToPhrase") class CaptionToPhraseBuilder(BaseDatasetBuilder): train_dataset_cls = CaptionToObjectDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/flickr/caption_to_phrase.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("flickr_ObjectToPhrase") class CaptionToPhraseBuilder(BaseDatasetBuilder): train_dataset_cls = PhraseToObjectDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/flickr/object_to_phrase.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets class DocumentVQABuilder(BaseDatasetBuilder): def _download_ann(self): pass def _download_vis(self): pass def build(self): self.build_processors() build_info = self.config.build_info datasets = dict() split = "train" dataset_cls = self.train_dataset_cls datasets[split] = dataset_cls( vis_processor=self.vis_processors[split], text_processor=self.text_processors[split], vis_root=build_info.image_path, ann_path=build_info.ann_path ) return datasets @registry.register_builder("ocrvqa") class OCRVQABuilder(DocumentVQABuilder): train_dataset_cls = OCRVQADataset DATASET_CONFIG_DICT = {"default": "configs/datasets/ocrvqa/ocrvqa.yaml"} @registry.register_builder("cc_sbu") class CCSBUBuilder(BaseDatasetBuilder): train_dataset_cls = CCSBUDataset DATASET_CONFIG_DICT = {"default": "configs/datasets/cc_sbu/defaults.yaml"} def _download_ann(self): pass def _download_vis(self): pass def build(self): self.build_processors() build_info = self.config.build_info datasets = dict() split = "train" # create datasets # [NOTE] return inner_datasets (wds.DataPipeline) dataset_cls = self.train_dataset_cls datasets[split] = dataset_cls( vis_processor=self.vis_processors[split], text_processor=self.text_processors[split], location=build_info.storage, ).inner_dataset return datasets @registry.register_builder("laion") class LaionBuilder(BaseDatasetBuilder): train_dataset_cls = LaionDataset DATASET_CONFIG_DICT = {"default": "configs/datasets/laion/defaults.yaml"} def _download_ann(self): pass def _download_vis(self): pass def build(self): self.build_processors() build_info = self.config.build_info datasets = dict() split = "train" # create datasets # [NOTE] return inner_datasets (wds.DataPipeline) dataset_cls = self.train_dataset_cls datasets[split] = dataset_cls( vis_processor=self.vis_processors[split], text_processor=self.text_processors[split], location=build_info.storage, ).inner_dataset return datasets @registry.register_builder("coco_caption") class COCOCapBuilder(BaseDatasetBuilder):
train_dataset_cls = COCOCapDataset
21
2023-12-28 05:47:18+00:00
16k
jiawei-ren/dreamgaussian4d
diffusers/src/diffusers/models/attention.py
[ { "identifier": "USE_PEFT_BACKEND", "path": "diffusers/src/diffusers/utils/constants.py", "snippet": "USE_PEFT_BACKEND = _required_peft_version and _required_transformers_version" }, { "identifier": "maybe_allow_in_graph", "path": "diffusers/src/diffusers/utils/torch_utils.py", "snippet"...
from typing import Any, Dict, Optional from torch import nn from ..utils import USE_PEFT_BACKEND from ..utils.torch_utils import maybe_allow_in_graph from .activations import GEGLU, GELU, ApproximateGELU from .attention_processor import Attention from .embeddings import SinusoidalPositionalEmbedding from .lora import LoRACompatibleLinear from .normalization import AdaLayerNorm, AdaLayerNormZero import torch
12,521
self.attn1 = Attention( query_dim=time_mix_inner_dim, heads=num_attention_heads, dim_head=attention_head_dim, cross_attention_dim=None, ) # 2. Cross-Attn if cross_attention_dim is not None: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. self.norm2 = nn.LayerNorm(time_mix_inner_dim) self.attn2 = Attention( query_dim=time_mix_inner_dim, cross_attention_dim=cross_attention_dim, heads=num_attention_heads, dim_head=attention_head_dim, ) # is self-attn if encoder_hidden_states is none else: self.norm2 = None self.attn2 = None # 3. Feed-forward self.norm3 = nn.LayerNorm(time_mix_inner_dim) self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu") # let chunk size default to None self._chunk_size = None self._chunk_dim = None def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs): # Sets chunk feed-forward self._chunk_size = chunk_size # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off self._chunk_dim = 1 def forward( self, hidden_states: torch.FloatTensor, num_frames: int, encoder_hidden_states: Optional[torch.FloatTensor] = None, ) -> torch.FloatTensor: # Notice that normalization is always applied before the real computation in the following blocks. # 0. Self-Attention batch_size = hidden_states.shape[0] batch_frames, seq_length, channels = hidden_states.shape batch_size = batch_frames // num_frames hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels) hidden_states = hidden_states.permute(0, 2, 1, 3) hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels) residual = hidden_states hidden_states = self.norm_in(hidden_states) if self._chunk_size is not None: hidden_states = _chunked_feed_forward(self.ff, hidden_states, self._chunk_dim, self._chunk_size) else: hidden_states = self.ff_in(hidden_states) if self.is_res: hidden_states = hidden_states + residual norm_hidden_states = self.norm1(hidden_states) attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None) hidden_states = attn_output + hidden_states # 3. Cross-Attention if self.attn2 is not None: norm_hidden_states = self.norm2(hidden_states) attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states) hidden_states = attn_output + hidden_states # 4. Feed-forward norm_hidden_states = self.norm3(hidden_states) if self._chunk_size is not None: ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size) else: ff_output = self.ff(norm_hidden_states) if self.is_res: hidden_states = ff_output + hidden_states else: hidden_states = ff_output hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels) hidden_states = hidden_states.permute(0, 2, 1, 3) hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels) return hidden_states class FeedForward(nn.Module): r""" A feed-forward layer. Parameters: dim (`int`): The number of channels in the input. dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`. mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. final_dropout (`bool` *optional*, defaults to False): Apply a final dropout. """ def __init__( self, dim: int, dim_out: Optional[int] = None, mult: int = 4, dropout: float = 0.0, activation_fn: str = "geglu", final_dropout: bool = False, ): super().__init__() inner_dim = int(dim * mult) dim_out = dim_out if dim_out is not None else dim
# Copyright 2023 The HuggingFace 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. def _chunked_feed_forward( ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None ): # "feed_forward_chunk_size" can be used to save memory if hidden_states.shape[chunk_dim] % chunk_size != 0: raise ValueError( f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." ) num_chunks = hidden_states.shape[chunk_dim] // chunk_size if lora_scale is None: ff_output = torch.cat( [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], dim=chunk_dim, ) else: # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete ff_output = torch.cat( [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)], dim=chunk_dim, ) return ff_output @maybe_allow_in_graph class GatedSelfAttentionDense(nn.Module): r""" A gated self-attention dense layer that combines visual features and object features. Parameters: query_dim (`int`): The number of channels in the query. context_dim (`int`): The number of channels in the context. n_heads (`int`): The number of heads to use for attention. d_head (`int`): The number of channels in each head. """ def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int): super().__init__() # we need a linear projection since we need cat visual feature and obj feature self.linear = nn.Linear(context_dim, query_dim) self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head) self.ff = FeedForward(query_dim, activation_fn="geglu") self.norm1 = nn.LayerNorm(query_dim) self.norm2 = nn.LayerNorm(query_dim) self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0))) self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0))) self.enabled = True def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor: if not self.enabled: return x n_visual = x.shape[1] objs = self.linear(objs) x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :] x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x)) return x @maybe_allow_in_graph class BasicTransformerBlock(nn.Module): r""" A basic Transformer block. Parameters: dim (`int`): The number of channels in the input and output. num_attention_heads (`int`): The number of heads to use for multi-head attention. attention_head_dim (`int`): The number of channels in each head. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. num_embeds_ada_norm (: obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`. attention_bias (: obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter. only_cross_attention (`bool`, *optional*): Whether to use only cross-attention layers. In this case two cross attention layers are used. double_self_attention (`bool`, *optional*): Whether to use two self-attention layers. In this case no cross attention layers are used. upcast_attention (`bool`, *optional*): Whether to upcast the attention computation to float32. This is useful for mixed precision training. norm_elementwise_affine (`bool`, *optional*, defaults to `True`): Whether to use learnable elementwise affine parameters for normalization. norm_type (`str`, *optional*, defaults to `"layer_norm"`): The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`. final_dropout (`bool` *optional*, defaults to False): Whether to apply a final dropout after the last feed-forward layer. attention_type (`str`, *optional*, defaults to `"default"`): The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`. positional_embeddings (`str`, *optional*, defaults to `None`): The type of positional embeddings to apply to. num_positional_embeddings (`int`, *optional*, defaults to `None`): The maximum number of positional embeddings to apply. """ def __init__( self, dim: int, num_attention_heads: int, attention_head_dim: int, dropout=0.0, cross_attention_dim: Optional[int] = None, activation_fn: str = "geglu", num_embeds_ada_norm: Optional[int] = None, attention_bias: bool = False, only_cross_attention: bool = False, double_self_attention: bool = False, upcast_attention: bool = False, norm_elementwise_affine: bool = True, norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single' norm_eps: float = 1e-5, final_dropout: bool = False, attention_type: str = "default", positional_embeddings: Optional[str] = None, num_positional_embeddings: Optional[int] = None, ): super().__init__() self.only_cross_attention = only_cross_attention self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero" self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm" self.use_ada_layer_norm_single = norm_type == "ada_norm_single" self.use_layer_norm = norm_type == "layer_norm" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to" f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." ) if positional_embeddings and (num_positional_embeddings is None): raise ValueError( "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined." ) if positional_embeddings == "sinusoidal": self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings) else: self.pos_embed = None # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) elif self.use_ada_layer_norm_zero: self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm) else: self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) self.attn1 = Attention( query_dim=dim, heads=num_attention_heads, dim_head=attention_head_dim, dropout=dropout, bias=attention_bias, cross_attention_dim=cross_attention_dim if only_cross_attention else None, upcast_attention=upcast_attention, ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. self.norm2 = ( AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) ) self.attn2 = Attention( query_dim=dim, cross_attention_dim=cross_attention_dim if not double_self_attention else None, heads=num_attention_heads, dim_head=attention_head_dim, dropout=dropout, bias=attention_bias, upcast_attention=upcast_attention, ) # is self-attn if encoder_hidden_states is none else: self.norm2 = None self.attn2 = None # 3. Feed-forward if not self.use_ada_layer_norm_single: self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) self.ff = FeedForward( dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout, ) # 4. Fuser if attention_type == "gated" or attention_type == "gated-text-image": self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim) # 5. Scale-shift for PixArt-Alpha. if self.use_ada_layer_norm_single: self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5) # let chunk size default to None self._chunk_size = None self._chunk_dim = 0 def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0): # Sets chunk feed-forward self._chunk_size = chunk_size self._chunk_dim = dim def forward( self, hidden_states: torch.FloatTensor, attention_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, timestep: Optional[torch.LongTensor] = None, cross_attention_kwargs: Dict[str, Any] = None, class_labels: Optional[torch.LongTensor] = None, ) -> torch.FloatTensor: # Notice that normalization is always applied before the real computation in the following blocks. # 0. Self-Attention batch_size = hidden_states.shape[0] if self.use_ada_layer_norm: norm_hidden_states = self.norm1(hidden_states, timestep) elif self.use_ada_layer_norm_zero: norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1( hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype ) elif self.use_layer_norm: norm_hidden_states = self.norm1(hidden_states) elif self.use_ada_layer_norm_single: shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1) ).chunk(6, dim=1) norm_hidden_states = self.norm1(hidden_states) norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa norm_hidden_states = norm_hidden_states.squeeze(1) else: raise ValueError("Incorrect norm used") if self.pos_embed is not None: norm_hidden_states = self.pos_embed(norm_hidden_states) # 1. Retrieve lora scale. lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0 # 2. Prepare GLIGEN inputs cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {} gligen_kwargs = cross_attention_kwargs.pop("gligen", None) attn_output = self.attn1( norm_hidden_states, encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, attention_mask=attention_mask, **cross_attention_kwargs, ) if self.use_ada_layer_norm_zero: attn_output = gate_msa.unsqueeze(1) * attn_output elif self.use_ada_layer_norm_single: attn_output = gate_msa * attn_output hidden_states = attn_output + hidden_states if hidden_states.ndim == 4: hidden_states = hidden_states.squeeze(1) # 2.5 GLIGEN Control if gligen_kwargs is not None: hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"]) # 3. Cross-Attention if self.attn2 is not None: if self.use_ada_layer_norm: norm_hidden_states = self.norm2(hidden_states, timestep) elif self.use_ada_layer_norm_zero or self.use_layer_norm: norm_hidden_states = self.norm2(hidden_states) elif self.use_ada_layer_norm_single: # For PixArt norm2 isn't applied here: # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103 norm_hidden_states = hidden_states else: raise ValueError("Incorrect norm") if self.pos_embed is not None and self.use_ada_layer_norm_single is False: norm_hidden_states = self.pos_embed(norm_hidden_states) attn_output = self.attn2( norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=encoder_attention_mask, **cross_attention_kwargs, ) hidden_states = attn_output + hidden_states # 4. Feed-forward if not self.use_ada_layer_norm_single: norm_hidden_states = self.norm3(hidden_states) if self.use_ada_layer_norm_zero: norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self.use_ada_layer_norm_single: norm_hidden_states = self.norm2(hidden_states) norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory ff_output = _chunked_feed_forward( self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale ) else: ff_output = self.ff(norm_hidden_states, scale=lora_scale) if self.use_ada_layer_norm_zero: ff_output = gate_mlp.unsqueeze(1) * ff_output elif self.use_ada_layer_norm_single: ff_output = gate_mlp * ff_output hidden_states = ff_output + hidden_states if hidden_states.ndim == 4: hidden_states = hidden_states.squeeze(1) return hidden_states @maybe_allow_in_graph class TemporalBasicTransformerBlock(nn.Module): r""" A basic Transformer block for video like data. Parameters: dim (`int`): The number of channels in the input and output. time_mix_inner_dim (`int`): The number of channels for temporal attention. num_attention_heads (`int`): The number of heads to use for multi-head attention. attention_head_dim (`int`): The number of channels in each head. cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention. """ def __init__( self, dim: int, time_mix_inner_dim: int, num_attention_heads: int, attention_head_dim: int, cross_attention_dim: Optional[int] = None, ): super().__init__() self.is_res = dim == time_mix_inner_dim self.norm_in = nn.LayerNorm(dim) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn self.norm_in = nn.LayerNorm(dim) self.ff_in = FeedForward( dim, dim_out=time_mix_inner_dim, activation_fn="geglu", ) self.norm1 = nn.LayerNorm(time_mix_inner_dim) self.attn1 = Attention( query_dim=time_mix_inner_dim, heads=num_attention_heads, dim_head=attention_head_dim, cross_attention_dim=None, ) # 2. Cross-Attn if cross_attention_dim is not None: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. self.norm2 = nn.LayerNorm(time_mix_inner_dim) self.attn2 = Attention( query_dim=time_mix_inner_dim, cross_attention_dim=cross_attention_dim, heads=num_attention_heads, dim_head=attention_head_dim, ) # is self-attn if encoder_hidden_states is none else: self.norm2 = None self.attn2 = None # 3. Feed-forward self.norm3 = nn.LayerNorm(time_mix_inner_dim) self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu") # let chunk size default to None self._chunk_size = None self._chunk_dim = None def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs): # Sets chunk feed-forward self._chunk_size = chunk_size # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off self._chunk_dim = 1 def forward( self, hidden_states: torch.FloatTensor, num_frames: int, encoder_hidden_states: Optional[torch.FloatTensor] = None, ) -> torch.FloatTensor: # Notice that normalization is always applied before the real computation in the following blocks. # 0. Self-Attention batch_size = hidden_states.shape[0] batch_frames, seq_length, channels = hidden_states.shape batch_size = batch_frames // num_frames hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels) hidden_states = hidden_states.permute(0, 2, 1, 3) hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels) residual = hidden_states hidden_states = self.norm_in(hidden_states) if self._chunk_size is not None: hidden_states = _chunked_feed_forward(self.ff, hidden_states, self._chunk_dim, self._chunk_size) else: hidden_states = self.ff_in(hidden_states) if self.is_res: hidden_states = hidden_states + residual norm_hidden_states = self.norm1(hidden_states) attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None) hidden_states = attn_output + hidden_states # 3. Cross-Attention if self.attn2 is not None: norm_hidden_states = self.norm2(hidden_states) attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states) hidden_states = attn_output + hidden_states # 4. Feed-forward norm_hidden_states = self.norm3(hidden_states) if self._chunk_size is not None: ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size) else: ff_output = self.ff(norm_hidden_states) if self.is_res: hidden_states = ff_output + hidden_states else: hidden_states = ff_output hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels) hidden_states = hidden_states.permute(0, 2, 1, 3) hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels) return hidden_states class FeedForward(nn.Module): r""" A feed-forward layer. Parameters: dim (`int`): The number of channels in the input. dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`. mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. final_dropout (`bool` *optional*, defaults to False): Apply a final dropout. """ def __init__( self, dim: int, dim_out: Optional[int] = None, mult: int = 4, dropout: float = 0.0, activation_fn: str = "geglu", final_dropout: bool = False, ): super().__init__() inner_dim = int(dim * mult) dim_out = dim_out if dim_out is not None else dim
linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
7
2023-12-28 08:17:40+00:00
16k
FoundationVision/UniRef
detectron2/evaluation/coco_evaluation.py
[ { "identifier": "CfgNode", "path": "detectron2/config/config.py", "snippet": "class CfgNode(_CfgNode):\n \"\"\"\n The same as `fvcore.common.config.CfgNode`, but different in:\n\n 1. Use unsafe yaml loading by default.\n Note that this may lead to arbitrary code execution: you must not\n ...
import contextlib import copy import io import itertools import json import logging import numpy as np import os import pickle import pycocotools.mask as mask_util import torch import detectron2.utils.comm as comm from collections import OrderedDict from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from tabulate import tabulate from detectron2.config import CfgNode from detectron2.data import MetadataCatalog from detectron2.data.datasets.coco import convert_to_coco_json from detectron2.structures import Boxes, BoxMode, pairwise_iou from detectron2.utils.file_io import PathManager from detectron2.utils.logger import create_small_table from .evaluator import DatasetEvaluator from detectron2.evaluation.fast_eval_api import COCOeval_opt from detectron2.evaluation.refcocoeval import RefCOCOeval
11,812
# Copyright (c) Facebook, Inc. and its affiliates. try: except ImportError: COCOeval_opt = COCOeval
# Copyright (c) Facebook, Inc. and its affiliates. try: except ImportError: COCOeval_opt = COCOeval
class COCOEvaluator(DatasetEvaluator):
8
2023-12-22 13:31:33+00:00
16k
xhuangcv/humannorm
threestudio/models/geometry/tetrahedra_sdf_grid.py
[ { "identifier": "BaseExplicitGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseExplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n\n cfg: Config\n\n def configure(self) -> None:\n self.bbox: Flo...
from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseExplicitGeometry, BaseGeometry, contract_to_unisphere, ) from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.models.geometry.implicit_volume import ImplicitVolume from threestudio.models.isosurface import MarchingTetrahedraHelper from threestudio.models.mesh import Mesh from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.ops import scale_tensor from threestudio.utils.typing import * from pysdf import SDF from tqdm import tqdm import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio import trimesh
13,963
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone())
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone())
self.isosurface_helper = MarchingTetrahedraHelper(
5
2023-12-23 12:37:48+00:00
16k
Con6924/SPM
evaluate_task.py
[ { "identifier": "config", "path": "src/configs/config.py", "snippet": "PRECISION_TYPES = Literal[\"fp32\", \"fp16\", \"bf16\", \"float32\", \"float16\", \"bfloat16\"]\nclass PretrainedModelConfig(BaseModel):\nclass NetworkConfig(BaseModel):\nclass TrainConfig(BaseModel): \nclass SaveConfig(BaseModel)...
import argparse import gc import warnings import torch from pathlib import Path from typing import Literal from torch.utils.data import DataLoader from accelerate import PartialState, Accelerator from src.configs import config from src.configs.config import RootConfig from src.configs.generation_config import GenerationConfig from src.engine import train_util from src.evaluation import * from src.models import model_util from src.models.spm import SPMLayer, SPMNetwork from src.models.merge_spm import load_state_dict from src.misc.sld_pipeline import SLDPipeline
11,759
def get_dataloader(args, num_processes=1): # parse task_args arguments task_args = parse_extra_args(args.task_args) task_args["save_folder"] = args.img_save_path task_args["output_path"] = args.save_path # parse generation arguments cfg = parse_extra_args(args.generation_cfg) cfg = GenerationConfig(**cfg) dataset_class = None if args.task == "general": dataset_class = ClipTemplateDataset elif args.task == "artwork": dataset_class = ArtworkDataset elif args.task == "i2p": dataset_class = I2PDataset elif args.task == "coco": dataset_class = Coco30kGenerationDataset else: raise ValueError(f"Unknown task: {args.task}") dataset = dataset_class(**task_args, base_cfg=cfg) dataloader = DataLoader(dataset, batch_size=num_processes, num_workers=0, shuffle=False) return dataloader def get_evaluator(args): evaluator_class = None if args.task == "general": evaluator_class = ClipEvaluator elif args.task == "artwork": evaluator_class = ArtworkEvaluator elif args.task == "i2p": evaluator_class = I2PEvaluator elif args.task == "coco": evaluator_class = CocoEvaluator else: raise ValueError(f"Unknown task: {args.task}") evaluator = evaluator_class( save_folder=args.img_save_path, output_path=args.save_path ) return evaluator def calculate_matching_score( prompt_tokens, prompt_embeds, erased_prompt_tokens, erased_prompt_embeds, matching_metric: MATCHING_METRICS, special_token_ids: set[int], weight_dtype: torch.dtype = torch.float32, ): scores = [] if "allone" in matching_metric: scores.append(torch.ones(prompt_embeds.shape[0]).to("cpu", dtype=weight_dtype)) if "clipcos" in matching_metric: clipcos = torch.cosine_similarity( prompt_embeds.flatten(1, 2), erased_prompt_embeds.flatten(1, 2), dim=-1 ).cpu() scores.append(clipcos) if "tokenuni" in matching_metric: prompt_set = set(prompt_tokens[0].tolist()) - special_token_ids tokenuni = [] for ep in erased_prompt_tokens: ep_set = set(ep.tolist()) - special_token_ids tokenuni.append(len(prompt_set.intersection(ep_set)) / len(ep_set)) scores.append(torch.tensor(tokenuni).to("cpu", dtype=weight_dtype)) return torch.max(torch.stack(scores), dim=0)[0] @torch.no_grad() def infer_with_spm( dataloader: DataLoader, spm_paths: list[str], matching_metric: MATCHING_METRICS, facilitate_factor: float = 1.0, assigned_multipliers: list[float] = None, finetuned_model_path: str = None, sld_target_concept: str = None, base_model: str = "CompVis/stable-diffusion-v1-4", v2: bool = False, precision: str = "fp32", ): spm_model_paths = [ lp / f"{lp.name}_last.safetensors" if lp.is_dir() else lp for lp in spm_paths ] weight_dtype = config.parse_precision(precision) if finetuned_model_path is not None and Path(finetuned_model_path).is_dir(): # folder path for the diffuser model base_model = finetuned_model_path print(f"Using models from {base_model}") # load the pretrained SD tokenizer, text_encoder, unet, pipe = model_util.load_checkpoint_model( base_model, v2=v2, weight_dtype=weight_dtype, device=distributed_state.device, ) special_token_ids = set( tokenizer.convert_tokens_to_ids(tokenizer.special_tokens_map.values()) ) text_encoder.to(distributed_state.device, dtype=weight_dtype) text_encoder.eval() unet.to(distributed_state.device, dtype=weight_dtype) unet.enable_xformers_memory_efficient_attention() unet.requires_grad_(False) unet.eval() if len(spm_model_paths) > 0: # load the SPM models spms, metadatas = zip( *[
DIFFUSERS_CACHE_DIR = ".cache/" UNET_NAME = "unet" TEXT_ENCODER_NAME = "text_encoder" MATCHING_METRICS = Literal[ "clipcos", "clipcos_tokenuni", "tokenuni", "allone", ] distributed_state = PartialState() accelerator = Accelerator() def flush(): torch.cuda.empty_cache() gc.collect() def parse_extra_args(extra_args): if extra_args is None or extra_args == ['']: return {} extra_args_dict = {} for extra_arg in extra_args: key, value = extra_arg.split("=") # convert value to various types if value.isdigit(): value = int(value) elif value.replace(".", "", 1).isdigit(): value = float(value) elif value[0] == "[" and value[-1] == "]": value = [i.replace('+', ' ') for i in value[1:-1].split(",")] value = [v.strip() for v in value] if value[0].isdigit(): value = [int(v) for v in value] elif value[0].replace(".", "", 1).isdigit(): value = [float(v) for v in value] extra_args_dict[key] = value return extra_args_dict def get_dataloader(args, num_processes=1): # parse task_args arguments task_args = parse_extra_args(args.task_args) task_args["save_folder"] = args.img_save_path task_args["output_path"] = args.save_path # parse generation arguments cfg = parse_extra_args(args.generation_cfg) cfg = GenerationConfig(**cfg) dataset_class = None if args.task == "general": dataset_class = ClipTemplateDataset elif args.task == "artwork": dataset_class = ArtworkDataset elif args.task == "i2p": dataset_class = I2PDataset elif args.task == "coco": dataset_class = Coco30kGenerationDataset else: raise ValueError(f"Unknown task: {args.task}") dataset = dataset_class(**task_args, base_cfg=cfg) dataloader = DataLoader(dataset, batch_size=num_processes, num_workers=0, shuffle=False) return dataloader def get_evaluator(args): evaluator_class = None if args.task == "general": evaluator_class = ClipEvaluator elif args.task == "artwork": evaluator_class = ArtworkEvaluator elif args.task == "i2p": evaluator_class = I2PEvaluator elif args.task == "coco": evaluator_class = CocoEvaluator else: raise ValueError(f"Unknown task: {args.task}") evaluator = evaluator_class( save_folder=args.img_save_path, output_path=args.save_path ) return evaluator def calculate_matching_score( prompt_tokens, prompt_embeds, erased_prompt_tokens, erased_prompt_embeds, matching_metric: MATCHING_METRICS, special_token_ids: set[int], weight_dtype: torch.dtype = torch.float32, ): scores = [] if "allone" in matching_metric: scores.append(torch.ones(prompt_embeds.shape[0]).to("cpu", dtype=weight_dtype)) if "clipcos" in matching_metric: clipcos = torch.cosine_similarity( prompt_embeds.flatten(1, 2), erased_prompt_embeds.flatten(1, 2), dim=-1 ).cpu() scores.append(clipcos) if "tokenuni" in matching_metric: prompt_set = set(prompt_tokens[0].tolist()) - special_token_ids tokenuni = [] for ep in erased_prompt_tokens: ep_set = set(ep.tolist()) - special_token_ids tokenuni.append(len(prompt_set.intersection(ep_set)) / len(ep_set)) scores.append(torch.tensor(tokenuni).to("cpu", dtype=weight_dtype)) return torch.max(torch.stack(scores), dim=0)[0] @torch.no_grad() def infer_with_spm( dataloader: DataLoader, spm_paths: list[str], matching_metric: MATCHING_METRICS, facilitate_factor: float = 1.0, assigned_multipliers: list[float] = None, finetuned_model_path: str = None, sld_target_concept: str = None, base_model: str = "CompVis/stable-diffusion-v1-4", v2: bool = False, precision: str = "fp32", ): spm_model_paths = [ lp / f"{lp.name}_last.safetensors" if lp.is_dir() else lp for lp in spm_paths ] weight_dtype = config.parse_precision(precision) if finetuned_model_path is not None and Path(finetuned_model_path).is_dir(): # folder path for the diffuser model base_model = finetuned_model_path print(f"Using models from {base_model}") # load the pretrained SD tokenizer, text_encoder, unet, pipe = model_util.load_checkpoint_model( base_model, v2=v2, weight_dtype=weight_dtype, device=distributed_state.device, ) special_token_ids = set( tokenizer.convert_tokens_to_ids(tokenizer.special_tokens_map.values()) ) text_encoder.to(distributed_state.device, dtype=weight_dtype) text_encoder.eval() unet.to(distributed_state.device, dtype=weight_dtype) unet.enable_xformers_memory_efficient_attention() unet.requires_grad_(False) unet.eval() if len(spm_model_paths) > 0: # load the SPM models spms, metadatas = zip( *[
load_state_dict(spm_model_path, weight_dtype)
7
2023-12-26 03:19:16+00:00
16k
dakpinaroglu/Frame2seq
frame2seq/openfold/model/structure_module.py
[ { "identifier": "Linear", "path": "frame2seq/openfold/model/primitives.py", "snippet": "class Linear(nn.Linear):\n \"\"\"\n A Linear layer with built-in nonstandard initializations. Called just\n like torch.nn.Linear.\n\n Implements the initializers in 1.11.4, plus some additional ones found...
from functools import reduce from operator import mul from typing import Optional, Tuple, Sequence from frame2seq.openfold.model.primitives import Linear, LayerNorm, ipa_point_weights_init_ from frame2seq.openfold.np.residue_constants import ( restype_rigid_group_default_frame, restype_atom14_to_rigid_group, restype_atom14_mask, restype_atom14_rigid_group_positions, ) from frame2seq.openfold.utils.feats import ( frames_and_literature_positions_to_atom14_pos, torsion_angles_to_frames, ) from frame2seq.openfold.utils.precision_utils import is_fp16_enabled from frame2seq.openfold.utils.rigid_utils import Rotation, Rigid from frame2seq.openfold.utils.tensor_utils import ( dict_multimap, permute_final_dims, flatten_final_dims, ) import importlib import math import sys import torch import torch.nn as nn
14,146
mask=None, inplace_safe=False, _offload_inference=False, ): """ Args: evoformer_output_dict: Dictionary containing: "single": [*, N_res, C_s] single representation "pair": [*, N_res, N_res, C_z] pair representation aatype: [*, N_res] amino acid indices mask: Optional [*, N_res] sequence mask Returns: A dictionary of outputs """ s = evoformer_output_dict["single"] if mask is None: # [*, N] mask = s.new_ones(s.shape[:-1]) # [*, N, C_s] s = self.layer_norm_s(s) # [*, N, N, C_z] z = self.layer_norm_z(evoformer_output_dict["pair"]) z_reference_list = None if(_offload_inference): assert(sys.getrefcount(evoformer_output_dict["pair"]) == 2) evoformer_output_dict["pair"] = evoformer_output_dict["pair"].cpu() z_reference_list = [z] z = None # [*, N, C_s] s_initial = s s = self.linear_in(s) # [*, N] rigids = Rigid.identity( s.shape[:-1], s.dtype, s.device, self.training, fmt="quat", ) outputs = [] for i in range(self.no_blocks): # [*, N, C_s] s = s + self.ipa( s, z, rigids, mask, inplace_safe=inplace_safe, _offload_inference=_offload_inference, _z_reference_list=z_reference_list ) s = self.ipa_dropout(s) s = self.layer_norm_ipa(s) s = self.transition(s) # [*, N] rigids = rigids.compose_q_update_vec(self.bb_update(s)) # To hew as closely as possible to AlphaFold, we convert our # quaternion-based transformations to rotation-matrix ones # here backb_to_global = Rigid( Rotation( rot_mats=rigids.get_rots().get_rot_mats(), quats=None ), rigids.get_trans(), ) backb_to_global = backb_to_global.scale_translation( self.trans_scale_factor ) # [*, N, 7, 2] unnormalized_angles, angles = self.angle_resnet(s, s_initial) all_frames_to_global = self.torsion_angles_to_frames( backb_to_global, angles, aatype, ) pred_xyz = self.frames_and_literature_positions_to_atom14_pos( all_frames_to_global, aatype, ) scaled_rigids = rigids.scale_translation(self.trans_scale_factor) preds = { "frames": scaled_rigids.to_tensor_7(), "sidechain_frames": all_frames_to_global.to_tensor_4x4(), "unnormalized_angles": unnormalized_angles, "angles": angles, "positions": pred_xyz, "states": s, } outputs.append(preds) rigids = rigids.stop_rot_gradient() del z, z_reference_list if(_offload_inference): evoformer_output_dict["pair"] = ( evoformer_output_dict["pair"].to(s.device) )
# Copyright 2021 AlQuraishi Laboratory # Copyright 2021 DeepMind Technologies Limited # # 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. attn_core_inplace_cuda = False class AngleResnetBlock(nn.Module): def __init__(self, c_hidden): """ Args: c_hidden: Hidden channel dimension """ super(AngleResnetBlock, self).__init__() self.c_hidden = c_hidden self.linear_1 = Linear(self.c_hidden, self.c_hidden, init="relu") self.linear_2 = Linear(self.c_hidden, self.c_hidden, init="final") self.relu = nn.ReLU() def forward(self, a: torch.Tensor) -> torch.Tensor: s_initial = a a = self.relu(a) a = self.linear_1(a) a = self.relu(a) a = self.linear_2(a) return a + s_initial class AngleResnet(nn.Module): """ Implements Algorithm 20, lines 11-14 """ def __init__(self, c_in, c_hidden, no_blocks, no_angles, epsilon): """ Args: c_in: Input channel dimension c_hidden: Hidden channel dimension no_blocks: Number of resnet blocks no_angles: Number of torsion angles to generate epsilon: Small constant for normalization """ super(AngleResnet, self).__init__() self.c_in = c_in self.c_hidden = c_hidden self.no_blocks = no_blocks self.no_angles = no_angles self.eps = epsilon self.linear_in = Linear(self.c_in, self.c_hidden) self.linear_initial = Linear(self.c_in, self.c_hidden) self.layers = nn.ModuleList() for _ in range(self.no_blocks): layer = AngleResnetBlock(c_hidden=self.c_hidden) self.layers.append(layer) self.linear_out = Linear(self.c_hidden, self.no_angles * 2) self.relu = nn.ReLU() def forward( self, s: torch.Tensor, s_initial: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: s: [*, C_hidden] single embedding s_initial: [*, C_hidden] single embedding as of the start of the StructureModule Returns: [*, no_angles, 2] predicted angles """ # NOTE: The ReLU's applied to the inputs are absent from the supplement # pseudocode but present in the source. For maximal compatibility with # the pretrained weights, I'm going with the source. # [*, C_hidden] s_initial = self.relu(s_initial) s_initial = self.linear_initial(s_initial) s = self.relu(s) s = self.linear_in(s) s = s + s_initial for l in self.layers: s = l(s) s = self.relu(s) # [*, no_angles * 2] s = self.linear_out(s) # [*, no_angles, 2] s = s.view(s.shape[:-1] + (-1, 2)) unnormalized_s = s norm_denom = torch.sqrt( torch.clamp( torch.sum(s ** 2, dim=-1, keepdim=True), min=self.eps, ) ) s = s / norm_denom return unnormalized_s, s class InvariantPointAttention(nn.Module): """ Implements Algorithm 22. """ def __init__( self, c_s: int, c_z: int, c_hidden: int, no_heads: int, no_qk_points: int, no_v_points: int, inf: float = 1e5, eps: float = 1e-8, ): """ Args: c_s: Single representation channel dimension c_z: Pair representation channel dimension c_hidden: Hidden channel dimension no_heads: Number of attention heads no_qk_points: Number of query/key points to generate no_v_points: Number of value points to generate """ super(InvariantPointAttention, self).__init__() self.c_s = c_s self.c_z = c_z self.c_hidden = c_hidden self.no_heads = no_heads self.no_qk_points = no_qk_points self.no_v_points = no_v_points self.inf = inf self.eps = eps # These linear layers differ from their specifications in the # supplement. There, they lack bias and use Glorot initialization. # Here as in the official source, they have bias and use the default # Lecun initialization. hc = self.c_hidden * self.no_heads self.linear_q = Linear(self.c_s, hc) self.linear_kv = Linear(self.c_s, 2 * hc) hpq = self.no_heads * self.no_qk_points * 3 self.linear_q_points = Linear(self.c_s, hpq) hpkv = self.no_heads * (self.no_qk_points + self.no_v_points) * 3 self.linear_kv_points = Linear(self.c_s, hpkv) hpv = self.no_heads * self.no_v_points * 3 self.linear_b = Linear(self.c_z, self.no_heads) self.head_weights = nn.Parameter(torch.zeros((no_heads))) ipa_point_weights_init_(self.head_weights) concat_out_dim = self.no_heads * ( self.c_z + self.c_hidden + self.no_v_points * 4 ) self.linear_out = Linear(concat_out_dim, self.c_s, init="final") self.softmax = nn.Softmax(dim=-1) self.softplus = nn.Softplus() def forward( self, s: torch.Tensor, z: Optional[torch.Tensor], r: Rigid, mask: torch.Tensor, inplace_safe: bool = False, _offload_inference: bool = False, _z_reference_list: Optional[Sequence[torch.Tensor]] = None, attn_drop_rate = 0.0, ) -> torch.Tensor: """ Args: s: [*, N_res, C_s] single representation z: [*, N_res, N_res, C_z] pair representation r: [*, N_res] transformation object mask: [*, N_res] mask Returns: [*, N_res, C_s] single representation update """ if(_offload_inference and inplace_safe): z = _z_reference_list else: z = [z] ####################################### # Generate scalar and point activations ####################################### # [*, N_res, H * C_hidden] q = self.linear_q(s) kv = self.linear_kv(s) # [*, N_res, H, C_hidden] q = q.view(q.shape[:-1] + (self.no_heads, -1)) # [*, N_res, H, 2 * C_hidden] kv = kv.view(kv.shape[:-1] + (self.no_heads, -1)) # [*, N_res, H, C_hidden] k, v = torch.split(kv, self.c_hidden, dim=-1) # [*, N_res, H * P_q * 3] q_pts = self.linear_q_points(s) # This is kind of clunky, but it's how the original does it # [*, N_res, H * P_q, 3] q_pts = torch.split(q_pts, q_pts.shape[-1] // 3, dim=-1) q_pts = torch.stack(q_pts, dim=-1) q_pts = r[..., None].apply(q_pts) # [*, N_res, H, P_q, 3] q_pts = q_pts.view( q_pts.shape[:-2] + (self.no_heads, self.no_qk_points, 3) ) # [*, N_res, H * (P_q + P_v) * 3] kv_pts = self.linear_kv_points(s) # [*, N_res, H * (P_q + P_v), 3] kv_pts = torch.split(kv_pts, kv_pts.shape[-1] // 3, dim=-1) kv_pts = torch.stack(kv_pts, dim=-1) kv_pts = r[..., None].apply(kv_pts) # [*, N_res, H, (P_q + P_v), 3] kv_pts = kv_pts.view(kv_pts.shape[:-2] + (self.no_heads, -1, 3)) # [*, N_res, H, P_q/P_v, 3] k_pts, v_pts = torch.split( kv_pts, [self.no_qk_points, self.no_v_points], dim=-2 ) ########################## # Compute attention scores ########################## # [*, N_res, N_res, H] b = self.linear_b(z[0]) if(_offload_inference): assert(sys.getrefcount(z[0]) == 2) z[0] = z[0].cpu() # [*, H, N_res, N_res] if(is_fp16_enabled()): with torch.cuda.amp.autocast(enabled=False): a = torch.matmul( permute_final_dims(q.float(), (1, 0, 2)), # [*, H, N_res, C_hidden] permute_final_dims(k.float(), (1, 2, 0)), # [*, H, C_hidden, N_res] ) else: a = torch.matmul( permute_final_dims(q, (1, 0, 2)), # [*, H, N_res, C_hidden] permute_final_dims(k, (1, 2, 0)), # [*, H, C_hidden, N_res] ) a *= math.sqrt(1.0 / (3 * self.c_hidden)) a += (math.sqrt(1.0 / 3) * permute_final_dims(b, (2, 0, 1))) # [*, N_res, N_res, H, P_q, 3] pt_att = q_pts.unsqueeze(-4) - k_pts.unsqueeze(-5) if(inplace_safe): pt_att *= pt_att else: pt_att = pt_att ** 2 # [*, N_res, N_res, H, P_q] pt_att = sum(torch.unbind(pt_att, dim=-1)) head_weights = self.softplus(self.head_weights).view( *((1,) * len(pt_att.shape[:-2]) + (-1, 1)) ) head_weights = head_weights * math.sqrt( 1.0 / (3 * (self.no_qk_points * 9.0 / 2)) ) if(inplace_safe): pt_att *= head_weights else: pt_att = pt_att * head_weights # [*, N_res, N_res, H] pt_att = torch.sum(pt_att, dim=-1) * (-0.5) # [*, N_res, N_res] square_mask = mask.unsqueeze(-1) * mask.unsqueeze(-2) square_mask = self.inf * (square_mask - 1) """ Frame2seq implementation of IPA regularization via attention dropout """ if attn_drop_rate > 0.0: random_square_mask = torch.rand(square_mask.shape, device=square_mask.device) random_square_mask = self.inf * -1 * (random_square_mask < attn_drop_rate) square_mask += random_square_mask # [*, H, N_res, N_res] pt_att = permute_final_dims(pt_att, (2, 0, 1)) if(inplace_safe): a += pt_att del pt_att a += square_mask.unsqueeze(-3) # in-place softmax attn_core_inplace_cuda.forward_( a, reduce(mul, a.shape[:-1]), a.shape[-1], ) else: a = a + pt_att a = a + square_mask.unsqueeze(-3) a = self.softmax(a) ################ # Compute output ################ # [*, N_res, H, C_hidden] o = torch.matmul( a, v.transpose(-2, -3).to(dtype=a.dtype) ).transpose(-2, -3) # [*, N_res, H * C_hidden] o = flatten_final_dims(o, 2) # [*, H, 3, N_res, P_v] if(inplace_safe): v_pts = permute_final_dims(v_pts, (1, 3, 0, 2)) o_pt = [ torch.matmul(a, v.to(a.dtype)) for v in torch.unbind(v_pts, dim=-3) ] o_pt = torch.stack(o_pt, dim=-3) else: o_pt = torch.sum( ( a[..., None, :, :, None] * permute_final_dims(v_pts, (1, 3, 0, 2))[..., None, :, :] ), dim=-2, ) # [*, N_res, H, P_v, 3] o_pt = permute_final_dims(o_pt, (2, 0, 3, 1)) o_pt = r[..., None, None].invert_apply(o_pt) # [*, N_res, H * P_v] o_pt_norm = flatten_final_dims( torch.sqrt(torch.sum(o_pt ** 2, dim=-1) + self.eps), 2 ) # [*, N_res, H * P_v, 3] o_pt = o_pt.reshape(*o_pt.shape[:-3], -1, 3) if(_offload_inference): z[0] = z[0].to(o_pt.device) # [*, N_res, H, C_z] o_pair = torch.matmul(a.transpose(-2, -3), z[0].to(dtype=a.dtype)) # [*, N_res, H * C_z] o_pair = flatten_final_dims(o_pair, 2) # [*, N_res, C_s] s = self.linear_out( torch.cat( (o, *torch.unbind(o_pt, dim=-1), o_pt_norm, o_pair), dim=-1 ).to(dtype=z[0].dtype) ) return s class BackboneUpdate(nn.Module): """ Implements part of Algorithm 23. """ def __init__(self, c_s): """ Args: c_s: Single representation channel dimension """ super(BackboneUpdate, self).__init__() self.c_s = c_s self.linear = Linear(self.c_s, 6, init="final") def forward(self, s: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Args: [*, N_res, C_s] single representation Returns: [*, N_res, 6] update vector """ # [*, 6] update = self.linear(s) return update class StructureModuleTransitionLayer(nn.Module): def __init__(self, c): super(StructureModuleTransitionLayer, self).__init__() self.c = c self.linear_1 = Linear(self.c, self.c, init="relu") self.linear_2 = Linear(self.c, self.c, init="relu") self.linear_3 = Linear(self.c, self.c, init="final") self.relu = nn.ReLU() def forward(self, s): s_initial = s s = self.linear_1(s) s = self.relu(s) s = self.linear_2(s) s = self.relu(s) s = self.linear_3(s) s = s + s_initial return s class StructureModuleTransition(nn.Module): def __init__(self, c, num_layers, dropout_rate): super(StructureModuleTransition, self).__init__() self.c = c self.num_layers = num_layers self.dropout_rate = dropout_rate self.layers = nn.ModuleList() for _ in range(self.num_layers): l = StructureModuleTransitionLayer(self.c) self.layers.append(l) self.dropout = nn.Dropout(self.dropout_rate) self.layer_norm = LayerNorm(self.c) def forward(self, s): for l in self.layers: s = l(s) s = self.dropout(s) s = self.layer_norm(s) return s class StructureModule(nn.Module): def __init__( self, c_s, c_z, c_ipa, c_resnet, no_heads_ipa, no_qk_points, no_v_points, dropout_rate, no_blocks, no_transition_layers, no_resnet_blocks, no_angles, trans_scale_factor, epsilon, inf, **kwargs, ): """ Args: c_s: Single representation channel dimension c_z: Pair representation channel dimension c_ipa: IPA hidden channel dimension c_resnet: Angle resnet (Alg. 23 lines 11-14) hidden channel dimension no_heads_ipa: Number of IPA heads no_qk_points: Number of query/key points to generate during IPA no_v_points: Number of value points to generate during IPA dropout_rate: Dropout rate used throughout the layer no_blocks: Number of structure module blocks no_transition_layers: Number of layers in the single representation transition (Alg. 23 lines 8-9) no_resnet_blocks: Number of blocks in the angle resnet no_angles: Number of angles to generate in the angle resnet trans_scale_factor: Scale of single representation transition hidden dimension epsilon: Small number used in angle resnet normalization inf: Large number used for attention masking """ super(StructureModule, self).__init__() self.c_s = c_s self.c_z = c_z self.c_ipa = c_ipa self.c_resnet = c_resnet self.no_heads_ipa = no_heads_ipa self.no_qk_points = no_qk_points self.no_v_points = no_v_points self.dropout_rate = dropout_rate self.no_blocks = no_blocks self.no_transition_layers = no_transition_layers self.no_resnet_blocks = no_resnet_blocks self.no_angles = no_angles self.trans_scale_factor = trans_scale_factor self.epsilon = epsilon self.inf = inf # Buffers to be lazily initialized later # self.default_frames # self.group_idx # self.atom_mask # self.lit_positions self.layer_norm_s = LayerNorm(self.c_s) self.layer_norm_z = LayerNorm(self.c_z) self.linear_in = Linear(self.c_s, self.c_s) self.ipa = InvariantPointAttention( self.c_s, self.c_z, self.c_ipa, self.no_heads_ipa, self.no_qk_points, self.no_v_points, inf=self.inf, eps=self.epsilon, ) self.ipa_dropout = nn.Dropout(self.dropout_rate) self.layer_norm_ipa = LayerNorm(self.c_s) self.transition = StructureModuleTransition( self.c_s, self.no_transition_layers, self.dropout_rate, ) self.bb_update = BackboneUpdate(self.c_s) self.angle_resnet = AngleResnet( self.c_s, self.c_resnet, self.no_resnet_blocks, self.no_angles, self.epsilon, ) def forward( self, evoformer_output_dict, aatype, mask=None, inplace_safe=False, _offload_inference=False, ): """ Args: evoformer_output_dict: Dictionary containing: "single": [*, N_res, C_s] single representation "pair": [*, N_res, N_res, C_z] pair representation aatype: [*, N_res] amino acid indices mask: Optional [*, N_res] sequence mask Returns: A dictionary of outputs """ s = evoformer_output_dict["single"] if mask is None: # [*, N] mask = s.new_ones(s.shape[:-1]) # [*, N, C_s] s = self.layer_norm_s(s) # [*, N, N, C_z] z = self.layer_norm_z(evoformer_output_dict["pair"]) z_reference_list = None if(_offload_inference): assert(sys.getrefcount(evoformer_output_dict["pair"]) == 2) evoformer_output_dict["pair"] = evoformer_output_dict["pair"].cpu() z_reference_list = [z] z = None # [*, N, C_s] s_initial = s s = self.linear_in(s) # [*, N] rigids = Rigid.identity( s.shape[:-1], s.dtype, s.device, self.training, fmt="quat", ) outputs = [] for i in range(self.no_blocks): # [*, N, C_s] s = s + self.ipa( s, z, rigids, mask, inplace_safe=inplace_safe, _offload_inference=_offload_inference, _z_reference_list=z_reference_list ) s = self.ipa_dropout(s) s = self.layer_norm_ipa(s) s = self.transition(s) # [*, N] rigids = rigids.compose_q_update_vec(self.bb_update(s)) # To hew as closely as possible to AlphaFold, we convert our # quaternion-based transformations to rotation-matrix ones # here backb_to_global = Rigid( Rotation( rot_mats=rigids.get_rots().get_rot_mats(), quats=None ), rigids.get_trans(), ) backb_to_global = backb_to_global.scale_translation( self.trans_scale_factor ) # [*, N, 7, 2] unnormalized_angles, angles = self.angle_resnet(s, s_initial) all_frames_to_global = self.torsion_angles_to_frames( backb_to_global, angles, aatype, ) pred_xyz = self.frames_and_literature_positions_to_atom14_pos( all_frames_to_global, aatype, ) scaled_rigids = rigids.scale_translation(self.trans_scale_factor) preds = { "frames": scaled_rigids.to_tensor_7(), "sidechain_frames": all_frames_to_global.to_tensor_4x4(), "unnormalized_angles": unnormalized_angles, "angles": angles, "positions": pred_xyz, "states": s, } outputs.append(preds) rigids = rigids.stop_rot_gradient() del z, z_reference_list if(_offload_inference): evoformer_output_dict["pair"] = ( evoformer_output_dict["pair"].to(s.device) )
outputs = dict_multimap(torch.stack, outputs)
9
2023-12-25 09:29:36+00:00
16k
KyanChen/TTP
mmdet/datasets/transforms/formatting.py
[ { "identifier": "TRANSFORMS", "path": "mmdet/registry.py", "snippet": "TRANSFORMS = Registry(\n 'transform',\n parent=MMENGINE_TRANSFORMS,\n locations=['mmdet.datasets.transforms'])" }, { "identifier": "DetDataSample", "path": "mmdet/structures/det_data_sample.py", "snippet": "c...
from typing import Optional, Sequence from mmcv.transforms import to_tensor from mmcv.transforms.base import BaseTransform from mmengine.structures import InstanceData, PixelData from mmdet.registry import TRANSFORMS from mmdet.structures import DetDataSample, ReIDDataSample, TrackDataSample from mmdet.structures.bbox import BaseBoxes import numpy as np
11,720
# Copyright (c) OpenMMLab. All rights reserved. @TRANSFORMS.register_module() class PackDetInputs(BaseTransform): """Pack the inputs data for the detection / semantic segmentation / panoptic segmentation. The ``img_meta`` item is always populated. The contents of the ``img_meta`` dictionary depends on ``meta_keys``. By default this includes: - ``img_id``: id of the image - ``img_path``: path to the image file - ``ori_shape``: original shape of the image as a tuple (h, w) - ``img_shape``: shape of the image input to the network as a tuple \ (h, w). Note that images may be zero padded on the \ bottom/right if the batch tensor is larger than this shape. - ``scale_factor``: a float indicating the preprocessing scale - ``flip``: a boolean indicating if image flip transform was used - ``flip_direction``: the flipping direction Args: meta_keys (Sequence[str], optional): Meta keys to be converted to ``mmcv.DataContainer`` and collected in ``data[img_metas]``. Default: ``('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction')`` """ mapping_table = { 'gt_bboxes': 'bboxes', 'gt_bboxes_labels': 'labels', 'gt_masks': 'masks' } def __init__(self, meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction')): self.meta_keys = meta_keys def transform(self, results: dict) -> dict: """Method to pack the input data. Args: results (dict): Result dict from the data pipeline. Returns: dict: - 'inputs' (obj:`torch.Tensor`): The forward data of models. - 'data_sample' (obj:`DetDataSample`): The annotation info of the sample. """ packed_results = dict() if 'img' in results: img = results['img'] if len(img.shape) < 3: img = np.expand_dims(img, -1) # To improve the computational speed by by 3-5 times, apply: # If image is not contiguous, use # `numpy.transpose()` followed by `numpy.ascontiguousarray()` # If image is already contiguous, use # `torch.permute()` followed by `torch.contiguous()` # Refer to https://github.com/open-mmlab/mmdetection/pull/9533 # for more details if not img.flags.c_contiguous: img = np.ascontiguousarray(img.transpose(2, 0, 1)) img = to_tensor(img) else: img = to_tensor(img).permute(2, 0, 1).contiguous() packed_results['inputs'] = img if 'gt_ignore_flags' in results: valid_idx = np.where(results['gt_ignore_flags'] == 0)[0] ignore_idx = np.where(results['gt_ignore_flags'] == 1)[0] data_sample = DetDataSample() instance_data = InstanceData() ignore_instance_data = InstanceData() for key in self.mapping_table.keys(): if key not in results: continue
# Copyright (c) OpenMMLab. All rights reserved. @TRANSFORMS.register_module() class PackDetInputs(BaseTransform): """Pack the inputs data for the detection / semantic segmentation / panoptic segmentation. The ``img_meta`` item is always populated. The contents of the ``img_meta`` dictionary depends on ``meta_keys``. By default this includes: - ``img_id``: id of the image - ``img_path``: path to the image file - ``ori_shape``: original shape of the image as a tuple (h, w) - ``img_shape``: shape of the image input to the network as a tuple \ (h, w). Note that images may be zero padded on the \ bottom/right if the batch tensor is larger than this shape. - ``scale_factor``: a float indicating the preprocessing scale - ``flip``: a boolean indicating if image flip transform was used - ``flip_direction``: the flipping direction Args: meta_keys (Sequence[str], optional): Meta keys to be converted to ``mmcv.DataContainer`` and collected in ``data[img_metas]``. Default: ``('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction')`` """ mapping_table = { 'gt_bboxes': 'bboxes', 'gt_bboxes_labels': 'labels', 'gt_masks': 'masks' } def __init__(self, meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'scale_factor', 'flip', 'flip_direction')): self.meta_keys = meta_keys def transform(self, results: dict) -> dict: """Method to pack the input data. Args: results (dict): Result dict from the data pipeline. Returns: dict: - 'inputs' (obj:`torch.Tensor`): The forward data of models. - 'data_sample' (obj:`DetDataSample`): The annotation info of the sample. """ packed_results = dict() if 'img' in results: img = results['img'] if len(img.shape) < 3: img = np.expand_dims(img, -1) # To improve the computational speed by by 3-5 times, apply: # If image is not contiguous, use # `numpy.transpose()` followed by `numpy.ascontiguousarray()` # If image is already contiguous, use # `torch.permute()` followed by `torch.contiguous()` # Refer to https://github.com/open-mmlab/mmdetection/pull/9533 # for more details if not img.flags.c_contiguous: img = np.ascontiguousarray(img.transpose(2, 0, 1)) img = to_tensor(img) else: img = to_tensor(img).permute(2, 0, 1).contiguous() packed_results['inputs'] = img if 'gt_ignore_flags' in results: valid_idx = np.where(results['gt_ignore_flags'] == 0)[0] ignore_idx = np.where(results['gt_ignore_flags'] == 1)[0] data_sample = DetDataSample() instance_data = InstanceData() ignore_instance_data = InstanceData() for key in self.mapping_table.keys(): if key not in results: continue
if key == 'gt_masks' or isinstance(results[key], BaseBoxes):
4
2023-12-23 08:36:47+00:00
16k
see2023/Bert-VITS2-ext
train_ms.py
[ { "identifier": "config", "path": "config.py", "snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, ...
import platform import os import torch import torch.distributed as dist import logging import argparse import datetime import gc import commons import utils from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from config import config from data_utils import ( TextAudioSpeakerLoader, TextAudioSpeakerCollate, DistributedBucketSampler, AudioVisemesLoader, ) from models import ( SynthesizerTrn, MultiPeriodDiscriminator, DurationDiscriminator, WavLMDiscriminator, VisemesNet, ) from losses import ( generator_loss, discriminator_loss, feature_loss, kl_loss, WavLMLoss, ) from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols
14,177
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) logger = logging.getLogger(__name__) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 global_step = 0 global_visemes_step = 0 def run_only_visemes(hps): # 使用最简单的单机模式,仅训练隐变量z到表情(visemes)的全连接 VisemesFCNet 的参数 global global_visemes_step torch.manual_seed(hps.train.seed) torch.cuda.set_device(0) train_dataset = AudioVisemesLoader(hps.data.training_visemes_files, hps.data) train_loader = DataLoader(train_dataset, num_workers=0, shuffle=False, pin_memory=True, batch_size=1, drop_last=True) eval_dataset = AudioVisemesLoader(hps.data.validation_visemes_files, hps.data) eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False) net_v = VisemesNet(hps.model.hidden_channels).cuda() latest_model_path = utils.latest_checkpoint_path(hps.model_dir, "V_*.pth") if latest_model_path is not None: _, optim_d, _, epoch_str = utils.load_checkpoint(latest_model_path, net_v, None, skip_optimizer=False) else : epoch_str = 1 global_visemes_step = 0 net_v.init_weights() optim_v = torch.optim.AdamW( net_v.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps) optim_v.param_groups[0]['initial_lr'] = hps.train.learning_rate scheduler_v = torch.optim.lr_scheduler.ExponentialLR(optim_v, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2, ) scaler = GradScaler(enabled=hps.train.bf16_run) for epoch in range(epoch_str, hps.train.epochs + 1): train_visemes_only(epoch, hps, net_v, train_loader, optim_v, scaler) scheduler_v.step() if epoch % hps.train.eval_interval == 0: eval_visemes_only(epoch, hps, net_v, eval_loader) utils.save_checkpoint(net_v, optim_v,hps.train.learning_rate , epoch, os.path.join(hps.model_dir, "V_{}.pth".format(epoch))) def train_visemes_only(epoch, hps, net_v, train_loader, optim_v, scaler): for batch_idx, (spec, visemes) in tqdm(enumerate(train_loader)): spec, visemes = spec.cuda(), visemes.cuda() with autocast(enabled=hps.train.bf16_run): # 通过VisemesNet从z生成visemes_hat,和均方差 visemes_hat = net_v(spec) visemes_hat_mse = get_visemes_mse(visemes, visemes_hat) optim_v.zero_grad() scaler.scale(visemes_hat_mse).backward() scaler.unscale_(optim_v) grad_norm_v = commons.clip_grad_value_(net_v.parameters(), None) scaler.step(optim_v) global global_visemes_step global_visemes_step += 1 if batch_idx % hps.train.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tvisemes_hat_mse: {:.6f}\tgrad_norm_v: {:.6f}'.format( epoch, batch_idx * len(spec), len(train_loader.dataset), 100. * batch_idx / len(train_loader), visemes_hat_mse.item(), grad_norm_v)) def get_visemes_mse(visemes, visemes_hat): if visemes.shape[-1] != visemes_hat.shape[-1]: # 如果y和x的最低维度不一样 visemes_hat = F.interpolate(visemes_hat, size=visemes.shape[-1], mode='linear', align_corners=True) # 对x进行线性插值,使其形状与y一致 visemes_hat_mse = torch.mean(torch.pow(visemes_hat - visemes, 2)) return visemes_hat_mse def eval_visemes_only(epoch, hps, net_v, eval_loader): net_v.eval() with torch.no_grad(): visemes_hat_mse_sum = 0.0 for batch_idx, (spec, visemes) in tqdm(enumerate(eval_loader)): spec, visemes = spec.cuda(), visemes.cuda() # 通过VisemesFCNet从z生成visemes_hat,和均方差 visemes_hat = net_v(spec) visemes_hat_mse = get_visemes_mse(visemes, visemes_hat) visemes_hat_mse_sum += visemes_hat_mse # print('visemes_hat_mse', visemes_hat_mse) break visemes_hat_mse_avg = visemes_hat_mse_sum / (batch_idx + 1) log_str = '------------------ eval epoch: {} visemes_hat_mse_avg: {:.6f}'.format(epoch, visemes_hat_mse_avg) print(log_str) logger.warning(log_str) net_v.train() def run(): # 环境变量解析
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) logger = logging.getLogger(__name__) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 global_step = 0 global_visemes_step = 0 def run_only_visemes(hps): # 使用最简单的单机模式,仅训练隐变量z到表情(visemes)的全连接 VisemesFCNet 的参数 global global_visemes_step torch.manual_seed(hps.train.seed) torch.cuda.set_device(0) train_dataset = AudioVisemesLoader(hps.data.training_visemes_files, hps.data) train_loader = DataLoader(train_dataset, num_workers=0, shuffle=False, pin_memory=True, batch_size=1, drop_last=True) eval_dataset = AudioVisemesLoader(hps.data.validation_visemes_files, hps.data) eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False) net_v = VisemesNet(hps.model.hidden_channels).cuda() latest_model_path = utils.latest_checkpoint_path(hps.model_dir, "V_*.pth") if latest_model_path is not None: _, optim_d, _, epoch_str = utils.load_checkpoint(latest_model_path, net_v, None, skip_optimizer=False) else : epoch_str = 1 global_visemes_step = 0 net_v.init_weights() optim_v = torch.optim.AdamW( net_v.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps) optim_v.param_groups[0]['initial_lr'] = hps.train.learning_rate scheduler_v = torch.optim.lr_scheduler.ExponentialLR(optim_v, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2, ) scaler = GradScaler(enabled=hps.train.bf16_run) for epoch in range(epoch_str, hps.train.epochs + 1): train_visemes_only(epoch, hps, net_v, train_loader, optim_v, scaler) scheduler_v.step() if epoch % hps.train.eval_interval == 0: eval_visemes_only(epoch, hps, net_v, eval_loader) utils.save_checkpoint(net_v, optim_v,hps.train.learning_rate , epoch, os.path.join(hps.model_dir, "V_{}.pth".format(epoch))) def train_visemes_only(epoch, hps, net_v, train_loader, optim_v, scaler): for batch_idx, (spec, visemes) in tqdm(enumerate(train_loader)): spec, visemes = spec.cuda(), visemes.cuda() with autocast(enabled=hps.train.bf16_run): # 通过VisemesNet从z生成visemes_hat,和均方差 visemes_hat = net_v(spec) visemes_hat_mse = get_visemes_mse(visemes, visemes_hat) optim_v.zero_grad() scaler.scale(visemes_hat_mse).backward() scaler.unscale_(optim_v) grad_norm_v = commons.clip_grad_value_(net_v.parameters(), None) scaler.step(optim_v) global global_visemes_step global_visemes_step += 1 if batch_idx % hps.train.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tvisemes_hat_mse: {:.6f}\tgrad_norm_v: {:.6f}'.format( epoch, batch_idx * len(spec), len(train_loader.dataset), 100. * batch_idx / len(train_loader), visemes_hat_mse.item(), grad_norm_v)) def get_visemes_mse(visemes, visemes_hat): if visemes.shape[-1] != visemes_hat.shape[-1]: # 如果y和x的最低维度不一样 visemes_hat = F.interpolate(visemes_hat, size=visemes.shape[-1], mode='linear', align_corners=True) # 对x进行线性插值,使其形状与y一致 visemes_hat_mse = torch.mean(torch.pow(visemes_hat - visemes, 2)) return visemes_hat_mse def eval_visemes_only(epoch, hps, net_v, eval_loader): net_v.eval() with torch.no_grad(): visemes_hat_mse_sum = 0.0 for batch_idx, (spec, visemes) in tqdm(enumerate(eval_loader)): spec, visemes = spec.cuda(), visemes.cuda() # 通过VisemesFCNet从z生成visemes_hat,和均方差 visemes_hat = net_v(spec) visemes_hat_mse = get_visemes_mse(visemes, visemes_hat) visemes_hat_mse_sum += visemes_hat_mse # print('visemes_hat_mse', visemes_hat_mse) break visemes_hat_mse_avg = visemes_hat_mse_sum / (batch_idx + 1) log_str = '------------------ eval epoch: {} visemes_hat_mse_avg: {:.6f}'.format(epoch, visemes_hat_mse_avg) print(log_str) logger.warning(log_str) net_v.train() def run(): # 环境变量解析
envs = config.train_ms_config.env
0
2023-12-27 03:09:11+00:00
16k
chinhsuanwu/ifusion-threestudio
extern/ldm_zero123/models/diffusion/ddpm.py
[ { "identifier": "AutoencoderKL", "path": "extern/ldm_zero123/models/autoencoder.py", "snippet": "class AutoencoderKL(pl.LightningModule):\n def __init__(\n self,\n ddconfig,\n lossconfig,\n embed_dim,\n ckpt_path=None,\n ignore_keys=[],\n image_key=\"i...
import itertools import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn from contextlib import contextmanager, nullcontext from functools import partial from einops import rearrange, repeat from omegaconf import ListConfig from pytorch_lightning.utilities.rank_zero import rank_zero_only from torch.optim.lr_scheduler import LambdaLR from torchvision.utils import make_grid from tqdm import tqdm from extern.ldm_zero123.models.autoencoder import ( AutoencoderKL, IdentityFirstStage, VQModelInterface, ) from extern.ldm_zero123.models.diffusion.ddim import DDIMSampler from extern.ldm_zero123.modules.attention import CrossAttention from extern.ldm_zero123.modules.diffusionmodules.util import ( extract_into_tensor, make_beta_schedule, noise_like, ) from extern.ldm_zero123.modules.distributions.distributions import ( DiagonalGaussianDistribution, normal_kl, ) from extern.ldm_zero123.modules.ema import LitEma from extern.ldm_zero123.util import ( count_params, default, exists, instantiate_from_config, isimage, ismap, log_txt_as_img, mean_flat, )
10,896
__conditioning_keys__ = {"concat": "c_concat", "crossattn": "c_crossattn", "adm": "y"} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__( self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0.0, v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1.0, conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0.0, make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in [ "eps", "x0", ], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print( f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode" ) self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if ckpt_path is not None: self.init_from_ckpt( ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet ) self.register_schedule( given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s, ) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule( self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, ): if exists(given_betas): betas = given_betas else:
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {"concat": "c_concat", "crossattn": "c_crossattn", "adm": "y"} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__( self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0.0, v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1.0, conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0.0, make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in [ "eps", "x0", ], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print( f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode" ) self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if ckpt_path is not None: self.init_from_ckpt( ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet ) self.register_schedule( given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s, ) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule( self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, ): if exists(given_betas): betas = given_betas else:
betas = make_beta_schedule(
6
2023-12-27 20:30:33+00:00
16k
gardenifi/server
app/ble/wifi.py
[ { "identifier": "Helpers", "path": "app/raspi/helpers.py", "snippet": "class Helpers:\n \"\"\"\n The `Helpers` class provides various helper methods for performing tasks\n such as setting valves, getting system information, storing and loading\n objects to/from files, managing WiFi networks,...
import json import dbus # pylint: disable=import-error,useless-import-alias from loguru import logger from dbus.exceptions import DBusException from app.raspi.helpers import Helpers from app.raspi.services import Services from app.ble.advertisement import Advertisement from app.ble.service import Application, Service, Characteristic
12,510
self.add_local_name("raspirriv1") self.include_tx_power = True logger.info( f"WifiNetworksAdvertisement initialized with index: {index}, \ advertising type: 'peripheral', local name: 'raspirriv1', and include_tx_power: True." ) def register_ad_callback(self): """Register ad callback.""" logger.info(f"{self.path}: GATT advertisement registered for WifiNetworksAdvertisement") def register_ad_error_callback(self): """Register ad error callback.""" logger.error(f"{self.path}: Failed to register GATT advertisement for WifiNetworksAdvertisement") class WifiNetworksService(Service): # pylint: disable=too-few-public-methods """Bluetooth module.""" SVC_UUID = "00000001-710e-4a5b-8d75-3e5b444bc3cf" def __init__(self, index, page=1, connected=0): self._page = page self._connected = connected super().__init__(index, self.SVC_UUID, True) self._add_characteristics() self._log_characteristics_added() def _add_characteristics(self): self.add_characteristic(WifiCharacteristic(self)) self.add_characteristic(ConnectivityCharacteristic(self)) def _log_characteristics_added(self): logger.info("Adding characteristics completed.") class WifiCharacteristic(Characteristic): """Bluetooth module.""" WIFI_CHARACTERISTIC_UUID = "00000003-710e-4a5b-8d75-3e5b444bc3cf" def __init__(self, service): super().__init__(self.WIFI_CHARACTERISTIC_UUID, ["read", "write", "write-without-response"], service) self._page_set = 1 self._refresh_set = False self._services = Services() logger.info("Adding WifiCharacteristic completed.") def WriteValue(self, values, options): # pylint: disable=unused-argument,invalid-name """Bluetooth module.""" command = "".join(str(value) for value in values) logger.debug(f"command: {command}") try: json_data = json.loads(command) if json_data.get("page"): self._page_set = int(json_data["page"]) logger.debug(f"Page set: {self._page_set}") elif json_data.get("refresh"): value = json_data["refresh"] if value.lower() == "true": self._refresh_set = True else: self._refresh_set = False logger.debug(f"refresh: {self._refresh_set}") elif json_data.get("ssid") and json_data.get("wifi_key"): connected = Helpers().store_wpa_ssid_key(json_data["ssid"], json_data["wifi_key"]) logger.info(f"Wifi changed: {json_data}. Connected: {connected}") else: raise ValueError(f"Missing data! You provided only: {json_data}") except json.JSONDecodeError as exception: logger.error(f"JSONDecodeError: {exception}") raise ValueError(f"{exception}") from exception except Exception as exception: logger.error(f"Error: {exception}") raise ValueError(f"{exception}") from exception def ReadValue(self, options): # pylint: disable=unused-argument,invalid-name """Bluetooth module.""" values = [] try: logger.debug(f"page set earlier: {self._page_set}") wifi_networks = self._services.discover_wifi_networks(1, self._page_set, self._refresh_set) logger.debug(f"wifi_networks: {wifi_networks}") if not wifi_networks: wifi_networks = "No wifi networks identified!" for char in str(wifi_networks): values.append(dbus.Byte(char.encode())) except DBusException as exception: logger.error(f"DBusException: {exception}") raise ValueError(f"{exception}") from exception except Exception as exception: logger.error(f"Error: {exception}") raise ValueError(f"{exception}") from exception return values class ConnectivityCharacteristic(Characteristic): # pylint: disable=too-few-public-methods """Bluetooth module.""" CONN_CHARACTERISTIC_UUID = "00000004-710e-4a5b-8d75-3e5b444bc3cf" def __init__(self, service): super().__init__(self.CONN_CHARACTERISTIC_UUID, ["read"], service) def ReadValue(self, options): # pylint: disable=invalid-name,unused-argument """Bluetooth module.""" values = [] logger.debug(f"connected: {Helpers().is_connected_to_inet}") if Helpers().is_connected_to_inet: values.append(dbus.Byte(b"1")) else: values.append(dbus.Byte(b"0")) logger.debug(f"values: {values}") return values def init_ble(): """Bluetooth module.""" logger.info("Initializing BLE module...")
"""Copyright (c) 2019, Douglas Otwell 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. """ GATT_CHRC_IFACE = "org.bluez.GattCharacteristic1" NOTIFY_TIMEOUT = 5000 class WifiNetworksAdvertisement(Advertisement): # pylint: disable=too-few-public-methods """Bluetooth module.""" def __init__(self, index): super().__init__(index, "peripheral") self.add_local_name("raspirriv1") self.include_tx_power = True logger.info( f"WifiNetworksAdvertisement initialized with index: {index}, \ advertising type: 'peripheral', local name: 'raspirriv1', and include_tx_power: True." ) def register_ad_callback(self): """Register ad callback.""" logger.info(f"{self.path}: GATT advertisement registered for WifiNetworksAdvertisement") def register_ad_error_callback(self): """Register ad error callback.""" logger.error(f"{self.path}: Failed to register GATT advertisement for WifiNetworksAdvertisement") class WifiNetworksService(Service): # pylint: disable=too-few-public-methods """Bluetooth module.""" SVC_UUID = "00000001-710e-4a5b-8d75-3e5b444bc3cf" def __init__(self, index, page=1, connected=0): self._page = page self._connected = connected super().__init__(index, self.SVC_UUID, True) self._add_characteristics() self._log_characteristics_added() def _add_characteristics(self): self.add_characteristic(WifiCharacteristic(self)) self.add_characteristic(ConnectivityCharacteristic(self)) def _log_characteristics_added(self): logger.info("Adding characteristics completed.") class WifiCharacteristic(Characteristic): """Bluetooth module.""" WIFI_CHARACTERISTIC_UUID = "00000003-710e-4a5b-8d75-3e5b444bc3cf" def __init__(self, service): super().__init__(self.WIFI_CHARACTERISTIC_UUID, ["read", "write", "write-without-response"], service) self._page_set = 1 self._refresh_set = False self._services = Services() logger.info("Adding WifiCharacteristic completed.") def WriteValue(self, values, options): # pylint: disable=unused-argument,invalid-name """Bluetooth module.""" command = "".join(str(value) for value in values) logger.debug(f"command: {command}") try: json_data = json.loads(command) if json_data.get("page"): self._page_set = int(json_data["page"]) logger.debug(f"Page set: {self._page_set}") elif json_data.get("refresh"): value = json_data["refresh"] if value.lower() == "true": self._refresh_set = True else: self._refresh_set = False logger.debug(f"refresh: {self._refresh_set}") elif json_data.get("ssid") and json_data.get("wifi_key"): connected = Helpers().store_wpa_ssid_key(json_data["ssid"], json_data["wifi_key"]) logger.info(f"Wifi changed: {json_data}. Connected: {connected}") else: raise ValueError(f"Missing data! You provided only: {json_data}") except json.JSONDecodeError as exception: logger.error(f"JSONDecodeError: {exception}") raise ValueError(f"{exception}") from exception except Exception as exception: logger.error(f"Error: {exception}") raise ValueError(f"{exception}") from exception def ReadValue(self, options): # pylint: disable=unused-argument,invalid-name """Bluetooth module.""" values = [] try: logger.debug(f"page set earlier: {self._page_set}") wifi_networks = self._services.discover_wifi_networks(1, self._page_set, self._refresh_set) logger.debug(f"wifi_networks: {wifi_networks}") if not wifi_networks: wifi_networks = "No wifi networks identified!" for char in str(wifi_networks): values.append(dbus.Byte(char.encode())) except DBusException as exception: logger.error(f"DBusException: {exception}") raise ValueError(f"{exception}") from exception except Exception as exception: logger.error(f"Error: {exception}") raise ValueError(f"{exception}") from exception return values class ConnectivityCharacteristic(Characteristic): # pylint: disable=too-few-public-methods """Bluetooth module.""" CONN_CHARACTERISTIC_UUID = "00000004-710e-4a5b-8d75-3e5b444bc3cf" def __init__(self, service): super().__init__(self.CONN_CHARACTERISTIC_UUID, ["read"], service) def ReadValue(self, options): # pylint: disable=invalid-name,unused-argument """Bluetooth module.""" values = [] logger.debug(f"connected: {Helpers().is_connected_to_inet}") if Helpers().is_connected_to_inet: values.append(dbus.Byte(b"1")) else: values.append(dbus.Byte(b"0")) logger.debug(f"values: {values}") return values def init_ble(): """Bluetooth module.""" logger.info("Initializing BLE module...")
app = Application()
3
2023-12-22 08:06:09+00:00
16k
shibing624/chatgpt-webui
src/models.py
[ { "identifier": "shared", "path": "src/shared.py", "snippet": "class State:\n def interrupt(self):\n def recover(self):\n def set_api_host(self, api_host: str):\n def reset_api_host(self):\n def reset_all(self):\n def set_api_key_queue(self, api_key_list):\n def switching_api_key(se...
import base64 import datetime import json import os import colorama import gradio as gr import requests import traceback import traceback from io import BytesIO from PIL import Image from loguru import logger from src import shared, config from src.base_model import BaseLLMModel, ModelType from src.chatglm import ChatGLMClient from src.llama import LLaMAClient from src.presets import ( INITIAL_SYSTEM_PROMPT, TIMEOUT_ALL, TIMEOUT_STREAMING, STANDARD_ERROR_MSG, CONNECTION_TIMEOUT_MSG, READ_TIMEOUT_MSG, ERROR_RETRIEVE_MSG, GENERAL_ERROR_MSG, CHAT_COMPLETION_URL, SUMMARY_CHAT_SYSTEM_PROMPT ) from src.utils import ( hide_middle_chars, count_token, construct_system, construct_user, get_last_day_of_month, i18n, replace_special_symbols, )
11,594
system_prompt=INITIAL_SYSTEM_PROMPT, temperature=1.0, top_p=1.0, user_name="", ) -> None: super().__init__( model_name=model_name, temperature=temperature, top_p=top_p, system_prompt=system_prompt, user=user_name, ) self.api_key = api_key self.need_api_key = True self._refresh_header() def get_answer_stream_iter(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response(stream=True) if response is not None: iter = self._decode_chat_response(response) partial_text = "" for i in iter: partial_text += i yield partial_text else: yield STANDARD_ERROR_MSG + GENERAL_ERROR_MSG def get_answer_at_once(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response() response = json.loads(response.text) content = response["choices"][0]["message"]["content"] total_token_count = response["usage"]["total_tokens"] return content, total_token_count def count_token(self, user_input): input_token_count = count_token(construct_user(user_input)) if self.system_prompt is not None and len(self.all_token_counts) == 0: system_prompt_token_count = count_token( construct_system(self.system_prompt) ) return input_token_count + system_prompt_token_count return input_token_count def billing_info(self): try: curr_time = datetime.datetime.now() last_day_of_month = get_last_day_of_month( curr_time).strftime("%Y-%m-%d") first_day_of_month = curr_time.replace(day=1).strftime("%Y-%m-%d") usage_url = f"{shared.state.usage_api_url}?start_date={first_day_of_month}&end_date={last_day_of_month}" try: usage_data = self._get_billing_data(usage_url) except Exception as e: logger.warning(f"获取API使用情况失败:" + str(e)) return i18n("**获取API使用情况失败**") rounded_usage = "{:.5f}".format(usage_data["total_usage"] / 100) return i18n("**本月使用金额** ") + f"\u3000 ${rounded_usage}" except requests.exceptions.ConnectTimeout: status_text = ( STANDARD_ERROR_MSG + CONNECTION_TIMEOUT_MSG + ERROR_RETRIEVE_MSG ) return status_text except requests.exceptions.ReadTimeout: status_text = STANDARD_ERROR_MSG + READ_TIMEOUT_MSG + ERROR_RETRIEVE_MSG return status_text except Exception as e: traceback.print_exc() logger.error(i18n("获取API使用情况失败:") + str(e)) return STANDARD_ERROR_MSG + ERROR_RETRIEVE_MSG def set_token_upper_limit(self, new_upper_limit): pass @shared.state.switching_api_key # 在不开启多账号模式的时候,这个装饰器不会起作用 def _get_response(self, stream=False): openai_api_key = self.api_key system_prompt = self.system_prompt history = self.history logger.debug(f"{history}") headers = { "Authorization": f"Bearer {openai_api_key}", "Content-Type": "application/json", } if system_prompt is not None: history = [construct_system(system_prompt), *history] payload = { "model": self.model_name, "messages": history, "temperature": self.temperature, "top_p": self.top_p, "n": self.n_choices, "stream": stream, "presence_penalty": self.presence_penalty, "frequency_penalty": self.frequency_penalty, } if self.max_generation_token is not None: payload["max_tokens"] = self.max_generation_token if self.stop_sequence is not None: payload["stop"] = self.stop_sequence if self.logit_bias is not None: payload["logit_bias"] = self.logit_bias if self.user_identifier is not None: payload["user"] = self.user_identifier if stream: timeout = TIMEOUT_STREAMING else: timeout = TIMEOUT_ALL # 如果有自定义的api-host,使用自定义host发送请求,否则使用默认设置发送请求 if shared.state.chat_completion_url != CHAT_COMPLETION_URL: logger.debug(f"使用自定义API URL: {shared.state.chat_completion_url}")
# -*- coding: utf-8 -*- """ Get model client from model name """ class OpenAIClient(BaseLLMModel): def __init__( self, model_name, api_key, system_prompt=INITIAL_SYSTEM_PROMPT, temperature=1.0, top_p=1.0, user_name="", ) -> None: super().__init__( model_name=model_name, temperature=temperature, top_p=top_p, system_prompt=system_prompt, user=user_name, ) self.api_key = api_key self.need_api_key = True self._refresh_header() def get_answer_stream_iter(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response(stream=True) if response is not None: iter = self._decode_chat_response(response) partial_text = "" for i in iter: partial_text += i yield partial_text else: yield STANDARD_ERROR_MSG + GENERAL_ERROR_MSG def get_answer_at_once(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response() response = json.loads(response.text) content = response["choices"][0]["message"]["content"] total_token_count = response["usage"]["total_tokens"] return content, total_token_count def count_token(self, user_input): input_token_count = count_token(construct_user(user_input)) if self.system_prompt is not None and len(self.all_token_counts) == 0: system_prompt_token_count = count_token( construct_system(self.system_prompt) ) return input_token_count + system_prompt_token_count return input_token_count def billing_info(self): try: curr_time = datetime.datetime.now() last_day_of_month = get_last_day_of_month( curr_time).strftime("%Y-%m-%d") first_day_of_month = curr_time.replace(day=1).strftime("%Y-%m-%d") usage_url = f"{shared.state.usage_api_url}?start_date={first_day_of_month}&end_date={last_day_of_month}" try: usage_data = self._get_billing_data(usage_url) except Exception as e: logger.warning(f"获取API使用情况失败:" + str(e)) return i18n("**获取API使用情况失败**") rounded_usage = "{:.5f}".format(usage_data["total_usage"] / 100) return i18n("**本月使用金额** ") + f"\u3000 ${rounded_usage}" except requests.exceptions.ConnectTimeout: status_text = ( STANDARD_ERROR_MSG + CONNECTION_TIMEOUT_MSG + ERROR_RETRIEVE_MSG ) return status_text except requests.exceptions.ReadTimeout: status_text = STANDARD_ERROR_MSG + READ_TIMEOUT_MSG + ERROR_RETRIEVE_MSG return status_text except Exception as e: traceback.print_exc() logger.error(i18n("获取API使用情况失败:") + str(e)) return STANDARD_ERROR_MSG + ERROR_RETRIEVE_MSG def set_token_upper_limit(self, new_upper_limit): pass @shared.state.switching_api_key # 在不开启多账号模式的时候,这个装饰器不会起作用 def _get_response(self, stream=False): openai_api_key = self.api_key system_prompt = self.system_prompt history = self.history logger.debug(f"{history}") headers = { "Authorization": f"Bearer {openai_api_key}", "Content-Type": "application/json", } if system_prompt is not None: history = [construct_system(system_prompt), *history] payload = { "model": self.model_name, "messages": history, "temperature": self.temperature, "top_p": self.top_p, "n": self.n_choices, "stream": stream, "presence_penalty": self.presence_penalty, "frequency_penalty": self.frequency_penalty, } if self.max_generation_token is not None: payload["max_tokens"] = self.max_generation_token if self.stop_sequence is not None: payload["stop"] = self.stop_sequence if self.logit_bias is not None: payload["logit_bias"] = self.logit_bias if self.user_identifier is not None: payload["user"] = self.user_identifier if stream: timeout = TIMEOUT_STREAMING else: timeout = TIMEOUT_ALL # 如果有自定义的api-host,使用自定义host发送请求,否则使用默认设置发送请求 if shared.state.chat_completion_url != CHAT_COMPLETION_URL: logger.debug(f"使用自定义API URL: {shared.state.chat_completion_url}")
with config.retrieve_proxy():
1
2023-12-27 12:14:26+00:00
16k
camenduru/AnyDoor-online-hf
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n ...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import itertools import torch.nn.functional as F from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from omegaconf import ListConfig from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler
12,309
else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim: ddim_sampler = DDIMSampler(self) shape = (self.channels, self.image_size, self.image_size) samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs) return samples, intermediates @torch.no_grad() def get_unconditional_conditioning(self, batch_size, null_label=None): if null_label is not None: xc = null_label if isinstance(xc, ListConfig): xc = list(xc) if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: if hasattr(xc, "to"): xc = xc.to(self.device) c = self.get_learned_conditioning(xc) else: if self.cond_stage_key in ["class_label", "cls"]: xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device) return self.get_learned_conditioning(xc) else: raise NotImplementedError("todo") if isinstance(c, list): # in case the encoder gives us a list for i in range(len(c)): c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device) else: c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device) return c @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True, **kwargs): ema_scope = self.ema_scope if use_ema_scope else nullcontext use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption", "txt"]:
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if reset_ema: assert exists(ckpt_path) if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) if reset_ema: assert self.use_ema print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) else: self.register_buffer('logvar', logvar) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) elif self.parameterization == "v": lvlb_weights = torch.ones_like(self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))) else: raise NotImplementedError("mu not supported") lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") @torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] if self.make_it_fit: n_params = len([name for name, _ in itertools.chain(self.named_parameters(), self.named_buffers())]) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys:\n {missing}") if len(unexpected) > 0: print(f"\nUnexpected Keys:\n {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def predict_start_from_z_and_v(self, x_t, t, v): # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def predict_eps_from_z_and_v(self, x_t, t, v): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_v(self, x, noise, t): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x ) def get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): for k in self.ucg_training: p = self.ucg_training[k]["p"] val = self.ucg_training[k]["val"] if val is None: val = "" for i in range(len(batch[k])): if self.ucg_prng.choice(2, p=[1 - p, p]): batch[k][i] = val loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, force_null_conditioning=False, *args, **kwargs): self.force_null_conditioning = force_null_conditioning self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning: conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) reset_ema = kwargs.pop("reset_ema", False) reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True if reset_ema: assert self.use_ema print( f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() def make_cond_schedule(self, ): self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx, dataloader_idx): # only for very first batch if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt: assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously' # set rescale weight to 1./std of encodings print("### USING STD-RESCALING ###") x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer('scale_factor', 1. / z.flatten().std()) print(f"setting self.scale_factor to {self.scale_factor}") print("### USING STD-RESCALING ###") def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append(self.decode_first_stage(zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented") return self.scale_factor * z def get_learned_conditioning(self, c): #c 1,3,224,224 if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): #1,1,1024 c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip(L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"]) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, return_x=False): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None and not self.force_null_conditioning: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox', "txt"]: xc = batch[cond_key] elif cond_key in ['class_label', 'cls']: xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_x: out.extend([x]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c) return loss def forward(self, x, c, *args, **kwargs): #t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() t = self.time_steps.reshape( (x.shape[0],) ).to(self.device).long() if self.model.conditioning_key is not None: assert c is not None if self.cond_stage_trainable: c = self.get_learned_conditioning(c) if self.shorten_cond_schedule: # TODO: drop this option tc = self.cond_ids[t].to(self.device) c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) return self.p_losses(x, c, t, *args, **kwargs) def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is expected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, t, **cond) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0) return mean_flat(kl_prior) / np.log(2.0) def p_losses(self, x_start, cond, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_output = self.apply_model(x_noisy, t, cond) loss_dict = {} prefix = 'train' if self.training else 'val' if self.parameterization == "x0": target = x_start elif self.parameterization == "eps": target = noise elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError() loss_simple = self.get_loss(model_output, target, mean=False) #boundary = self.boundary.to(loss_simple.device) #boundary = F.interpolate(boundary, size = (64,64)) * 5 + 1.0 #16,1,64,64 #print(loss_simple.shape) #16,4,64,64 loss_simple = loss_simple.mean([1, 2, 3]) #.mean([1, 2, 3]) loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()}) logvar_t = self.logvar[t].to(self.device) loss = loss_simple / torch.exp(logvar_t) + logvar_t # loss = loss_simple / torch.exp(self.logvar) + self.logvar if self.learn_logvar: loss_dict.update({f'{prefix}/loss_gamma': loss.mean()}) loss_dict.update({'logvar': self.logvar.data.mean()}) loss = self.l_simple_weight * loss.mean() loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3)) loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean() loss_dict.update({f'{prefix}/loss_vlb': loss_vlb}) loss += (self.original_elbo_weight * loss_vlb) loss_dict.update({f'{prefix}/loss': loss}) #print(self.parameterization, self.learn_logvar, self.original_elbo_weight, self.lvlb_weights[t]) return loss, loss_dict def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False, return_x0=False, score_corrector=None, corrector_kwargs=None): t_in = t model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) if score_corrector is not None: assert self.parameterization == "eps" model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs) if return_codebook_ids: model_out, logits = model_out if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out else: raise NotImplementedError() if clip_denoised: x_recon.clamp_(-1., 1.) if quantize_denoised: x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) if return_codebook_ids: return model_mean, posterior_variance, posterior_log_variance, logits elif return_x0: return model_mean, posterior_variance, posterior_log_variance, x_recon else: return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_codebook_ids=False, quantize_denoised=False, return_x0=False, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): b, *_, device = *x.shape, x.device outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_codebook_ids=return_codebook_ids, quantize_denoised=quantize_denoised, return_x0=return_x0, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if return_codebook_ids: raise DeprecationWarning("Support dropped.") model_mean, _, model_log_variance, logits = outputs elif return_x0: model_mean, _, model_log_variance, x0 = outputs else: model_mean, _, model_log_variance = outputs noise = noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) if return_codebook_ids: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1) if return_x0: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0 else: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False, img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t timesteps = self.num_timesteps if batch_size is not None: b = batch_size if batch_size is not None else shape[0] shape = [batch_size] + list(shape) else: b = batch_size = shape[0] if x_T is None: img = torch.randn(shape, device=self.device) else: img = x_T intermediates = [] if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation', total=timesteps) if verbose else reversed( range(0, timesteps)) if type(temperature) == float: temperature = [temperature] * timesteps for i in iterator: ts = torch.full((b,), i, device=self.device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img, x0_partial = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, return_x0=True, temperature=temperature[i], noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if mask is not None: assert x0 is not None img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(x0_partial) if callback: callback(i) if img_callback: img_callback(img, i) return img, intermediates @torch.no_grad() def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t device = self.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim: ddim_sampler = DDIMSampler(self) shape = (self.channels, self.image_size, self.image_size) samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs) return samples, intermediates @torch.no_grad() def get_unconditional_conditioning(self, batch_size, null_label=None): if null_label is not None: xc = null_label if isinstance(xc, ListConfig): xc = list(xc) if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: if hasattr(xc, "to"): xc = xc.to(self.device) c = self.get_learned_conditioning(xc) else: if self.cond_stage_key in ["class_label", "cls"]: xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device) return self.get_learned_conditioning(xc) else: raise NotImplementedError("todo") if isinstance(c, list): # in case the encoder gives us a list for i in range(len(c)): c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device) else: c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device) return c @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True, **kwargs): ema_scope = self.ema_scope if use_ema_scope else nullcontext use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption", "txt"]:
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
0
2023-12-25 04:48:34+00:00
16k
smonsays/modular-hyperteacher
metax/data/imitation.py
[ { "identifier": "Environment", "path": "metax/data/envs/base.py", "snippet": "class Environment(abc.ABC):\n @abc.abstractproperty\n def num_actions(self) -> int:\n \"\"\" Number of possible actions.\"\"\"\n\n @abc.abstractproperty\n def observation_shape(self):\n \"\"\"The shap...
from functools import partial from typing import Optional from chex import PRNGKey from metax.data.envs.base import Environment from metax.data.envs.grid import CompositionalGrid from metax.data.envs.preference import CompositionalPreference from .base import Dataloader, MetaDataset, MultitaskDataset import jax import jax.numpy as jnp import jax.tree_util as jtu
11,048
""" Copyright (c) Simon Schug All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class ImitationMetaDataloader(Dataloader): def __init__( self, env: Environment, num_tasks: int, shots_train: int, shots_test: int, meta_batch_size: int, mode: str, train_test_split: bool, rng: PRNGKey, ): super().__init__(input_shape=env.observation_shape, output_dim=env.num_actions) self.env = env self.num_tasks = num_tasks self.shots_train = shots_train self.shots_test = shots_test self.meta_batch_size = meta_batch_size self.mode = mode self.train_test_split = train_test_split self.fixed_rng = rng assert num_tasks % meta_batch_size == 0, "num_tasks must be divisible by meta_batch_size" self.num_steps = num_tasks // meta_batch_size @property def sample_input(self): return jnp.zeros((1,) + self.env.observation_shape) def __len__(self): return self.num_steps def __iter__(self): for rng in jax.random.split(self.fixed_rng, self.num_steps): # Sample batch and wrap as MetaDataset rngs_batch = jax.random.split(rng, self.meta_batch_size) yield self.sample_metatask(rngs_batch) @partial(jax.jit, static_argnames="self") @partial(jax.vmap, in_axes=(None, 0)) def sample_metatask(self, rng: PRNGKey) -> MetaDataset: rng_goal, rng_task = jax.random.split(rng, 2) goal, info = self.env.reset_goal(rng_goal, mode=self.mode) @jax.vmap def sample_task(rng): rng_reset, rng_demo = jax.random.split(rng, 2) env_state, _ = self.env.reset(rng_reset, goal=goal) trajectory, actions = self.env.demonstrate(rng_demo, env_state) return MultitaskDataset( x=trajectory.observation, y=actions, task_id=jnp.full(actions.shape[:1], info["task_id"]), info={ "mask": ~trajectory.done, "embeddings": jnp.repeat(info["embedding"][None, :], actions.shape[0], axis=0), }, ) rngs_task = jax.random.split(rng_task, self.shots_train + self.shots_test) train_and_test_task = sample_task(rngs_task) if self.train_test_split: # Split into train and test set return MetaDataset( train=jtu.tree_map( lambda x: x[:self.shots_train].reshape(-1, *x.shape[2:]), train_and_test_task ), test=jtu.tree_map( lambda x: x[self.shots_train:].reshape(-1, *x.shape[2:]), train_and_test_task ), ) else: # No train_test split means, meta.train == meta.test set return MetaDataset( train=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), test=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), ) def create_imitation_metaloader( name, meta_batch_size, shots_train, shots_test, train_test_split, num_tasks_train, num_tasks_test, num_tasks_valid, num_tasks_ood: Optional[int] = None, seed=None, **kwargs, ): ood_sets_hot = None if name == "compositional_grid":
""" Copyright (c) Simon Schug All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class ImitationMetaDataloader(Dataloader): def __init__( self, env: Environment, num_tasks: int, shots_train: int, shots_test: int, meta_batch_size: int, mode: str, train_test_split: bool, rng: PRNGKey, ): super().__init__(input_shape=env.observation_shape, output_dim=env.num_actions) self.env = env self.num_tasks = num_tasks self.shots_train = shots_train self.shots_test = shots_test self.meta_batch_size = meta_batch_size self.mode = mode self.train_test_split = train_test_split self.fixed_rng = rng assert num_tasks % meta_batch_size == 0, "num_tasks must be divisible by meta_batch_size" self.num_steps = num_tasks // meta_batch_size @property def sample_input(self): return jnp.zeros((1,) + self.env.observation_shape) def __len__(self): return self.num_steps def __iter__(self): for rng in jax.random.split(self.fixed_rng, self.num_steps): # Sample batch and wrap as MetaDataset rngs_batch = jax.random.split(rng, self.meta_batch_size) yield self.sample_metatask(rngs_batch) @partial(jax.jit, static_argnames="self") @partial(jax.vmap, in_axes=(None, 0)) def sample_metatask(self, rng: PRNGKey) -> MetaDataset: rng_goal, rng_task = jax.random.split(rng, 2) goal, info = self.env.reset_goal(rng_goal, mode=self.mode) @jax.vmap def sample_task(rng): rng_reset, rng_demo = jax.random.split(rng, 2) env_state, _ = self.env.reset(rng_reset, goal=goal) trajectory, actions = self.env.demonstrate(rng_demo, env_state) return MultitaskDataset( x=trajectory.observation, y=actions, task_id=jnp.full(actions.shape[:1], info["task_id"]), info={ "mask": ~trajectory.done, "embeddings": jnp.repeat(info["embedding"][None, :], actions.shape[0], axis=0), }, ) rngs_task = jax.random.split(rng_task, self.shots_train + self.shots_test) train_and_test_task = sample_task(rngs_task) if self.train_test_split: # Split into train and test set return MetaDataset( train=jtu.tree_map( lambda x: x[:self.shots_train].reshape(-1, *x.shape[2:]), train_and_test_task ), test=jtu.tree_map( lambda x: x[self.shots_train:].reshape(-1, *x.shape[2:]), train_and_test_task ), ) else: # No train_test split means, meta.train == meta.test set return MetaDataset( train=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), test=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), ) def create_imitation_metaloader( name, meta_batch_size, shots_train, shots_test, train_test_split, num_tasks_train, num_tasks_test, num_tasks_valid, num_tasks_ood: Optional[int] = None, seed=None, **kwargs, ): ood_sets_hot = None if name == "compositional_grid":
env = CompositionalGrid(
1
2023-12-22 16:35:49+00:00
16k
AContesini/Convert_PDF_to_DOCX_or_vice-versa
venv/Lib/site-packages/tqdm/cli.py
[ { "identifier": "TqdmKeyError", "path": "venv/Lib/site-packages/tqdm/std.py", "snippet": "class TqdmKeyError(KeyError):\n pass" }, { "identifier": "TqdmTypeError", "path": "venv/Lib/site-packages/tqdm/std.py", "snippet": "class TqdmTypeError(TypeError):\n pass" }, { "identi...
import logging import re import sys from ast import literal_eval as numeric from .std import TqdmKeyError, TqdmTypeError, tqdm from .version import __version__ from importlib import resources from os import path from shutil import copyfile
13,763
fout : binary file with `write` (and optionally `flush`) methods. callback : function(float), e.g.: `tqdm.update` callback_len : If (default: True) do `callback(len(buffer))`. Otherwise, do `callback(data) for data in buffer.split(delim)`. """ fp_write = fout.write if not delim: while True: tmp = fin.read(buf_size) # flush at EOF if not tmp: getattr(fout, 'flush', lambda: None)() return fp_write(tmp) callback(len(tmp)) # return buf = b'' len_delim = len(delim) # n = 0 while True: tmp = fin.read(buf_size) # flush at EOF if not tmp: if buf: fp_write(buf) if callback_len: # n += 1 + buf.count(delim) callback(1 + buf.count(delim)) else: for i in buf.split(delim): callback(i) getattr(fout, 'flush', lambda: None)() return # n while True: i = tmp.find(delim) if i < 0: buf += tmp break fp_write(buf + tmp[:i + len(delim)]) # n += 1 callback(1 if callback_len else (buf + tmp[:i])) buf = b'' tmp = tmp[i + len_delim:] # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file') # The 8 leading spaces are required for consistency CLI_EXTRA_DOC = r""" Extra CLI Options ----------------- name : type, optional TODO: find out why this is needed. delim : chr, optional Delimiting character [default: '\n']. Use '\0' for null. N.B.: on Windows systems, Python converts '\n' to '\r\n'. buf_size : int, optional String buffer size in bytes [default: 256] used when `delim` is specified. bytes : bool, optional If true, will count bytes, ignore `delim`, and default `unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'. tee : bool, optional If true, passes `stdin` to both `stderr` and `stdout`. update : bool, optional If true, will treat input as newly elapsed iterations, i.e. numbers to pass to `update()`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. update_to : bool, optional If true, will treat input as total elapsed iterations, i.e. numbers to assign to `self.n`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. null : bool, optional If true, will discard input (no stdout). manpath : str, optional Directory in which to install tqdm man pages. comppath : str, optional Directory in which to place tqdm completion. log : str, optional CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET. """ def main(fp=sys.stderr, argv=None): """ Parameters (internal use only) --------- fp : file-like object for tqdm argv : list (default: sys.argv[1:]) """ if argv is None: argv = sys.argv[1:] try: log_idx = argv.index('--log') except ValueError: for i in argv: if i.startswith('--log='): logLevel = i[len('--log='):] break else: logLevel = 'INFO' else: # argv.pop(log_idx) # logLevel = argv.pop(log_idx) logLevel = argv[log_idx + 1] logging.basicConfig(level=getattr(logging, logLevel), format="%(levelname)s:%(module)s:%(lineno)d:%(message)s")
""" Module version for monitoring CLI pipes (`... | python -m tqdm | ...`). """ __all__ = ["main"] log = logging.getLogger(__name__) def cast(val, typ): log.debug((val, typ)) if " or " in typ: for t in typ.split(" or "): try: return cast(val, t) except TqdmTypeError: pass raise TqdmTypeError(val + ' : ' + typ) # sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n') if typ == 'bool': if (val == 'True') or (val == ''): return True elif val == 'False': return False else: raise TqdmTypeError(val + ' : ' + typ) try: return eval(typ + '("' + val + '")') except Exception: if typ == 'chr': return chr(ord(eval('"' + val + '"'))).encode() else: raise TqdmTypeError(val + ' : ' + typ) def posix_pipe(fin, fout, delim=b'\\n', buf_size=256, callback=lambda float: None, callback_len=True): """ Params ------ fin : binary file with `read(buf_size : int)` method fout : binary file with `write` (and optionally `flush`) methods. callback : function(float), e.g.: `tqdm.update` callback_len : If (default: True) do `callback(len(buffer))`. Otherwise, do `callback(data) for data in buffer.split(delim)`. """ fp_write = fout.write if not delim: while True: tmp = fin.read(buf_size) # flush at EOF if not tmp: getattr(fout, 'flush', lambda: None)() return fp_write(tmp) callback(len(tmp)) # return buf = b'' len_delim = len(delim) # n = 0 while True: tmp = fin.read(buf_size) # flush at EOF if not tmp: if buf: fp_write(buf) if callback_len: # n += 1 + buf.count(delim) callback(1 + buf.count(delim)) else: for i in buf.split(delim): callback(i) getattr(fout, 'flush', lambda: None)() return # n while True: i = tmp.find(delim) if i < 0: buf += tmp break fp_write(buf + tmp[:i + len(delim)]) # n += 1 callback(1 if callback_len else (buf + tmp[:i])) buf = b'' tmp = tmp[i + len_delim:] # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file') # The 8 leading spaces are required for consistency CLI_EXTRA_DOC = r""" Extra CLI Options ----------------- name : type, optional TODO: find out why this is needed. delim : chr, optional Delimiting character [default: '\n']. Use '\0' for null. N.B.: on Windows systems, Python converts '\n' to '\r\n'. buf_size : int, optional String buffer size in bytes [default: 256] used when `delim` is specified. bytes : bool, optional If true, will count bytes, ignore `delim`, and default `unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'. tee : bool, optional If true, passes `stdin` to both `stderr` and `stdout`. update : bool, optional If true, will treat input as newly elapsed iterations, i.e. numbers to pass to `update()`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. update_to : bool, optional If true, will treat input as total elapsed iterations, i.e. numbers to assign to `self.n`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. null : bool, optional If true, will discard input (no stdout). manpath : str, optional Directory in which to install tqdm man pages. comppath : str, optional Directory in which to place tqdm completion. log : str, optional CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET. """ def main(fp=sys.stderr, argv=None): """ Parameters (internal use only) --------- fp : file-like object for tqdm argv : list (default: sys.argv[1:]) """ if argv is None: argv = sys.argv[1:] try: log_idx = argv.index('--log') except ValueError: for i in argv: if i.startswith('--log='): logLevel = i[len('--log='):] break else: logLevel = 'INFO' else: # argv.pop(log_idx) # logLevel = argv.pop(log_idx) logLevel = argv[log_idx + 1] logging.basicConfig(level=getattr(logging, logLevel), format="%(levelname)s:%(module)s:%(lineno)d:%(message)s")
d = tqdm.__doc__ + CLI_EXTRA_DOC
2
2023-12-24 15:46:18+00:00
16k
pkariz/grin-explorer
backend/api/views.py
[ { "identifier": "fetch_and_store_block", "path": "backend/api/bootstrap.py", "snippet": "def fetch_and_store_block(blockchain, block_height, prefetch=True):\n # initialize node api\n node_api = NodeV2API(blockchain.node)\n if block_height < 0:\n # no such block height\n raise Node...
from asgiref.sync import async_to_sync from django.contrib.contenttypes.models import ContentType from django.db.models.deletion import ProtectedError from django.views.generic import TemplateView from django.views.decorators.cache import never_cache from dramatiq_abort import abort from rest_framework import status from rest_framework.exceptions import APIException from rest_framework.exceptions import NotFound from rest_framework.exceptions import ValidationError as DRFValidationError from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from slugify import slugify from .bootstrap import fetch_and_store_block, update_blockchain_progress from .exceptions import UpdateBlockchainProgressError from .helpers import get_filter_backends, load_data_from_redis from .filters import ( BlockFilter, CustomBlockSearchFilter, NodeFilter, NodeGroupFilter, ) from .mixins import CustomModelViewSet from .models import Blockchain, Block, Reorg, Node, NodeGroup, DramatiqTask from .serializers import ( BlockchainSerializer, BlockchainExtendedSerializer, BlockSerializer, BlockDetailSerializer, NodeSerializer, NodeGroupSerializer, DramatiqTaskSerializer, ) from .tasks import bootstrap_blockchain, delete_blockchain import channels import logging import pytz
10,998
# nothing to do, ignore the new block return Response(status=status.HTTP_404_NOT_FOUND) # get request data height = request.data['data']['header']['height'] hash = request.data['hash'] # prev_hash comes as list of int bytes, so we convert it to hex # NOTE: the same is true for some other data which we currently don't # need so we don't transform it, eg. data.header.kernel_root prev_hash = None if request.data['data']['header']['prev_hash']: prev_hash = bytes(request.data['data']['header']['prev_hash']).hex() logger.info( 'Block accepted', extra={ 'height': height, 'hash': hash, 'prev_hash': prev_hash, 'blockchain': blockchain.slug, }, ) web_socket_msg_type = 'send_block' # handle reorg case # we expect blocks to come ordered by height, there are some edge cases # here which are not handled, but they're unlikely to happen (eg. reorg # happens but websocket calls for first blocks fails while for later it # doesn't and then the code bellow wouldn't spot a reorg) block_at_this_height = blockchain.blocks\ .filter(height=height, reorg__isnull=True)\ .first() # we fetch here because anyone can call this view - we don't want to # work with fake data new_block = fetch_and_store_block(blockchain, height, prefetch=False) if block_at_this_height: if block_at_this_height.hash == new_block.hash: # probably have fetched this block while bootstraping, accepted # view got called a bit later so we already have it, noop return Response(status=status.HTTP_200_OK) logger.info( 'Block accepted - reorg spotted', extra={ 'block_at_this_height': block_at_this_height, 'block_at_this_height.hash': block_at_this_height.hash, 'block_at_this_height.reorg': block_at_this_height.reorg, 'hash': new_block.hash }, ) # reorg spotted reorged_blocks = list(blockchain.blocks\ .filter(height__gte=height, reorg__isnull=True) .exclude(pk=new_block.pk) .order_by('height')) logger.info('reorged_blocks at start: {}'.format(reorged_blocks)) # these reorged blocks are guaranteed to be reorged, now find any # previous blocks which were also reorged - aka get common # ancestor of the reorged block at 'height' and the new (main) block # find the common ancestor of this block and the reorged block at # the same height. We start with the current height to avoid more # logic for Reorg instance params if new_block.hash == block_at_this_height.hash: # at height X we got H1, then we got H2 (this call), but now it # reorged back to H1, so we don't do anything, no reorg is # stored since we didn't fetch the block in time from the node logger.info('Reorg cancelled out, noop') return Response(status=status.HTTP_200_OK) logger.info('new_block', extra={'hash': new_block.hash, 'prev_hash': new_block.prev_hash}) prev_block_new_chain = new_block prev_block_old_chain = reorged_blocks[0] logger.info('prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) # remove the first one since it will get added again reorged_blocks = reorged_blocks[1:] logger.info('reorged_blocks after [1:]: {}'.format(reorged_blocks)) main_blocks = [] while True: # theoretically we might be missing the block in db but we don't # cover such cases currently if not prev_block_new_chain: logger.info('reached break in IF NOT prev_block_new_chain') # this means that prev_block_old_chain is also None, since # they're both "previous" of their genesis block break if prev_block_new_chain == prev_block_old_chain: logger.info('reached break in IF NOT prev_block_new_chain == prev_block_old_chain') # found the common ancestor break # add to the left because we want to keep it sorted by height reorged_blocks.insert(0, prev_block_old_chain) main_blocks.insert(0, prev_block_new_chain) logger.info('new reorged_blocks: {}'.format(reorged_blocks)) logger.info('new main_blocks: {}'.format(main_blocks)) prev_block_new_chain = prev_block_new_chain.get_previous_block() prev_block_old_chain = prev_block_old_chain.get_previous_block() logger.info('new prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) logger.info('before reorg create: reorged_blocks: {}, main_blocks: {}'.format(reorged_blocks, main_blocks)) reorg = Reorg.objects.create( blockchain=blockchain, start_reorg_block=reorged_blocks[0], end_reorg_block=reorged_blocks[-1], start_main_block=main_blocks[0], ) # Reorg post_save signal fixes .reorg on new/old blocks and fixes # inputs/outputs web_socket_msg_type = 'reorged' web_socket_msg = BlockSerializer(new_block).data if web_socket_msg_type == 'reorged': web_socket_msg = blockchain.slug # TODO: check if channels-redis 4.x is fixed: https://github.com/django/channels_redis/issues/332 channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( 'default_group', { 'type': web_socket_msg_type, 'message': web_socket_msg, } ) # update the loading progress since it could be skewed due to the # periodic task updating it before this view has been called try:
logger = logging.getLogger(__name__) # Serve Vue Application index_view = never_cache(TemplateView.as_view(template_name='index.html')) class NodeGroupViewSet(CustomModelViewSet): """API endpoint for NodeGroup.""" queryset = NodeGroup.objects.all() filterset_class = NodeGroupFilter serializer_class = NodeGroupSerializer lookup_field = 'slug' permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): slug = request.data.get('slug') if not slug: request.data['slug'] = slugify(request.data['name'], to_lower=True) return super().create(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): try: return super().destroy(request, *args, **kwargs) except ProtectedError as e: raise DRFValidationError( detail='Node group is related to nodes, delete them first') class NodeViewSet(CustomModelViewSet): """API endpoint for Node.""" queryset = Node.objects.all() filterset_class = NodeFilter serializer_class = NodeSerializer # currently all node views require authentication permission_classes = [IsAuthenticated] lookup_field = 'slug' def create(self, request, *args, **kwargs): slug = request.data.get('slug') if not slug: request.data['slug'] = slugify(request.data['name'], to_lower=True) request.data['group'] = NodeGroup.objects.get(slug=request.data['group']).pk return super().create(request, *args, **kwargs) def update(self, request, *args, **kwargs): # NOTE: super().partial_update calls update(..., partial=True) if not kwargs.get('partial'): # we don't allow full updates - aka PUT raise DRFPermissionDenied() return super().update(request, *args, **kwargs) def partial_update(self, request, slug=None): request.data['group'] = NodeGroup.objects.get(slug=request.data['group']).pk return super().partial_update(request, slug=slug) @action(detail=True, methods=['get']) def reachable(self, request, slug=None): node = self.get_object() try: res = node.is_reachable() except Exception as e: logger.exception('Unreachable node') res = False return Response(res, status=status.HTTP_200_OK) def destroy(self, request, *args, **kwargs): try: return super().destroy(request, *args, **kwargs) except ProtectedError as e: raise DRFValidationError( detail='Node is related to blockchains, delete them first') class BlockchainViewSet(CustomModelViewSet): """API endpoint for Blockchain.""" queryset = Blockchain.objects.all() serializer_class = BlockchainSerializer lookup_field = 'slug' def get_serializer_class(self): # when authenticated we return also NodeSerializer data if self.request.user.is_authenticated: return BlockchainExtendedSerializer return BlockchainSerializer def create(self, request, *args, **kwargs): slug = request.data.get('slug') if not slug: request.data['slug'] = slugify(request.data['name'], to_lower=True) request.data['node'] = request.data['node'] return super().create(request, *args, **kwargs) def destroy(self, request, slug=None): instance = self.get_object() message = delete_blockchain.send(instance.slug) task = DramatiqTask.objects.create( type=DramatiqTask.Type.BLOCKCHAIN_DELETE, status=DramatiqTask.Status.IN_PROGRESS, message_id=message.message_id, content_object=instance, ) return Response( DramatiqTaskSerializer(task).data, status=status.HTTP_200_OK) def _abort_previous_tasks(self, blockchain): conflicting_message_ids = DramatiqTask.objects.filter( status=DramatiqTask.Status.IN_PROGRESS, object_id=blockchain.id, content_type=ContentType.objects.get_for_model(blockchain) ).values_list('message_id', flat=True) # abort previous conflicting tasks if they exist for conflicting_message_id in conflicting_message_ids: abort(conflicting_message_id) @action(detail=True, methods=['post']) def bootstrap(self, request, slug=None): blockchain = self.get_object() if not blockchain.node.is_reachable: raise APIException(detail='Node is unreachable') self._abort_previous_tasks(blockchain) # create a new task message = bootstrap_blockchain.send(blockchain.slug) task = DramatiqTask.objects.create( type=DramatiqTask.Type.BOOTSTRAP, status=DramatiqTask.Status.IN_PROGRESS, message_id=message.message_id, content_object=blockchain, ) return Response( DramatiqTaskSerializer(task).data, status=status.HTTP_200_OK) @action( detail=True, methods=['post'], url_path='bootstrap/abort', url_name='bootstrap-abort', ) def abort_bootstrap(self, request, slug=None): blockchain = self.get_object() self._abort_previous_tasks(blockchain) return Response(status=status.HTTP_200_OK) @action(detail=True, methods=['get']) def graphs(self, request, slug=None): """Returns data for all graphs.""" data = { 'transaction_graph': load_data_from_redis(f'tx_graph__{slug}'), } return Response(data=data, status=status.HTTP_200_OK) @action(detail=True, methods=['post']) def accepted(self, request, slug=None): # NOTE: if node is offline and then you start it again then it will # call this view for each block it will get. In this case there will be # many fast sequential calls to this view, there might be too many # postgres connections opened so view executions might actually fail. # The suggested solution is to comment out 'block_accepted_url' in # node's config file, run the node, wait for it to sync, uncomment # 'block_accepted_url' and then manually bootstrap it. blockchain = self.get_object() # check if new block has been receiver when this blockchain is in the # process of being deleted. deleting = DramatiqTask.objects.filter( type=DramatiqTask.Type.BLOCKCHAIN_DELETE, object_id=blockchain.id, content_type=ContentType.objects.get_for_model(blockchain) ).exists() if deleting: # nothing to do, ignore the new block return Response(status=status.HTTP_404_NOT_FOUND) # get request data height = request.data['data']['header']['height'] hash = request.data['hash'] # prev_hash comes as list of int bytes, so we convert it to hex # NOTE: the same is true for some other data which we currently don't # need so we don't transform it, eg. data.header.kernel_root prev_hash = None if request.data['data']['header']['prev_hash']: prev_hash = bytes(request.data['data']['header']['prev_hash']).hex() logger.info( 'Block accepted', extra={ 'height': height, 'hash': hash, 'prev_hash': prev_hash, 'blockchain': blockchain.slug, }, ) web_socket_msg_type = 'send_block' # handle reorg case # we expect blocks to come ordered by height, there are some edge cases # here which are not handled, but they're unlikely to happen (eg. reorg # happens but websocket calls for first blocks fails while for later it # doesn't and then the code bellow wouldn't spot a reorg) block_at_this_height = blockchain.blocks\ .filter(height=height, reorg__isnull=True)\ .first() # we fetch here because anyone can call this view - we don't want to # work with fake data new_block = fetch_and_store_block(blockchain, height, prefetch=False) if block_at_this_height: if block_at_this_height.hash == new_block.hash: # probably have fetched this block while bootstraping, accepted # view got called a bit later so we already have it, noop return Response(status=status.HTTP_200_OK) logger.info( 'Block accepted - reorg spotted', extra={ 'block_at_this_height': block_at_this_height, 'block_at_this_height.hash': block_at_this_height.hash, 'block_at_this_height.reorg': block_at_this_height.reorg, 'hash': new_block.hash }, ) # reorg spotted reorged_blocks = list(blockchain.blocks\ .filter(height__gte=height, reorg__isnull=True) .exclude(pk=new_block.pk) .order_by('height')) logger.info('reorged_blocks at start: {}'.format(reorged_blocks)) # these reorged blocks are guaranteed to be reorged, now find any # previous blocks which were also reorged - aka get common # ancestor of the reorged block at 'height' and the new (main) block # find the common ancestor of this block and the reorged block at # the same height. We start with the current height to avoid more # logic for Reorg instance params if new_block.hash == block_at_this_height.hash: # at height X we got H1, then we got H2 (this call), but now it # reorged back to H1, so we don't do anything, no reorg is # stored since we didn't fetch the block in time from the node logger.info('Reorg cancelled out, noop') return Response(status=status.HTTP_200_OK) logger.info('new_block', extra={'hash': new_block.hash, 'prev_hash': new_block.prev_hash}) prev_block_new_chain = new_block prev_block_old_chain = reorged_blocks[0] logger.info('prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) # remove the first one since it will get added again reorged_blocks = reorged_blocks[1:] logger.info('reorged_blocks after [1:]: {}'.format(reorged_blocks)) main_blocks = [] while True: # theoretically we might be missing the block in db but we don't # cover such cases currently if not prev_block_new_chain: logger.info('reached break in IF NOT prev_block_new_chain') # this means that prev_block_old_chain is also None, since # they're both "previous" of their genesis block break if prev_block_new_chain == prev_block_old_chain: logger.info('reached break in IF NOT prev_block_new_chain == prev_block_old_chain') # found the common ancestor break # add to the left because we want to keep it sorted by height reorged_blocks.insert(0, prev_block_old_chain) main_blocks.insert(0, prev_block_new_chain) logger.info('new reorged_blocks: {}'.format(reorged_blocks)) logger.info('new main_blocks: {}'.format(main_blocks)) prev_block_new_chain = prev_block_new_chain.get_previous_block() prev_block_old_chain = prev_block_old_chain.get_previous_block() logger.info('new prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) logger.info('before reorg create: reorged_blocks: {}, main_blocks: {}'.format(reorged_blocks, main_blocks)) reorg = Reorg.objects.create( blockchain=blockchain, start_reorg_block=reorged_blocks[0], end_reorg_block=reorged_blocks[-1], start_main_block=main_blocks[0], ) # Reorg post_save signal fixes .reorg on new/old blocks and fixes # inputs/outputs web_socket_msg_type = 'reorged' web_socket_msg = BlockSerializer(new_block).data if web_socket_msg_type == 'reorged': web_socket_msg = blockchain.slug # TODO: check if channels-redis 4.x is fixed: https://github.com/django/channels_redis/issues/332 channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( 'default_group', { 'type': web_socket_msg_type, 'message': web_socket_msg, } ) # update the loading progress since it could be skewed due to the # periodic task updating it before this view has been called try:
update_blockchain_progress(blockchain)
1
2023-12-24 22:15:11+00:00
16k
wuhy68/Parameter-Efficient-MoE
train_moe.py
[ { "identifier": "CamelidaeConfig", "path": "camelidae/configuration_camelidae.py", "snippet": "class CamelidaeConfig(PretrainedConfig):\n r\"\"\"\n This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA\n model according to the specifi...
import os import gc import json import math import random import copy import logging import torch import utils import bitsandbytes as bnb import transformers import warnings import transformers.integrations import transformers.modeling_utils from os.path import exists, join, isdir from copy import deepcopy from dataclasses import dataclass, field from typing import Dict, Optional, Sequence, Callable, List, Tuple, Union, Any from torch import nn from torch.utils.data import Dataset from transformers import Trainer, BitsAndBytesConfig, set_seed from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training from peft.tuners.lora import LoraLayer from camelidae.configuration_camelidae import CamelidaeConfig from camelidae.modeling_camelidae import LlamaForCausalLM from transformers_utils import ( get_keys_to_not_convert, _load_pretrained_model, )
11,078
labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ) class SavePeftModelCallback(transformers.TrainerCallback): def save_model(self, args, state, kwargs): # print('Saving PEFT checkpoint...') if state.best_model_checkpoint is not None: checkpoint_folder = os.path.join( state.best_model_checkpoint, "adapter_model" ) else: checkpoint_folder = os.path.join( args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}" ) peft_model_path = os.path.join(checkpoint_folder, "adapter_model") model = kwargs["model"] model.save_pretrained(peft_model_path) moe_state = {} for param_tensor in model.state_dict(): if "adapter" in param_tensor: moe_state.update({param_tensor: model.state_dict()[param_tensor]}) # if "adapter" in param_tensor or "norm" in param_tensor: # moe_state.update({param_tensor: model.state_dict()[param_tensor]}) moe_model_path = os.path.join(checkpoint_folder, "moe_model.bin") # print(moe_state.keys()) torch.save(moe_state, moe_model_path) pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin") if os.path.exists(pytorch_model_path): os.remove(pytorch_model_path) def on_save(self, args, state, control, **kwargs): self.save_model(args, state, kwargs) return control def on_train_end(self, args, state, control, **kwargs): def touch(fname, times=None): with open(fname, "a"): os.utime(fname, times) touch(join(args.output_dir, "completed")) self.save_model(args, state, kwargs) def make_supervised_data_module( tokenizer: transformers.PreTrainedTokenizer, data_args ) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = SupervisedDataset( tokenizer=tokenizer, data_path=data_args.data_path ) data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) return dict( train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator ) def find_all_linear_names(model, bits=4): cls = ( bnb.nn.Linear4bit if bits == 4 else (bnb.nn.Linear8bitLt if bits == 8 else torch.nn.Linear) ) lora_module_names = set() for name, module in model.named_modules(): if isinstance(module, cls): names = name.split(".") lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if "lm_head" in lora_module_names: # needed for 16-bit lora_module_names.remove("lm_head") return list(lora_module_names) def print_trainable_parameters(model): """ Prints the number of trainable parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): all_param += param.numel() if param.requires_grad: trainable_params += param.numel() print( f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}" ) def train(): parser = transformers.HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments) ) model_args, data_args, training_args = parser.parse_args_into_dataclasses() training_args.ddp_find_unused_parameters = False set_seed(42) model_config = CamelidaeConfig.from_pretrained(model_args.model_name_or_path) model_config.pretraining_tp = 1 ## without tensor parallelism rank # Camelidae Config model_config.moe_dtype = "bfloat16" model_config.lora_r = 64 model_config.lora_alpha = 16 model_config.adapter_dim = 64 model_config.topk = 2 model_config.moe_scaling = 1 model_config.num_experts = 8 model_config.output_router_logits = False # # Seq Length Extension # model_config.rope_scaling = { # "type": "dynamic", # "factor": 2, # }
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. warnings.filterwarnings("ignore") transformers.integrations.get_keys_to_not_convert = get_keys_to_not_convert transformers.modeling_utils.PreTrainedModel._load_pretrained_model = ( _load_pretrained_model ) IGNORE_INDEX = -100 DEFAULT_PAD_TOKEN = "[PAD]" @dataclass class ModelArguments: model_name_or_path: Optional[str] = field(default="facebook/opt-125m") @dataclass class DataArguments: data_path: str = field( default=None, metadata={"help": "Path to the training data."} ) @dataclass class TrainingArguments(transformers.TrainingArguments): report_to: str = field(default="none") cache_dir: Optional[str] = field(default=None) optim: str = field( default="paged_adamw_32bit" ) # "paged_lion_8bit", "paged_adamw_8bit", "paged_lion_32bit", "paged_adamw_32bit" lr_scheduler_type: str = field( default="constant_with_warmup" ) # "constant", "constant_with_warmup", "cosine", "cosine_with_restarts", "linear" model_max_length: int = field( default=2048, metadata={ "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)." }, ) def _tokenize_fn( strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer ) -> Dict: """Tokenize a list of strings.""" tokenized_list = [ tokenizer( text, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ) for text in strings ] input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list] input_ids_lens = labels_lens = [ tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list ] return dict( input_ids=input_ids, labels=labels, input_ids_lens=input_ids_lens, labels_lens=labels_lens, ) def preprocess( sources: Sequence[str], targets: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, ) -> Dict: """Preprocess the data by tokenizing.""" examples = [s + t for s, t in zip(sources, targets)] examples_tokenized, sources_tokenized = [ _tokenize_fn(strings, tokenizer) for strings in (examples, sources) ] input_ids = examples_tokenized["input_ids"] labels = copy.deepcopy(input_ids) for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]): label[:source_len] = IGNORE_INDEX return dict(input_ids=input_ids, labels=labels) class SupervisedDataset(Dataset): """Dataset for supervised fine-tuning.""" def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer): super(SupervisedDataset, self).__init__() logging.warning("Loading data: {}".format(data_path)) data_list = utils.jload(data_path) # Preprocess Data logging.warning("Processing data") self.tokenizer = tokenizer self.sources = [] self.targets = [] for idx in range(len(data_list)): data = data_list[idx] corpus = data["corpus"] if corpus != "": # pretrain mode source = f"{tokenizer.bos_token}" self.sources.append(source) target = f"{corpus}{tokenizer.eos_token}" self.targets.append(target) else: # instruction mode instruction = data["instruction"] conversation = data["conversation"] if len(conversation) == 1: if instruction == "": source = f"{tokenizer.bos_token}" else: source = f"{tokenizer.bos_token}### System:\n{instruction}\n" source += ( f"### Human:\n{conversation[0]['input']}\n### Assistant:\n" ) self.sources.append(source) target = f"{conversation[0]['output']}{tokenizer.eos_token}" self.targets.append(target) # else: # dialog mode del data_list gc.collect() # ## Debug Mode # self.sources = self.sources[:10000] # self.targets = self.targets[:10000] # logging.warning("Tokenizing inputs... This may take some time...") # data_dict = preprocess(sources, targets, tokenizer) # del sources, targets # gc.collect() # self.input_ids = data_dict["input_ids"] # self.labels = data_dict["labels"] # del data_dict # gc.collect() logging.warning("there are {} data in dataset".format(len(self.sources))) def __len__(self): return len(self.sources) def __getitem__(self, i): # return dict(input_ids=self.input_ids[i], labels=self.labels[i]) source = [self.sources[i]] target = [self.targets[i]] data_dict = preprocess(source, target, self.tokenizer) input_ids = data_dict["input_ids"][0] labels = data_dict["labels"][0] return dict(input_ids=input_ids, labels=labels) @dataclass class DataCollatorForSupervisedDataset(object): """Collate examples for supervised fine-tuning.""" tokenizer: transformers.PreTrainedTokenizer def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: input_ids, labels = tuple( [instance[key] for instance in instances] for key in ("input_ids", "labels") ) input_ids = torch.nn.utils.rnn.pad_sequence( input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id ) labels = torch.nn.utils.rnn.pad_sequence( labels, batch_first=True, padding_value=IGNORE_INDEX ) return dict( input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ) class SavePeftModelCallback(transformers.TrainerCallback): def save_model(self, args, state, kwargs): # print('Saving PEFT checkpoint...') if state.best_model_checkpoint is not None: checkpoint_folder = os.path.join( state.best_model_checkpoint, "adapter_model" ) else: checkpoint_folder = os.path.join( args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}" ) peft_model_path = os.path.join(checkpoint_folder, "adapter_model") model = kwargs["model"] model.save_pretrained(peft_model_path) moe_state = {} for param_tensor in model.state_dict(): if "adapter" in param_tensor: moe_state.update({param_tensor: model.state_dict()[param_tensor]}) # if "adapter" in param_tensor or "norm" in param_tensor: # moe_state.update({param_tensor: model.state_dict()[param_tensor]}) moe_model_path = os.path.join(checkpoint_folder, "moe_model.bin") # print(moe_state.keys()) torch.save(moe_state, moe_model_path) pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin") if os.path.exists(pytorch_model_path): os.remove(pytorch_model_path) def on_save(self, args, state, control, **kwargs): self.save_model(args, state, kwargs) return control def on_train_end(self, args, state, control, **kwargs): def touch(fname, times=None): with open(fname, "a"): os.utime(fname, times) touch(join(args.output_dir, "completed")) self.save_model(args, state, kwargs) def make_supervised_data_module( tokenizer: transformers.PreTrainedTokenizer, data_args ) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = SupervisedDataset( tokenizer=tokenizer, data_path=data_args.data_path ) data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) return dict( train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator ) def find_all_linear_names(model, bits=4): cls = ( bnb.nn.Linear4bit if bits == 4 else (bnb.nn.Linear8bitLt if bits == 8 else torch.nn.Linear) ) lora_module_names = set() for name, module in model.named_modules(): if isinstance(module, cls): names = name.split(".") lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if "lm_head" in lora_module_names: # needed for 16-bit lora_module_names.remove("lm_head") return list(lora_module_names) def print_trainable_parameters(model): """ Prints the number of trainable parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): all_param += param.numel() if param.requires_grad: trainable_params += param.numel() print( f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}" ) def train(): parser = transformers.HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments) ) model_args, data_args, training_args = parser.parse_args_into_dataclasses() training_args.ddp_find_unused_parameters = False set_seed(42) model_config = CamelidaeConfig.from_pretrained(model_args.model_name_or_path) model_config.pretraining_tp = 1 ## without tensor parallelism rank # Camelidae Config model_config.moe_dtype = "bfloat16" model_config.lora_r = 64 model_config.lora_alpha = 16 model_config.adapter_dim = 64 model_config.topk = 2 model_config.moe_scaling = 1 model_config.num_experts = 8 model_config.output_router_logits = False # # Seq Length Extension # model_config.rope_scaling = { # "type": "dynamic", # "factor": 2, # }
model = LlamaForCausalLM.from_pretrained(
1
2023-12-22 02:54:29+00:00
16k
lchen1019/Image_Cropper
ISAT/widgets/mainwindow.py
[ { "identifier": "Ui_MainWindow", "path": "ISAT/ui/MainWindow.py", "snippet": "class Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(1280, 764)\n MainWindow.setMinimumSize(QtCore.QSize(800, 600))\n font ...
from PyQt5 import QtWidgets, QtCore, QtGui from ISAT.ui.MainWindow import Ui_MainWindow from ISAT.widgets.files_dock_widget import FilesDockWidget from ISAT.widgets.canvas import AnnotationScene, AnnotationView from ISAT.configs import STATUSMode, MAPMode, load_config, save_config, CONFIG_FILE, DEFAULT_CONFIG_FILE, CHECKPOINT_PATH, ISAT_ROOT from ISAT.annotation import Object, Annotation from ISAT.widgets.polygon import Polygon, PromptPoint from ISAT.widgets.converter_dialog import ConverterDialog from PIL import Image from PyQt5.QtCore import QThread, pyqtSignal import os import json import functools import imgviz import ISAT.icons_rc import numpy as np import cv2 # 调整图像饱和度
13,407
self.png_palette = None # 图像拥有调色盘,说明是单通道的标注png文件 self.instance_cmap = imgviz.label_colormap() # 标注目标 self.current_label:Annotation = None # 新增 手动/自动 group选择 self.group_select_mode = 'auto' # 所有labels self.rects = [] self.is_show_bitmap = False self.init_ui() self.init_connect() self.reset_action() def init_ui(self): #q self.files_dock_widget = FilesDockWidget(mainwindow=self) self.files_dock.setWidget(self.files_dock_widget) # 新增 group 选择 快捷键 self.next_group_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("Tab"), self) self.prev_group_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("`"), self) self.next_group_shortcut.setContext(QtCore.Qt.ApplicationShortcut) self.prev_group_shortcut.setContext(QtCore.Qt.ApplicationShortcut) self.scene = AnnotationScene(mainwindow=self) self.view = AnnotationView(parent=self) self.view.setScene(self.scene) self.setCentralWidget(self.view) self.labelCoord = QtWidgets.QLabel('') self.labelCoord.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight) self.labelCoord.setFixedWidth(150) self.statusbar.addPermanentWidget(self.labelCoord) self.labelData = QtWidgets.QLabel('') self.labelData.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight) self.labelData.setFixedWidth(150) self.statusbar.addPermanentWidget(self.labelData) self.trans = QtCore.QTranslator() self.Converter_dialog = ConverterDialog(self, mainwindow=self) def set_saved_state(self, is_saved:bool): self.saved = is_saved if self.files_list is not None and self.current_index is not None: if is_saved: self.setWindowTitle(self.current_label.label_path) else: self.setWindowTitle('*{}'.format(self.current_label.label_path)) def open_dir(self): dir = QtWidgets.QFileDialog.getExistingDirectory(self) if not dir: return self.files_list.clear() self.files_dock_widget.listWidget.clear() files = [] suffixs = tuple(['{}'.format(fmt.data().decode('ascii').lower()) for fmt in QtGui.QImageReader.supportedImageFormats()]) for f in os.listdir(dir): if f.lower().endswith(suffixs): # f = os.path.join(dir, f) files.append(f) files = sorted(files) self.files_list = files self.files_dock_widget.update_widget() self.current_index = 0 self.image_root = dir self.actionOpen_dir.setStatusTip("Image root: {}".format(self.image_root)) if self.label_root is None: self.label_root = dir self.actionSave_dir.setStatusTip("Label root: {}".format(self.label_root)) # load setting yaml if os.path.exists(os.path.join(dir, 'isat.yaml')): self.config_file = os.path.join(dir, 'isat.yaml') self.show_image(self.current_index) def save_dir(self): dir = QtWidgets.QFileDialog.getExistingDirectory(self) if not dir: return self.label_root = dir self.actionSave_dir.setStatusTip("Label root: {}".format(self.label_root)) # load setting yaml if os.path.exists(os.path.join(dir, 'isat.yaml')): self.config_file = os.path.join(dir, 'isat.yaml') self.reload_cfg() # 刷新图片 if self.current_index is not None: self.show_image(self.current_index) def save(self): print('save') print(self.rects) save_name = self.files_list[self.current_index].split('.')[0] + '.json' save_path = os.path.join(self.label_root, save_name) # 保存json文件 self.rects print(save_path) with open(save_path, 'w') as file: json.dump(self.rects, file) # 保存所有的矩形
# -*- coding: utf-8 -*- # @Author : LG class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.image_root: str = None self.label_root:str = None self.files_list: list = [] self.current_index = None self.current_file_index: int = None self.current_group = 1 self.config_file = CONFIG_FILE if os.path.exists(CONFIG_FILE) else DEFAULT_CONFIG_FILE self.saved = True self.can_be_annotated = True self.load_finished = False self.png_palette = None # 图像拥有调色盘,说明是单通道的标注png文件 self.instance_cmap = imgviz.label_colormap() # 标注目标 self.current_label:Annotation = None # 新增 手动/自动 group选择 self.group_select_mode = 'auto' # 所有labels self.rects = [] self.is_show_bitmap = False self.init_ui() self.init_connect() self.reset_action() def init_ui(self): #q self.files_dock_widget = FilesDockWidget(mainwindow=self) self.files_dock.setWidget(self.files_dock_widget) # 新增 group 选择 快捷键 self.next_group_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("Tab"), self) self.prev_group_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("`"), self) self.next_group_shortcut.setContext(QtCore.Qt.ApplicationShortcut) self.prev_group_shortcut.setContext(QtCore.Qt.ApplicationShortcut) self.scene = AnnotationScene(mainwindow=self) self.view = AnnotationView(parent=self) self.view.setScene(self.scene) self.setCentralWidget(self.view) self.labelCoord = QtWidgets.QLabel('') self.labelCoord.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight) self.labelCoord.setFixedWidth(150) self.statusbar.addPermanentWidget(self.labelCoord) self.labelData = QtWidgets.QLabel('') self.labelData.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight) self.labelData.setFixedWidth(150) self.statusbar.addPermanentWidget(self.labelData) self.trans = QtCore.QTranslator() self.Converter_dialog = ConverterDialog(self, mainwindow=self) def set_saved_state(self, is_saved:bool): self.saved = is_saved if self.files_list is not None and self.current_index is not None: if is_saved: self.setWindowTitle(self.current_label.label_path) else: self.setWindowTitle('*{}'.format(self.current_label.label_path)) def open_dir(self): dir = QtWidgets.QFileDialog.getExistingDirectory(self) if not dir: return self.files_list.clear() self.files_dock_widget.listWidget.clear() files = [] suffixs = tuple(['{}'.format(fmt.data().decode('ascii').lower()) for fmt in QtGui.QImageReader.supportedImageFormats()]) for f in os.listdir(dir): if f.lower().endswith(suffixs): # f = os.path.join(dir, f) files.append(f) files = sorted(files) self.files_list = files self.files_dock_widget.update_widget() self.current_index = 0 self.image_root = dir self.actionOpen_dir.setStatusTip("Image root: {}".format(self.image_root)) if self.label_root is None: self.label_root = dir self.actionSave_dir.setStatusTip("Label root: {}".format(self.label_root)) # load setting yaml if os.path.exists(os.path.join(dir, 'isat.yaml')): self.config_file = os.path.join(dir, 'isat.yaml') self.show_image(self.current_index) def save_dir(self): dir = QtWidgets.QFileDialog.getExistingDirectory(self) if not dir: return self.label_root = dir self.actionSave_dir.setStatusTip("Label root: {}".format(self.label_root)) # load setting yaml if os.path.exists(os.path.join(dir, 'isat.yaml')): self.config_file = os.path.join(dir, 'isat.yaml') self.reload_cfg() # 刷新图片 if self.current_index is not None: self.show_image(self.current_index) def save(self): print('save') print(self.rects) save_name = self.files_list[self.current_index].split('.')[0] + '.json' save_path = os.path.join(self.label_root, save_name) # 保存json文件 self.rects print(save_path) with open(save_path, 'w') as file: json.dump(self.rects, file) # 保存所有的矩形
if self.scene.mode != STATUSMode.VIEW:
4
2023-12-24 16:19:16+00:00
16k
khabbazan/Mattermost-Subscriptions
helpers/channels_graphql_ws/subscription.py
[ { "identifier": "GraphqlWsConsumer", "path": "helpers/channels_graphql_ws/graphql_ws_consumer.py", "snippet": "class GraphqlWsConsumer(ch_websocket.AsyncJsonWebsocketConsumer):\n \"\"\"Channels consumer for the WebSocket GraphQL backend.\n\n NOTE: Each instance of this class maintains one WebSocke...
import asyncio import collections import hashlib import logging import asgiref.sync import channels.db import channels.layers import graphene import graphene.types.objecttype import graphene.types.utils import graphene.utils.get_unbound_function import graphene.utils.props from typing import Optional from .graphql_ws_consumer import GraphqlWsConsumer from .serializer import Serializer
13,467
return cls.unsubscribe_sync(group=group) @classmethod async def unsubscribe_async(cls, *, group=None): """Unsubscribe, asynchronous version.""" # Send the 'unsubscribe' message to the Channels group. group = cls._group_name(group) await cls._channel_layer().group_send(group=group, message={"type": "unsubscribe", "group": group}) @classmethod def unsubscribe_sync(cls, *, group=None): """Unsubscribe, synchronous version.""" # Send the message to the Channels group. group = cls._group_name(group) sync_channel_layer_group_send = asgiref.sync.async_to_sync(cls._channel_layer().group_send) sync_channel_layer_group_send( group=group, message={ "type": "unsubscribe", "group": group, }, ) @classmethod def Field(cls, name=None, description=None, deprecation_reason=None, required=False): # noqa """Represent subscription as a field to mount it to the schema. Typical usage: class Subscription(graphene.ObjectType): on_new_chat_message = OnNewChatMessage.Field() """ return graphene.Field( cls._meta.output, args=cls._meta.arguments, resolver=cls._meta.publish, name=name, description=description, deprecation_reason=deprecation_reason, required=required, ) # ------------------------------------------------------------------- IMPLEMENTATION @classmethod def __init_subclass_with_meta__( cls, subscribe=None, publish=None, unsubscribed=None, output=None, arguments=None, _meta=None, **options, ): # pylint: disable=arguments-renamed """Prepare subscription on subclass creation. This method is invoked by the superclass `__init__subclass__`. It is needed to process class fields, `Meta` and inheritance parameters. This is genuine Graphene approach inherited/cloned from the original Mutation class implementation. """ if not _meta: _meta = SubscriptionOptions(cls) output = output or getattr(cls, "Output", None) # Collect fields if output class is not explicitly defined. fields: dict = {} if not output: fields = collections.OrderedDict() for base in reversed(cls.__mro__): fields.update(graphene.types.utils.yank_fields_from_attrs(base.__dict__, _as=graphene.Field)) output = cls if not arguments: input_class = getattr(cls, "Arguments", None) if input_class: arguments = graphene.utils.props.props(input_class) else: arguments = {} # Get `publish`, `subscribe`, and `unsubscribe` handlers. subscribe = subscribe or getattr(cls, "subscribe", None) publish = publish or getattr(cls, "publish", None) unsubscribed = unsubscribed or getattr(cls, "unsubscribed", None) assert publish is not None, ( f"Subscription '{cls.__qualname__}' does not define a" " method 'publish'! All subscriptions must define" " 'publish' which processes GraphQL queries!" ) if _meta.fields: _meta.fields.update(fields) else: _meta.fields = fields # Auxiliary alias. graphene_get_function = graphene.utils.get_unbound_function.get_unbound_function # pylint: disable=attribute-defined-outside-init _meta.arguments = arguments _meta.output = output _meta.publish = graphene_get_function(publish) _meta.subscribe = graphene_get_function(subscribe) _meta.unsubscribed = graphene_get_function(unsubscribed) super().__init_subclass_with_meta__(_meta=_meta, **options) @classmethod def _group_name(cls, group=None): """Group name based on the name of the subscription class.""" suffix = f"{cls.__module__}.{cls.__qualname__}" if group is not None: suffix += "-" + group # Wrap the suffix into SHA256 to guarantee that the length of # the group name is limited. Otherwise Channels will complain # about that the group name is wrong (actually is too long). suffix_sha256 = hashlib.sha256() suffix_sha256.update(suffix.encode("utf-8"))
# Copyright (C) DATADVANCE, 2010-2023 # # 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. """Graphene-like subscription class. The `Subscription` class itself is a "creative" copy of `Mutation` class from the Graphene (`graphene/types/mutation.py`). """ # Module logger. LOG = logging.getLogger(__name__) class Subscription(graphene.ObjectType): """Subscription type definition. Subclass this the Subscription class to define a GraphQL subscription. The class works with the `GraphqlWsConsumer` which maintains a WebSocket connection with the client. The subclass specifies the following methods. You can define each of them as a `@classmethod`, as a `@staticmethod`, or even as a regular method (like Graphene typically does). It shall work fine either way. NOTE, if you define the method as a regular method (not a classmethod or a staticmethod) you will receive the first argument (`payload`/`root`) into the `self` argument. [async] publish(payload, info, *args, **kwds): This method invoked each time subscription "triggers". Raising an exception here will lead to sending the notification with the error. Technically the WebSocket message will contain extra field "extensions.code" holding the classname of the exception raised. To suppress the notification return `None`. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Required. Args: payload: The `payload` from the `broadcast` invocation. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. Returns: The same that any Graphene resolver returns. [async] subscribe(root, info, *args, **kwds): Called when client subscribes. Define this to do some extra work when client subscribes and to group subscriptions into different subscription groups. Method signature is the same as in other GraphQL "resolver" methods but it may return the subscription groups names to put the subscription into. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Optional. Args: root: Root resolver object. Typically `None`. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. Returns: The list or tuple of subscription group names this subscription instance belongs to. Later the subscription will trigger on publishes to any of that groups. If method returns None (default behavior) then the subscription is only put to the default group (the one which corresponds to the `Subscription` subclass). [async] unsubscribed(root, info, *args, **kwds): Called when client unsubscribes. Define this to be notified when client unsubscribes. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Args: root: Always `None`. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. The methods enlisted above receives "standard" set of GraphQL resolver arguments. The `info` field has `context` which can be used to transmit some useful payload between these methods. For example if `subscribe` sets `info.context.zen=42` then `publish` will have access to this value as `info.context.zen`. Static methods of subscription subclass: broadcast(): Call this to notify all subscriptions in the group. unsubscribe(): Call this to stop all subscriptions in the group. NOTE: If you call any of these methods from the asynchronous context then `await` the result of the call. """ # ----------------------------------------------------------------------- PUBLIC API # Subscription notifications queue limit. Set this to control the # amount of notifications server keeps in the queue when # notifications come faster than server processes them. Setting this # to 1 drops all notifications in the queue except the latest one. # Useful to skip intermediate notifications, e.g. progress reports. notification_queue_limit: Optional[int] = None @classmethod def broadcast(cls, *, group=None, payload=None): """Call this method to notify all subscriptions in the group. Can be called from both synchronous and asynchronous contexts. It is necessary to `await` if called from the async context. Args: group: Name of the subscription group which members must be notified. `None` means that all the subscriptions of type will be triggered. payload: The payload delivered to the `publish` handler. NOTE: The `payload` is serialized before sending to the subscription group. """ try: event_loop = asyncio.get_event_loop() except RuntimeError: pass else: if event_loop.is_running(): return event_loop.create_task(cls.broadcast_async(group=group, payload=payload)) return cls.broadcast_sync(group=group, payload=payload) @classmethod async def broadcast_async(cls, *, group=None, payload=None): """Broadcast, asynchronous version.""" # Manually serialize the `payload` to allow transfer of Django # models inside `payload`, auto serialization does not do this. serialized_payload = await channels.db.database_sync_to_async(Serializer.serialize, thread_sensitive=False)(payload) # Send the message to the Channels group. group = cls._group_name(group) group_send = cls._channel_layer().group_send # Will result in a call of `GraphqlWsConsumer.broadcast`. await group_send( group=group, message={ "type": "broadcast", "group": group, "payload": serialized_payload, }, ) @classmethod def broadcast_sync(cls, *, group=None, payload=None): """Broadcast, synchronous version.""" # Manually serialize the `payload` to allow transfer of Django # models inside the `payload`. serialized_payload = Serializer.serialize(payload) group = cls._group_name(group) sync_channel_layer_group_send = asgiref.sync.async_to_sync(cls._channel_layer().group_send) # Will result in a call of `GraphqlWsConsumer.broadcast`. sync_channel_layer_group_send( group=group, message={ "type": "broadcast", "group": group, "payload": serialized_payload, }, ) @classmethod def unsubscribe(cls, *, group=None): """Call this method to stop all subscriptions in the group. This method can be called from both synchronous and asynchronous contexts. If you call it from the asynchronous context then you have to `await`. Args: group: Name of the subscription group which members must be unsubscribed. `None` means that all the client of the subscription will be unsubscribed. """ try: event_loop = asyncio.get_event_loop() except RuntimeError: pass else: if event_loop.is_running(): return asyncio.create_task(cls.unsubscribe_async(group=group)) return cls.unsubscribe_sync(group=group) @classmethod async def unsubscribe_async(cls, *, group=None): """Unsubscribe, asynchronous version.""" # Send the 'unsubscribe' message to the Channels group. group = cls._group_name(group) await cls._channel_layer().group_send(group=group, message={"type": "unsubscribe", "group": group}) @classmethod def unsubscribe_sync(cls, *, group=None): """Unsubscribe, synchronous version.""" # Send the message to the Channels group. group = cls._group_name(group) sync_channel_layer_group_send = asgiref.sync.async_to_sync(cls._channel_layer().group_send) sync_channel_layer_group_send( group=group, message={ "type": "unsubscribe", "group": group, }, ) @classmethod def Field(cls, name=None, description=None, deprecation_reason=None, required=False): # noqa """Represent subscription as a field to mount it to the schema. Typical usage: class Subscription(graphene.ObjectType): on_new_chat_message = OnNewChatMessage.Field() """ return graphene.Field( cls._meta.output, args=cls._meta.arguments, resolver=cls._meta.publish, name=name, description=description, deprecation_reason=deprecation_reason, required=required, ) # ------------------------------------------------------------------- IMPLEMENTATION @classmethod def __init_subclass_with_meta__( cls, subscribe=None, publish=None, unsubscribed=None, output=None, arguments=None, _meta=None, **options, ): # pylint: disable=arguments-renamed """Prepare subscription on subclass creation. This method is invoked by the superclass `__init__subclass__`. It is needed to process class fields, `Meta` and inheritance parameters. This is genuine Graphene approach inherited/cloned from the original Mutation class implementation. """ if not _meta: _meta = SubscriptionOptions(cls) output = output or getattr(cls, "Output", None) # Collect fields if output class is not explicitly defined. fields: dict = {} if not output: fields = collections.OrderedDict() for base in reversed(cls.__mro__): fields.update(graphene.types.utils.yank_fields_from_attrs(base.__dict__, _as=graphene.Field)) output = cls if not arguments: input_class = getattr(cls, "Arguments", None) if input_class: arguments = graphene.utils.props.props(input_class) else: arguments = {} # Get `publish`, `subscribe`, and `unsubscribe` handlers. subscribe = subscribe or getattr(cls, "subscribe", None) publish = publish or getattr(cls, "publish", None) unsubscribed = unsubscribed or getattr(cls, "unsubscribed", None) assert publish is not None, ( f"Subscription '{cls.__qualname__}' does not define a" " method 'publish'! All subscriptions must define" " 'publish' which processes GraphQL queries!" ) if _meta.fields: _meta.fields.update(fields) else: _meta.fields = fields # Auxiliary alias. graphene_get_function = graphene.utils.get_unbound_function.get_unbound_function # pylint: disable=attribute-defined-outside-init _meta.arguments = arguments _meta.output = output _meta.publish = graphene_get_function(publish) _meta.subscribe = graphene_get_function(subscribe) _meta.unsubscribed = graphene_get_function(unsubscribed) super().__init_subclass_with_meta__(_meta=_meta, **options) @classmethod def _group_name(cls, group=None): """Group name based on the name of the subscription class.""" suffix = f"{cls.__module__}.{cls.__qualname__}" if group is not None: suffix += "-" + group # Wrap the suffix into SHA256 to guarantee that the length of # the group name is limited. Otherwise Channels will complain # about that the group name is wrong (actually is too long). suffix_sha256 = hashlib.sha256() suffix_sha256.update(suffix.encode("utf-8"))
return f"{GraphqlWsConsumer.group_name_prefix}-{suffix_sha256.hexdigest()}"
0
2023-12-25 11:40:56+00:00
16k
facebookresearch/ca_body
ca_body/models/mesh_vae_drivable.py
[ { "identifier": "ConvBlock", "path": "ca_body/nn/blocks.py", "snippet": "class ConvBlock(nn.Module):\n def __init__(\n self,\n in_channels,\n out_channels,\n size,\n lrelu_slope=0.2,\n kernel_size=3,\n padding=1,\n wnorm_dim=0,\n ):\n ...
import logging import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F import ca_body.nn.layers as la from typing import Dict, Optional, Tuple from torchvision.utils import make_grid from torchvision.transforms.functional import gaussian_blur from ca_body.nn.blocks import ( ConvBlock, ConvDownBlock, UpConvBlockDeep, tile2d, weights_initializer, ) from ca_body.nn.dof_cal import LearnableBlur from ca_body.utils.geom import ( GeometryModule, compute_view_cos, depth_discontuity_mask, depth2normals, ) from ca_body.nn.shadow import ShadowUNet, PoseToShadow from ca_body.nn.unet import UNetWB from ca_body.nn.color_cal import CalV5 from ca_body.utils.image import linear2displayBatch from ca_body.utils.lbs import LBSModule from ca_body.utils.render import RenderLayer from ca_body.utils.seams import SeamSampler from ca_body.utils.render import RenderLayer from ca_body.nn.face import FaceDecoderFrontal
11,646
class AutoEncoder(nn.Module): def __init__( self, encoder, decoder, decoder_view, encoder_face, # hqlp decoder to get the codes decoder_face, shadow_net, upscale_net, assets, pose_to_shadow=None, renderer=None, cal=None, pixel_cal=None, learn_blur: bool = True, ): super().__init__() # TODO: should we have a shared LBS here? self.geo_fn = GeometryModule( assets.topology.vi, assets.topology.vt, assets.topology.vti, assets.topology.v2uv, uv_size=1024, impaint=True, ) self.lbs_fn = LBSModule( assets.lbs_model_json, assets.lbs_config_dict, assets.lbs_template_verts, assets.lbs_scale, assets.global_scaling, ) self.seam_sampler = SeamSampler(assets.seam_data_1024) self.seam_sampler_2k = SeamSampler(assets.seam_data_2048) # joint tex -> body and clothes # TODO: why do we have a joint one in the first place? tex_mean = gaussian_blur(th.as_tensor(assets.tex_mean)[np.newaxis], kernel_size=11) self.register_buffer("tex_mean", F.interpolate(tex_mean, (2048, 2048), mode='bilinear')) # this is shared self.tex_std = assets.tex_var if 'tex_var' in assets else 64.0 face_cond_mask = th.as_tensor(assets.face_cond_mask, dtype=th.float32)[ np.newaxis, np.newaxis ] self.register_buffer("face_cond_mask", face_cond_mask) meye_mask = self.geo_fn.to_uv( th.as_tensor(assets.mouth_eyes_mask_geom[np.newaxis, :, np.newaxis]) ) meye_mask = F.interpolate(meye_mask, (2048, 2048), mode='bilinear') self.register_buffer("meye_mask", meye_mask) self.decoder = ConvDecoder( geo_fn=self.geo_fn, seam_sampler=self.seam_sampler, **decoder, assets=assets, ) # embs for everything but face non_head_mask = 1.0 - assets.face_mask self.encoder = Encoder( geo_fn=self.geo_fn, mask=non_head_mask, **encoder, ) self.encoder_face = FaceEncoder( assets=assets, **encoder_face, ) # using face decoder to generate better conditioning decoder_face_ckpt_path = None if 'ckpt' in decoder_face: decoder_face_ckpt_path = decoder_face.pop('ckpt') self.decoder_face = FaceDecoderFrontal(assets=assets, **decoder_face) if decoder_face_ckpt_path is not None: self.decoder_face.load_state_dict(th.load(decoder_face_ckpt_path), strict=False) self.decoder_view = UNetViewDecoder( self.geo_fn, seam_sampler=self.seam_sampler, **decoder_view, ) self.shadow_net = ShadowUNet( ao_mean=assets.ao_mean, interp_mode="bilinear", biases=False, **shadow_net, ) self.pose_to_shadow_enabled = False if pose_to_shadow is not None: self.pose_to_shadow_enabled = True self.pose_to_shadow = PoseToShadow(**pose_to_shadow) self.upscale_net = UpscaleNet( in_channels=6, size=1024, upscale_factor=2, out_channels=3, **upscale_net ) self.pixel_cal_enabled = False if pixel_cal is not None: self.pixel_cal_enabled = True self.pixel_cal = CameraPixelBias(**pixel_cal, cameras=assets.camera_ids) self.learn_blur_enabled = False if learn_blur: self.learn_blur_enabled = True
# 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__) class CameraPixelBias(nn.Module): def __init__(self, image_height, image_width, cameras, ds_rate) -> None: super().__init__() self.image_height = image_height self.image_width = image_width self.cameras = cameras self.n_cameras = len(cameras) bias = th.zeros( (self.n_cameras, 1, image_width // ds_rate, image_height // ds_rate), dtype=th.float32 ) self.register_parameter("bias", nn.Parameter(bias)) def forward(self, idxs: th.Tensor): bias_up = F.interpolate( self.bias[idxs], size=(self.image_height, self.image_width), mode='bilinear' ) return bias_up class AutoEncoder(nn.Module): def __init__( self, encoder, decoder, decoder_view, encoder_face, # hqlp decoder to get the codes decoder_face, shadow_net, upscale_net, assets, pose_to_shadow=None, renderer=None, cal=None, pixel_cal=None, learn_blur: bool = True, ): super().__init__() # TODO: should we have a shared LBS here? self.geo_fn = GeometryModule( assets.topology.vi, assets.topology.vt, assets.topology.vti, assets.topology.v2uv, uv_size=1024, impaint=True, ) self.lbs_fn = LBSModule( assets.lbs_model_json, assets.lbs_config_dict, assets.lbs_template_verts, assets.lbs_scale, assets.global_scaling, ) self.seam_sampler = SeamSampler(assets.seam_data_1024) self.seam_sampler_2k = SeamSampler(assets.seam_data_2048) # joint tex -> body and clothes # TODO: why do we have a joint one in the first place? tex_mean = gaussian_blur(th.as_tensor(assets.tex_mean)[np.newaxis], kernel_size=11) self.register_buffer("tex_mean", F.interpolate(tex_mean, (2048, 2048), mode='bilinear')) # this is shared self.tex_std = assets.tex_var if 'tex_var' in assets else 64.0 face_cond_mask = th.as_tensor(assets.face_cond_mask, dtype=th.float32)[ np.newaxis, np.newaxis ] self.register_buffer("face_cond_mask", face_cond_mask) meye_mask = self.geo_fn.to_uv( th.as_tensor(assets.mouth_eyes_mask_geom[np.newaxis, :, np.newaxis]) ) meye_mask = F.interpolate(meye_mask, (2048, 2048), mode='bilinear') self.register_buffer("meye_mask", meye_mask) self.decoder = ConvDecoder( geo_fn=self.geo_fn, seam_sampler=self.seam_sampler, **decoder, assets=assets, ) # embs for everything but face non_head_mask = 1.0 - assets.face_mask self.encoder = Encoder( geo_fn=self.geo_fn, mask=non_head_mask, **encoder, ) self.encoder_face = FaceEncoder( assets=assets, **encoder_face, ) # using face decoder to generate better conditioning decoder_face_ckpt_path = None if 'ckpt' in decoder_face: decoder_face_ckpt_path = decoder_face.pop('ckpt') self.decoder_face = FaceDecoderFrontal(assets=assets, **decoder_face) if decoder_face_ckpt_path is not None: self.decoder_face.load_state_dict(th.load(decoder_face_ckpt_path), strict=False) self.decoder_view = UNetViewDecoder( self.geo_fn, seam_sampler=self.seam_sampler, **decoder_view, ) self.shadow_net = ShadowUNet( ao_mean=assets.ao_mean, interp_mode="bilinear", biases=False, **shadow_net, ) self.pose_to_shadow_enabled = False if pose_to_shadow is not None: self.pose_to_shadow_enabled = True self.pose_to_shadow = PoseToShadow(**pose_to_shadow) self.upscale_net = UpscaleNet( in_channels=6, size=1024, upscale_factor=2, out_channels=3, **upscale_net ) self.pixel_cal_enabled = False if pixel_cal is not None: self.pixel_cal_enabled = True self.pixel_cal = CameraPixelBias(**pixel_cal, cameras=assets.camera_ids) self.learn_blur_enabled = False if learn_blur: self.learn_blur_enabled = True
self.learn_blur = LearnableBlur(assets.camera_ids)
5
2023-12-27 15:31:35+00:00
16k
daswer123/rvc-python
rvc_python/modules/vc/modules.py
[ { "identifier": "load_audio", "path": "rvc_python/lib/audio.py", "snippet": "def load_audio(file, sr):\n file = (\n file.strip(\" \").strip('\"').strip(\"\\n\").strip('\"').strip(\" \")\n ) # 防止小白拷路径头尾带了空格和\"和回车\n if os.path.exists(file) == False:\n raise RuntimeError(\n ...
import traceback import logging import numpy as np import soundfile as sf import torch from io import BytesIO from rvc_python.lib.audio import load_audio, wav2 from rvc_python.lib.infer_pack.models import ( SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono, SynthesizerTrnMs768NSFsid, SynthesizerTrnMs768NSFsid_nono, ) from rvc_python.modules.vc.pipeline import Pipeline from rvc_python.modules.vc.utils import *
10,867
file_index = ( file_index.strip(" ") .strip('"') .strip("\n") .strip('"') .strip(" ") .replace("trained", "added") ) elif file_index2: file_index = file_index2 else: file_index = "" # 防止小白写错,自动帮他替换掉 audio_opt = self.pipeline.pipeline( self.hubert_model, self.net_g, sid, audio, input_audio_path, times, f0_up_key, f0_method, file_index, index_rate, self.if_f0, filter_radius, self.tgt_sr, resample_sr, rms_mix_rate, self.version, protect, f0_file, ) if self.tgt_sr != resample_sr >= 16000: tgt_sr = resample_sr else: tgt_sr = self.tgt_sr index_info = ( "Index:\n%s." % file_index if os.path.exists(file_index) else "Index not used." ) return audio_opt except: info = traceback.format_exc() logger.warning(info) return info, (None, None) def vc_multi( self, sid, dir_path, opt_root, paths, f0_up_key, f0_method, file_index, file_index2, index_rate, filter_radius, resample_sr, rms_mix_rate, protect, format1, ): try: dir_path = ( dir_path.strip(" ").strip('"').strip("\n").strip('"').strip(" ") ) # 防止小白拷路径头尾带了空格和"和回车 opt_root = opt_root.strip(" ").strip('"').strip("\n").strip('"').strip(" ") os.makedirs(opt_root, exist_ok=True) try: if dir_path != "": paths = [ os.path.join(dir_path, name) for name in os.listdir(dir_path) ] else: paths = [path.name for path in paths] except: traceback.print_exc() paths = [path.name for path in paths] infos = [] print(paths) for path in paths: info, opt = self.vc_single( sid, path, f0_up_key, None, f0_method, file_index, file_index2, # file_big_npy, index_rate, filter_radius, resample_sr, rms_mix_rate, protect, ) print(info) if "Success" in info: try: tgt_sr, audio_opt = opt if format1 in ["wav", "flac"]: sf.write( "%s/%s.%s" % (opt_root, os.path.basename(path), format1), audio_opt, tgt_sr, ) else: path = "%s/%s.%s" % ( opt_root, os.path.basename(path), format1, ) with BytesIO() as wavf: sf.write(wavf, audio_opt, tgt_sr, format="wav") wavf.seek(0, 0) with open(path, "wb") as outf:
logger = logging.getLogger(__name__) class VC: def __init__(self, lib_dir, config): self.lib_dir = lib_dir self.n_spk = None self.tgt_sr = None self.net_g = None self.pipeline = None self.cpt = None self.version = None self.if_f0 = None self.version = None self.hubert_model = None self.config = config def get_vc(self,sid,version = "v2", *to_return_protect): # logger.info("Get sid: " + sid) to_return_protect0 = { "visible": self.if_f0 != 0, "value": to_return_protect[0] if self.if_f0 != 0 and to_return_protect else 0.5, "__type__": "update", } to_return_protect1 = { "visible": self.if_f0 != 0, "value": to_return_protect[1] if self.if_f0 != 0 and to_return_protect else 0.33, "__type__": "update", } if sid == "" or sid == []: if self.hubert_model is not None: # 考虑到轮询, 需要加个判断看是否 sid 是由有模型切换到无模型的 logger.info("Clean model cache") del (self.net_g, self.n_spk, self.hubert_model, self.tgt_sr) # ,cpt self.hubert_model = ( self.net_g ) = self.n_spk = self.hubert_model = self.tgt_sr = None if torch.cuda.is_available(): torch.cuda.empty_cache() ###楼下不这么折腾清理不干净 self.if_f0 = self.cpt.get("f0", 1) self.version = self.cpt.get("version", "v1") if self.version == "v1": if self.if_f0 == 1: self.net_g = SynthesizerTrnMs256NSFsid( *self.cpt["config"], is_half=self.config.is_half ) else: self.net_g = SynthesizerTrnMs256NSFsid_nono(*self.cpt["config"]) elif self.version == "v2": if self.if_f0 == 1: self.net_g = SynthesizerTrnMs768NSFsid( *self.cpt["config"], is_half=self.config.is_half ) else: self.net_g = SynthesizerTrnMs768NSFsid_nono(*self.cpt["config"]) del self.net_g, self.cpt if torch.cuda.is_available(): torch.cuda.empty_cache() return ( {"visible": False, "__type__": "update"}, { "visible": True, "value": to_return_protect0, "__type__": "update", }, { "visible": True, "value": to_return_protect1, "__type__": "update", }, "", "", ) person = f'{sid}' logger.info(f"Loading: {person}") # print(sid,person) self.cpt = torch.load(sid, map_location="cpu") self.tgt_sr = self.cpt["config"][-1] self.cpt["config"][-3] = self.cpt["weight"]["emb_g.weight"].shape[0] # n_spk self.if_f0 = self.cpt.get("f0", 1) self.version = version synthesizer_class = { ("v1", 1): SynthesizerTrnMs256NSFsid, ("v1", 0): SynthesizerTrnMs256NSFsid_nono, ("v2", 1): SynthesizerTrnMs768NSFsid, ("v2", 0): SynthesizerTrnMs768NSFsid_nono, } self.net_g = synthesizer_class.get( (self.version, self.if_f0), SynthesizerTrnMs256NSFsid )(*self.cpt["config"], is_half=self.config.is_half) del self.net_g.enc_q self.net_g.load_state_dict(self.cpt["weight"], strict=False) self.net_g.eval().to(self.config.device) if self.config.is_half: self.net_g = self.net_g.half() else: self.net_g = self.net_g.float() self.pipeline = Pipeline(self.tgt_sr, self.config,lib_dir=self.lib_dir) n_spk = self.cpt["config"][-3] return ( ( {"visible": True, "maximum": n_spk, "__type__": "update"}, to_return_protect0, to_return_protect1, ) if to_return_protect else {"visible": True, "maximum": n_spk, "__type__": "update"} ) def vc_single( self, sid, input_audio_path, f0_up_key, f0_file, f0_method, file_index, file_index2, index_rate, filter_radius, resample_sr, rms_mix_rate, protect, ): if input_audio_path is None: return "You need to upload an audio", None f0_up_key = int(f0_up_key) try: audio = load_audio(input_audio_path, 16000) audio_max = np.abs(audio).max() / 0.95 if audio_max > 1: audio /= audio_max times = [0, 0, 0] if self.hubert_model is None: self.hubert_model = load_hubert(self.config,self.lib_dir) if file_index: file_index = ( file_index.strip(" ") .strip('"') .strip("\n") .strip('"') .strip(" ") .replace("trained", "added") ) elif file_index2: file_index = file_index2 else: file_index = "" # 防止小白写错,自动帮他替换掉 audio_opt = self.pipeline.pipeline( self.hubert_model, self.net_g, sid, audio, input_audio_path, times, f0_up_key, f0_method, file_index, index_rate, self.if_f0, filter_radius, self.tgt_sr, resample_sr, rms_mix_rate, self.version, protect, f0_file, ) if self.tgt_sr != resample_sr >= 16000: tgt_sr = resample_sr else: tgt_sr = self.tgt_sr index_info = ( "Index:\n%s." % file_index if os.path.exists(file_index) else "Index not used." ) return audio_opt except: info = traceback.format_exc() logger.warning(info) return info, (None, None) def vc_multi( self, sid, dir_path, opt_root, paths, f0_up_key, f0_method, file_index, file_index2, index_rate, filter_radius, resample_sr, rms_mix_rate, protect, format1, ): try: dir_path = ( dir_path.strip(" ").strip('"').strip("\n").strip('"').strip(" ") ) # 防止小白拷路径头尾带了空格和"和回车 opt_root = opt_root.strip(" ").strip('"').strip("\n").strip('"').strip(" ") os.makedirs(opt_root, exist_ok=True) try: if dir_path != "": paths = [ os.path.join(dir_path, name) for name in os.listdir(dir_path) ] else: paths = [path.name for path in paths] except: traceback.print_exc() paths = [path.name for path in paths] infos = [] print(paths) for path in paths: info, opt = self.vc_single( sid, path, f0_up_key, None, f0_method, file_index, file_index2, # file_big_npy, index_rate, filter_radius, resample_sr, rms_mix_rate, protect, ) print(info) if "Success" in info: try: tgt_sr, audio_opt = opt if format1 in ["wav", "flac"]: sf.write( "%s/%s.%s" % (opt_root, os.path.basename(path), format1), audio_opt, tgt_sr, ) else: path = "%s/%s.%s" % ( opt_root, os.path.basename(path), format1, ) with BytesIO() as wavf: sf.write(wavf, audio_opt, tgt_sr, format="wav") wavf.seek(0, 0) with open(path, "wb") as outf:
wav2(wavf, outf, format1)
1
2023-12-26 19:05:42+00:00
16k
open-mmlab/Amphion
modules/wenet_extractor/transformer/encoder.py
[ { "identifier": "MultiHeadedAttention", "path": "modules/wenet_extractor/transformer/attention.py", "snippet": "class MultiHeadedAttention(nn.Module):\n \"\"\"Multi-Head Attention layer.\n\n Args:\n n_head (int): The number of heads.\n n_feat (int): The number of features.\n d...
from typing import Tuple from modules.wenet_extractor.transformer.attention import MultiHeadedAttention from modules.wenet_extractor.transformer.attention import ( RelPositionMultiHeadedAttention, ) from modules.wenet_extractor.transformer.convolution import ConvolutionModule from modules.wenet_extractor.transformer.embedding import PositionalEncoding from modules.wenet_extractor.transformer.embedding import RelPositionalEncoding from modules.wenet_extractor.transformer.embedding import NoPositionalEncoding from modules.wenet_extractor.transformer.encoder_layer import TransformerEncoderLayer from modules.wenet_extractor.transformer.encoder_layer import ConformerEncoderLayer from modules.wenet_extractor.transformer.positionwise_feed_forward import ( PositionwiseFeedForward, ) from modules.wenet_extractor.transformer.subsampling import Conv2dSubsampling4 from modules.wenet_extractor.transformer.subsampling import Conv2dSubsampling6 from modules.wenet_extractor.transformer.subsampling import Conv2dSubsampling8 from modules.wenet_extractor.transformer.subsampling import LinearNoSubsampling from modules.wenet_extractor.utils.common import get_activation from modules.wenet_extractor.utils.mask import make_pad_mask from modules.wenet_extractor.utils.mask import add_optional_chunk_mask import torch
14,261
"""Encoder definition.""" class BaseEncoder(torch.nn.Module): def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, input_layer: str = "conv2d", pos_enc_layer_type: str = "abs_pos", normalize_before: bool = True, static_chunk_size: int = 0, use_dynamic_chunk: bool = False, global_cmvn: torch.nn.Module = None, use_dynamic_left_chunk: bool = False, ): """ Args: input_size (int): input dim output_size (int): dimension of attention attention_heads (int): the number of heads of multi head attention linear_units (int): the hidden units number of position-wise feed forward num_blocks (int): the number of decoder blocks dropout_rate (float): dropout rate attention_dropout_rate (float): dropout rate in attention positional_dropout_rate (float): dropout rate after adding positional encoding input_layer (str): input layer type. optional [linear, conv2d, conv2d6, conv2d8] pos_enc_layer_type (str): Encoder positional encoding layer type. opitonal [abs_pos, scaled_abs_pos, rel_pos, no_pos] normalize_before (bool): True: use layer_norm before each sub-block of a layer. False: use layer_norm after each sub-block of a layer. static_chunk_size (int): chunk size for static chunk training and decoding use_dynamic_chunk (bool): whether use dynamic chunk size for training or not, You can only use fixed chunk(chunk_size > 0) or dyanmic chunk size(use_dynamic_chunk = True) global_cmvn (Optional[torch.nn.Module]): Optional GlobalCMVN module use_dynamic_left_chunk (bool): whether use dynamic left chunk in dynamic chunk training """ super().__init__() self._output_size = output_size if pos_enc_layer_type == "abs_pos": pos_enc_class = PositionalEncoding elif pos_enc_layer_type == "rel_pos": pos_enc_class = RelPositionalEncoding elif pos_enc_layer_type == "no_pos": pos_enc_class = NoPositionalEncoding else: raise ValueError("unknown pos_enc_layer: " + pos_enc_layer_type) if input_layer == "linear": subsampling_class = LinearNoSubsampling elif input_layer == "conv2d": subsampling_class = Conv2dSubsampling4 elif input_layer == "conv2d6": subsampling_class = Conv2dSubsampling6 elif input_layer == "conv2d8": subsampling_class = Conv2dSubsampling8 else: raise ValueError("unknown input_layer: " + input_layer) self.global_cmvn = global_cmvn self.embed = subsampling_class( input_size, output_size, dropout_rate, pos_enc_class(output_size, positional_dropout_rate), ) self.normalize_before = normalize_before self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5) self.static_chunk_size = static_chunk_size self.use_dynamic_chunk = use_dynamic_chunk self.use_dynamic_left_chunk = use_dynamic_left_chunk def output_size(self) -> int: return self._output_size def forward( self, xs: torch.Tensor, xs_lens: torch.Tensor, decoding_chunk_size: int = 0, num_decoding_left_chunks: int = -1, ) -> Tuple[torch.Tensor, torch.Tensor]: """Embed positions in tensor. Args: xs: padded input tensor (B, T, D) xs_lens: input length (B) decoding_chunk_size: decoding chunk size for dynamic chunk 0: default for training, use random dynamic chunk. <0: for decoding, use full chunk. >0: for decoding, use fixed chunk size as set. num_decoding_left_chunks: number of left chunks, this is for decoding, the chunk size is decoding_chunk_size. >=0: use num_decoding_left_chunks <0: use all left chunks Returns: encoder output tensor xs, and subsampled masks xs: padded output tensor (B, T' ~= T/subsample_rate, D) masks: torch.Tensor batch padding mask after subsample (B, 1, T' ~= T/subsample_rate) """ T = xs.size(1)
# This module is from [WeNet](https://github.com/wenet-e2e/wenet). # ## Citations # ```bibtex # @inproceedings{yao2021wenet, # title={WeNet: Production oriented Streaming and Non-streaming End-to-End Speech Recognition Toolkit}, # author={Yao, Zhuoyuan and Wu, Di and Wang, Xiong and Zhang, Binbin and Yu, Fan and Yang, Chao and Peng, Zhendong and Chen, Xiaoyu and Xie, Lei and Lei, Xin}, # booktitle={Proc. Interspeech}, # year={2021}, # address={Brno, Czech Republic }, # organization={IEEE} # } # @article{zhang2022wenet, # title={WeNet 2.0: More Productive End-to-End Speech Recognition Toolkit}, # author={Zhang, Binbin and Wu, Di and Peng, Zhendong and Song, Xingchen and Yao, Zhuoyuan and Lv, Hang and Xie, Lei and Yang, Chao and Pan, Fuping and Niu, Jianwei}, # journal={arXiv preprint arXiv:2203.15455}, # year={2022} # } # """Encoder definition.""" class BaseEncoder(torch.nn.Module): def __init__( self, input_size: int, output_size: int = 256, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 6, dropout_rate: float = 0.1, positional_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.0, input_layer: str = "conv2d", pos_enc_layer_type: str = "abs_pos", normalize_before: bool = True, static_chunk_size: int = 0, use_dynamic_chunk: bool = False, global_cmvn: torch.nn.Module = None, use_dynamic_left_chunk: bool = False, ): """ Args: input_size (int): input dim output_size (int): dimension of attention attention_heads (int): the number of heads of multi head attention linear_units (int): the hidden units number of position-wise feed forward num_blocks (int): the number of decoder blocks dropout_rate (float): dropout rate attention_dropout_rate (float): dropout rate in attention positional_dropout_rate (float): dropout rate after adding positional encoding input_layer (str): input layer type. optional [linear, conv2d, conv2d6, conv2d8] pos_enc_layer_type (str): Encoder positional encoding layer type. opitonal [abs_pos, scaled_abs_pos, rel_pos, no_pos] normalize_before (bool): True: use layer_norm before each sub-block of a layer. False: use layer_norm after each sub-block of a layer. static_chunk_size (int): chunk size for static chunk training and decoding use_dynamic_chunk (bool): whether use dynamic chunk size for training or not, You can only use fixed chunk(chunk_size > 0) or dyanmic chunk size(use_dynamic_chunk = True) global_cmvn (Optional[torch.nn.Module]): Optional GlobalCMVN module use_dynamic_left_chunk (bool): whether use dynamic left chunk in dynamic chunk training """ super().__init__() self._output_size = output_size if pos_enc_layer_type == "abs_pos": pos_enc_class = PositionalEncoding elif pos_enc_layer_type == "rel_pos": pos_enc_class = RelPositionalEncoding elif pos_enc_layer_type == "no_pos": pos_enc_class = NoPositionalEncoding else: raise ValueError("unknown pos_enc_layer: " + pos_enc_layer_type) if input_layer == "linear": subsampling_class = LinearNoSubsampling elif input_layer == "conv2d": subsampling_class = Conv2dSubsampling4 elif input_layer == "conv2d6": subsampling_class = Conv2dSubsampling6 elif input_layer == "conv2d8": subsampling_class = Conv2dSubsampling8 else: raise ValueError("unknown input_layer: " + input_layer) self.global_cmvn = global_cmvn self.embed = subsampling_class( input_size, output_size, dropout_rate, pos_enc_class(output_size, positional_dropout_rate), ) self.normalize_before = normalize_before self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5) self.static_chunk_size = static_chunk_size self.use_dynamic_chunk = use_dynamic_chunk self.use_dynamic_left_chunk = use_dynamic_left_chunk def output_size(self) -> int: return self._output_size def forward( self, xs: torch.Tensor, xs_lens: torch.Tensor, decoding_chunk_size: int = 0, num_decoding_left_chunks: int = -1, ) -> Tuple[torch.Tensor, torch.Tensor]: """Embed positions in tensor. Args: xs: padded input tensor (B, T, D) xs_lens: input length (B) decoding_chunk_size: decoding chunk size for dynamic chunk 0: default for training, use random dynamic chunk. <0: for decoding, use full chunk. >0: for decoding, use fixed chunk size as set. num_decoding_left_chunks: number of left chunks, this is for decoding, the chunk size is decoding_chunk_size. >=0: use num_decoding_left_chunks <0: use all left chunks Returns: encoder output tensor xs, and subsampled masks xs: padded output tensor (B, T' ~= T/subsample_rate, D) masks: torch.Tensor batch padding mask after subsample (B, 1, T' ~= T/subsample_rate) """ T = xs.size(1)
masks = ~make_pad_mask(xs_lens, T).unsqueeze(1) # (B, 1, T)
14
2023-11-15 09:19:27+00:00
16k
BobaZooba/xllm
tests/unit/run/test_train.py
[ { "identifier": "Config", "path": "src/xllm/core/config.py", "snippet": "class Config:\n \"\"\"\n The `Config` class serves as a comprehensive configuration schema for managing various parameters required during\n the setup and execution of experiments relating to language models, such as train...
from pytest import MonkeyPatch from src.xllm.core.config import Config from src.xllm.run.train import train from tests.helpers.constants import LLAMA_TOKENIZER_DIR from tests.helpers.patches import patch_from_pretrained_auto_causal_lm, patch_trainer_train
11,899
# Copyright 2023 Boris Zubarev. 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. def test_train(monkeypatch: MonkeyPatch, path_to_train_prepared_dummy_data: str, path_to_outputs: str): config = Config( push_to_hub=False, deepspeed_stage="0", train_local_path_to_data=path_to_train_prepared_dummy_data, report_to_wandb=False, save_total_limit=0, max_steps=2, tokenizer_name_or_path=LLAMA_TOKENIZER_DIR, output_dir=path_to_outputs, )
# Copyright 2023 Boris Zubarev. 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. def test_train(monkeypatch: MonkeyPatch, path_to_train_prepared_dummy_data: str, path_to_outputs: str): config = Config( push_to_hub=False, deepspeed_stage="0", train_local_path_to_data=path_to_train_prepared_dummy_data, report_to_wandb=False, save_total_limit=0, max_steps=2, tokenizer_name_or_path=LLAMA_TOKENIZER_DIR, output_dir=path_to_outputs, )
with patch_from_pretrained_auto_causal_lm(monkeypatch=monkeypatch):
3
2023-11-10 17:55:03+00:00
16k
AMAAI-Lab/mustango
diffusers/src/diffusers/schedulers/scheduling_ddpm.py
[ { "identifier": "ConfigMixin", "path": "diffusers/src/diffusers/configuration_utils.py", "snippet": "class ConfigMixin:\n r\"\"\"\n Base class for all configuration classes. Stores all configuration parameters under `self.config` Also handles all\n methods for loading/downloading/saving classes...
import math import numpy as np import torch from dataclasses import dataclass from typing import List, Optional, Tuple, Union from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
11,615
# For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample variance = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * current_beta_t if variance_type is None: variance_type = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": variance = torch.clamp(variance, min=1e-20) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": variance = torch.log(torch.clamp(variance, min=1e-20)) variance = torch.exp(0.5 * variance) elif variance_type == "fixed_large": variance = current_beta_t elif variance_type == "fixed_large_log": # Glide max_log variance = torch.log(current_beta_t) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": min_log = torch.log(variance) max_log = torch.log(self.betas[t]) frac = (predicted_variance + 1) / 2 variance = frac * max_log + (1 - frac) * min_log return variance def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor: # Dynamic thresholding in https://arxiv.org/abs/2205.11487 dynamic_max_val = ( sample.flatten(1) .abs() .quantile(self.config.dynamic_thresholding_ratio, dim=1) .clamp_min(self.config.sample_max_value) .view(-1, *([1] * (sample.ndim - 1))) ) return sample.clamp(-dynamic_max_val, dynamic_max_val) / dynamic_max_val def step( self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor, generator=None, return_dict: bool = True, ) -> Union[DDPMSchedulerOutput, Tuple]: """ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion process from the learned model outputs (most often the predicted noise). Args: model_output (`torch.FloatTensor`): direct output from learned diffusion model. timestep (`int`): current discrete timestep in the diffusion chain. sample (`torch.FloatTensor`): current instance of sample being created by diffusion process. generator: random number generator. return_dict (`bool`): option for returning tuple rather than DDPMSchedulerOutput class Returns: [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] or `tuple`: [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor. """ t = timestep num_inference_steps = self.num_inference_steps if self.num_inference_steps else self.config.num_train_timesteps prev_t = timestep - self.config.num_train_timesteps // num_inference_steps if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1) else: predicted_variance = None # 1. compute alphas, betas alpha_prod_t = self.alphas_cumprod[t] alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else self.one beta_prod_t = 1 - alpha_prod_t beta_prod_t_prev = 1 - alpha_prod_t_prev current_alpha_t = alpha_prod_t / alpha_prod_t_prev current_beta_t = 1 - current_alpha_t # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) elif self.config.prediction_type == "sample": pred_original_sample = model_output elif self.config.prediction_type == "v_prediction": pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` or" " `v_prediction` for the DDPMScheduler." ) # 3. Clip or threshold "predicted x_0" if self.config.clip_sample: pred_original_sample = pred_original_sample.clamp( -self.config.clip_sample_range, self.config.clip_sample_range ) if self.config.thresholding: pred_original_sample = self._threshold_sample(pred_original_sample) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * current_beta_t) / beta_prod_t current_sample_coeff = current_alpha_t ** (0.5) * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise variance = 0 if t > 0: device = model_output.device
# Copyright 2023 UC Berkeley Team and The HuggingFace 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. # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim @dataclass class DDPMSchedulerOutput(BaseOutput): """ Output class for the scheduler's step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. """ prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None def betas_for_alpha_bar(num_diffusion_timesteps, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up to that part of the diffusion process. Args: num_diffusion_timesteps (`int`): the number of betas to produce. max_beta (`float`): the maximum beta to use; use values lower than 1 to prevent singularities. Returns: betas (`np.ndarray`): the betas used by the scheduler to step the model outputs """ def alpha_bar(time_step): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2) ** 2 betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return torch.tensor(betas, dtype=torch.float32) class DDPMScheduler(SchedulerMixin, ConfigMixin): """ Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and Langevin dynamics sampling. [`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__` function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`. [`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and [`~SchedulerMixin.from_pretrained`] functions. For more details, see the original paper: https://arxiv.org/abs/2006.11239 Args: num_train_timesteps (`int`): number of diffusion steps used to train the model. beta_start (`float`): the starting `beta` value of inference. beta_end (`float`): the final `beta` value. beta_schedule (`str`): the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from `linear`, `scaled_linear`, or `squaredcos_cap_v2`. trained_betas (`np.ndarray`, optional): option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc. variance_type (`str`): options to clip the variance used when adding noise to the denoised sample. Choose from `fixed_small`, `fixed_small_log`, `fixed_large`, `fixed_large_log`, `learned` or `learned_range`. clip_sample (`bool`, default `True`): option to clip predicted sample for numerical stability. clip_sample_range (`float`, default `1.0`): the maximum magnitude for sample clipping. Valid only when `clip_sample=True`. prediction_type (`str`, default `epsilon`, optional): prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4 https://imagen.research.google/video/paper.pdf) thresholding (`bool`, default `False`): whether to use the "dynamic thresholding" method (introduced by Imagen, https://arxiv.org/abs/2205.11487). Note that the thresholding method is unsuitable for latent-space diffusion models (such as stable-diffusion). dynamic_thresholding_ratio (`float`, default `0.995`): the ratio for the dynamic thresholding method. Default is `0.995`, the same as Imagen (https://arxiv.org/abs/2205.11487). Valid only when `thresholding=True`. sample_max_value (`float`, default `1.0`): the threshold value for dynamic thresholding. Valid only when `thresholding=True`. """ _compatibles = [e.name for e in KarrasDiffusionSchedulers] order = 1 @register_to_config def __init__( self, num_train_timesteps: int = 1000, beta_start: float = 0.0001, beta_end: float = 0.02, beta_schedule: str = "linear", trained_betas: Optional[Union[np.ndarray, List[float]]] = None, variance_type: str = "fixed_small", clip_sample: bool = True, prediction_type: str = "epsilon", thresholding: bool = False, dynamic_thresholding_ratio: float = 0.995, clip_sample_range: float = 1.0, sample_max_value: float = 1.0, ): if trained_betas is not None: self.betas = torch.tensor(trained_betas, dtype=torch.float32) elif beta_schedule == "linear": self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. self.betas = ( torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule self.betas = betas_for_alpha_bar(num_train_timesteps) elif beta_schedule == "sigmoid": # GeoDiff sigmoid schedule betas = torch.linspace(-6, 6, num_train_timesteps) self.betas = torch.sigmoid(betas) * (beta_end - beta_start) + beta_start else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}") self.alphas = 1.0 - self.betas self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) self.one = torch.tensor(1.0) # standard deviation of the initial noise distribution self.init_noise_sigma = 1.0 # setable values self.num_inference_steps = None self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy()) self.variance_type = variance_type def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor: """ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the current timestep. Args: sample (`torch.FloatTensor`): input sample timestep (`int`, optional): current timestep Returns: `torch.FloatTensor`: scaled input sample """ return sample def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None): """ Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. Args: num_inference_steps (`int`): the number of diffusion steps used when generating samples with a pre-trained model. """ if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:" f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle" f" maximal {self.config.num_train_timesteps} timesteps." ) self.num_inference_steps = num_inference_steps step_ratio = self.config.num_train_timesteps // self.num_inference_steps timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64) self.timesteps = torch.from_numpy(timesteps).to(device) def _get_variance(self, t, predicted_variance=None, variance_type=None): num_inference_steps = self.num_inference_steps if self.num_inference_steps else self.config.num_train_timesteps prev_t = t - self.config.num_train_timesteps // num_inference_steps alpha_prod_t = self.alphas_cumprod[t] alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else self.one current_beta_t = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample variance = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * current_beta_t if variance_type is None: variance_type = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": variance = torch.clamp(variance, min=1e-20) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": variance = torch.log(torch.clamp(variance, min=1e-20)) variance = torch.exp(0.5 * variance) elif variance_type == "fixed_large": variance = current_beta_t elif variance_type == "fixed_large_log": # Glide max_log variance = torch.log(current_beta_t) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": min_log = torch.log(variance) max_log = torch.log(self.betas[t]) frac = (predicted_variance + 1) / 2 variance = frac * max_log + (1 - frac) * min_log return variance def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor: # Dynamic thresholding in https://arxiv.org/abs/2205.11487 dynamic_max_val = ( sample.flatten(1) .abs() .quantile(self.config.dynamic_thresholding_ratio, dim=1) .clamp_min(self.config.sample_max_value) .view(-1, *([1] * (sample.ndim - 1))) ) return sample.clamp(-dynamic_max_val, dynamic_max_val) / dynamic_max_val def step( self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor, generator=None, return_dict: bool = True, ) -> Union[DDPMSchedulerOutput, Tuple]: """ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion process from the learned model outputs (most often the predicted noise). Args: model_output (`torch.FloatTensor`): direct output from learned diffusion model. timestep (`int`): current discrete timestep in the diffusion chain. sample (`torch.FloatTensor`): current instance of sample being created by diffusion process. generator: random number generator. return_dict (`bool`): option for returning tuple rather than DDPMSchedulerOutput class Returns: [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] or `tuple`: [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor. """ t = timestep num_inference_steps = self.num_inference_steps if self.num_inference_steps else self.config.num_train_timesteps prev_t = timestep - self.config.num_train_timesteps // num_inference_steps if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1) else: predicted_variance = None # 1. compute alphas, betas alpha_prod_t = self.alphas_cumprod[t] alpha_prod_t_prev = self.alphas_cumprod[prev_t] if prev_t >= 0 else self.one beta_prod_t = 1 - alpha_prod_t beta_prod_t_prev = 1 - alpha_prod_t_prev current_alpha_t = alpha_prod_t / alpha_prod_t_prev current_beta_t = 1 - current_alpha_t # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) elif self.config.prediction_type == "sample": pred_original_sample = model_output elif self.config.prediction_type == "v_prediction": pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` or" " `v_prediction` for the DDPMScheduler." ) # 3. Clip or threshold "predicted x_0" if self.config.clip_sample: pred_original_sample = pred_original_sample.clamp( -self.config.clip_sample_range, self.config.clip_sample_range ) if self.config.thresholding: pred_original_sample = self._threshold_sample(pred_original_sample) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * current_beta_t) / beta_prod_t current_sample_coeff = current_alpha_t ** (0.5) * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise variance = 0 if t > 0: device = model_output.device
variance_noise = randn_tensor(
3
2023-11-14 23:29:31+00:00
16k
BraveGroup/Drive-WM
src/diffusers/pipelines/pipeline_flax_utils.py
[ { "identifier": "ConfigMixin", "path": "src/diffusers/configuration_utils.py", "snippet": "class ConfigMixin:\n r\"\"\"\n Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also\n provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.sa...
import importlib import inspect import os import flax import numpy as np import PIL.Image from typing import Any, Dict, List, Optional, Union from flax.core.frozen_dict import FrozenDict from huggingface_hub import create_repo, snapshot_download from PIL import Image from tqdm.auto import tqdm from ..configuration_utils import ConfigMixin from ..models.modeling_flax_utils import FLAX_WEIGHTS_NAME, FlaxModelMixin from ..schedulers.scheduling_utils_flax import SCHEDULER_CONFIG_NAME, FlaxSchedulerMixin from ..utils import ( CONFIG_NAME, DIFFUSERS_CACHE, BaseOutput, PushToHubMixin, http_user_agent, is_transformers_available, logging, ) from transformers import FlaxPreTrainedModel from diffusers import pipelines from diffusers import pipelines
10,923
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if is_transformers_available(): INDEX_FILE = "diffusion_flax_model.bin" logger = logging.get_logger(__name__) LOADABLE_CLASSES = { "diffusers": { "FlaxModelMixin": ["save_pretrained", "from_pretrained"], "FlaxSchedulerMixin": ["save_pretrained", "from_pretrained"], "FlaxDiffusionPipeline": ["save_pretrained", "from_pretrained"], }, "transformers": { "PreTrainedTokenizer": ["save_pretrained", "from_pretrained"], "PreTrainedTokenizerFast": ["save_pretrained", "from_pretrained"], "FlaxPreTrainedModel": ["save_pretrained", "from_pretrained"], "FeatureExtractionMixin": ["save_pretrained", "from_pretrained"], "ProcessorMixin": ["save_pretrained", "from_pretrained"], "ImageProcessingMixin": ["save_pretrained", "from_pretrained"], }, } ALL_IMPORTABLE_CLASSES = {} for library in LOADABLE_CLASSES: ALL_IMPORTABLE_CLASSES.update(LOADABLE_CLASSES[library]) def import_flax_or_no_model(module, class_name): try: # 1. First make sure that if a Flax object is present, import this one class_obj = getattr(module, "Flax" + class_name) except AttributeError: # 2. If this doesn't work, it's not a model and we don't append "Flax" class_obj = getattr(module, class_name) except AttributeError: raise ValueError(f"Neither Flax{class_name} nor {class_name} exist in {module}") return class_obj @flax.struct.dataclass
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if is_transformers_available(): INDEX_FILE = "diffusion_flax_model.bin" logger = logging.get_logger(__name__) LOADABLE_CLASSES = { "diffusers": { "FlaxModelMixin": ["save_pretrained", "from_pretrained"], "FlaxSchedulerMixin": ["save_pretrained", "from_pretrained"], "FlaxDiffusionPipeline": ["save_pretrained", "from_pretrained"], }, "transformers": { "PreTrainedTokenizer": ["save_pretrained", "from_pretrained"], "PreTrainedTokenizerFast": ["save_pretrained", "from_pretrained"], "FlaxPreTrainedModel": ["save_pretrained", "from_pretrained"], "FeatureExtractionMixin": ["save_pretrained", "from_pretrained"], "ProcessorMixin": ["save_pretrained", "from_pretrained"], "ImageProcessingMixin": ["save_pretrained", "from_pretrained"], }, } ALL_IMPORTABLE_CLASSES = {} for library in LOADABLE_CLASSES: ALL_IMPORTABLE_CLASSES.update(LOADABLE_CLASSES[library]) def import_flax_or_no_model(module, class_name): try: # 1. First make sure that if a Flax object is present, import this one class_obj = getattr(module, "Flax" + class_name) except AttributeError: # 2. If this doesn't work, it's not a model and we don't append "Flax" class_obj = getattr(module, class_name) except AttributeError: raise ValueError(f"Neither Flax{class_name} nor {class_name} exist in {module}") return class_obj @flax.struct.dataclass
class FlaxImagePipelineOutput(BaseOutput):
10
2023-11-18 01:40:55+00:00
16k
BAAI-DCAI/SegVol
inference_demo.py
[ { "identifier": "sam_model_registry", "path": "segment_anything_volumetric/build_sam.py", "snippet": "def build_sam_vit_3d(args, checkpoint=None):\ndef _build_sam(\n image_encoder_type,\n embed_dim,\n patch_size,\n checkpoint,\n image_size,\n):" }, { "identifier": "SegVol", "p...
import argparse import os import torch import torch.nn.functional as F import json import monai.transforms as transforms from segment_anything_volumetric import sam_model_registry from network.model import SegVol from data_process.demo_data_process import process_ct_gt from utils.monai_inferers_utils import sliding_window_inference, generate_box, select_points, build_binary_cube, build_binary_points, logits2roi_coor from utils.visualize import draw_result
11,656
logits_global_single.cpu(), size=ori_shape, mode='nearest')[0][0] # build prompt reflection for zoom-in if args.use_point_prompt: binary_points = F.interpolate( binary_points_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] if args.use_box_prompt: binary_cube = F.interpolate( binary_cube_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] zoom_out_dice = dice_score(logits_global_single.squeeze(), label_single.squeeze()) logits_labels_record[categories[item_idx]] = ( zoom_out_dice, image_single, points_single, box_single, logits_global_single, label_single) print(f'zoom out inference done with zoom_out_dice: {zoom_out_dice:.4f}') if not args.use_zoom_in: continue #################### # zoom-in inference: min_d, min_h, min_w, max_d, max_h, max_w = logits2roi_coor(args.spatial_size, logits_global_single) if min_d is None: print('Fail to detect foreground!') continue # Crop roi image_single_cropped = image_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1].unsqueeze(0).unsqueeze(0) global_preds = (torch.sigmoid(logits_global_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1])>0.5).long() assert not (args.use_box_prompt and args.use_point_prompt) prompt_reflection = None if args.use_box_prompt: binary_cube_cropped = binary_cube[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_cube_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) if args.use_point_prompt: binary_points_cropped = binary_points[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_points_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) ## inference with torch.no_grad(): logits_single_cropped = sliding_window_inference( image_single_cropped.cuda(), prompt_reflection, args.spatial_size, 1, segvol_model, args.infer_overlap, text=text_single, use_box=args.use_box_prompt, use_point=args.use_point_prompt, ) logits_single_cropped = logits_single_cropped.cpu().squeeze() logits_global_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] = logits_single_cropped zoom_in_dice = dice_score(logits_global_single.squeeze(), label_single.squeeze()) logits_labels_record[categories[item_idx]] = ( zoom_in_dice, image_single, points_single, box_single, logits_global_single, label_single) print(f'===> zoom out dice {zoom_out_dice:.4f} -> zoom-out-zoom-in dice {zoom_in_dice:.4f} <===') return logits_labels_record def inference_single_ct(args, segvol_model, data_item, categories): segvol_model.eval() image, gt3D = data_item["image"].float(), data_item["label"] image_zoom_out, gt3D__zoom_out = data_item["zoom_out_image"].float(), data_item['zoom_out_label'] logits_labels_record = zoom_in_zoom_out( args, segvol_model, image.unsqueeze(0), image_zoom_out.unsqueeze(0), gt3D.unsqueeze(0), gt3D__zoom_out.unsqueeze(0), categories=categories) # visualize if args.visualize: for target, values in logits_labels_record.items(): dice_score, image, point_prompt, box_prompt, logits, labels = values print(f'{target} result with Dice score {dice_score:.4f} visualizing') draw_result(target + f"-Dice {dice_score:.4f}", image, box_prompt, point_prompt, logits, labels, args.spatial_size, args.work_dir) def main(args): gpu = 0 torch.cuda.set_device(gpu) # build model sam_model = sam_model_registry['vit'](args=args) segvol_model = SegVol( image_encoder=sam_model.image_encoder, mask_decoder=sam_model.mask_decoder, prompt_encoder=sam_model.prompt_encoder, clip_ckpt=args.clip_ckpt, roi_size=args.spatial_size, patch_size=args.patch_size, test_mode=args.test_mode, ).cuda() segvol_model = torch.nn.DataParallel(segvol_model, device_ids=[gpu]) # load param if os.path.isfile(args.resume): ## Map model to be loaded to specified single GPU loc = 'cuda:{}'.format(gpu) checkpoint = torch.load(args.resume, map_location=loc) segvol_model.load_state_dict(checkpoint['model'], strict=True) print("loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) # load demo config with open(args.demo_config, 'r') as file: config_dict = json.load(file) ct_path, gt_path, categories = config_dict['demo_case']['ct_path'], config_dict['demo_case']['gt_path'], config_dict['categories'] # preprocess for data
def set_parse(): # %% set up parser parser = argparse.ArgumentParser() parser.add_argument("--test_mode", default=True, type=bool) parser.add_argument("--resume", type = str, default = '') parser.add_argument("-infer_overlap", default=0.5, type=float, help="sliding window inference overlap") parser.add_argument("-spatial_size", default=(32, 256, 256), type=tuple) parser.add_argument("-patch_size", default=(4, 16, 16), type=tuple) parser.add_argument('-work_dir', type=str, default='./work_dir') ### demo parser.add_argument('--demo_config', type=str, required=True) parser.add_argument("--clip_ckpt", type = str, default = './config/clip') args = parser.parse_args() return args def dice_score(preds, labels): # on GPU assert preds.shape[0] == labels.shape[0], "predict & target batch size don't match\n" + str(preds.shape) + str(labels.shape) predict = preds.view(1, -1) target = labels.view(1, -1) if target.shape[1] < 1e8: predict = predict.cuda() target = target.cuda() predict = torch.sigmoid(predict) predict = torch.where(predict > 0.5, 1., 0.) tp = torch.sum(torch.mul(predict, target)) den = torch.sum(predict) + torch.sum(target) + 1 dice = 2 * tp / den if target.shape[1] < 1e8: predict = predict.cpu() target = target.cpu() return dice def zoom_in_zoom_out(args, segvol_model, image, image_resize, gt3D, gt3D_resize, categories=None): logits_labels_record = {} image_single_resize = image_resize image_single = image[0,0] ori_shape = image_single.shape for item_idx in range(len(categories)): # get label to generate prompts label_single = gt3D[0][item_idx] label_single_resize = gt3D_resize[0][item_idx] # skip meaningless categories if torch.sum(label_single) == 0: print('No object, skip') continue # generate prompts text_single = categories[item_idx] if args.use_text_prompt else None if categories is not None: print(f'inference |{categories[item_idx]}| target...') points_single = None box_single = None if args.use_point_prompt: point, point_label = select_points(label_single_resize, num_positive_extra=3, num_negative_extra=3) points_single = (point.unsqueeze(0).float().cuda(), point_label.unsqueeze(0).float().cuda()) binary_points_resize = build_binary_points(point, point_label, label_single_resize.shape) if args.use_box_prompt: box_single = generate_box(label_single_resize).unsqueeze(0).float().cuda() binary_cube_resize = build_binary_cube(box_single, binary_cube_shape=label_single_resize.shape) #################### # zoom-out inference: print('--- zoom out inference ---') print(f'use text-prompt [{text_single!=None}], use box-prompt [{box_single!=None}], use point-prompt [{points_single!=None}]') with torch.no_grad(): logits_global_single = segvol_model(image_single_resize.cuda(), text=text_single, boxes=box_single, points=points_single) # resize back global logits logits_global_single = F.interpolate( logits_global_single.cpu(), size=ori_shape, mode='nearest')[0][0] # build prompt reflection for zoom-in if args.use_point_prompt: binary_points = F.interpolate( binary_points_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] if args.use_box_prompt: binary_cube = F.interpolate( binary_cube_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] zoom_out_dice = dice_score(logits_global_single.squeeze(), label_single.squeeze()) logits_labels_record[categories[item_idx]] = ( zoom_out_dice, image_single, points_single, box_single, logits_global_single, label_single) print(f'zoom out inference done with zoom_out_dice: {zoom_out_dice:.4f}') if not args.use_zoom_in: continue #################### # zoom-in inference: min_d, min_h, min_w, max_d, max_h, max_w = logits2roi_coor(args.spatial_size, logits_global_single) if min_d is None: print('Fail to detect foreground!') continue # Crop roi image_single_cropped = image_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1].unsqueeze(0).unsqueeze(0) global_preds = (torch.sigmoid(logits_global_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1])>0.5).long() assert not (args.use_box_prompt and args.use_point_prompt) prompt_reflection = None if args.use_box_prompt: binary_cube_cropped = binary_cube[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_cube_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) if args.use_point_prompt: binary_points_cropped = binary_points[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_points_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) ## inference with torch.no_grad(): logits_single_cropped = sliding_window_inference( image_single_cropped.cuda(), prompt_reflection, args.spatial_size, 1, segvol_model, args.infer_overlap, text=text_single, use_box=args.use_box_prompt, use_point=args.use_point_prompt, ) logits_single_cropped = logits_single_cropped.cpu().squeeze() logits_global_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] = logits_single_cropped zoom_in_dice = dice_score(logits_global_single.squeeze(), label_single.squeeze()) logits_labels_record[categories[item_idx]] = ( zoom_in_dice, image_single, points_single, box_single, logits_global_single, label_single) print(f'===> zoom out dice {zoom_out_dice:.4f} -> zoom-out-zoom-in dice {zoom_in_dice:.4f} <===') return logits_labels_record def inference_single_ct(args, segvol_model, data_item, categories): segvol_model.eval() image, gt3D = data_item["image"].float(), data_item["label"] image_zoom_out, gt3D__zoom_out = data_item["zoom_out_image"].float(), data_item['zoom_out_label'] logits_labels_record = zoom_in_zoom_out( args, segvol_model, image.unsqueeze(0), image_zoom_out.unsqueeze(0), gt3D.unsqueeze(0), gt3D__zoom_out.unsqueeze(0), categories=categories) # visualize if args.visualize: for target, values in logits_labels_record.items(): dice_score, image, point_prompt, box_prompt, logits, labels = values print(f'{target} result with Dice score {dice_score:.4f} visualizing') draw_result(target + f"-Dice {dice_score:.4f}", image, box_prompt, point_prompt, logits, labels, args.spatial_size, args.work_dir) def main(args): gpu = 0 torch.cuda.set_device(gpu) # build model sam_model = sam_model_registry['vit'](args=args) segvol_model = SegVol( image_encoder=sam_model.image_encoder, mask_decoder=sam_model.mask_decoder, prompt_encoder=sam_model.prompt_encoder, clip_ckpt=args.clip_ckpt, roi_size=args.spatial_size, patch_size=args.patch_size, test_mode=args.test_mode, ).cuda() segvol_model = torch.nn.DataParallel(segvol_model, device_ids=[gpu]) # load param if os.path.isfile(args.resume): ## Map model to be loaded to specified single GPU loc = 'cuda:{}'.format(gpu) checkpoint = torch.load(args.resume, map_location=loc) segvol_model.load_state_dict(checkpoint['model'], strict=True) print("loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch'])) # load demo config with open(args.demo_config, 'r') as file: config_dict = json.load(file) ct_path, gt_path, categories = config_dict['demo_case']['ct_path'], config_dict['demo_case']['gt_path'], config_dict['categories'] # preprocess for data
data_item = process_ct_gt(ct_path, gt_path, categories, args.spatial_size)
2
2023-11-10 08:25:37+00:00
16k
theroyallab/tabbyAPI
main.py
[ { "identifier": "convert_args_to_dict", "path": "args.py", "snippet": "def convert_args_to_dict(args: argparse.Namespace, parser: argparse.ArgumentParser):\n \"\"\"Broad conversion of surface level arg groups to dictionaries\"\"\"\n\n arg_groups = {}\n for group in parser._action_groups:\n ...
import pathlib import uvicorn import gen_logging from asyncio import CancelledError from typing import Optional from uuid import uuid4 from jinja2 import TemplateError from fastapi import FastAPI, Depends, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse from functools import partial from progress.bar import IncrementalBar from args import convert_args_to_dict, init_argparser from auth import check_admin_key, check_api_key, load_auth_keys from config import ( override_config_from_args, read_config_from_file, get_gen_logging_config, get_model_config, get_draft_model_config, get_lora_config, get_network_config, ) from generators import call_with_semaphore, generate_with_semaphore from model import ModelContainer from OAI.types.completion import CompletionRequest from OAI.types.chat_completion import ChatCompletionRequest from OAI.types.lora import LoraCard, LoraList, LoraLoadRequest, LoraLoadResponse from OAI.types.model import ( ModelCard, ModelLoadRequest, ModelLoadResponse, ModelCardParameters, ) from OAI.types.template import TemplateList from OAI.types.token import ( TokenEncodeRequest, TokenEncodeResponse, TokenDecodeRequest, TokenDecodeResponse, ) from OAI.utils_oai import ( create_completion_response, get_model_list, get_lora_list, create_chat_completion_response, create_chat_completion_stream_chunk, ) from templating import get_all_templates, get_prompt_from_template from utils import get_generator_error, get_sse_packet, load_progress, unwrap from logger import init_logger
12,983
"""The main tabbyAPI module. Contains the FastAPI server and endpoints.""" logger = init_logger(__name__) app = FastAPI( title="TabbyAPI", summary="An OAI compatible exllamav2 API that's both lightweight and fast", description=( "This docs page is not meant to send requests! Please use a service " "like Postman or a frontend UI." ), ) # Globally scoped variables. Undefined until initalized in main MODEL_CONTAINER: Optional[ModelContainer] = None def _check_model_container(): if MODEL_CONTAINER is None or MODEL_CONTAINER.model is None: raise HTTPException(400, "No models are loaded.") # ALlow CORS requests app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Model list endpoint @app.get("/v1/models", dependencies=[Depends(check_api_key)]) @app.get("/v1/model/list", dependencies=[Depends(check_api_key)]) async def list_models(): """Lists all models in the model directory.""" model_config = get_model_config() model_dir = unwrap(model_config.get("model_dir"), "models") model_path = pathlib.Path(model_dir) draft_model_dir = get_draft_model_config().get("draft_model_dir") models = get_model_list(model_path.resolve(), draft_model_dir) if unwrap(model_config.get("use_dummy_models"), False): models.data.insert(0, ModelCard(id="gpt-3.5-turbo")) return models # Currently loaded model endpoint @app.get( "/v1/model", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) @app.get( "/v1/internal/model/info", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def get_current_model(): """Returns the currently loaded model.""" model_name = MODEL_CONTAINER.get_model_path().name prompt_template = MODEL_CONTAINER.prompt_template model_card = ModelCard( id=model_name, parameters=ModelCardParameters( rope_scale=MODEL_CONTAINER.config.scale_pos_emb, rope_alpha=MODEL_CONTAINER.config.scale_alpha_value, max_seq_len=MODEL_CONTAINER.config.max_seq_len, cache_mode="FP8" if MODEL_CONTAINER.cache_fp8 else "FP16", prompt_template=prompt_template.name if prompt_template else None, num_experts_per_token=MODEL_CONTAINER.config.num_experts_per_token, use_cfg=MODEL_CONTAINER.use_cfg, ), logging=gen_logging.PREFERENCES, ) if MODEL_CONTAINER.draft_config: draft_card = ModelCard( id=MODEL_CONTAINER.get_model_path(True).name, parameters=ModelCardParameters( rope_scale=MODEL_CONTAINER.draft_config.scale_pos_emb, rope_alpha=MODEL_CONTAINER.draft_config.scale_alpha_value, max_seq_len=MODEL_CONTAINER.draft_config.max_seq_len, ), ) model_card.parameters.draft = draft_card return model_card @app.get("/v1/model/draft/list", dependencies=[Depends(check_api_key)]) async def list_draft_models(): """Lists all draft models in the model directory.""" draft_model_dir = unwrap(get_draft_model_config().get("draft_model_dir"), "models") draft_model_path = pathlib.Path(draft_model_dir) models = get_model_list(draft_model_path.resolve()) return models # Load model endpoint @app.post("/v1/model/load", dependencies=[Depends(check_admin_key)])
"""The main tabbyAPI module. Contains the FastAPI server and endpoints.""" logger = init_logger(__name__) app = FastAPI( title="TabbyAPI", summary="An OAI compatible exllamav2 API that's both lightweight and fast", description=( "This docs page is not meant to send requests! Please use a service " "like Postman or a frontend UI." ), ) # Globally scoped variables. Undefined until initalized in main MODEL_CONTAINER: Optional[ModelContainer] = None def _check_model_container(): if MODEL_CONTAINER is None or MODEL_CONTAINER.model is None: raise HTTPException(400, "No models are loaded.") # ALlow CORS requests app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Model list endpoint @app.get("/v1/models", dependencies=[Depends(check_api_key)]) @app.get("/v1/model/list", dependencies=[Depends(check_api_key)]) async def list_models(): """Lists all models in the model directory.""" model_config = get_model_config() model_dir = unwrap(model_config.get("model_dir"), "models") model_path = pathlib.Path(model_dir) draft_model_dir = get_draft_model_config().get("draft_model_dir") models = get_model_list(model_path.resolve(), draft_model_dir) if unwrap(model_config.get("use_dummy_models"), False): models.data.insert(0, ModelCard(id="gpt-3.5-turbo")) return models # Currently loaded model endpoint @app.get( "/v1/model", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) @app.get( "/v1/internal/model/info", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def get_current_model(): """Returns the currently loaded model.""" model_name = MODEL_CONTAINER.get_model_path().name prompt_template = MODEL_CONTAINER.prompt_template model_card = ModelCard( id=model_name, parameters=ModelCardParameters( rope_scale=MODEL_CONTAINER.config.scale_pos_emb, rope_alpha=MODEL_CONTAINER.config.scale_alpha_value, max_seq_len=MODEL_CONTAINER.config.max_seq_len, cache_mode="FP8" if MODEL_CONTAINER.cache_fp8 else "FP16", prompt_template=prompt_template.name if prompt_template else None, num_experts_per_token=MODEL_CONTAINER.config.num_experts_per_token, use_cfg=MODEL_CONTAINER.use_cfg, ), logging=gen_logging.PREFERENCES, ) if MODEL_CONTAINER.draft_config: draft_card = ModelCard( id=MODEL_CONTAINER.get_model_path(True).name, parameters=ModelCardParameters( rope_scale=MODEL_CONTAINER.draft_config.scale_pos_emb, rope_alpha=MODEL_CONTAINER.draft_config.scale_alpha_value, max_seq_len=MODEL_CONTAINER.draft_config.max_seq_len, ), ) model_card.parameters.draft = draft_card return model_card @app.get("/v1/model/draft/list", dependencies=[Depends(check_api_key)]) async def list_draft_models(): """Lists all draft models in the model directory.""" draft_model_dir = unwrap(get_draft_model_config().get("draft_model_dir"), "models") draft_model_path = pathlib.Path(draft_model_dir) models = get_model_list(draft_model_path.resolve()) return models # Load model endpoint @app.post("/v1/model/load", dependencies=[Depends(check_admin_key)])
async def load_model(request: Request, data: ModelLoadRequest):
22
2023-11-10 05:54:02+00:00
16k
ShipBit/wingman-ai
services/tower.py
[ { "identifier": "MissingApiKeyException", "path": "exceptions.py", "snippet": "class MissingApiKeyException(Exception):\n pass" }, { "identifier": "OpenAiWingman", "path": "wingmen/open_ai_wingman.py", "snippet": "class OpenAiWingman(Wingman):\n \"\"\"Our OpenAI Wingman base gives ...
import copy from exceptions import MissingApiKeyException from wingmen.open_ai_wingman import OpenAiWingman from wingmen.wingman import Wingman from services.printr import Printr from services.secret_keeper import SecretKeeper
12,641
printr = Printr() class Tower: def __init__(self, config: dict[str, any], secret_keeper: SecretKeeper, app_root_dir: str): # type: ignore self.config = config self.app_root_dir = app_root_dir self.secret_keeper = secret_keeper self.key_wingman_dict: dict[str, Wingman] = {} self.broken_wingmen = [] self.wingmen = self.__instantiate_wingmen() self.key_wingman_dict: dict[str, Wingman] = {} for wingman in self.wingmen: self.key_wingman_dict[wingman.get_record_key()] = wingman def __instantiate_wingmen(self) -> list[Wingman]: wingmen = [] for wingman_name, wingman_config in self.config["wingmen"].items(): if wingman_config.get("disabled") is True: continue global_config = { "sound": self.config.get("sound", {}), "openai": self.config.get("openai", {}), "features": self.config.get("features", {}), "edge_tts": self.config.get("edge_tts", {}), "commands": self.config.get("commands", {}), "elevenlabs": self.config.get("elevenlabs", {}), "azure": self.config.get("azure", {}), } merged_config = self.__merge_configs(global_config, wingman_config) class_config = merged_config.get("class") wingman = None # it's a custom Wingman try: if class_config: kwargs = class_config.get("args", {}) wingman = Wingman.create_dynamically( name=wingman_name, config=merged_config, secret_keeper=self.secret_keeper, module_path=class_config.get("module"), class_name=class_config.get("name"), app_root_dir=self.app_root_dir, **kwargs ) else:
printr = Printr() class Tower: def __init__(self, config: dict[str, any], secret_keeper: SecretKeeper, app_root_dir: str): # type: ignore self.config = config self.app_root_dir = app_root_dir self.secret_keeper = secret_keeper self.key_wingman_dict: dict[str, Wingman] = {} self.broken_wingmen = [] self.wingmen = self.__instantiate_wingmen() self.key_wingman_dict: dict[str, Wingman] = {} for wingman in self.wingmen: self.key_wingman_dict[wingman.get_record_key()] = wingman def __instantiate_wingmen(self) -> list[Wingman]: wingmen = [] for wingman_name, wingman_config in self.config["wingmen"].items(): if wingman_config.get("disabled") is True: continue global_config = { "sound": self.config.get("sound", {}), "openai": self.config.get("openai", {}), "features": self.config.get("features", {}), "edge_tts": self.config.get("edge_tts", {}), "commands": self.config.get("commands", {}), "elevenlabs": self.config.get("elevenlabs", {}), "azure": self.config.get("azure", {}), } merged_config = self.__merge_configs(global_config, wingman_config) class_config = merged_config.get("class") wingman = None # it's a custom Wingman try: if class_config: kwargs = class_config.get("args", {}) wingman = Wingman.create_dynamically( name=wingman_name, config=merged_config, secret_keeper=self.secret_keeper, module_path=class_config.get("module"), class_name=class_config.get("name"), app_root_dir=self.app_root_dir, **kwargs ) else:
wingman = OpenAiWingman(
1
2023-11-15 09:36:06+00:00
16k
wjun0830/CGDETR
cg_detr/inference.py
[ { "identifier": "AverageMeter", "path": "utils/basic_utils.py", "snippet": "class AverageMeter(object):\n \"\"\"Computes and stores the average and current/max/min value\"\"\"\n def __init__(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n s...
import pprint import numpy as np import os import torch import torch.nn.functional as F import torch.backends.cudnn as cudnn import logging from tqdm import tqdm, trange from collections import OrderedDict, defaultdict from utils.basic_utils import AverageMeter from torch.utils.data import DataLoader from cg_detr.config import TestOptions from cg_detr.model import build_model from cg_detr.span_utils import span_cxw_to_xx from cg_detr.start_end_dataset import StartEndDataset, start_end_collate, prepare_batch_inputs from cg_detr.postprocessing_cg_detr import PostProcessorDETR from standalone_eval.eval import eval_submission from utils.basic_utils import save_jsonl, save_json from utils.temporal_nms import temporal_nms from collections import OrderedDict from sys import argv
10,919
logger = logging.getLogger(__name__) logging.basicConfig(format="%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) def post_processing_mr_nms(mr_res, nms_thd, max_before_nms, max_after_nms): mr_res_after_nms = [] for e in mr_res: e["pred_relevant_windows"] = temporal_nms( e["pred_relevant_windows"][:max_before_nms], nms_thd=nms_thd, max_after_nms=max_after_nms ) mr_res_after_nms.append(e) return mr_res_after_nms def eval_epoch_post_processing(submission, opt, gt_data, save_submission_filename): # IOU_THDS = (0.5, 0.7) logger.info("Saving/Evaluating before nms results") submission_path = os.path.join(opt.results_dir, save_submission_filename) save_jsonl(submission, submission_path) if opt.eval_split_name in ["val"]: # since test_public has no GT metrics = eval_submission( submission, gt_data, verbose=opt.debug, match_number=not opt.debug ) save_metrics_path = submission_path.replace(".jsonl", "_metrics.json")
logger = logging.getLogger(__name__) logging.basicConfig(format="%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) def post_processing_mr_nms(mr_res, nms_thd, max_before_nms, max_after_nms): mr_res_after_nms = [] for e in mr_res: e["pred_relevant_windows"] = temporal_nms( e["pred_relevant_windows"][:max_before_nms], nms_thd=nms_thd, max_after_nms=max_after_nms ) mr_res_after_nms.append(e) return mr_res_after_nms def eval_epoch_post_processing(submission, opt, gt_data, save_submission_filename): # IOU_THDS = (0.5, 0.7) logger.info("Saving/Evaluating before nms results") submission_path = os.path.join(opt.results_dir, save_submission_filename) save_jsonl(submission, submission_path) if opt.eval_split_name in ["val"]: # since test_public has no GT metrics = eval_submission( submission, gt_data, verbose=opt.debug, match_number=not opt.debug ) save_metrics_path = submission_path.replace(".jsonl", "_metrics.json")
save_json(metrics, save_metrics_path, save_pretty=True, sort_keys=False)
10
2023-11-10 12:45:25+00:00
16k
dazhangyu123/ACMIL
Step1_create_patches_fp.py
[ { "identifier": "WholeSlideImage", "path": "wsi_core/WholeSlideImage.py", "snippet": "class WholeSlideImage(object):\n def __init__(self, path):\n\n \"\"\"\n Args:\n path (str): fullpath to WSI file\n \"\"\"\n\n# self.name = \".\".join(path.split(\"/\")[-1].spl...
from wsi_core.WholeSlideImage import WholeSlideImage from wsi_core.wsi_utils import StitchCoords from wsi_core.batch_process_utils import initialize_df from glob import glob import os import numpy as np import time import argparse import pdb import pandas as pd
11,839
# internal imports # other imports def stitching(file_path, wsi_object, downscale=64): start = time.time() heatmap = StitchCoords(file_path, wsi_object, downscale=downscale, bg_color=(0, 0, 0), alpha=-1, draw_grid=False) total_time = time.time() - start return heatmap, total_time def segment(WSI_object, seg_params, filter_params): ### Start Seg Timer start_time = time.time() # Segment WSI_object.segmentTissue(**seg_params, filter_params=filter_params) ### Stop Seg Timers seg_time_elapsed = time.time() - start_time return WSI_object, seg_time_elapsed def patching(WSI_object, **kwargs): ### Start Patch Timer start_time = time.time() # Patch file_path = WSI_object.process_contours(**kwargs) ### Stop Patch Timer patch_time_elapsed = time.time() - start_time return file_path, patch_time_elapsed def walk_dir(data_dir, file_types=['.kfb', '.tif', '.svs', '.ndpi', '.mrxs', '.hdx', '.sdpc', '.mdsx', '.tiff', '.tmap']): path_list = [] for dirpath, dirnames, files in os.walk(data_dir): for f in files: for this_type in file_types: if f.lower().endswith(this_type): path_list.append(os.path.join(dirpath, f)) break return path_list def seg_and_patch(source, save_dir, patch_save_dir, mask_save_dir, stitch_save_dir, patch_size=256, step_size=256, seg_params={'seg_level': -1, 'sthresh': 8, 'mthresh': 7, 'close': 4, 'use_otsu': False, 'keep_ids': 'none', 'exclude_ids': 'none'}, filter_params={'a_t': 100, 'a_h': 16, 'max_n_holes': 8}, vis_params={'vis_level': -1, 'line_thickness': 500}, patch_params={'use_padding': True, 'contour_fn': 'four_pt'}, patch_level=1, use_default_params=False, seg=False, save_mask=True, stitch=False, patch=False, auto_skip=True, process_list=None): slides = glob(source + '/*/*/*/*.svs') # slides = sorted(os.listdir(source), reverse=True) # slides = # pdb.set_trace() # slides = slides[-10:] slides = [slide for slide in slides if os.path.isfile(os.path.join(source, slide))] if process_list is None:
# internal imports # other imports def stitching(file_path, wsi_object, downscale=64): start = time.time() heatmap = StitchCoords(file_path, wsi_object, downscale=downscale, bg_color=(0, 0, 0), alpha=-1, draw_grid=False) total_time = time.time() - start return heatmap, total_time def segment(WSI_object, seg_params, filter_params): ### Start Seg Timer start_time = time.time() # Segment WSI_object.segmentTissue(**seg_params, filter_params=filter_params) ### Stop Seg Timers seg_time_elapsed = time.time() - start_time return WSI_object, seg_time_elapsed def patching(WSI_object, **kwargs): ### Start Patch Timer start_time = time.time() # Patch file_path = WSI_object.process_contours(**kwargs) ### Stop Patch Timer patch_time_elapsed = time.time() - start_time return file_path, patch_time_elapsed def walk_dir(data_dir, file_types=['.kfb', '.tif', '.svs', '.ndpi', '.mrxs', '.hdx', '.sdpc', '.mdsx', '.tiff', '.tmap']): path_list = [] for dirpath, dirnames, files in os.walk(data_dir): for f in files: for this_type in file_types: if f.lower().endswith(this_type): path_list.append(os.path.join(dirpath, f)) break return path_list def seg_and_patch(source, save_dir, patch_save_dir, mask_save_dir, stitch_save_dir, patch_size=256, step_size=256, seg_params={'seg_level': -1, 'sthresh': 8, 'mthresh': 7, 'close': 4, 'use_otsu': False, 'keep_ids': 'none', 'exclude_ids': 'none'}, filter_params={'a_t': 100, 'a_h': 16, 'max_n_holes': 8}, vis_params={'vis_level': -1, 'line_thickness': 500}, patch_params={'use_padding': True, 'contour_fn': 'four_pt'}, patch_level=1, use_default_params=False, seg=False, save_mask=True, stitch=False, patch=False, auto_skip=True, process_list=None): slides = glob(source + '/*/*/*/*.svs') # slides = sorted(os.listdir(source), reverse=True) # slides = # pdb.set_trace() # slides = slides[-10:] slides = [slide for slide in slides if os.path.isfile(os.path.join(source, slide))] if process_list is None:
df = initialize_df(slides, seg_params, filter_params, vis_params, patch_params)
2
2023-11-12 14:07:34+00:00
16k
zhang-tao-whu/DVIS_Plus
dvis_Plus/meta_architecture.py
[ { "identifier": "VideoSetCriterion", "path": "mask2former_video/modeling/criterion.py", "snippet": "class VideoSetCriterion(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 ...
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.structures import Boxes, ImageList, Instances, BitMasks from mask2former_video.modeling.criterion import VideoSetCriterion from mask2former_video.modeling.matcher import VideoHungarianMatcher, VideoHungarianMatcher_Consistent from mask2former_video.utils.memory import retry_if_cuda_oom from scipy.optimize import linear_sum_assignment from .tracker import ReferringTracker_noiser from .refiner import TemporalRefiner from .utils import loss_reid, Outputs_Memory_PerClasses import einops import torch
11,986
@META_ARCH_REGISTRY.register() class MinVIS(nn.Module): """ Copied from "https://github.com/NVlabs/MinVIS". """ @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], # video num_frames, window_inference, ): """ 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) self.num_frames = num_frames self.window_inference = window_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
@META_ARCH_REGISTRY.register() class MinVIS(nn.Module): """ Copied from "https://github.com/NVlabs/MinVIS". """ @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], # video num_frames, window_inference, ): """ 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) self.num_frames = num_frames self.window_inference = window_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 = VideoHungarianMatcher(
1
2023-11-14 10:55:11+00:00
16k
ej0cl6/TextEE
TextEE/models/Degree/EAEtrainer.py
[ { "identifier": "BasicTrainer", "path": "TextEE/models/trainer.py", "snippet": "class BasicTrainer(object):\n def __init__(self, config, type_set=None):\n self.config = config\n self.type_set = type_set\n \n @classmethod\n def add_extra_info_fn(cls, instances, raw_data, con...
import os, sys, logging, tqdm, pprint import torch import numpy as np import ipdb from collections import namedtuple from transformers import BartTokenizer, AutoTokenizer, get_linear_schedule_with_warmup from torch.utils.data import DataLoader from torch.optim import AdamW from ..trainer import BasicTrainer from .EAEmodel import DegreeEAEModel from .template_generate import event_template, eve_template_generator from .pattern import patterns, ROLE_PH_MAP from scorer import compute_EAE_scores, print_scores
11,981
logger = logging.getLogger(__name__) EAEBatch_fields = ['batch_doc_id', 'batch_wnd_id', 'batch_tokens', 'batch_text', 'batch_piece_idxs', 'batch_token_start_idxs', 'batch_trigger', 'batch_arguments', 'batch_input', 'batch_target'] EAEBatch = namedtuple('EAEBatch', field_names=EAEBatch_fields, defaults=[None] * len(EAEBatch_fields)) def EAE_collate_fn(batch): return EAEBatch( batch_doc_id=[instance["doc_id"] for instance in batch], batch_wnd_id=[instance["wnd_id"] for instance in batch], batch_tokens=[instance["tokens"] for instance in batch], batch_text=[instance["text"] for instance in batch], batch_piece_idxs=[instance["piece_idxs"] for instance in batch], batch_token_start_idxs=[instance["token_start_idxs"] for instance in batch], batch_trigger=[instance["trigger"] for instance in batch], batch_arguments=[instance["arguments"] for instance in batch], batch_input=[instance["input"] for instance in batch], batch_target=[instance["target"] for instance in batch], ) def get_span_idx(pieces, token_start_idxs, span, tokenizer, trigger_span=None): """ This function is how we map the generated prediction back to span prediction. Detailed Explanation: We will first split our prediction and use tokenizer to tokenize our predicted "span" into pieces. Then, we will find whether we can find a continuous span in the original "pieces" can match tokenized "span". If it is an argument/relation extraction task, we will return the one which is closest to the trigger_span. """ words = [] for s in span.split(' '): words.extend(tokenizer.encode(s, add_special_tokens=False)) candidates = [] for i in range(len(pieces)): j = 0 k = 0 while j < len(words) and i+k < len(pieces): if pieces[i+k] == words[j]: j += 1 k += 1 elif tokenizer.decode(words[j]) == "": j += 1 elif tokenizer.decode(pieces[i+k]) == "": k += 1 else: break if j == len(words): candidates.append((i, i+k)) candidates = [(token_start_idxs.index(c1), token_start_idxs.index(c2)) for c1, c2 in candidates if c1 in token_start_idxs and c2 in token_start_idxs] if len(candidates) < 1: return -1, -1 else: if trigger_span is None: return candidates[0] else: return sorted(candidates, key=lambda x: np.abs(trigger_span[0]-x[0]))[0] class DegreeEAETrainer(BasicTrainer): def __init__(self, config, type_set=None): super().__init__(config, type_set) self.tokenizer = None self.model = None def load_model(self, checkpoint=None): if checkpoint: logger.info(f"Loading model from {checkpoint}") state = torch.load(os.path.join(checkpoint, "best_model.state"), map_location=f'cuda:{self.config.gpu_device}') self.tokenizer = state["tokenizer"] self.type_set = state["type_set"]
logger = logging.getLogger(__name__) EAEBatch_fields = ['batch_doc_id', 'batch_wnd_id', 'batch_tokens', 'batch_text', 'batch_piece_idxs', 'batch_token_start_idxs', 'batch_trigger', 'batch_arguments', 'batch_input', 'batch_target'] EAEBatch = namedtuple('EAEBatch', field_names=EAEBatch_fields, defaults=[None] * len(EAEBatch_fields)) def EAE_collate_fn(batch): return EAEBatch( batch_doc_id=[instance["doc_id"] for instance in batch], batch_wnd_id=[instance["wnd_id"] for instance in batch], batch_tokens=[instance["tokens"] for instance in batch], batch_text=[instance["text"] for instance in batch], batch_piece_idxs=[instance["piece_idxs"] for instance in batch], batch_token_start_idxs=[instance["token_start_idxs"] for instance in batch], batch_trigger=[instance["trigger"] for instance in batch], batch_arguments=[instance["arguments"] for instance in batch], batch_input=[instance["input"] for instance in batch], batch_target=[instance["target"] for instance in batch], ) def get_span_idx(pieces, token_start_idxs, span, tokenizer, trigger_span=None): """ This function is how we map the generated prediction back to span prediction. Detailed Explanation: We will first split our prediction and use tokenizer to tokenize our predicted "span" into pieces. Then, we will find whether we can find a continuous span in the original "pieces" can match tokenized "span". If it is an argument/relation extraction task, we will return the one which is closest to the trigger_span. """ words = [] for s in span.split(' '): words.extend(tokenizer.encode(s, add_special_tokens=False)) candidates = [] for i in range(len(pieces)): j = 0 k = 0 while j < len(words) and i+k < len(pieces): if pieces[i+k] == words[j]: j += 1 k += 1 elif tokenizer.decode(words[j]) == "": j += 1 elif tokenizer.decode(pieces[i+k]) == "": k += 1 else: break if j == len(words): candidates.append((i, i+k)) candidates = [(token_start_idxs.index(c1), token_start_idxs.index(c2)) for c1, c2 in candidates if c1 in token_start_idxs and c2 in token_start_idxs] if len(candidates) < 1: return -1, -1 else: if trigger_span is None: return candidates[0] else: return sorted(candidates, key=lambda x: np.abs(trigger_span[0]-x[0]))[0] class DegreeEAETrainer(BasicTrainer): def __init__(self, config, type_set=None): super().__init__(config, type_set) self.tokenizer = None self.model = None def load_model(self, checkpoint=None): if checkpoint: logger.info(f"Loading model from {checkpoint}") state = torch.load(os.path.join(checkpoint, "best_model.state"), map_location=f'cuda:{self.config.gpu_device}') self.tokenizer = state["tokenizer"] self.type_set = state["type_set"]
self.model = DegreeEAEModel(self.config, self.tokenizer, self.type_set)
1
2023-11-15 21:32:56+00:00
16k
ahayler/s4c
scripts/videos/gen_vid_transition.py
[ { "identifier": "BTSNet", "path": "models/bts/model/models_bts.py", "snippet": "class BTSNet(torch.nn.Module):\n def __init__(self, conf):\n super().__init__()\n\n self.d_min = conf.get(\"z_near\")\n self.d_max = conf.get(\"z_far\")\n\n self.learn_empty = conf.get(\"learn_...
import numpy as np import sys import copy import hydra import torch from moviepy.video.io.ImageSequenceClip import ImageSequenceClip from scipy.spatial.transform import Rotation from tqdm import tqdm from scripts.inference_setup import * from models.bts.model import BTSNet, ImageRaySampler from models.common.render import NeRFRenderer from utils.array_operations import map_fn, unsqueezer from utils.plotting import color_tensor
12,693
if task == "KITTI-360": dataset, config_path, cp_path, out_path, resolution, cam_incl_adjust = setup_kitti360("videos/transition", "test") z_top = 10 y_top = -6 t_near = 5 t_far = 7 target_angle = math.radians(85) elif task == "KITTI-Raw": dataset, config_path, cp_path, out_path, resolution, cam_incl_adjust = setup_kittiraw("videos/transition", "test") z_top = 14 y_top = -8 t_near = 8 t_far = 10 target_angle = math.radians(90) else: raise ValueError(f"Invalid task: {task}") # Slightly hacky, but we need to load the config based on the task global config config = {} @hydra.main(version_base=None, config_path="../../configs", config_name=config_path) def main_dummy(cfg): global config config = copy.deepcopy(cfg) main_dummy() print("Setup folders") out_path.mkdir(exist_ok=True, parents=True) print('Loading checkpoint') cp = torch.load(cp_path, map_location=device) net = BTSNet(config["model_conf"]) renderer = NeRFRenderer.from_conf(config["renderer"]) renderer = renderer.bind_parallel(net, gpus=None).eval() renderer.renderer.n_coarse = 64 renderer.renderer.lindisp = True class _Wrapper(nn.Module): def __init__(self): super().__init__() self.renderer = renderer _wrapper = _Wrapper() _wrapper.load_state_dict(cp["model"], strict=False) renderer.to(device) renderer.eval() ray_sampler = ImageRaySampler(config["model_conf"]["z_near"], config["model_conf"]["z_far"], *resolution, norm_dir=False) z_near = config["model_conf"]["z_near"] z_far = config["model_conf"]["z_far"] z_near = d_min z_far = d_max with torch.no_grad(): for idx in indices: data = dataset[idx] data_batch = map_fn(map_fn(data, torch.tensor), unsqueezer) images = torch.stack(data_batch["imgs"], dim=1).to(device) poses = torch.stack(data_batch["poses"], dim=1).to(device) projs = torch.stack(data_batch["projs"], dim=1).to(device) # Move coordinate system to input frame poses = torch.inverse(poses[:, :1, :, :]) @ poses net.encode(images, projs, poses, ids_encoder=[0], ids_render=[0]) net.set_scale(0) frames = [] for i in tqdm(range(length + 5)): prog = (i / (length - 1)) ** 2 prog = min(prog, 1) pose = torch.eye(4, device=device) angle = -target_angle * prog rotation = torch.tensor(Rotation.from_euler("x", angle, degrees=False).as_matrix(), device=device) pose[:3, :3] = rotation z = z_top - math.cos(-angle) * z_top y = math.sin(-angle) * y_top pose[1, 3] = y pose[2, 3] = z z_near_ = z_near * (1 - prog) + t_near * prog z_far_ = z_far * (1 - prog) + t_far * prog target_width = int(resolution[1] * (1 - prog) + resolution[0] * prog) pad_left = (resolution[1] - target_width) // 2 pad_right = (resolution[1] - target_width) - pad_left projs_ = projs[:, :1].clone() projs_[0, 0, 1, 1] = projs_[0, 0, 1, 1] * (target_width / resolution[1]) ray_sampler.width = target_width ray_sampler.z_near = z_near_ ray_sampler.z_far = z_far_ novel_view, depth = render_poses(renderer, ray_sampler, pose.view(1, 1, 4, 4), projs_[:, :1]) depth = 1 / depth.squeeze() depth = ((depth - 1 / z_far_) / (1 / z_near_ - 1 / z_far_)).clamp(0, 1) novel_view = novel_view.squeeze(-2).squeeze(0) if i > 0: depth_ = torch.zeros(*resolution, device=device) depth_[:, pad_left:-pad_right] = depth depth = depth_ novel_view_ = torch.zeros(*resolution, 3, device=device) novel_view_[:, pad_left:-pad_right, :] = novel_view novel_view = novel_view_ novel_view = novel_view[:, :].cpu().numpy()
sys.path.append(".") def main(): s_img = True s_depth = True dry_run = False indices = [0] task = "KITTI-360" assert task in ["KITTI-360", "KITTI-Raw"] length = 30 d_min = 3 d_max = 40 if task == "KITTI-360": dataset, config_path, cp_path, out_path, resolution, cam_incl_adjust = setup_kitti360("videos/transition", "test") z_top = 10 y_top = -6 t_near = 5 t_far = 7 target_angle = math.radians(85) elif task == "KITTI-Raw": dataset, config_path, cp_path, out_path, resolution, cam_incl_adjust = setup_kittiraw("videos/transition", "test") z_top = 14 y_top = -8 t_near = 8 t_far = 10 target_angle = math.radians(90) else: raise ValueError(f"Invalid task: {task}") # Slightly hacky, but we need to load the config based on the task global config config = {} @hydra.main(version_base=None, config_path="../../configs", config_name=config_path) def main_dummy(cfg): global config config = copy.deepcopy(cfg) main_dummy() print("Setup folders") out_path.mkdir(exist_ok=True, parents=True) print('Loading checkpoint') cp = torch.load(cp_path, map_location=device) net = BTSNet(config["model_conf"]) renderer = NeRFRenderer.from_conf(config["renderer"]) renderer = renderer.bind_parallel(net, gpus=None).eval() renderer.renderer.n_coarse = 64 renderer.renderer.lindisp = True class _Wrapper(nn.Module): def __init__(self): super().__init__() self.renderer = renderer _wrapper = _Wrapper() _wrapper.load_state_dict(cp["model"], strict=False) renderer.to(device) renderer.eval() ray_sampler = ImageRaySampler(config["model_conf"]["z_near"], config["model_conf"]["z_far"], *resolution, norm_dir=False) z_near = config["model_conf"]["z_near"] z_far = config["model_conf"]["z_far"] z_near = d_min z_far = d_max with torch.no_grad(): for idx in indices: data = dataset[idx] data_batch = map_fn(map_fn(data, torch.tensor), unsqueezer) images = torch.stack(data_batch["imgs"], dim=1).to(device) poses = torch.stack(data_batch["poses"], dim=1).to(device) projs = torch.stack(data_batch["projs"], dim=1).to(device) # Move coordinate system to input frame poses = torch.inverse(poses[:, :1, :, :]) @ poses net.encode(images, projs, poses, ids_encoder=[0], ids_render=[0]) net.set_scale(0) frames = [] for i in tqdm(range(length + 5)): prog = (i / (length - 1)) ** 2 prog = min(prog, 1) pose = torch.eye(4, device=device) angle = -target_angle * prog rotation = torch.tensor(Rotation.from_euler("x", angle, degrees=False).as_matrix(), device=device) pose[:3, :3] = rotation z = z_top - math.cos(-angle) * z_top y = math.sin(-angle) * y_top pose[1, 3] = y pose[2, 3] = z z_near_ = z_near * (1 - prog) + t_near * prog z_far_ = z_far * (1 - prog) + t_far * prog target_width = int(resolution[1] * (1 - prog) + resolution[0] * prog) pad_left = (resolution[1] - target_width) // 2 pad_right = (resolution[1] - target_width) - pad_left projs_ = projs[:, :1].clone() projs_[0, 0, 1, 1] = projs_[0, 0, 1, 1] * (target_width / resolution[1]) ray_sampler.width = target_width ray_sampler.z_near = z_near_ ray_sampler.z_far = z_far_ novel_view, depth = render_poses(renderer, ray_sampler, pose.view(1, 1, 4, 4), projs_[:, :1]) depth = 1 / depth.squeeze() depth = ((depth - 1 / z_far_) / (1 / z_near_ - 1 / z_far_)).clamp(0, 1) novel_view = novel_view.squeeze(-2).squeeze(0) if i > 0: depth_ = torch.zeros(*resolution, device=device) depth_[:, pad_left:-pad_right] = depth depth = depth_ novel_view_ = torch.zeros(*resolution, 3, device=device) novel_view_[:, pad_left:-pad_right, :] = novel_view novel_view = novel_view_ novel_view = novel_view[:, :].cpu().numpy()
depth = color_tensor(depth.cpu(), "magma", norm=False).numpy()
4
2023-11-12 21:53:27+00:00
16k
TCLResearchEurope/torch-dag
torch_dag_algorithms/pruning/module_multipliers.py
[ { "identifier": "structured_modules", "path": "torch_dag/structured_modules.py", "snippet": "ACTIVATION_MODULES_T = Union[\n nn.ReLU,\n nn.ReLU6,\n nn.SiLU,\n nn.Softmax,\n nn.Sigmoid,\n nn.Hardswish,\n nn.Hardsigmoid,\n nn.GELU,\n nn.LeakyReLU,\n nn.ELU,\n nn.Tanh,\n ...
import logging import torch from typing import List, Tuple, Dict, Union from torch_dag import structured_modules as smodules from torch_dag.core.dag_module import DagModule from torch_dag.core.dag_module import InputVertex, InnerVertex, Vertex from torch_dag_algorithms.pruning.commons import PASS_THROUGH_CHANNELS_CLASSES from torch_dag_algorithms.pruning.commons import is_source, get_orbits_dict, is_linear_source, is_depthwise_conv from torch_dag_algorithms.pruning.modules import OrbitModule from torch_dag_timm_plugin.module_multipliers import compute_timm_average_num_channels, \ CUSTOM_AVERAGE_CHANNELS_TIMM_CLASSES
11,644
# # Copyright © TCL Research Europe. All rights reserved. # logger = logging.getLogger(__name__) PASS_THROUGH_MULTIPLIER_CLASSES = PASS_THROUGH_CHANNELS_CLASSES def shape_to_float(shape, device, dim=1): return torch.tensor(shape[dim], device=device).to(torch.float32) def compute_elementwise_op_average_channels(average_number_input_channels: List[List[torch.Tensor]], ): average_number_input_channels = [e for e in average_number_input_channels if e is not None] if len(average_number_input_channels) == 0: return None return [torch.max(torch.stack([e[0] for e in average_number_input_channels]))] def compute_average_num_channels(
# # Copyright © TCL Research Europe. All rights reserved. # logger = logging.getLogger(__name__) PASS_THROUGH_MULTIPLIER_CLASSES = PASS_THROUGH_CHANNELS_CLASSES def shape_to_float(shape, device, dim=1): return torch.tensor(shape[dim], device=device).to(torch.float32) def compute_elementwise_op_average_channels(average_number_input_channels: List[List[torch.Tensor]], ): average_number_input_channels = [e for e in average_number_input_channels if e is not None] if len(average_number_input_channels) == 0: return None return [torch.max(torch.stack([e[0] for e in average_number_input_channels]))] def compute_average_num_channels(
vertex: InnerVertex,
3
2023-11-17 15:36:44+00:00
16k
newcastleuniversity/DISPEL
dispel/providers/generic/tasks/gait/lee.py
[ { "identifier": "MeasureValueDefinitionPrototype", "path": "dispel/data/measures.py", "snippet": "class MeasureValueDefinitionPrototype(ValueDefinitionPrototype):\n \"\"\"A task measure value definition prototype.\n\n This is a convenience method that populates the ``cls`` argument with the\n :...
import enum import pandas as pd from typing import List, Optional, Tuple from dispel.data.measures import MeasureValueDefinitionPrototype from dispel.data.validators import GREATER_THAN_ZERO from dispel.data.values import AbbreviatedValue as AV from dispel.processing.core import ProcessingStep from dispel.processing.extract import ( DEFAULT_AGGREGATIONS, AggregateRawDataSetColumn, ExtractStep, ) from dispel.processing.level import ProcessingStepGroup from dispel.providers.generic.tasks.gait.bout_strategy import BoutStrategyModality from dispel.providers.generic.tasks.gait.core import ( DetectStepsProcessingBase, DetectStepsWithoutBoutsBase, ExtractPowerBoutDivSteps, ExtractStepCount, ExtractStepDurationAll, FootUsed, StepEvent, power_bout_div_steps, step_count, ) from dispel.providers.generic.tasks.gait.hip import ( ExtractHipRotation, ExtractHipRotationWithoutBouts, HipRotationGroup, ) from dispel.signal.core import index_time_diff
11,440
t_thresh=peak_threshold, acc_threshold=acc_peak, further=False, ): # (3) _set_state(it_peak, StepState.INTMD) _set_state(it_n, StepState.PEAK) last_state = StepState.PEAK it_peak = it_n acc_peak, peak_threshold = _update_peak_valley( res, StepState.PEAK, it_n, BETA, M_SIGMA ) # This should only be triggered once at the initialization of the # algorithm, when it is 1. elif last_state == StepState.INITIAL: # (1) _set_state(it_n, StepState.PEAK) last_state = StepState.PEAK it_peak = it_n acc_peak, peak_threshold = _update_peak_valley( res, StepState.PEAK, it_n, BETA, M_SIGMA ) elif candidate_state == StepState.VALLEY: if _check_state( data=res["vertical_acc"], last_state=last_state, expected_state=StepState.PEAK, index_s=it_valley, index_c=it_n, t_thresh=valley_threshold, ): # (4) _set_state(it_n, StepState.VALLEY) last_state = StepState.VALLEY it_valley = it_n acc_valley, valley_threshold = _update_peak_valley( res, StepState.VALLEY, it_n, BETA, M_SIGMA ) step_index += 1 mu_a = (acc_peak + acc_valley) / 2 elif _check_state( data=res["vertical_acc"], last_state=last_state, expected_state=StepState.VALLEY, index_s=it_valley, index_c=it_n, t_thresh=valley_threshold, acc_threshold=acc_valley, greater=False, further=False, ): # (5) _set_state(it_valley, StepState.INTMD) _set_state(it_n, StepState.VALLEY) last_state = StepState.VALLEY it_valley = it_n acc_valley, valley_threshold = _update_peak_valley( res, StepState.VALLEY, it_n, BETA, M_SIGMA ) # Update sigma sigma_a = _update_sigma(res.iloc[max(0, it_n - K_SIGMA) : it_n]["vertical_acc"]) res.loc[res.index[it_n], "step_index"] = step_index return res def detect_steps(data: pd.DataFrame) -> pd.DataFrame: """Run step Detection Algorithm from Lee et al. and format the results. We use a revisited Lee et al. algorithm since we don't perform step detection on the acceleration norm but on the vertical acceleration. The results are formatted to return a generic data frame with the following columns: ``timestamp``, ``event``, ``foot``. Where ``event`` annotate what is happening as in Bourke et al. doi:10.3390/s20205906. Parameters ---------- data A data frame containing a column 'vertical_acc' referring to the vertical acceleration. Returns ------- pandas.DataFrame A pandas data frame with columns ``event``, ``foot`` and ``timestamp``. """ detected_steps = _detect_steps(data["vertical_acc"]) timestamp = detected_steps.index[detected_steps["state"] == StepState.PEAK] return pd.DataFrame( { "event": StepEvent.INITIAL_CONTACT, "foot": FootUsed.UNKNOWN, "timestamp": timestamp, } ).set_index(keys="timestamp") class LeeDetectSteps(DetectStepsProcessingBase): """Detect steps using Lee et al. algorithm on vertical acceleration.""" new_data_set_id = "lee_with_walking_bouts" @staticmethod def step_detection_method(data: pd.DataFrame) -> pd.DataFrame: """Define and declare the step detection as a static method.""" return detect_steps(data) class LeeDetectStepsWithoutBout(DetectStepsWithoutBoutsBase): """Detect steps using Lee et al. algorithm on vertical acceleration.""" data_set_ids = "vertical_acceleration" new_data_set_id = "lee" transform_function = detect_steps class LeeStepCountWithoutBout(ExtractStep): """Extract step count with lee dataset without walking bouts.""" def __init__(self, **kwargs): data_set_ids = "lee"
"""Step detection module specific to Lee et al. algorithm. This module contains functionality to perform step detection with a revisited version of the Lee et al. algorithm. """ class StepState(enum.IntEnum): """Step detection states for Lee et al. algorithm.""" PEAK = 2 VALLEY = 1 INTMD = 0 INITIAL = -1 LEE_MOD = AV("Lee algorithm", "lee") r"""A modality indicating something has been computed with Lee algorithm.""" # MODEL CONSTANTS K_SIGMA = 25 r"""Parameter K_SIGMA should be selected such that the step deviation can reflect the long-term variation in the statistics of the vertical acceleration. The value of 25 is assigned to K to cover one step cycle in normal walking speed with the sampling rate of 50 Hz.""" M_SIGMA = 10 r"""Parameter M should be selected with :math:`\beta` such that the statistics of peak or valley intervals can reflect the time-varying speed of walking or running and the noisy peaks or valleys can be delineated from real peaks or valleys.""" ALPHA = 4 r"""Parameter :math:`\alpha` is a magnitude constant that should be assigned so as not to disturb the peak or valley detection due to large step deviation during step mode change, especially from running to walking.""" BETA = 1 / 3 r"""Parameter :math:`\beta` is a time scale constant that should be assigned with M. It is used to rescale (as a denominator) the standard deviation of the last M peak or valley time-intervals when computing the time threshold used to accept or reject any peak or valley candidate.""" # Parameters Initialization (not defined in the paper). DEFAULT_MU = 0.25 r"""Default parameter :math:`\mu` is used to initiate the average time between two consecutive peaks (valleys) for the last M peaks (valleys).""" DEFAULT_SIGMA = 0.0 r"""Default parameter :math:`\sigma` is used to initiate the standard deviation of the time between two consecutive peaks (valleys) for the last M peaks (valleys).""" DEFAULT_SIGMA_A = 0.0 r"""Default parameter :math:`\sigma` is used to initiate the standard deviation of the vertical acceleration for recent K_SIGMA acceleration samples.""" DEFAULT_PEAK_THRESHOLD = 0.025 # the adaptive time threshold for peaks r"""Default parameter peak threshold is used to initialize the adaptive time threshold for peaks. This threshold will be used to accept or reject a peak candidate based on the time-interval separating it from the previous peak in addition to other conditions.""" DEFAULT_VALLEY_THRESHOLD = 0.025 # the adaptive time threshold for valley r"""Default parameter valley threshold is used to initialize the valley threshold. This threshold will be used to accept or reject any valley candidates based on the time interval separating it from the previous valley candidate and other conditions.""" DEFAULT_VALLEY_ACC = 0.0 r"""Default parameter used to initialize the vertical acceleration of a valley.""" DEFAULT_PEAK_ACC = 1.0 r"""Default parameter used to initialize the vertical acceleration of a peak.""" def _detect_candidate( data: pd.Series, index_sample: int, mu_a: float, sigma_a: float, alpha: float ) -> StepState: """Detect peak and valley candidates in the signal. This function labels each sample as valley, peak, or intermediate. The sample is considered a peak if: case 1 it is the first sample or case 2 , if the sample vertical acceleration is greater than the previous and next vertical acceleration and more significant than the average detection step (plus a modulation). Parameters ---------- data A series of the vertical acceleration. index_sample An integer indicating which sample is under examination. mu_a The average of the vertical acceleration of a step. Defined as the mean of the magnitude of the recent peak and recent valley. sigma_a The standard deviation of the vertical acceleration. alpha A constant to modulate the threshold on vertical acceleration used to label a sample. Returns ------- StepState A label indicating if the sample is a good candidate for a peak, a valley or an intermediate sample. """ if index_sample == 1: return StepState.PEAK acc_minus, acc, acc_plus = data.iloc[index_sample - 1 : index_sample + 2] if acc > max(max(acc_minus, acc_plus), mu_a + sigma_a / alpha): return StepState.PEAK if acc < min(min(acc_minus, acc_plus), mu_a - sigma_a / alpha): return StepState.VALLEY return StepState.INTMD def _update_peak_valley( data: pd.DataFrame, new_state: StepState, index_sample: int, beta: float, m_sigma: int, ) -> Tuple[float, float]: """Update a peak or a valley. Parameters ---------- data A data frame of the vertical acceleration and states. new_state Either peak or valley, it indicates if a peak or a valley is to be updated. index_sample An integer indicating which sample is under examination. beta A time scale constant. m_sigma A parameter used to delineate noisy peaks or valley from real peaks or valleys. Returns ------- Tuple[float, float] The vertical acceleration of current sample. And the minimum time distance to the recent peak (or valley). """ peaks_or_valley = data.loc[data["state"] == new_state] t_between = index_time_diff(peaks_or_valley)[1:] if len(t_between) > 1: # enough data sigma = t_between.tail(m_sigma).std() mu_x = t_between.tail(m_sigma).mean() elif len(t_between) == 1: # just enough for the mean mu_x = t_between.tail(m_sigma).mean() sigma = DEFAULT_SIGMA else: # initialization sigma = DEFAULT_SIGMA mu_x = DEFAULT_MU threshold = mu_x - sigma / beta return data.iloc[index_sample]["vertical_acc"], threshold def _update_sigma(data: pd.Series) -> float: """Update sigma. ``sigma_a`` is defined as the standard deviation of the vertical acceleration for recent ``k_sigma`` acceleration samples. Parameters ---------- data A series of the last k_sigma vertical acceleration. Returns ------- float The standard deviation of the vertical acceleration over the last k_sigma samples. """ if len(data) > 1: return data.std() return DEFAULT_SIGMA_A def _check_state( data: pd.Series, last_state: StepState, expected_state: StepState, index_s: int, index_c: int, t_thresh: float, acc_threshold: Optional[float] = None, greater: bool = True, further: bool = True, ) -> bool: """Check conditions on the last_state, time, and vertical acceleration. Parameters ---------- data A series of the vertical acceleration. last_state Either peak or valley, it indicates if a peak or a valley was the last specific state. expected_state Expected value for the last_state. index_s Index of the last state. index_c Index of the current state. t_thresh A threshold on time to remove close peaks/valleys acc_threshold A threshold on the vertical acceleration to potentially replace peaks/valleys. greater A boolean deciding if acc_threshold should be compared with a greater or less than comparator. further A boolean deciding if the time threshold should be compared with a a greater or less than comparator. Returns ------- bool A boolean indicating if the conditions are respected """ # Does the last_state matches the expected state c_1 = last_state == expected_state # Is the current sample far enough from the previous specific state c_2 = (data.index[index_c] - data.index[index_s]).total_seconds() if further: c_2 = c_2 > t_thresh else: c_2 = c_2 <= t_thresh # If the acceleration threshold is provided compare it to the current # sample if acc_threshold: c_3 = data[data.index[index_c]] if greater: c_3 = c_3 > acc_threshold else: c_3 = c_3 <= acc_threshold return c_1 and c_2 and c_3 return c_1 and c_2 def _detect_steps(data: pd.Series) -> pd.DataFrame: """Step Detection Algorithm from Lee et al. 2015. Full reference: Lee, H.-H.; Choi, S.; Lee, M.-J. Step Detection Robust against the Dynamics of Smartphones. Sensors 2015, 15, 27230-27250. Parameters ---------- data A series of the vertical acceleration. Returns ------- pandas.DataFrame A data frame containing the candidate and final state detected, as well as the step_index, a variable keeping track of when a step is detected. """ res = pd.DataFrame( { "vertical_acc": data.copy(), "state": StepState.INTMD, "candidate_state": None, "step_index": 0, } ) # the adaptive time threshold for peaks peak_threshold = DEFAULT_PEAK_THRESHOLD # the adaptive time threshold for valley valley_threshold = DEFAULT_VALLEY_THRESHOLD acc_valley = DEFAULT_VALLEY_ACC acc_peak = DEFAULT_PEAK_ACC # the step average mu_a = res["vertical_acc"].mean() # the step deviation of the vertical acceleration sigma_a = DEFAULT_SIGMA_A # ``last_state`` tracks the last particular state, either peak or valley # and will replace Sn-1 in the algorithm description page 27240. last_state = StepState.INITIAL step_index = 0 it_peak = 0 it_valley = 0 def _set_state(i: int, state: StepState, state_column: str = "state"): """Set the state at a given index.""" res.loc[res.index[i], state_column] = state for it_n in range(1, len(res) - 1): # Determine if the sample is a potential peak or valley candidate candidate_state = _detect_candidate( res["vertical_acc"], it_n, mu_a, sigma_a, ALPHA ) # Save the candidate state _set_state(it_n, candidate_state, "candidate_state") # Initialize the ``state`` to 'intermediate' _set_state(it_n, StepState.INTMD) if candidate_state == StepState.PEAK: if _check_state( data=res["vertical_acc"], last_state=last_state, expected_state=StepState.VALLEY, index_s=it_peak, index_c=it_n, t_thresh=peak_threshold, ): # (2) _set_state(it_n, StepState.PEAK) last_state = StepState.PEAK it_peak = it_n acc_peak, peak_threshold = _update_peak_valley( res, StepState.PEAK, it_n, BETA, M_SIGMA ) mu_a = (acc_peak + acc_valley) / 2 elif _check_state( data=res["vertical_acc"], last_state=last_state, expected_state=StepState.PEAK, index_s=it_peak, index_c=it_n, t_thresh=peak_threshold, acc_threshold=acc_peak, further=False, ): # (3) _set_state(it_peak, StepState.INTMD) _set_state(it_n, StepState.PEAK) last_state = StepState.PEAK it_peak = it_n acc_peak, peak_threshold = _update_peak_valley( res, StepState.PEAK, it_n, BETA, M_SIGMA ) # This should only be triggered once at the initialization of the # algorithm, when it is 1. elif last_state == StepState.INITIAL: # (1) _set_state(it_n, StepState.PEAK) last_state = StepState.PEAK it_peak = it_n acc_peak, peak_threshold = _update_peak_valley( res, StepState.PEAK, it_n, BETA, M_SIGMA ) elif candidate_state == StepState.VALLEY: if _check_state( data=res["vertical_acc"], last_state=last_state, expected_state=StepState.PEAK, index_s=it_valley, index_c=it_n, t_thresh=valley_threshold, ): # (4) _set_state(it_n, StepState.VALLEY) last_state = StepState.VALLEY it_valley = it_n acc_valley, valley_threshold = _update_peak_valley( res, StepState.VALLEY, it_n, BETA, M_SIGMA ) step_index += 1 mu_a = (acc_peak + acc_valley) / 2 elif _check_state( data=res["vertical_acc"], last_state=last_state, expected_state=StepState.VALLEY, index_s=it_valley, index_c=it_n, t_thresh=valley_threshold, acc_threshold=acc_valley, greater=False, further=False, ): # (5) _set_state(it_valley, StepState.INTMD) _set_state(it_n, StepState.VALLEY) last_state = StepState.VALLEY it_valley = it_n acc_valley, valley_threshold = _update_peak_valley( res, StepState.VALLEY, it_n, BETA, M_SIGMA ) # Update sigma sigma_a = _update_sigma(res.iloc[max(0, it_n - K_SIGMA) : it_n]["vertical_acc"]) res.loc[res.index[it_n], "step_index"] = step_index return res def detect_steps(data: pd.DataFrame) -> pd.DataFrame: """Run step Detection Algorithm from Lee et al. and format the results. We use a revisited Lee et al. algorithm since we don't perform step detection on the acceleration norm but on the vertical acceleration. The results are formatted to return a generic data frame with the following columns: ``timestamp``, ``event``, ``foot``. Where ``event`` annotate what is happening as in Bourke et al. doi:10.3390/s20205906. Parameters ---------- data A data frame containing a column 'vertical_acc' referring to the vertical acceleration. Returns ------- pandas.DataFrame A pandas data frame with columns ``event``, ``foot`` and ``timestamp``. """ detected_steps = _detect_steps(data["vertical_acc"]) timestamp = detected_steps.index[detected_steps["state"] == StepState.PEAK] return pd.DataFrame( { "event": StepEvent.INITIAL_CONTACT, "foot": FootUsed.UNKNOWN, "timestamp": timestamp, } ).set_index(keys="timestamp") class LeeDetectSteps(DetectStepsProcessingBase): """Detect steps using Lee et al. algorithm on vertical acceleration.""" new_data_set_id = "lee_with_walking_bouts" @staticmethod def step_detection_method(data: pd.DataFrame) -> pd.DataFrame: """Define and declare the step detection as a static method.""" return detect_steps(data) class LeeDetectStepsWithoutBout(DetectStepsWithoutBoutsBase): """Detect steps using Lee et al. algorithm on vertical acceleration.""" data_set_ids = "vertical_acceleration" new_data_set_id = "lee" transform_function = detect_steps class LeeStepCountWithoutBout(ExtractStep): """Extract step count with lee dataset without walking bouts.""" def __init__(self, **kwargs): data_set_ids = "lee"
definition = MeasureValueDefinitionPrototype(
0
2023-11-14 10:06:46+00:00
16k
shinomakoi/AI-Messenger
main.py
[ { "identifier": "Ui_CharacterForm", "path": "character_window.py", "snippet": "class Ui_CharacterForm(object):\n def setupUi(self, CharacterForm):\n if not CharacterForm.objectName():\n CharacterForm.setObjectName(u\"CharacterForm\")\n CharacterForm.resize(674, 856)\n ...
import asyncio import base64 import glob import json import platform import random import sys import cpp_server_gen import exllamav2_server_gen from pathlib import Path from PIL import Image from PySide6.QtCore import QSize, Qt, QThread, Signal, Slot from PySide6.QtGui import QIcon, QTextCursor from PySide6.QtWidgets import ( QApplication, QFileDialog, QMainWindow, QPlainTextEdit, QTreeWidgetItem, QWidget, ) from qt_material import apply_stylesheet from character_window import Ui_CharacterForm from chat_window import Ui_ChatWindow
12,963
# Constants for the directories and file names APP_ICON = Path("assets/icons/appicon.png") INSTRUCT_PRESETS_DIR = Path("presets/Assistants") CHARACTER_PRESETS_DIR = Path("presets/Characters") CARDS_PRESETS_DIR = Path("presets/Cards") SETTINGS_FILE = Path("saved/settings.json") SESSION_FILE = Path("saved/session.json") PARAMS_DIR = Path("presets/model_params")
# Constants for the directories and file names APP_ICON = Path("assets/icons/appicon.png") INSTRUCT_PRESETS_DIR = Path("presets/Assistants") CHARACTER_PRESETS_DIR = Path("presets/Characters") CARDS_PRESETS_DIR = Path("presets/Cards") SETTINGS_FILE = Path("saved/settings.json") SESSION_FILE = Path("saved/session.json") PARAMS_DIR = Path("presets/model_params")
class CharacterWindow(QWidget, Ui_CharacterForm):
0
2023-11-15 20:44:28+00:00
16k
believethehype/nostrdvm
main.py
[ { "identifier": "Bot", "path": "nostr_dvm/bot.py", "snippet": "class Bot:\n job_list: list\n\n # This is a simple list just to keep track which events we created and manage, so we don't pay for other requests\n def __init__(self, dvm_config, admin_config=None):\n self.NAME = \"Bot\"\n ...
import os import dotenv from pathlib import Path from sys import platform from nostr_dvm.bot import Bot from nostr_dvm.tasks import videogeneration_replicate_svd, imagegeneration_replicate_sdxl, textgeneration_llmlite, \ trending_notes_nostrband, discovery_inactive_follows, translation_google, textextraction_pdf, \ translation_libretranslate, textextraction_google, convert_media, imagegeneration_openai_dalle, texttospeech, \ imagegeneration_sd21_mlx, advanced_search, textgeneration_huggingchat, summarization_huggingchat from nostr_dvm.utils.admin_utils import AdminConfig from nostr_dvm.utils.backend_utils import keep_alive from nostr_dvm.utils.definitions import EventDefinitions from nostr_dvm.utils.dvmconfig import DVMConfig from nostr_dvm.utils.external_dvm_utils import build_external_dvm from nostr_dvm.utils.nostr_utils import check_and_set_private_key from nostr_dvm.utils.output_utils import PostProcessFunctionType from nostr_dvm.utils.zap_utils import check_and_set_ln_bits_keys from nostr_sdk import Keys
13,799
# We will run an optional bot that can communicate with the DVMs # Note this is very basic for now and still under development bot_config = DVMConfig() bot_config.PRIVATE_KEY = check_and_set_private_key("bot") npub = Keys.from_sk_str(bot_config.PRIVATE_KEY).public_key().to_bech32() invoice_key, admin_key, wallet_id, user_id, lnaddress = check_and_set_ln_bits_keys("bot", npub) bot_config.LNBITS_INVOICE_KEY = invoice_key bot_config.LNBITS_ADMIN_KEY = admin_key # The dvm might pay failed jobs back bot_config.LNBITS_URL = os.getenv("LNBITS_HOST") # Generate an optional Admin Config, in this case, whenever we give our DVMs this config, they will (re)broadcast # their NIP89 announcement # You can create individual admins configs and hand them over when initializing the dvm, # for example to whilelist users or add to their balance. # If you use this global config, options will be set for all dvms that use it. admin_config = AdminConfig() admin_config.REBROADCAST_NIP89 = False admin_config.LUD16 = lnaddress # Set rebroadcast to true once you have set your NIP89 descriptions and d tags. You only need to rebroadcast once you # want to update your NIP89 descriptions # Update the DVMs (not the bot) profile. For example after you updated the NIP89 or the lnaddress, you can automatically update profiles here. admin_config.UPDATE_PROFILE = False # Spawn some DVMs in the playground and run them # You can add arbitrary DVMs there and instantiate them here # Spawn DVM1 Kind 5000: A local Text Extractor from PDFs pdfextractor = textextraction_pdf.build_example("PDF Extractor", "pdf_extractor", admin_config) # If we don't add it to the bot, the bot will not provide access to the DVM pdfextractor.run() # Spawn DVM2 Kind 5002 Local Text TranslationGoogle, calling the free Google API. translator = translation_google.build_example("Google Translator", "google_translator", admin_config) bot_config.SUPPORTED_DVMS.append(translator) # We add translator to the bot translator.run() # Spawn DVM3 Kind 5002 Local Text TranslationLibre, calling the free LibreTranslateApi, as an alternative. # This will only run and appear on the bot if an endpoint is set in the .env if os.getenv("LIBRE_TRANSLATE_ENDPOINT") is not None and os.getenv("LIBRE_TRANSLATE_ENDPOINT") != "": libre_translator = translation_libretranslate.build_example("Libre Translator", "libre_translator", admin_config) bot_config.SUPPORTED_DVMS.append(libre_translator) # We add translator to the bot libre_translator.run() # Spawn DVM4, this one requires an OPENAI API Key and balance with OpenAI, you will move the task to them and pay # per call. Make sure you have enough balance and the DVM's cost is set higher than what you pay yourself, except, you know, # you're being generous. if os.getenv("OPENAI_API_KEY") is not None and os.getenv("OPENAI_API_KEY") != "": dalle = imagegeneration_openai_dalle.build_example("Dall-E 3", "dalle3", admin_config) bot_config.SUPPORTED_DVMS.append(dalle) dalle.run() if os.getenv("REPLICATE_API_TOKEN") is not None and os.getenv("REPLICATE_API_TOKEN") != "": sdxlreplicate = imagegeneration_replicate_sdxl.build_example("Stable Diffusion XL", "replicate_sdxl", admin_config) bot_config.SUPPORTED_DVMS.append(sdxlreplicate) sdxlreplicate.run() if os.getenv("REPLICATE_API_TOKEN") is not None and os.getenv("REPLICATE_API_TOKEN") != "": svdreplicate = videogeneration_replicate_svd.build_example("Stable Video Diffusion", "replicate_svd", admin_config) bot_config.SUPPORTED_DVMS.append(svdreplicate) svdreplicate.run() #Let's define a function so we can add external DVMs to our bot, we will instanciate it afterwards # Spawn DVM5.. oh wait, actually we don't spawn a new DVM, we use the dvmtaskinterface to define an external dvm by providing some info about it, such as # their pubkey, a name, task, kind etc. (unencrypted) tasktiger_external = build_external_dvm(pubkey="d483935d6bfcef3645195c04c97bbb70aedb6e65665c5ea83e562ca3c7acb978", task="text-to-image", kind=EventDefinitions.KIND_NIP90_GENERATE_IMAGE, fix_cost=80, per_unit_cost=0, config=bot_config) bot_config.SUPPORTED_DVMS.append(tasktiger_external) # Don't run it, it's on someone else's machine, and we simply make the bot aware of it. # DVM: 6 Another external dvm for recommendations: ymhm_external = build_external_dvm(pubkey="6b37d5dc88c1cbd32d75b713f6d4c2f7766276f51c9337af9d32c8d715cc1b93", task="content-discovery", kind=EventDefinitions.KIND_NIP90_CONTENT_DISCOVERY, fix_cost=0, per_unit_cost=0, external_post_process=PostProcessFunctionType.LIST_TO_EVENTS, config=bot_config) # If we get back a list of people or events, we can post-process it to make it readable in social clients bot_config.SUPPORTED_DVMS.append(ymhm_external) # Spawn DVM 7 Find inactive followers googleextractor = textextraction_google.build_example("Extractor", "speech_recognition", admin_config) bot_config.SUPPORTED_DVMS.append(googleextractor) googleextractor.run() # Spawn DVM 8 A Media Grabber/Converter media_bringer = convert_media.build_example("Media Bringer", "media_converter", admin_config) bot_config.SUPPORTED_DVMS.append(media_bringer) media_bringer.run() # Spawn DVM9 Find inactive followers discover_inactive = discovery_inactive_follows.build_example("Bygones", "discovery_inactive_follows", admin_config) bot_config.SUPPORTED_DVMS.append(discover_inactive) discover_inactive.run() trending = trending_notes_nostrband.build_example("Trending Notes on nostr.band", "trending_notes_nostrband", admin_config) bot_config.SUPPORTED_DVMS.append(trending) trending.run() ollama = textgeneration_llmlite.build_example("LLM", "llmlite", admin_config) bot_config.SUPPORTED_DVMS.append(ollama) ollama.run() tts = texttospeech.build_example("Text To Speech Test", "tts", admin_config) bot_config.SUPPORTED_DVMS.append(tts) tts.run()
def playground(): # We will run an optional bot that can communicate with the DVMs # Note this is very basic for now and still under development bot_config = DVMConfig() bot_config.PRIVATE_KEY = check_and_set_private_key("bot") npub = Keys.from_sk_str(bot_config.PRIVATE_KEY).public_key().to_bech32() invoice_key, admin_key, wallet_id, user_id, lnaddress = check_and_set_ln_bits_keys("bot", npub) bot_config.LNBITS_INVOICE_KEY = invoice_key bot_config.LNBITS_ADMIN_KEY = admin_key # The dvm might pay failed jobs back bot_config.LNBITS_URL = os.getenv("LNBITS_HOST") # Generate an optional Admin Config, in this case, whenever we give our DVMs this config, they will (re)broadcast # their NIP89 announcement # You can create individual admins configs and hand them over when initializing the dvm, # for example to whilelist users or add to their balance. # If you use this global config, options will be set for all dvms that use it. admin_config = AdminConfig() admin_config.REBROADCAST_NIP89 = False admin_config.LUD16 = lnaddress # Set rebroadcast to true once you have set your NIP89 descriptions and d tags. You only need to rebroadcast once you # want to update your NIP89 descriptions # Update the DVMs (not the bot) profile. For example after you updated the NIP89 or the lnaddress, you can automatically update profiles here. admin_config.UPDATE_PROFILE = False # Spawn some DVMs in the playground and run them # You can add arbitrary DVMs there and instantiate them here # Spawn DVM1 Kind 5000: A local Text Extractor from PDFs pdfextractor = textextraction_pdf.build_example("PDF Extractor", "pdf_extractor", admin_config) # If we don't add it to the bot, the bot will not provide access to the DVM pdfextractor.run() # Spawn DVM2 Kind 5002 Local Text TranslationGoogle, calling the free Google API. translator = translation_google.build_example("Google Translator", "google_translator", admin_config) bot_config.SUPPORTED_DVMS.append(translator) # We add translator to the bot translator.run() # Spawn DVM3 Kind 5002 Local Text TranslationLibre, calling the free LibreTranslateApi, as an alternative. # This will only run and appear on the bot if an endpoint is set in the .env if os.getenv("LIBRE_TRANSLATE_ENDPOINT") is not None and os.getenv("LIBRE_TRANSLATE_ENDPOINT") != "": libre_translator = translation_libretranslate.build_example("Libre Translator", "libre_translator", admin_config) bot_config.SUPPORTED_DVMS.append(libre_translator) # We add translator to the bot libre_translator.run() # Spawn DVM4, this one requires an OPENAI API Key and balance with OpenAI, you will move the task to them and pay # per call. Make sure you have enough balance and the DVM's cost is set higher than what you pay yourself, except, you know, # you're being generous. if os.getenv("OPENAI_API_KEY") is not None and os.getenv("OPENAI_API_KEY") != "": dalle = imagegeneration_openai_dalle.build_example("Dall-E 3", "dalle3", admin_config) bot_config.SUPPORTED_DVMS.append(dalle) dalle.run() if os.getenv("REPLICATE_API_TOKEN") is not None and os.getenv("REPLICATE_API_TOKEN") != "": sdxlreplicate = imagegeneration_replicate_sdxl.build_example("Stable Diffusion XL", "replicate_sdxl", admin_config) bot_config.SUPPORTED_DVMS.append(sdxlreplicate) sdxlreplicate.run() if os.getenv("REPLICATE_API_TOKEN") is not None and os.getenv("REPLICATE_API_TOKEN") != "": svdreplicate = videogeneration_replicate_svd.build_example("Stable Video Diffusion", "replicate_svd", admin_config) bot_config.SUPPORTED_DVMS.append(svdreplicate) svdreplicate.run() #Let's define a function so we can add external DVMs to our bot, we will instanciate it afterwards # Spawn DVM5.. oh wait, actually we don't spawn a new DVM, we use the dvmtaskinterface to define an external dvm by providing some info about it, such as # their pubkey, a name, task, kind etc. (unencrypted) tasktiger_external = build_external_dvm(pubkey="d483935d6bfcef3645195c04c97bbb70aedb6e65665c5ea83e562ca3c7acb978", task="text-to-image", kind=EventDefinitions.KIND_NIP90_GENERATE_IMAGE, fix_cost=80, per_unit_cost=0, config=bot_config) bot_config.SUPPORTED_DVMS.append(tasktiger_external) # Don't run it, it's on someone else's machine, and we simply make the bot aware of it. # DVM: 6 Another external dvm for recommendations: ymhm_external = build_external_dvm(pubkey="6b37d5dc88c1cbd32d75b713f6d4c2f7766276f51c9337af9d32c8d715cc1b93", task="content-discovery", kind=EventDefinitions.KIND_NIP90_CONTENT_DISCOVERY, fix_cost=0, per_unit_cost=0, external_post_process=PostProcessFunctionType.LIST_TO_EVENTS, config=bot_config) # If we get back a list of people or events, we can post-process it to make it readable in social clients bot_config.SUPPORTED_DVMS.append(ymhm_external) # Spawn DVM 7 Find inactive followers googleextractor = textextraction_google.build_example("Extractor", "speech_recognition", admin_config) bot_config.SUPPORTED_DVMS.append(googleextractor) googleextractor.run() # Spawn DVM 8 A Media Grabber/Converter media_bringer = convert_media.build_example("Media Bringer", "media_converter", admin_config) bot_config.SUPPORTED_DVMS.append(media_bringer) media_bringer.run() # Spawn DVM9 Find inactive followers discover_inactive = discovery_inactive_follows.build_example("Bygones", "discovery_inactive_follows", admin_config) bot_config.SUPPORTED_DVMS.append(discover_inactive) discover_inactive.run() trending = trending_notes_nostrband.build_example("Trending Notes on nostr.band", "trending_notes_nostrband", admin_config) bot_config.SUPPORTED_DVMS.append(trending) trending.run() ollama = textgeneration_llmlite.build_example("LLM", "llmlite", admin_config) bot_config.SUPPORTED_DVMS.append(ollama) ollama.run() tts = texttospeech.build_example("Text To Speech Test", "tts", admin_config) bot_config.SUPPORTED_DVMS.append(tts) tts.run()
search = advanced_search.build_example("Advanced Search", "discovery_content_search", admin_config)
14
2023-11-17 18:32:56+00:00
16k
IBM/oper8
tests/watch_manager/python_watch_manager/threads/test_watch_thread.py
[ { "identifier": "DryRunDeployManager", "path": "oper8/deploy_manager/dry_run_deploy_manager.py", "snippet": "class DryRunDeployManager(DeployManagerBase):\n \"\"\"\n Deploy manager which doesn't actually deploy!\n \"\"\"\n\n def __init__(self, resources=None, owner_cr=None, strict_resource_v...
import time import pytest from oper8.deploy_manager.dry_run_deploy_manager import DryRunDeployManager from oper8.deploy_manager.kube_event import KubeEventType from oper8.test_helpers.helpers import library_config from oper8.test_helpers.pwm_helpers import ( DisabledLeadershipManager, MockedReconcileThread, clear_caches, make_ownerref, make_resource, ) from oper8.watch_manager.python_watch_manager.filters.filters import DisableFilter from oper8.watch_manager.python_watch_manager.threads.watch import WatchThread from oper8.watch_manager.python_watch_manager.utils.types import ( ReconcileRequestType, ResourceId, WatchRequest, )
11,704
watch_thread.start_thread() request = WatchRequest( # Set watched and requester to the same watched=request_resource_id, requester=request_resource_id, ) watch_thread.request_watch(request) dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) dm.deploy([make_resource(name="second_obj")]) dm.disable([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert mocked_reconcile_thread.get_request().type == KubeEventType.ADDED assert mocked_reconcile_thread.get_request().type == KubeEventType.MODIFIED assert mocked_reconcile_thread.get_request().type == KubeEventType.ADDED assert mocked_reconcile_thread.get_request().type == KubeEventType.DELETED @pytest.mark.timeout(5) def test_watch_thread_global_watch_two_owners(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() owner_object = make_resource(kind="OwnerKind", name="owner", spec={"test": "value"}) owner_2_object = make_resource( kind="OwnerKind", name="owner2", spec={"test": "value"} ) watched_object = make_resource( spec={"test": "value"}, owner_refs=[make_ownerref(owner_object), make_ownerref(owner_2_object)], ) watched_object_id = ResourceId.from_resource(watched_object) dm.deploy([owner_object]) dm.deploy([owner_2_object]) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) request = WatchRequest( # Set watched and requester to the same watched=watched_object_id, requester=ResourceId( api_version=owner_object.get("apiVersion"), kind=owner_object.get("kind"), ), ) watch_thread.request_watch(request) watch_thread.start_thread() dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(1.5) watch_thread.stop_thread() add_events = [ mocked_reconcile_thread.get_request(), mocked_reconcile_thread.get_request(), ] assert "owner" in [event.resource.name for event in add_events] assert "owner2" in [event.resource.name for event in add_events] assert add_events[0].type == ReconcileRequestType.DEPENDENT assert add_events[1].type == ReconcileRequestType.DEPENDENT modified_events = [ mocked_reconcile_thread.get_request(), mocked_reconcile_thread.get_request(), ] assert "owner" in [event.resource.name for event in modified_events] assert "owner2" in [event.resource.name for event in modified_events] assert modified_events[0].type == ReconcileRequestType.DEPENDENT assert modified_events[1].type == ReconcileRequestType.DEPENDENT @pytest.mark.timeout(5) def test_watch_thread_no_watch(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) with library_config(python_watch_manager={"filter": DisableFilter}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) watch_thread.start_thread() dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert mocked_reconcile_thread.requests.empty() @pytest.mark.timeout(5) def test_watch_thread_not_leader(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) watched_object_id = ResourceId.from_resource(watched_object) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread(
""" Tests for the WatchThread """ # Standard # Third Party # Local ## Helpers ##################################################################### @pytest.mark.timeout(5) def test_watch_thread_happy_path(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) watched_object_id = ResourceId.from_resource(watched_object) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) watch_thread.start_thread() request = WatchRequest( # Set watched and requester to the same watched=watched_object_id, requester=watched_object_id, ) watch_thread.request_watch(request) dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert mocked_reconcile_thread.get_request().type == KubeEventType.ADDED assert mocked_reconcile_thread.get_request().type == KubeEventType.MODIFIED @pytest.mark.timeout(5) def test_watch_thread_filtered(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) watched_object_id = ResourceId.from_resource(watched_object) with library_config(python_watch_manager={"filter": DisableFilter}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) watch_thread.start_thread() request = WatchRequest( # Set watched and requester to the same watched=watched_object_id, requester=watched_object_id, ) watch_thread.request_watch(request) dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert mocked_reconcile_thread.requests.empty() @pytest.mark.timeout(5) def test_watch_thread_deleted(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) watched_object_id = ResourceId.from_resource(watched_object) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) watch_thread.start_thread() request = WatchRequest( # Set watched and requester to the same watched=watched_object_id, requester=watched_object_id, ) watch_thread.request_watch(request) dm.deploy([watched_object]) dm.disable([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert mocked_reconcile_thread.get_request().type == KubeEventType.ADDED assert mocked_reconcile_thread.get_request().type == KubeEventType.DELETED @pytest.mark.timeout(5) def test_watch_thread_owner_watch(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() owner_object = make_resource( kind="DifferentKind", name="owner", spec={"test": "value"} ) owner_object_id = ResourceId.from_resource(owner_object) watched_object = make_resource( spec={"test": "value"}, owner_refs=[make_ownerref(owner_object)] ) watched_object_id = ResourceId.from_resource(watched_object) # Deploy owner before watch has started dm.deploy([owner_object]) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) request = WatchRequest( # Set watched and requester to the same watched=watched_object_id, requester=owner_object_id, ) watch_thread.request_watch(request) watch_thread.start_thread() dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert ( mocked_reconcile_thread.get_request().type == ReconcileRequestType.DEPENDENT ) assert ( mocked_reconcile_thread.get_request().type == ReconcileRequestType.DEPENDENT ) @pytest.mark.timeout(5) def test_watch_thread_global_watch(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() owner_object = make_resource( kind="DifferentKind", name="owner", spec={"test": "value"} ) watched_object = make_resource( spec={"test": "value"}, owner_refs=[make_ownerref(owner_object)] ) watched_object_id = ResourceId.from_resource(watched_object) dm.deploy([owner_object]) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) watch_thread.start_thread() request = WatchRequest( # Set watched and requester to the same watched=watched_object_id, requester=ResourceId( api_version=owner_object.get("apiVersion"), kind=owner_object.get("kind"), ), ) watch_thread.request_watch(request) dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(3) watch_thread.stop_thread() assert ( mocked_reconcile_thread.get_request().type == ReconcileRequestType.DEPENDENT ) assert ( mocked_reconcile_thread.get_request().type == ReconcileRequestType.DEPENDENT ) @pytest.mark.timeout(5) def test_watch_thread_all_events(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) request_resource_id = ResourceId( api_version=watched_object.get("apiVersion"), kind=watched_object.get("kind") ) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) watch_thread.start_thread() request = WatchRequest( # Set watched and requester to the same watched=request_resource_id, requester=request_resource_id, ) watch_thread.request_watch(request) dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) dm.deploy([make_resource(name="second_obj")]) dm.disable([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert mocked_reconcile_thread.get_request().type == KubeEventType.ADDED assert mocked_reconcile_thread.get_request().type == KubeEventType.MODIFIED assert mocked_reconcile_thread.get_request().type == KubeEventType.ADDED assert mocked_reconcile_thread.get_request().type == KubeEventType.DELETED @pytest.mark.timeout(5) def test_watch_thread_global_watch_two_owners(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() owner_object = make_resource(kind="OwnerKind", name="owner", spec={"test": "value"}) owner_2_object = make_resource( kind="OwnerKind", name="owner2", spec={"test": "value"} ) watched_object = make_resource( spec={"test": "value"}, owner_refs=[make_ownerref(owner_object), make_ownerref(owner_2_object)], ) watched_object_id = ResourceId.from_resource(watched_object) dm.deploy([owner_object]) dm.deploy([owner_2_object]) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) request = WatchRequest( # Set watched and requester to the same watched=watched_object_id, requester=ResourceId( api_version=owner_object.get("apiVersion"), kind=owner_object.get("kind"), ), ) watch_thread.request_watch(request) watch_thread.start_thread() dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(1.5) watch_thread.stop_thread() add_events = [ mocked_reconcile_thread.get_request(), mocked_reconcile_thread.get_request(), ] assert "owner" in [event.resource.name for event in add_events] assert "owner2" in [event.resource.name for event in add_events] assert add_events[0].type == ReconcileRequestType.DEPENDENT assert add_events[1].type == ReconcileRequestType.DEPENDENT modified_events = [ mocked_reconcile_thread.get_request(), mocked_reconcile_thread.get_request(), ] assert "owner" in [event.resource.name for event in modified_events] assert "owner2" in [event.resource.name for event in modified_events] assert modified_events[0].type == ReconcileRequestType.DEPENDENT assert modified_events[1].type == ReconcileRequestType.DEPENDENT @pytest.mark.timeout(5) def test_watch_thread_no_watch(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) with library_config(python_watch_manager={"filter": DisableFilter}): watch_thread = WatchThread( reconcile_thread=mocked_reconcile_thread, kind="Foo", api_version="foo.bar.com/v1", namespace="test", deploy_manager=dm, ) watch_thread.start_thread() dm.deploy([watched_object]) watched_object["spec"] = {"test": "updated"} dm.deploy([watched_object]) time.sleep(1.5) watch_thread.stop_thread() assert mocked_reconcile_thread.requests.empty() @pytest.mark.timeout(5) def test_watch_thread_not_leader(): dm = DryRunDeployManager() mocked_reconcile_thread = MockedReconcileThread() watched_object = make_resource(spec={"test": "value"}) watched_object_id = ResourceId.from_resource(watched_object) with library_config(python_watch_manager={"filter": None}): watch_thread = WatchThread(
leadership_manager=DisabledLeadershipManager(),
3
2023-11-15 16:43:29+00:00
16k
Jisencc/yolov5_dual_weighting
utils/segment/dataloaders.py
[ { "identifier": "augment_hsv", "path": "utils/augmentations.py", "snippet": "def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):\n # HSV color-space augmentation\n if hgain or sgain or vgain:\n r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains\n hue, sat, ...
import os import random import cv2 import numpy as np import torch from torch.utils.data import DataLoader, distributed from ..augmentations import augment_hsv, copy_paste, letterbox from ..dataloaders import InfiniteDataLoader, LoadImagesAndLabels, seed_worker from ..general import LOGGER, xyn2xy, xywhn2xyxy, xyxy2xywhn from ..torch_utils import torch_distributed_zero_first from .augmentations import mixup, random_perspective
10,983
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Dataloaders """ RANK = int(os.getenv('RANK', -1)) def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0, rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix='', shuffle=False, mask_downsample_ratio=1, overlap_mask=False, seed=0): if rect and shuffle: LOGGER.warning('WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False') shuffle = False with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP dataset = LoadImagesAndLabelsAndMasks( path, imgsz, batch_size, augment=augment, # augmentation hyp=hyp, # hyperparameters rect=rect, # rectangular batches cache_images=cache, single_cls=single_cls, stride=int(stride), pad=pad, image_weights=image_weights, prefix=prefix, downsample_ratio=mask_downsample_ratio, overlap=overlap_mask) batch_size = min(batch_size, len(dataset)) nd = torch.cuda.device_count() # number of CUDA devices nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle) loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates generator = torch.Generator() generator.manual_seed(6148914691236517205 + seed + RANK) return loader( dataset, batch_size=batch_size, shuffle=shuffle and sampler is None, num_workers=nw, sampler=sampler, pin_memory=True, collate_fn=LoadImagesAndLabelsAndMasks.collate_fn4 if quad else LoadImagesAndLabelsAndMasks.collate_fn, worker_init_fn=seed_worker, generator=generator, ), dataset class LoadImagesAndLabelsAndMasks(LoadImagesAndLabels): # for training/testing def __init__( self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, stride=32, pad=0, min_items=0, prefix='', downsample_ratio=1, overlap=False, ): super().__init__(path, img_size, batch_size, augment, hyp, rect, image_weights, cache_images, single_cls, stride, pad, min_items, prefix) self.downsample_ratio = downsample_ratio self.overlap = overlap def __getitem__(self, index): index = self.indices[index] # linear, shuffled, or image_weights hyp = self.hyp mosaic = self.mosaic and random.random() < hyp['mosaic'] masks = [] if mosaic: # Load mosaic img, labels, segments = self.load_mosaic(index) shapes = None # MixUp augmentation if random.random() < hyp['mixup']:
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Dataloaders """ RANK = int(os.getenv('RANK', -1)) def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0, rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix='', shuffle=False, mask_downsample_ratio=1, overlap_mask=False, seed=0): if rect and shuffle: LOGGER.warning('WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False') shuffle = False with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP dataset = LoadImagesAndLabelsAndMasks( path, imgsz, batch_size, augment=augment, # augmentation hyp=hyp, # hyperparameters rect=rect, # rectangular batches cache_images=cache, single_cls=single_cls, stride=int(stride), pad=pad, image_weights=image_weights, prefix=prefix, downsample_ratio=mask_downsample_ratio, overlap=overlap_mask) batch_size = min(batch_size, len(dataset)) nd = torch.cuda.device_count() # number of CUDA devices nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle) loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates generator = torch.Generator() generator.manual_seed(6148914691236517205 + seed + RANK) return loader( dataset, batch_size=batch_size, shuffle=shuffle and sampler is None, num_workers=nw, sampler=sampler, pin_memory=True, collate_fn=LoadImagesAndLabelsAndMasks.collate_fn4 if quad else LoadImagesAndLabelsAndMasks.collate_fn, worker_init_fn=seed_worker, generator=generator, ), dataset class LoadImagesAndLabelsAndMasks(LoadImagesAndLabels): # for training/testing def __init__( self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, stride=32, pad=0, min_items=0, prefix='', downsample_ratio=1, overlap=False, ): super().__init__(path, img_size, batch_size, augment, hyp, rect, image_weights, cache_images, single_cls, stride, pad, min_items, prefix) self.downsample_ratio = downsample_ratio self.overlap = overlap def __getitem__(self, index): index = self.indices[index] # linear, shuffled, or image_weights hyp = self.hyp mosaic = self.mosaic and random.random() < hyp['mosaic'] masks = [] if mosaic: # Load mosaic img, labels, segments = self.load_mosaic(index) shapes = None # MixUp augmentation if random.random() < hyp['mixup']:
img, labels, segments = mixup(img, labels, segments, *self.load_mosaic(random.randint(0, self.n - 1)))
11
2023-11-12 13:28:26+00:00
16k
RAIVNLab/MatFormer-OLMo
olmo/train.py
[ { "identifier": "PathOrStr", "path": "olmo/aliases.py", "snippet": "" }, { "identifier": "CheckpointType", "path": "olmo/config.py", "snippet": "class CheckpointType(StrEnum):\n sharded = \"sharded\"\n unsharded = \"unsharded\"" }, { "identifier": "SpeedMonitorConfig", ...
import logging import math import random import shutil import time import numpy as np import torch import torch.nn.functional as F import wandb from collections import deque from dataclasses import dataclass, field from itertools import islice from pathlib import Path from typing import Any, Deque, Dict, List, Optional, TextIO, Tuple from packaging import version from torch.distributed.fsdp import FullStateDictConfig from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import StateDictType from torch.distributed.fsdp.api import ( FullOptimStateDictConfig, ShardedOptimStateDictConfig, ShardedStateDictConfig, ) from torch.utils.data import DataLoader from torchmetrics import MeanMetric from .aliases import PathOrStr from .config import CheckpointType, SpeedMonitorConfig, TrainConfig from .data import IterableDataset from .eval import Evaluator from .exceptions import OlmoConfigurationError from .model import Olmo, MatformerManager from .optim import set_new_base_lr from .util import ( barrier, get_global_rank, get_world_size, move_to_device, peak_gpu_memory, resource_path, syncronize_flag, upload, wait_on, )
11,117
from __future__ import annotations __all__ = ["SpeedMonitor", "LRMonitor", "Trainer"] log = logging.getLogger(__name__) @dataclass class SpeedMonitor: cfg: SpeedMonitorConfig start_times: Deque[float] = field(default_factory=lambda: deque([])) global_total_tokens: int = 0 device_interval_tokens: Deque[int] = field(default_factory=lambda: deque([])) def batch_start(self, global_total_tokens: int, device_batch_num_tokens: int, record: bool = True) -> None: self.global_total_tokens = global_total_tokens if record: if len(self.start_times) >= self.cfg.window_size: self.start_times.popleft() self.device_interval_tokens.popleft() self.start_times.append(time.monotonic()) self.device_interval_tokens.append(device_batch_num_tokens) def reset(self) -> None: self.start_times.clear() self.device_interval_tokens.clear() def check(self) -> Dict[str, float]: metrics: Dict[str, float] = {"throughput/total_tokens": self.global_total_tokens} if self.start_times: interval_seconds = time.monotonic() - self.start_times[0] interval_batches = len(self.start_times) interval_tokens = sum(self.device_interval_tokens) metrics["throughput/device/tokens_per_second"] = interval_tokens / interval_seconds metrics["throughput/device/batches_per_second"] = interval_batches / interval_seconds return metrics @dataclass class LRMonitor: optim: torch.optim.Optimizer def check(self) -> Dict[str, float]: lrs = [group["lr"] for group in self.optim.param_groups] return {f"optim/learning_rate_group{idx}": lr for idx, lr in enumerate(lrs)} @dataclass class Trainer: cfg: TrainConfig
from __future__ import annotations __all__ = ["SpeedMonitor", "LRMonitor", "Trainer"] log = logging.getLogger(__name__) @dataclass class SpeedMonitor: cfg: SpeedMonitorConfig start_times: Deque[float] = field(default_factory=lambda: deque([])) global_total_tokens: int = 0 device_interval_tokens: Deque[int] = field(default_factory=lambda: deque([])) def batch_start(self, global_total_tokens: int, device_batch_num_tokens: int, record: bool = True) -> None: self.global_total_tokens = global_total_tokens if record: if len(self.start_times) >= self.cfg.window_size: self.start_times.popleft() self.device_interval_tokens.popleft() self.start_times.append(time.monotonic()) self.device_interval_tokens.append(device_batch_num_tokens) def reset(self) -> None: self.start_times.clear() self.device_interval_tokens.clear() def check(self) -> Dict[str, float]: metrics: Dict[str, float] = {"throughput/total_tokens": self.global_total_tokens} if self.start_times: interval_seconds = time.monotonic() - self.start_times[0] interval_batches = len(self.start_times) interval_tokens = sum(self.device_interval_tokens) metrics["throughput/device/tokens_per_second"] = interval_tokens / interval_seconds metrics["throughput/device/batches_per_second"] = interval_batches / interval_seconds return metrics @dataclass class LRMonitor: optim: torch.optim.Optimizer def check(self) -> Dict[str, float]: lrs = [group["lr"] for group in self.optim.param_groups] return {f"optim/learning_rate_group{idx}": lr for idx, lr in enumerate(lrs)} @dataclass class Trainer: cfg: TrainConfig
model: Olmo
7
2023-11-14 02:24:07+00:00
16k
1in-oos/ccplus
caringcaribou/modules/uds.py
[ { "identifier": "auto_blacklist", "path": "caringcaribou/utils/can_actions.py", "snippet": "def auto_blacklist(bus, duration, classifier_function, print_results):\n \"\"\"Listens for false positives on the CAN bus and generates an arbitration ID blacklist.\n\n Finds all can.Message <msg> on 'bus' ...
from caringcaribou.utils.can_actions import auto_blacklist from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MAX_EXTENDED,ARBITRATION_ID_MIN_EXTENDED from caringcaribou.utils.constants import ARBITRATION_ID_MIN from caringcaribou.utils.iso15765_2 import IsoTp from caringcaribou.utils.iso14229_1 import Constants, Iso14229_1, NegativeResponseCodes, Services, ServiceID from sys import stdout, version_info, stderr import argparse import datetime import time
12,841
Returns the first response received from 'arb_id_response' within 'timeout' seconds or None otherwise. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param level: vehicle manufacturer specific access level to send key for :param key: key to transmit :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :type arb_id_request: int :type arb_id_response: int :type level: int :type key: [int] :type timeout: float or None :return: list of response byte values on success, None otherwise :rtype [int] or None """ # Sanity checks if (not Services.SecurityAccess.RequestSeedOrSendKey() .is_valid_send_key_level(level)): raise ValueError("Invalid send key level") if isinstance(timeout, float) and timeout < 0.0: raise ValueError("Timeout value ({0}) cannot be negative" .format(timeout)) with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout response = uds.security_access_send_key(level=level, key=key) return response def __dump_dids_wrapper(args): """Wrapper used to initiate data identifier dump""" arb_id_request = args.src arb_id_response = args.dst timeout = args.timeout min_did = args.min_did max_did = args.max_did print_results = True dump_dids(arb_id_request, arb_id_response, timeout, min_did, max_did, print_results) def __auto_wrapper(args): """Wrapper used to initiate automated UDS scan""" E=args.E min_id = args.min max_id = args.max blacklist = args.blacklist auto_blacklist_duration = args.autoblacklist delay = args.delay verify = not args.skipverify print_results = True timeout = args.timeout min_did = args.min_did max_did = args.max_did try: arb_id_pairs = uds_discovery(E, min_id, max_id, blacklist, auto_blacklist_duration, delay, verify, print_results) print("\n") if len(arb_id_pairs) == 0: # No UDS discovered print("\nDiagnostics service could not be found.") else: # Print result table print("\nIdentified diagnostics:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) for (client_id, server_id) in arb_id_pairs: print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) print("\n") # Enumerate each pair for (client_id, server_id) in arb_id_pairs: args.src = client_id args.dst = server_id # Print Client/Server result table print("\nTarget Diagnostic IDs:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) print("\nEnumerating Services:\n") found_services = service_discovery(client_id, server_id, timeout) found_subservices = [] print("\nIdentified services:\n") # Print available services result table for service_id in found_services: service_name = UDS_SERVICE_NAMES.get(service_id, "Unknown service") print("Supported service 0x{0:02x}: {1}" .format(service_id, service_name)) print("\n") dump_dids(client_id, server_id, timeout, min_did, max_did, print_results)
''' module_template.py This file contains a template for a simple CaringCaribou module. The module's entry point is the 'module_main' function. Steps to add this module to CaringCaribou and run it: 1. Copy this template into the `caringcaribou/modules` directory: $ cp module_template.py my_module.py 2. In `setup.py`, add an entry under `caringcaribou.modules`, referencing your new module like: `my_module = caringcaribou.modules.my_module` 3. Run: `setup.py install` 4. Verify that the module is available, it should be listed in the output of `cc.py -h` 5. Run the following command to run module and show usage instructions: $ cc.py my_module -h ''' from __future__ import print_function # Handle large ranges efficiently in both python 2 and 3 if version_info[0] == 2: range = xrange UDS_SERVICE_NAMES = { 0x10: "DIAGNOSTIC_SESSION_CONTROL", 0x11: "ECU_RESET", 0x14: "CLEAR_DIAGNOSTIC_INFORMATION", 0x19: "READ_DTC_INFORMATION", 0x20: "RETURN_TO_NORMAL", 0x22: "READ_DATA_BY_IDENTIFIER", 0x23: "READ_MEMORY_BY_ADDRESS", 0x24: "READ_SCALING_DATA_BY_IDENTIFIER", 0x27: "SECURITY_ACCESS", 0x28: "COMMUNICATION_CONTROL", 0x2A: "READ_DATA_BY_PERIODIC_IDENTIFIER", 0x2C: "DYNAMICALLY_DEFINE_DATA_IDENTIFIER", 0x2D: "DEFINE_PID_BY_MEMORY_ADDRESS", 0x2E: "WRITE_DATA_BY_IDENTIFIER", 0x2F: "INPUT_OUTPUT_CONTROL_BY_IDENTIFIER", 0x31: "ROUTINE_CONTROL", 0x34: "REQUEST_DOWNLOAD", 0x35: "REQUEST_UPLOAD", 0x36: "TRANSFER_DATA", 0x37: "REQUEST_TRANSFER_EXIT", 0x38: "REQUEST_FILE_TRANSFER", 0x3D: "WRITE_MEMORY_BY_ADDRESS", 0x3E: "TESTER_PRESENT", 0x7F: "NEGATIVE_RESPONSE", 0x83: "ACCESS_TIMING_PARAMETER", 0x84: "SECURED_DATA_TRANSMISSION", 0x85: "CONTROL_DTC_SETTING", 0x86: "RESPONSE_ON_EVENT", 0x87: "LINK_CONTROL" } NRC_NAMES = { 0x00: "POSITIVE_RESPONSE", 0x10: "GENERAL_REJECT", 0x11: "SERVICE_NOT_SUPPORTED", 0x12: "SUB_FUNCTION_NOT_SUPPORTED", 0x13: "INCORRECT_MESSAGE_LENGTH_OR_INVALID_FORMAT", 0x14: "RESPONSE_TOO_LONG", 0x21: "BUSY_REPEAT_REQUEST", 0x22: "CONDITIONS_NOT_CORRECT", 0x24: "REQUEST_SEQUENCE_ERROR", 0x25: "NO_RESPONSE_FROM_SUBNET_COMPONENT", 0x26: "FAILURE_PREVENTS_EXECUTION_OF_REQUESTED_ACTION", 0x31: "REQUEST_OUT_OF_RANGE", 0x33: "SECURITY_ACCESS_DENIED", 0x35: "INVALID_KEY", 0x36: "EXCEEDED_NUMBER_OF_ATTEMPTS", 0x37: "REQUIRED_TIME_DELAY_NOT_EXPIRED", 0x70: "UPLOAD_DOWNLOAD_NOT_ACCEPTED", 0x71: "TRANSFER_DATA_SUSPENDED", 0x72: "GENERAL_PROGRAMMING_FAILURE", 0x73: "WRONG_BLOCK_SEQUENCE_COUNTER", 0x78: "REQUEST_CORRECTLY_RECEIVED_RESPONSE_PENDING", 0x7E: "SUB_FUNCTION_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x7F: "SERVICE_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x81: "RPM_TOO_HIGH", 0x82: "RPM_TOO_LOW", 0x83: "ENGINE_IS_RUNNING", 0x84: "ENGINE_IS_NOT_RUNNING", 0x85: "ENGINE_RUN_TIME_TOO_LOW", 0x86: "TEMPERATURE_TOO_HIGH", 0x87: "TEMPERATURE_TOO_LOW", 0x88: "VEHICLE_SPEED_TOO_HIGH", 0x89: "VEHICLE_SPEED_TOO_LOW", 0x8A: "THROTTLE_PEDAL_TOO_HIGH", 0x8B: "THROTTLE_PEDAL_TOO_LOW", 0x8C: "TRANSMISSION_RANGE_NOT_IN_NEUTRAL", 0x8D: "TRANSMISSION_RANGE_NOT_IN_GEAR", 0x8F: "BRAKE_SWITCHES_NOT_CLOSED", 0x90: "SHIFT_LEVER_NOT_IN_PARK", 0x91: "TORQUE_CONVERTER_CLUTCH_LOCKED", 0x92: "VOLTAGE_TOO_HIGH", 0x93: "VOLTAGE_TOO_LOW" } DELAY_DISCOVERY = 0.01 DELAY_TESTER_PRESENT = 0.5 DELAY_SECSEED_RESET = 0.01 TIMEOUT_SERVICES = 0.2 TIMEOUT_SUBSERVICES = 0.02 # Max number of arbitration IDs to backtrack during verification VERIFICATION_BACKTRACK = 5 # Extra time in seconds to wait for responses during verification VERIFICATION_EXTRA_DELAY = 0.5 BYTE_MIN = 0x00 BYTE_MAX = 0xFF DUMP_DID_MIN = 0x0000 DUMP_DID_MAX = 0xFFFF DUMP_DID_TIMEOUT = 0.2 def uds_discovery(E, min_id, max_id, blacklist_args, auto_blacklist_duration, delay, verify, print_results=True): """Scans for diagnostics support by brute forcing session control messages to different arbitration IDs. Returns a list of all (client_arb_id, server_arb_id) pairs found. :param min_id: start arbitration ID value :param max_id: end arbitration ID value :param blacklist_args: blacklist for arbitration ID values :param auto_blacklist_duration: seconds to scan for interfering arbitration IDs to blacklist automatically :param delay: delay between each message :param verify: whether found arbitration IDs should be verified :param print_results: whether results should be printed to stdout :type min_id: int :type max_id: int :type blacklist_args: [int] :type auto_blacklist_duration: float :type delay: float :type verify: bool :type print_results: bool :return: list of (client_arbitration_id, server_arbitration_id) pairs :rtype [(int, int)] """ # Set defaults #-E为扩展帧 if E: max_id = ARBITRATION_ID_MAX_EXTENDED min_id = ARBITRATION_ID_MIN_EXTENDED elif min_id is None: min_id = ARBITRATION_ID_MIN max_id = ARBITRATION_ID_MAX if auto_blacklist_duration is None: auto_blacklist_duration = 0 if blacklist_args is None: blacklist_args = [] # Sanity checks if max_id < min_id: raise ValueError("max_id must not be smaller than min_id -" " got min:0x{0:x}, max:0x{1:x}".format(min_id, max_id)) if auto_blacklist_duration < 0: raise ValueError("auto_blacklist_duration must not be smaller " "than 0, got {0}'".format(auto_blacklist_duration)) diagnostic_session_control = Services.DiagnosticSessionControl service_id = diagnostic_session_control.service_id sub_function = diagnostic_session_control.DiagnosticSessionType.DEFAULT_SESSION session_control_data = [service_id, sub_function] valid_session_control_responses = [0x50, 0x7F] def is_valid_response(message): return (len(message.data) >= 2 and message.data[1] in valid_session_control_responses) found_arbitration_ids = [] with IsoTp(None, None) as tp: blacklist = set(blacklist_args) # Perform automatic blacklist scan if auto_blacklist_duration > 0: auto_bl_arb_ids = auto_blacklist(tp.bus, auto_blacklist_duration, is_valid_response, print_results) blacklist |= auto_bl_arb_ids # Prepare session control frame sess_ctrl_frm = tp.get_frames_from_message(session_control_data) if E is None: temp = 1 else: temp = 0x100 send_arb_id = min_id - temp while send_arb_id < max_id: send_arb_id += temp if print_results: print("\rSending Diagnostic Session Control to 0x{0:04x}" .format(send_arb_id), end="") stdout.flush() # Send Diagnostic Session Control tp.transmit(sess_ctrl_frm, send_arb_id, None) end_time = time.time() + delay # Listen for response while time.time() < end_time: msg = tp.bus.recv(0) if msg is None: # No response received continue if msg.arbitration_id in blacklist: # Ignore blacklisted arbitration IDs continue if is_valid_response(msg): # Valid response if verify: # Verification - backtrack the latest IDs and # verify that the same response is received verified = False # Set filter to only receive messages for the # arbitration ID being verified tp.set_filter_single_arbitration_id(msg.arbitration_id) if print_results: print("\n Verifying potential response from " "0x{0:04x}".format(send_arb_id)) verify_id_range = range(send_arb_id, send_arb_id - VERIFICATION_BACKTRACK, -1) for verify_arb_id in verify_id_range: if print_results: print(" Resending 0x{0:0x}... " .format(verify_arb_id), end=" ") tp.transmit(sess_ctrl_frm, verify_arb_id, None) # Give some extra time for verification, in # case of slow responses verification_end_time = (time.time() + delay + VERIFICATION_EXTRA_DELAY) while time.time() < verification_end_time: verification_msg = tp.bus.recv(0) if verification_msg is None: continue if is_valid_response(verification_msg): # Verified verified = True # Update send ID - if server responds # slowly, initial value may be faulty. # Also ensures we resume searching on # the next arb ID after the actual # match, rather than the one after the # last potential match (which could lead # to false negatives if multiple servers # listen to adjacent arbitration IDs and # respond slowly) send_arb_id = verify_arb_id break if print_results: # Print result if verified: print("Success") else: print("No response") if verified: # Verification succeeded - stop checking break # Remove filter after verification tp.clear_filters() if not verified: # Verification failed - move on if print_results: print(" False match - skipping") continue if print_results: if not verify: # Blank line needed print() print("Found diagnostics server " "listening at 0x{0:04x}, " "response at 0x{1:04x}" .format(send_arb_id, msg.arbitration_id)) # Add found arbitration ID pair found_arb_id_pair = (send_arb_id, msg.arbitration_id) found_arbitration_ids.append(found_arb_id_pair) if print_results: print() return found_arbitration_ids def __uds_discovery_wrapper(args): """Wrapper used to initiate a UDS discovery scan""" E=args.E min_id = args.min max_id = args.max blacklist = args.blacklist auto_blacklist_duration = args.autoblacklist delay = args.delay verify = not args.skipverify print_results = True try: arb_id_pairs = uds_discovery(E, min_id, max_id, blacklist, auto_blacklist_duration, delay, verify, print_results) if len(arb_id_pairs) == 0: # No UDS discovered print("\nDiagnostics service could not be found.") else: # Print result table print("\nIdentified diagnostics:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) for (client_id, server_id) in arb_id_pairs: print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) except ValueError as e: print("Discovery failed: {0}".format(e)) def service_discovery(arb_id_request, arb_id_response, timeout, min_id=BYTE_MIN, max_id=BYTE_MAX, print_results=True): """Scans for supported UDS services on the specified arbitration ID. Returns a list of found service IDs. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param timeout: delay between each request sent :param min_id: first service ID to scan :param max_id: last service ID to scan :param print_results: whether progress should be printed to stdout :type arb_id_request: int :type arb_id_response: int :type timeout: float :type min_id: int :type max_id: int :type print_results: bool :return: list of supported service IDs :rtype [int] """ found_services = [] with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) # Send requests try: for service_id in range(min_id, max_id + 1): tp.send_request([service_id]) if print_results: print("\rProbing service 0x{0:02x} ({0}/{1}): found {2}" .format(service_id, max_id, len(found_services)), end="") stdout.flush() # Get response msg = tp.bus.recv(timeout) if msg is None: # No response received continue # Parse response if len(msg.data) > 3: # Since service ID is included in the response, mapping is correct even if response is delayed response_id = msg.data[1] response_service_id = msg.data[2] status = msg.data[3] if response_id != Constants.NR_SI: request_id = Iso14229_1.get_service_request_id(response_id) found_services.append(request_id) elif status != NegativeResponseCodes.SERVICE_NOT_SUPPORTED: # Any other response than "service not supported" counts found_services.append(response_service_id) if print_results: print("\nDone!\n") except KeyboardInterrupt: if print_results: print("\nInterrupted by user!\n") return found_services def __service_discovery_wrapper(args): """Wrapper used to initiate a service discovery scan""" arb_id_request = args.src arb_id_response = args.dst timeout = args.timeout # Probe services found_services = service_discovery(arb_id_request, arb_id_response, timeout) # Print results for service_id in found_services: service_name = UDS_SERVICE_NAMES.get(service_id, "Unknown service") print("Supported service 0x{0:02x}: {1}" .format(service_id, service_name)) def sub_discovery(arb_id_request, arb_id_response, diagnostic, service, timeout, print_results=True): """Scans for supported UDS Diagnostic Session Control subservices on the specified arbitration ID. Returns a list of found Diagnostic Session Control subservice IDs. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param timeout: delay between each request sent :param diagnostic: the diagnostic session control subfunction in which the target service is accessible :param service: the target service to be enumerated :param print_results: whether progress should be printed to stdout :type arb_id_request: int :type arb_id_response: int :type timeout: float :type diagnostic: int :type service: int :type print_results: bool :return: list of supported service IDs :rtype [int] """ found_subservices = [] subservice_status = [] try: for i in range(0, 256): if service != Services.DiagnosticSessionControl: extended_session(arb_id_request, arb_id_response, diagnostic) else: extended_session(arb_id_request, arb_id_response, 1) time.sleep(0.1) response = raw_send(arb_id_request, arb_id_response, service, i) service_name = UDS_SERVICE_NAMES.get(service, "Unknown service") print("\rProbing sub-service ID 0x{0:02x} for service {1} (0x{2:02x}).".format(i, service_name, service), end="") if response is None: # No response received continue # Parse response if len(response) >= 2: response_id = response[0] response_service_id = response[1] if len(response) >= 3: status = response[2] else: status = None if Iso14229_1.is_positive_response(response): found_subservices.append(i) subservice_status.append(0x00) elif response_id == Constants.NR_SI and response_service_id == service and status != NegativeResponseCodes.SUB_FUNCTION_NOT_SUPPORTED: # Any other response than "service not supported" counts found_subservices.append(i) subservice_status.append(response_service_id) time.sleep(timeout) except KeyboardInterrupt: if print_results: print("\nInterrupted by user!\n") return found_subservices, subservice_status def __sub_discovery_wrapper(args): """Wrapper used to initiate a subservice discovery scan""" arb_id_request = args.src arb_id_response = args.dst diagnostic = args.dsc service = args.service timeout = args.timeout # Probe subservices found_subservices, subservice_status = sub_discovery(arb_id_request, arb_id_response, diagnostic, service, timeout) service_name = UDS_SERVICE_NAMES.get(service, "Unknown service") # Print results if len(found_subservices) == 0: print("\nNo Sub-Services were discovered for service {0:02x} - {1}.\n".format(service, service_name, end=' ')) else: print("\nSub-Services Discovered for Service {0:02x} - {1}:\n".format(service, service_name, end=' ')) for subservice_id in found_subservices: nrc_description = NRC_NAMES.get(subservice_status[found_subservices.index(subservice_id)]) print("\n0x{0:02x} : {1}".format(subservice_id, nrc_description), end=' ') def raw_send(arb_id_request, arb_id_response, service, session_type): with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages request = [0] * 2 request[0] = service request[1] = session_type tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: tp.send_request(request) response = uds.receive_response(Iso14229_1.P3_CLIENT) return response def tester_present(arb_id_request, delay, duration, suppress_positive_response): """Sends TesterPresent messages to 'arb_id_request'. Stops automatically after 'duration' seconds or runs forever if this is None. :param arb_id_request: arbitration ID for requests :param delay: seconds between each request :param duration: seconds before automatically stopping, or None to continue forever :param suppress_positive_response: whether positive responses should be suppressed :type arb_id_request: int :type delay: float :type duration: float or None :type suppress_positive_response: bool """ # SPR simply tells the recipient not to send a positive response to # each TesterPresent message if suppress_positive_response: sub_function = 0x80 else: sub_function = 0x00 # Calculate end timestamp if the TesterPresent should automatically # stop after a given duration auto_stop = duration is not None end_time = None if auto_stop: end_time = (datetime.datetime.now() + datetime.timedelta(seconds=duration)) service_id = Services.TesterPresent.service_id message_data = [service_id, sub_function] print("Sending TesterPresent to arbitration ID {0} (0x{0:02x})" .format(arb_id_request)) print("\nPress Ctrl+C to stop\n") with IsoTp(arb_id_request, None) as can_wrap: counter = 1 while True: can_wrap.send_request(message_data) print("\rCounter:", counter, end="") stdout.flush() time.sleep(delay) counter += 1 if auto_stop and datetime.datetime.now() >= end_time: break def __tester_present_wrapper(args): """Wrapper used to initiate a TesterPresent session""" arb_id_request = args.src delay = args.delay duration = args.duration suppress_positive_response = args.spr tester_present(arb_id_request, delay, duration, suppress_positive_response) def ecu_reset(arb_id_request, arb_id_response, reset_type, timeout): """Sends an ECU Reset message to 'arb_id_request'. Returns the first response received from 'arb_id_response' within 'timeout' seconds or None otherwise. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param reset_type: value corresponding to a reset type :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :type arb_id_request: int :type arb_id_response int :type reset_type: int :type timeout: float or None :return: list of response byte values on success, None otherwise :rtype [int] or None """ # Sanity checks if not BYTE_MIN <= reset_type <= BYTE_MAX: raise ValueError("reset type must be within interval " "0x{0:02x}-0x{1:02x}" .format(BYTE_MIN, BYTE_MAX)) if isinstance(timeout, float) and timeout < 0.0: raise ValueError("timeout value ({0}) cannot be negative" .format(timeout)) with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout response = uds.ecu_reset(reset_type=reset_type) return response def __ecu_reset_wrapper(args): """Wrapper used to initiate ECU Reset""" arb_id_request = args.src arb_id_response = args.dst reset_type = args.reset_type timeout = args.timeout print("Sending ECU reset, type 0x{0:02x} to arbitration ID {1} " "(0x{1:02x})".format(reset_type, arb_id_request)) try: response = ecu_reset(arb_id_request, arb_id_response, reset_type, timeout) except ValueError as e: print("ValueError: {0}".format(e)) return # Decode response if response is None: print("No response was received") else: response_length = len(response) if response_length == 0: # Empty response print("Received empty response") elif response_length == 1: # Invalid response length print("Received response [{0:02x}] (1 byte), expected at least " "2 bytes".format(response[0], len(response))) elif Iso14229_1.is_positive_response(response): # Positive response handling response_service_id = response[0] subfunction = response[1] expected_response_id = \ Iso14229_1.get_service_response_id( Services.EcuReset.service_id) if (response_service_id == expected_response_id and subfunction == reset_type): # Positive response pos_msg = "Received positive response" if response_length > 2: # Additional data can be seconds left to reset # (powerDownTime) or manufacturer specific additional_data = list_to_hex_str(response[2:], ",") pos_msg += (" with additional data: [{0}]" .format(additional_data)) print(pos_msg) else: # Service and/or subfunction mismatch print("Response service ID 0x{0:02x} and subfunction " "0x{1:02x} do not match expected values 0x{2:02x} " "and 0x{3:02x}".format(response_service_id, subfunction, Services.EcuReset.service_id, reset_type)) else: # Negative response handling print_negative_response(response) def print_negative_response(response): """ Helper function for decoding and printing a negative response received from a UDS server. :param response: Response data after CAN-TP layer has been removed :type response: [int] :return: Nothing """ nrc = response[2] nrc_description = NRC_NAMES.get(nrc, "Unknown NRC value") print("Received negative response code (NRC) 0x{0:02x}: {1}" .format(nrc, nrc_description)) def __security_seed_wrapper(args): """Wrapper used to initiate security seed dump""" arb_id_request = args.src arb_id_response = args.dst reset_type = args.reset session_type = args.sess_type level = args.sec_level num_seeds = args.num reset_delay = args.delay seed_list = [] try: print("Security seed dump started. Press Ctrl+C to stop.\n") while num_seeds > len(seed_list) or num_seeds == 0: # Extended diagnostics response = extended_session(arb_id_request, arb_id_response, session_type) if not Iso14229_1.is_positive_response(response): print("Unable to enter extended session. Retrying...\n") continue # Request seed response = request_seed(arb_id_request, arb_id_response, level, None, None) if response is None: print("\nInvalid response") elif Iso14229_1.is_positive_response(response): seed_list.append(list_to_hex_str(response[2:])) print("Seed received: {}\t(Total captured: {})" .format(list_to_hex_str(response[2:]), len(seed_list)), end="\r") stdout.flush() else: print_negative_response(response) break if reset_type: ecu_reset(arb_id_request, arb_id_response, reset_type, None) time.sleep(reset_delay) except KeyboardInterrupt: print("Interrupted by user.") except ValueError as e: print(e) return if len(seed_list) > 0: print("\n") print("Security Access Seeds captured:") for seed in seed_list: print(seed) def extended_session(arb_id_request, arb_id_response, session_type): with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: response = uds.diagnostic_session_control(session_type) return response def request_seed(arb_id_request, arb_id_response, level, data_record, timeout): """Sends an Request seed message to 'arb_id_request'. Returns the first response received from 'arb_id_response' within 'timeout' seconds or None otherwise. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param level: vehicle manufacturer specific access level to request seed for :param data_record: optional vehicle manufacturer specific data to transmit when requesting seed :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :type arb_id_request: int :type arb_id_response: int :type level: int :type data_record: [int] or None :type timeout: float or None :return: list of response byte values on success, None otherwise :rtype [int] or None """ # Sanity checks if (not Services.SecurityAccess.RequestSeedOrSendKey() .is_valid_request_seed_level(level)): raise ValueError("Invalid request seed level") if isinstance(timeout, float) and timeout < 0.0: raise ValueError("Timeout value ({0}) cannot be negative" .format(timeout)) with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout response = uds.security_access_request_seed(level, data_record) return response def send_key(arb_id_request, arb_id_response, level, key, timeout): """ Sends a Send key message to 'arb_id_request'. Returns the first response received from 'arb_id_response' within 'timeout' seconds or None otherwise. :param arb_id_request: arbitration ID for requests :param arb_id_response: arbitration ID for responses :param level: vehicle manufacturer specific access level to send key for :param key: key to transmit :param timeout: seconds to wait for response before timeout, or None for default UDS timeout :type arb_id_request: int :type arb_id_response: int :type level: int :type key: [int] :type timeout: float or None :return: list of response byte values on success, None otherwise :rtype [int] or None """ # Sanity checks if (not Services.SecurityAccess.RequestSeedOrSendKey() .is_valid_send_key_level(level)): raise ValueError("Invalid send key level") if isinstance(timeout, float) and timeout < 0.0: raise ValueError("Timeout value ({0}) cannot be negative" .format(timeout)) with IsoTp(arb_id_request=arb_id_request, arb_id_response=arb_id_response) as tp: # Setup filter for incoming messages tp.set_filter_single_arbitration_id(arb_id_response) with Iso14229_1(tp) as uds: # Set timeout if timeout is not None: uds.P3_CLIENT = timeout response = uds.security_access_send_key(level=level, key=key) return response def __dump_dids_wrapper(args): """Wrapper used to initiate data identifier dump""" arb_id_request = args.src arb_id_response = args.dst timeout = args.timeout min_did = args.min_did max_did = args.max_did print_results = True dump_dids(arb_id_request, arb_id_response, timeout, min_did, max_did, print_results) def __auto_wrapper(args): """Wrapper used to initiate automated UDS scan""" E=args.E min_id = args.min max_id = args.max blacklist = args.blacklist auto_blacklist_duration = args.autoblacklist delay = args.delay verify = not args.skipverify print_results = True timeout = args.timeout min_did = args.min_did max_did = args.max_did try: arb_id_pairs = uds_discovery(E, min_id, max_id, blacklist, auto_blacklist_duration, delay, verify, print_results) print("\n") if len(arb_id_pairs) == 0: # No UDS discovered print("\nDiagnostics service could not be found.") else: # Print result table print("\nIdentified diagnostics:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) for (client_id, server_id) in arb_id_pairs: print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) print("\n") # Enumerate each pair for (client_id, server_id) in arb_id_pairs: args.src = client_id args.dst = server_id # Print Client/Server result table print("\nTarget Diagnostic IDs:\n") table_line = "+------------+------------+" print(table_line) print("| CLIENT ID | SERVER ID |") print(table_line) print("| 0x{0:08x} | 0x{1:08x} |" .format(client_id, server_id)) print(table_line) print("\nEnumerating Services:\n") found_services = service_discovery(client_id, server_id, timeout) found_subservices = [] print("\nIdentified services:\n") # Print available services result table for service_id in found_services: service_name = UDS_SERVICE_NAMES.get(service_id, "Unknown service") print("Supported service 0x{0:02x}: {1}" .format(service_id, service_name)) print("\n") dump_dids(client_id, server_id, timeout, min_did, max_did, print_results)
if ServiceID.DIAGNOSTIC_SESSION_CONTROL in found_services:
12
2023-11-13 05:05:46+00:00
16k
L1bra1/WeakMotion
train_WeakMotionNet.py
[ { "identifier": "WeakMotionNet", "path": "weak_model.py", "snippet": "class WeakMotionNet(nn.Module):\n def __init__(self, out_seq_len=1, FGBG_category_num=2, height_feat_size=13):\n super(WeakMotionNet, self).__init__()\n self.out_seq_len = out_seq_len\n\n self.motion_pred = Mot...
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import time import sys import argparse import os from shutil import copytree, copy from weak_model import WeakMotionNet from data.weak_nuscenes_dataloader import DatasetSingleSeq_Stage2 from data.weak_waymo_dataloader import DatasetSingleSeq_Stage2 as DatasetSingleSeq_Stage2_waymo from sklearn.metrics import confusion_matrix from tqdm import tqdm from loss_utils import FGBG_seg_loss, CCD_loss from evaluation_utils import evaluate_FGBG_prediction, evaluate_motion_prediction
11,577
def __str__(self): fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' return fmtstr.format(**self.__dict__) def check_folder(folder_path): if not os.path.exists(folder_path): os.mkdir(folder_path) return folder_path out_seq_len = 1 # The number of future frames we are going to predict height_feat_size = 13 # The size along the height dimension parser = argparse.ArgumentParser() parser.add_argument('-md', '--motiondata', default='/path_to/nuScenes/input-data/train/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-wd', '--weakdata', default='/path_to/nuScenes/weak-data/train/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-FBd', '--FBdata', default='/path_to/nuScenes/FGBG-data/nuscenes_seg_0-01/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--datatype', default='nuScenes', type=str, choices=['Waymo', 'nuScenes']) parser.add_argument('-t', '--evaldata', default='/path_to/nuScenes/input-data/val/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--resume', default='', type=str, help='The path to the saved model that is loaded to resume training') parser.add_argument('--batch', default=8, type=int, help='Batch size') parser.add_argument('--nepoch', default=60, type=int, help='Number of epochs') parser.add_argument('--nworker', default=4, type=int, help='Number of workers') parser.add_argument('--log', default=True, action='store_true', help='Whether to log') parser.add_argument('--logpath', default='', help='The path to the output log file') parser.add_argument('--gpu', default='1') parser.add_argument('--annotation_ratio', default=0.01, type=float) args = parser.parse_args() print(args) num_epochs = args.nepoch need_log = args.log BATCH_SIZE = args.batch num_workers = args.nworker os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu datatype = args.datatype annotation_ratio = args.annotation_ratio def main(): start_epoch = 1 # Whether to log the training information if need_log: logger_root = args.logpath if args.logpath != '' else 'logs' time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S") if args.resume == '': model_save_path = check_folder(logger_root) model_save_path = check_folder(os.path.join(model_save_path, 'Stage2')) model_save_path = check_folder(os.path.join(model_save_path, time_stamp)) log_file_name = os.path.join(model_save_path, 'log.txt') saver = open(log_file_name, "w") saver.write("GPU number: {}\n".format(torch.cuda.device_count())) saver.flush() # Logging the details for this experiment saver.write("command line: {}\n".format(" ".join(sys.argv[0:]))) saver.write(args.__repr__() + "\n\n") saver.flush() else: model_save_path = args.resume log_file_name = os.path.join(model_save_path, 'log.txt') saver = open(log_file_name, "a") saver.write("GPU number: {}\n".format(torch.cuda.device_count())) saver.flush() # Logging the details for this experiment saver.write("command line: {}\n".format(" ".join(sys.argv[1:]))) saver.write(args.__repr__() + "\n\n") saver.flush() # Specify gpu device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device_num = torch.cuda.device_count() print("device number", device_num) voxel_size = (0.25, 0.25, 0.4) if datatype == 'nuScenes': area_extents = np.array([[-32., 32.], [-32., 32.], [-3., 2.]]) elif datatype == 'Waymo': area_extents = np.array([[-32., 32.], [-32., 32.], [-1., 4.]]) tmp = args.motiondata trainset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': trainset = DatasetSingleSeq_Stage2(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': trainset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=num_workers) print("Training dataset size:", len(trainset)) tmp = args.evaldata evalset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': evalset = DatasetSingleSeq_Stage2(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': evalset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) evalloader = torch.utils.data.DataLoader(evalset, batch_size=1, shuffle=False, num_workers=num_workers) print("Training dataset size:", len(trainset))
""" Train WeakMotionNet in Stage2 Some of the code are modified based on 'train_single_seq.py' in MotionNet. Reference: MotionNet (https://www.merl.com/research/?research=license-request&sw=MotionNet) """ class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def __str__(self): fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' return fmtstr.format(**self.__dict__) def check_folder(folder_path): if not os.path.exists(folder_path): os.mkdir(folder_path) return folder_path out_seq_len = 1 # The number of future frames we are going to predict height_feat_size = 13 # The size along the height dimension parser = argparse.ArgumentParser() parser.add_argument('-md', '--motiondata', default='/path_to/nuScenes/input-data/train/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-wd', '--weakdata', default='/path_to/nuScenes/weak-data/train/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-FBd', '--FBdata', default='/path_to/nuScenes/FGBG-data/nuscenes_seg_0-01/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--datatype', default='nuScenes', type=str, choices=['Waymo', 'nuScenes']) parser.add_argument('-t', '--evaldata', default='/path_to/nuScenes/input-data/val/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--resume', default='', type=str, help='The path to the saved model that is loaded to resume training') parser.add_argument('--batch', default=8, type=int, help='Batch size') parser.add_argument('--nepoch', default=60, type=int, help='Number of epochs') parser.add_argument('--nworker', default=4, type=int, help='Number of workers') parser.add_argument('--log', default=True, action='store_true', help='Whether to log') parser.add_argument('--logpath', default='', help='The path to the output log file') parser.add_argument('--gpu', default='1') parser.add_argument('--annotation_ratio', default=0.01, type=float) args = parser.parse_args() print(args) num_epochs = args.nepoch need_log = args.log BATCH_SIZE = args.batch num_workers = args.nworker os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu datatype = args.datatype annotation_ratio = args.annotation_ratio def main(): start_epoch = 1 # Whether to log the training information if need_log: logger_root = args.logpath if args.logpath != '' else 'logs' time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S") if args.resume == '': model_save_path = check_folder(logger_root) model_save_path = check_folder(os.path.join(model_save_path, 'Stage2')) model_save_path = check_folder(os.path.join(model_save_path, time_stamp)) log_file_name = os.path.join(model_save_path, 'log.txt') saver = open(log_file_name, "w") saver.write("GPU number: {}\n".format(torch.cuda.device_count())) saver.flush() # Logging the details for this experiment saver.write("command line: {}\n".format(" ".join(sys.argv[0:]))) saver.write(args.__repr__() + "\n\n") saver.flush() else: model_save_path = args.resume log_file_name = os.path.join(model_save_path, 'log.txt') saver = open(log_file_name, "a") saver.write("GPU number: {}\n".format(torch.cuda.device_count())) saver.flush() # Logging the details for this experiment saver.write("command line: {}\n".format(" ".join(sys.argv[1:]))) saver.write(args.__repr__() + "\n\n") saver.flush() # Specify gpu device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device_num = torch.cuda.device_count() print("device number", device_num) voxel_size = (0.25, 0.25, 0.4) if datatype == 'nuScenes': area_extents = np.array([[-32., 32.], [-32., 32.], [-3., 2.]]) elif datatype == 'Waymo': area_extents = np.array([[-32., 32.], [-32., 32.], [-1., 4.]]) tmp = args.motiondata trainset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': trainset = DatasetSingleSeq_Stage2(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': trainset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=num_workers) print("Training dataset size:", len(trainset)) tmp = args.evaldata evalset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': evalset = DatasetSingleSeq_Stage2(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': evalset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) evalloader = torch.utils.data.DataLoader(evalset, batch_size=1, shuffle=False, num_workers=num_workers) print("Training dataset size:", len(trainset))
model = WeakMotionNet(out_seq_len=out_seq_len, FGBG_category_num=2, height_feat_size=height_feat_size)
0
2023-11-12 07:03:29+00:00
16k
c3exchange/c3-smartcontracts-v1
contracts_unified/core/main.py
[ { "identifier": "update", "path": "contracts_unified/core/bare_calls/update.py", "snippet": "@Subroutine(TealType.none)\ndef update() -> Expr:\n \"\"\"Implements the contract method called on update\"\"\"\n\n return sender_is_creator()" }, { "identifier": "delete", "path": "contracts_u...
from pyteal import ( BareCallActions, CallConfig, MethodConfig, OnCompleteAction, OptimizeOptions, Reject, Router, ) from contracts_unified.core.bare_calls import delete, update from contracts_unified.core.methods import ( account_move, add_order, clean_orders, create, deposit, fund_mbr, liquidate, pool_move, portal_transfer, settle, update_instrument, update_parameter, withdraw, wormhole_deposit, )
11,556
""" This file implements the router of the Core contract. """ CORE_ROUTER = Router( "C3 Core", BareCallActions( update_application=OnCompleteAction.always(update()),
""" This file implements the router of the Core contract. """ CORE_ROUTER = Router( "C3 Core", BareCallActions( update_application=OnCompleteAction.always(update()),
delete_application=OnCompleteAction.always(delete()),
1
2023-11-17 20:54:15+00:00
16k
cyberark/ark-sdk-python
ark_sdk_python/auth/ark_isp_auth.py
[ { "identifier": "ArkAuth", "path": "ark_sdk_python/auth/ark_auth.py", "snippet": "class ArkAuth(ABC):\n def __init__(self, cache_authentication: bool = True) -> None:\n self._logger = get_logger(app=self.__class__.__name__)\n self._cache_authentication = cache_authentication\n se...
import codecs import os import pickle from datetime import datetime, timedelta from typing import Final, List, Optional, Tuple, cast from overrides import overrides from ark_sdk_python.auth.ark_auth import ArkAuth from ark_sdk_python.auth.identity.ark_identity import ArkIdentity from ark_sdk_python.auth.identity.ark_identity_service_user import ArkIdentityServiceUser from ark_sdk_python.common.ark_system_config import ArkSystemConfig from ark_sdk_python.common.env import ROOT_DOMAIN, AwsEnv from ark_sdk_python.models import ArkProfile from ark_sdk_python.models.ark_exceptions import ArkAuthException, ArkException from ark_sdk_python.models.auth import ( ArkAuthMethod, ArkAuthMethodSettings, ArkAuthProfile, ArkSecret, ArkToken, ArkTokenType, IdentityArkAuthMethodSettings, IdentityServiceUserArkAuthMethodSettings, )
11,757
# pylint: disable=unused-argument AUTH_NAME: Final[str] = 'isp' AUTH_HUMAN_READABLE_NAME: Final[str] = 'Identity Security Platform' AUTH_METHODS: Final[List[ArkAuthMethod]] = [ ArkAuthMethod.Identity, ArkAuthMethod.IdentityServiceUser, ] DEFAULT_AUTH_METHOD: Final[ArkAuthMethod] = ArkAuthMethod.Identity DEFAULT_AUTH_METHOD_SETTINGS: Final[IdentityArkAuthMethodSettings] = IdentityArkAuthMethodSettings() DEFAULT_TOKEN_LIFETIME: Final[int] = 3600
# pylint: disable=unused-argument AUTH_NAME: Final[str] = 'isp' AUTH_HUMAN_READABLE_NAME: Final[str] = 'Identity Security Platform' AUTH_METHODS: Final[List[ArkAuthMethod]] = [ ArkAuthMethod.Identity, ArkAuthMethod.IdentityServiceUser, ] DEFAULT_AUTH_METHOD: Final[ArkAuthMethod] = ArkAuthMethod.Identity DEFAULT_AUTH_METHOD_SETTINGS: Final[IdentityArkAuthMethodSettings] = IdentityArkAuthMethodSettings() DEFAULT_TOKEN_LIFETIME: Final[int] = 3600
class ArkISPAuth(ArkAuth):
0
2023-11-13 09:24:31+00:00
16k
mohenghui/detectAuto_v8
ultralytics/trackers/bot_sort.py
[ { "identifier": "TrackState", "path": "ultralytics/trackers/basetrack.py", "snippet": "class TrackState:\n \"\"\"Enumeration of possible object tracking states.\"\"\"\n\n New = 0\n Tracked = 1\n Lost = 2\n Removed = 3" }, { "identifier": "BYTETracker", "path": "ultralytics/tra...
from collections import deque from .basetrack import TrackState from .byte_tracker import BYTETracker, STrack from .utils import matching from .utils.gmc import GMC from .utils.kalman_filter import KalmanFilterXYWH import numpy as np
11,217
bo_track.update(new_track, frame_id) """ shared_kalman = KalmanFilterXYWH() def __init__(self, tlwh, score, cls, feat=None, feat_history=50): """Initialize YOLOv8 object with temporal parameters, such as feature history, alpha and current features.""" super().__init__(tlwh, score, cls) self.smooth_feat = None self.curr_feat = None if feat is not None: self.update_features(feat) self.features = deque([], maxlen=feat_history) self.alpha = 0.9 def update_features(self, feat): """Update features vector and smooth it using exponential moving average.""" feat /= np.linalg.norm(feat) self.curr_feat = feat if self.smooth_feat is None: self.smooth_feat = feat else: self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat self.features.append(feat) self.smooth_feat /= np.linalg.norm(self.smooth_feat) def predict(self): """Predicts the mean and covariance using Kalman filter.""" mean_state = self.mean.copy() if self.state != TrackState.Tracked: mean_state[6] = 0 mean_state[7] = 0 self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance) def re_activate(self, new_track, frame_id, new_id=False): """Reactivates a track with updated features and optionally assigns a new ID.""" if new_track.curr_feat is not None: self.update_features(new_track.curr_feat) super().re_activate(new_track, frame_id, new_id) def update(self, new_track, frame_id): """Update the YOLOv8 instance with new track and frame ID.""" if new_track.curr_feat is not None: self.update_features(new_track.curr_feat) super().update(new_track, frame_id) @property def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`.""" if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() ret[:2] -= ret[2:] / 2 return ret @staticmethod def multi_predict(stracks): """Predicts the mean and covariance of multiple object tracks using shared Kalman filter.""" if len(stracks) <= 0: return multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) for i, st in enumerate(stracks): if st.state != TrackState.Tracked: multi_mean[i][6] = 0 multi_mean[i][7] = 0 multi_mean, multi_covariance = BOTrack.shared_kalman.multi_predict(multi_mean, multi_covariance) for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): stracks[i].mean = mean stracks[i].covariance = cov def convert_coords(self, tlwh): """Converts Top-Left-Width-Height bounding box coordinates to X-Y-Width-Height format.""" return self.tlwh_to_xywh(tlwh) @staticmethod def tlwh_to_xywh(tlwh): """Convert bounding box to format `(center x, center y, width, height)`.""" ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 return ret class BOTSORT(BYTETracker): """ An extended version of the BYTETracker class for YOLOv8, designed for object tracking with ReID and GMC algorithm. Attributes: proximity_thresh (float): Threshold for spatial proximity (IoU) between tracks and detections. appearance_thresh (float): Threshold for appearance similarity (ReID embeddings) between tracks and detections. encoder (object): Object to handle ReID embeddings, set to None if ReID is not enabled. gmc (GMC): An instance of the GMC algorithm for data association. args (object): Parsed command-line arguments containing tracking parameters. Methods: get_kalmanfilter(): Returns an instance of KalmanFilterXYWH for object tracking. init_track(dets, scores, cls, img): Initialize track with detections, scores, and classes. get_dists(tracks, detections): Get distances between tracks and detections using IoU and (optionally) ReID. multi_predict(tracks): Predict and track multiple objects with YOLOv8 model. Usage: bot_sort = BOTSORT(args, frame_rate) bot_sort.init_track(dets, scores, cls, img) bot_sort.multi_predict(tracks) Note: The class is designed to work with the YOLOv8 object detection model and supports ReID only if enabled via args. """ def __init__(self, args, frame_rate=30): """Initialize YOLOv8 object with ReID module and GMC algorithm.""" super().__init__(args, frame_rate) # ReID module self.proximity_thresh = args.proximity_thresh self.appearance_thresh = args.appearance_thresh if args.with_reid: # Haven't supported BoT-SORT(reid) yet self.encoder = None
# Ultralytics YOLO 🚀, AGPL-3.0 license class BOTrack(STrack): """ An extended version of the STrack class for YOLOv8, adding object tracking features. Attributes: shared_kalman (KalmanFilterXYWH): A shared Kalman filter for all instances of BOTrack. smooth_feat (np.ndarray): Smoothed feature vector. curr_feat (np.ndarray): Current feature vector. features (deque): A deque to store feature vectors with a maximum length defined by `feat_history`. alpha (float): Smoothing factor for the exponential moving average of features. mean (np.ndarray): The mean state of the Kalman filter. covariance (np.ndarray): The covariance matrix of the Kalman filter. Methods: update_features(feat): Update features vector and smooth it using exponential moving average. predict(): Predicts the mean and covariance using Kalman filter. re_activate(new_track, frame_id, new_id): Reactivates a track with updated features and optionally new ID. update(new_track, frame_id): Update the YOLOv8 instance with new track and frame ID. tlwh: Property that gets the current position in tlwh format `(top left x, top left y, width, height)`. multi_predict(stracks): Predicts the mean and covariance of multiple object tracks using shared Kalman filter. convert_coords(tlwh): Converts tlwh bounding box coordinates to xywh format. tlwh_to_xywh(tlwh): Convert bounding box to xywh format `(center x, center y, width, height)`. Usage: bo_track = BOTrack(tlwh, score, cls, feat) bo_track.predict() bo_track.update(new_track, frame_id) """ shared_kalman = KalmanFilterXYWH() def __init__(self, tlwh, score, cls, feat=None, feat_history=50): """Initialize YOLOv8 object with temporal parameters, such as feature history, alpha and current features.""" super().__init__(tlwh, score, cls) self.smooth_feat = None self.curr_feat = None if feat is not None: self.update_features(feat) self.features = deque([], maxlen=feat_history) self.alpha = 0.9 def update_features(self, feat): """Update features vector and smooth it using exponential moving average.""" feat /= np.linalg.norm(feat) self.curr_feat = feat if self.smooth_feat is None: self.smooth_feat = feat else: self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat self.features.append(feat) self.smooth_feat /= np.linalg.norm(self.smooth_feat) def predict(self): """Predicts the mean and covariance using Kalman filter.""" mean_state = self.mean.copy() if self.state != TrackState.Tracked: mean_state[6] = 0 mean_state[7] = 0 self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance) def re_activate(self, new_track, frame_id, new_id=False): """Reactivates a track with updated features and optionally assigns a new ID.""" if new_track.curr_feat is not None: self.update_features(new_track.curr_feat) super().re_activate(new_track, frame_id, new_id) def update(self, new_track, frame_id): """Update the YOLOv8 instance with new track and frame ID.""" if new_track.curr_feat is not None: self.update_features(new_track.curr_feat) super().update(new_track, frame_id) @property def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`.""" if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() ret[:2] -= ret[2:] / 2 return ret @staticmethod def multi_predict(stracks): """Predicts the mean and covariance of multiple object tracks using shared Kalman filter.""" if len(stracks) <= 0: return multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) for i, st in enumerate(stracks): if st.state != TrackState.Tracked: multi_mean[i][6] = 0 multi_mean[i][7] = 0 multi_mean, multi_covariance = BOTrack.shared_kalman.multi_predict(multi_mean, multi_covariance) for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): stracks[i].mean = mean stracks[i].covariance = cov def convert_coords(self, tlwh): """Converts Top-Left-Width-Height bounding box coordinates to X-Y-Width-Height format.""" return self.tlwh_to_xywh(tlwh) @staticmethod def tlwh_to_xywh(tlwh): """Convert bounding box to format `(center x, center y, width, height)`.""" ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 return ret class BOTSORT(BYTETracker): """ An extended version of the BYTETracker class for YOLOv8, designed for object tracking with ReID and GMC algorithm. Attributes: proximity_thresh (float): Threshold for spatial proximity (IoU) between tracks and detections. appearance_thresh (float): Threshold for appearance similarity (ReID embeddings) between tracks and detections. encoder (object): Object to handle ReID embeddings, set to None if ReID is not enabled. gmc (GMC): An instance of the GMC algorithm for data association. args (object): Parsed command-line arguments containing tracking parameters. Methods: get_kalmanfilter(): Returns an instance of KalmanFilterXYWH for object tracking. init_track(dets, scores, cls, img): Initialize track with detections, scores, and classes. get_dists(tracks, detections): Get distances between tracks and detections using IoU and (optionally) ReID. multi_predict(tracks): Predict and track multiple objects with YOLOv8 model. Usage: bot_sort = BOTSORT(args, frame_rate) bot_sort.init_track(dets, scores, cls, img) bot_sort.multi_predict(tracks) Note: The class is designed to work with the YOLOv8 object detection model and supports ReID only if enabled via args. """ def __init__(self, args, frame_rate=30): """Initialize YOLOv8 object with ReID module and GMC algorithm.""" super().__init__(args, frame_rate) # ReID module self.proximity_thresh = args.proximity_thresh self.appearance_thresh = args.appearance_thresh if args.with_reid: # Haven't supported BoT-SORT(reid) yet self.encoder = None
self.gmc = GMC(method=args.gmc_method)
4
2023-11-16 12:49:59+00:00
16k
i-super/Saleor
saleor/graphql/product/tests/test_category.py
[ { "identifier": "CustomJsonEncoder", "path": "saleor/core/utils/json_serializer.py", "snippet": "class CustomJsonEncoder(DjangoJSONEncoder):\n def default(self, obj):\n if isinstance(obj, Money):\n return {\"_type\": MONEY_TYPE, \"amount\": obj.amount, \"currency\": obj.currency}\n ...
import json import os import graphene import pytest from unittest.mock import MagicMock, Mock, patch from django.core.files import File from django.utils import timezone from django.utils.functional import SimpleLazyObject from django.utils.text import slugify from freezegun import freeze_time from graphql_relay import to_global_id from ....core.utils.json_serializer import CustomJsonEncoder from ....product.error_codes import ProductErrorCode from ....product.models import Category, Product, ProductChannelListing from ....product.tests.utils import create_image, create_zip_file_with_image_ext from ....product.utils.costs import get_product_costs_data from ....tests.utils import dummy_editorjs from ....thumbnail.models import Thumbnail from ....webhook.event_types import WebhookEventAsyncType from ....webhook.payloads import generate_meta, generate_requestor from ...core.enums import ThumbnailFormatEnum from ...tests.utils import ( get_graphql_content, get_graphql_content_from_response, get_multipart_request_body, )
11,693
): # given category = Category.objects.first() product_list[0].channel_listings.all().update(visible_in_listings=False) product_count = Product.objects.count() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } # when response = app_api_client.post_graphql(QUERY_CATEGORY, variables=variables) # then content = get_graphql_content(response, ignore_errors=True) assert ( len(content["data"]["category"]["products"]["edges"]) == product_count - 1 ) # invisible doesn't count def test_query_category_product_only_visible_in_listings_as_app_with_perm( app_api_client, product_list, permission_manage_products ): # given app_api_client.app.permissions.add(permission_manage_products) category = Category.objects.first() product_list[0].channel_listings.all().update(visible_in_listings=False) product_count = Product.objects.count() variables = {"id": graphene.Node.to_global_id("Category", category.pk)} # when response = app_api_client.post_graphql(QUERY_CATEGORY, variables=variables) # then content = get_graphql_content(response, ignore_errors=True) assert len(content["data"]["category"]["products"]["edges"]) == product_count CATEGORY_CREATE_MUTATION = """ mutation( $name: String, $slug: String, $description: JSONString, $backgroundImage: Upload, $backgroundImageAlt: String, $parentId: ID, $metadata: [MetadataInput!], $privateMetadata: [MetadataInput!]) { categoryCreate( input: { name: $name slug: $slug description: $description backgroundImage: $backgroundImage backgroundImageAlt: $backgroundImageAlt metadata: $metadata privateMetadata: $privateMetadata }, parent: $parentId ) { category { id name slug description parent { name id } backgroundImage{ alt } metadata { key value } privateMetadata { key value } } errors { field code message } } } """ def test_category_create_mutation( monkeypatch, staff_api_client, permission_manage_products, media_root ): # given staff_api_client.user.user_permissions.add(permission_manage_products) category_name = "Test category" description = "description" category_slug = slugify(category_name) category_description = dummy_editorjs(description, True) image_file, image_name = create_image() image_alt = "Alt text for an image." metadata_key = "md key" metadata_value = "md value" # test creating root category variables = { "name": category_name, "description": category_description, "backgroundImage": image_name, "backgroundImageAlt": image_alt, "slug": category_slug, "metadata": [{"key": metadata_key, "value": metadata_value}], "privateMetadata": [{"key": metadata_key, "value": metadata_value}], }
QUERY_CATEGORY = """ query ($id: ID, $slug: String, $channel: String){ category( id: $id, slug: $slug, ) { id name ancestors(first: 20) { edges { node { name } } } children(first: 20) { edges { node { name } } } products(first: 10, channel: $channel) { edges { node { id } } } } } """ def test_category_query_by_id(user_api_client, product, channel_USD): category = Category.objects.first() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables) content = get_graphql_content(response) category_data = content["data"]["category"] assert category_data is not None assert category_data["name"] == category.name assert len(category_data["ancestors"]["edges"]) == category.get_ancestors().count() assert len(category_data["children"]["edges"]) == category.get_children().count() def test_category_query_invalid_id(user_api_client, product, channel_USD): category_id = "'" variables = { "id": category_id, "channel": channel_USD.slug, } response = user_api_client.post_graphql(QUERY_CATEGORY, variables) content = get_graphql_content_from_response(response) assert len(content["errors"]) == 1 assert ( content["errors"][0]["message"] == f"Invalid ID: {category_id}. Expected: Category." ) assert content["data"]["category"] is None def test_category_query_object_with_given_id_does_not_exist( user_api_client, product, channel_USD ): category_id = graphene.Node.to_global_id("Category", -1) variables = { "id": category_id, "channel": channel_USD.slug, } response = user_api_client.post_graphql(QUERY_CATEGORY, variables) content = get_graphql_content(response) assert content["data"]["category"] is None def test_category_query_object_with_invalid_object_type( user_api_client, product, channel_USD ): category = Category.objects.first() category_id = graphene.Node.to_global_id("Product", category.pk) variables = { "id": category_id, "channel": channel_USD.slug, } response = user_api_client.post_graphql(QUERY_CATEGORY, variables) content = get_graphql_content(response) assert content["data"]["category"] is None def test_category_query_doesnt_show_not_available_products( user_api_client, product, channel_USD ): category = Category.objects.first() variant = product.variants.get() # Set product as not visible due to lack of price. variant.channel_listings.update(price_amount=None) variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables) content = get_graphql_content(response) category_data = content["data"]["category"] assert category_data is not None assert category_data["name"] == category.name assert not category_data["products"]["edges"] def test_category_query_description(user_api_client, product, channel_USD): category = Category.objects.first() description = dummy_editorjs("Test description.", json_format=True) category.description = dummy_editorjs("Test description.") category.save() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } query = """ query ($id: ID, $slug: String){ category( id: $id, slug: $slug, ) { id name description descriptionJson } } """ response = user_api_client.post_graphql(query, variables=variables) content = get_graphql_content(response) category_data = content["data"]["category"] assert category_data["description"] == description assert category_data["descriptionJson"] == description def test_category_query_without_description(user_api_client, product, channel_USD): category = Category.objects.first() category.save() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } query = """ query ($id: ID, $slug: String){ category( id: $id, slug: $slug, ) { id name description descriptionJson } } """ response = user_api_client.post_graphql(query, variables=variables) content = get_graphql_content(response) category_data = content["data"]["category"] assert category_data["description"] is None assert category_data["descriptionJson"] == "{}" def test_category_query_by_slug(user_api_client, product, channel_USD): category = Category.objects.first() variables = {"slug": category.slug, "channel": channel_USD.slug} response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables) content = get_graphql_content(response) category_data = content["data"]["category"] assert category_data is not None assert category_data["name"] == category.name assert len(category_data["ancestors"]["edges"]) == category.get_ancestors().count() assert len(category_data["children"]["edges"]) == category.get_children().count() def test_category_query_error_when_id_and_slug_provided( user_api_client, product, graphql_log_handler, channel_USD ): category = Category.objects.first() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "slug": category.slug, "channel": channel_USD.slug, } response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables) assert graphql_log_handler.messages == [ "saleor.graphql.errors.handled[INFO].GraphQLError" ] content = get_graphql_content(response, ignore_errors=True) assert len(content["errors"]) == 1 def test_category_query_error_when_no_param( user_api_client, product, graphql_log_handler ): variables = {} response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables) assert graphql_log_handler.messages == [ "saleor.graphql.errors.handled[INFO].GraphQLError" ] content = get_graphql_content(response, ignore_errors=True) assert len(content["errors"]) == 1 def test_query_category_product_only_visible_in_listings_as_customer( user_api_client, product_list, channel_USD ): # given category = Category.objects.first() product_list[0].channel_listings.all().update(visible_in_listings=False) product_count = Product.objects.count() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } # when response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables) # then content = get_graphql_content(response, ignore_errors=True) assert len(content["data"]["category"]["products"]["edges"]) == product_count - 1 def test_query_category_product_visible_in_listings_as_staff_without_manage_products( staff_api_client, product_list, channel_USD ): # given category = Category.objects.first() product_list[0].channel_listings.all().update(visible_in_listings=False) product_count = Product.objects.count() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } # when response = staff_api_client.post_graphql(QUERY_CATEGORY, variables=variables) # then content = get_graphql_content(response, ignore_errors=True) assert ( len(content["data"]["category"]["products"]["edges"]) == product_count - 1 ) # invisible doesn't count def test_query_category_product_only_visible_in_listings_as_staff_with_perm( staff_api_client, product_list, permission_manage_products ): # given staff_api_client.user.user_permissions.add(permission_manage_products) category = Category.objects.first() product_list[0].channel_listings.all().update(visible_in_listings=False) product_count = Product.objects.count() variables = {"id": graphene.Node.to_global_id("Category", category.pk)} # when response = staff_api_client.post_graphql(QUERY_CATEGORY, variables=variables) # then content = get_graphql_content(response, ignore_errors=True) assert len(content["data"]["category"]["products"]["edges"]) == product_count def test_query_category_product_only_visible_in_listings_as_app_without_manage_products( app_api_client, product_list, channel_USD ): # given category = Category.objects.first() product_list[0].channel_listings.all().update(visible_in_listings=False) product_count = Product.objects.count() variables = { "id": graphene.Node.to_global_id("Category", category.pk), "channel": channel_USD.slug, } # when response = app_api_client.post_graphql(QUERY_CATEGORY, variables=variables) # then content = get_graphql_content(response, ignore_errors=True) assert ( len(content["data"]["category"]["products"]["edges"]) == product_count - 1 ) # invisible doesn't count def test_query_category_product_only_visible_in_listings_as_app_with_perm( app_api_client, product_list, permission_manage_products ): # given app_api_client.app.permissions.add(permission_manage_products) category = Category.objects.first() product_list[0].channel_listings.all().update(visible_in_listings=False) product_count = Product.objects.count() variables = {"id": graphene.Node.to_global_id("Category", category.pk)} # when response = app_api_client.post_graphql(QUERY_CATEGORY, variables=variables) # then content = get_graphql_content(response, ignore_errors=True) assert len(content["data"]["category"]["products"]["edges"]) == product_count CATEGORY_CREATE_MUTATION = """ mutation( $name: String, $slug: String, $description: JSONString, $backgroundImage: Upload, $backgroundImageAlt: String, $parentId: ID, $metadata: [MetadataInput!], $privateMetadata: [MetadataInput!]) { categoryCreate( input: { name: $name slug: $slug description: $description backgroundImage: $backgroundImage backgroundImageAlt: $backgroundImageAlt metadata: $metadata privateMetadata: $privateMetadata }, parent: $parentId ) { category { id name slug description parent { name id } backgroundImage{ alt } metadata { key value } privateMetadata { key value } } errors { field code message } } } """ def test_category_create_mutation( monkeypatch, staff_api_client, permission_manage_products, media_root ): # given staff_api_client.user.user_permissions.add(permission_manage_products) category_name = "Test category" description = "description" category_slug = slugify(category_name) category_description = dummy_editorjs(description, True) image_file, image_name = create_image() image_alt = "Alt text for an image." metadata_key = "md key" metadata_value = "md value" # test creating root category variables = { "name": category_name, "description": category_description, "backgroundImage": image_name, "backgroundImageAlt": image_alt, "slug": category_slug, "metadata": [{"key": metadata_key, "value": metadata_value}], "privateMetadata": [{"key": metadata_key, "value": metadata_value}], }
body = get_multipart_request_body(
16
2023-11-13 05:00:35+00:00
16k
Aues6uen11Z/Zafkiel
tests/test.py
[ { "identifier": "logger", "path": "zafkiel/logger.py", "snippet": "" }, { "identifier": "Config", "path": "zafkiel/config.py", "snippet": "class Config:\n ST = Settings\n ST.CVSTRATEGY = [\"mstpl\", \"sift\"]\n ST.THRESHOLD = 0.8\n\n GAME_PATH = None\n SERVER_LANG = 'cn'\n...
from zafkiel import API, Template, logger, Timer, simple_report, Config from zafkiel.ocr import Keyword, Ocr, Digit, DigitCounter, Duration, OcrResultButton from zafkiel.ui import Page, Switch, UI
12,430
# Auto import test Keyword Ocr Digit DigitCounter Duration OcrResultButton Page Switch UI API
# Auto import test Keyword Ocr Digit DigitCounter Duration OcrResultButton Page Switch UI API
Template
3
2023-11-12 09:33:35+00:00
16k
medkit-lib/medkit
tests/unit/io/test_brat_output_converter.py
[ { "identifier": "Attribute", "path": "medkit/core/attribute.py", "snippet": "class Attribute(dict_conv.SubclassMapping):\n \"\"\"\n Medkit attribute, to be added to an annotation\n\n Attributes\n ----------\n label:\n The attribute label\n value:\n The value of the attrib...
from pathlib import Path from medkit.core import Attribute from medkit.core.text import ( Entity, EntityNormAttribute, ModifiedSpan, Relation, Segment, Span, TextDocument, UMLSNormAttribute, ) from medkit.io._brat_utils import ( BratAnnConfiguration, BratAttribute, BratEntity, BratNote, BratRelation, ) from medkit.io._common import get_anns_by_type from medkit.io.brat import BratOutputConverter import pytest
12,658
def _get_medkit_doc(): text = "Le patient présente une douleur abdominale de grade 4, la douleur abdominale" " est sévère." doc = TextDocument(uid="doc_brat", text=text) medkit_anns = [
def _get_medkit_doc(): text = "Le patient présente une douleur abdominale de grade 4, la douleur abdominale" " est sévère." doc = TextDocument(uid="doc_brat", text=text) medkit_anns = [
Entity(
1
2023-11-13 16:28:56+00:00
16k
kampta/asic
train.py
[ { "identifier": "Logger", "path": "commons/logger.py", "snippet": "class Logger(SummaryWriter):\n\n def __init__(self, results_path, log_to_tb=False, log_to_wandb=True):\n super().__init__(results_path)\n self.results_path = results_path\n self.log_to_tb = log_to_tb\n self...
import argparse import torch import numpy as np import json import os import torch.nn.functional as F import wandb from torch import nn, optim from tqdm import tqdm from pathlib import Path from commons.logger import Logger, log_visuals from commons.distributed import get_rank, setup_distributed, reduce_loss_dict,\ get_world_size, primary from commons.utils import sample_tuples from datasets.cub import CUBDataset from datasets.in_memory import InMemoryDataset from datasets.spair import SpairDataset from datasets.utils import Augmentor from models.utils import accumulate, requires_grad from models.canonical import Canonical, CanonicalMLP from models.asic import Asic from losses.reg_losses import total_variation_loss from thirdparty.lpips.lpips import get_perceptual_loss from losses.matching_losses import LossCorrsSparse from thirdparty.gangealing.annealing import DecayingCosineAnnealingWarmRestarts,\ lr_cycle_iters
14,383
def save_state_dict(ckpt_name, c_module, t_module, c_ema, t_ema, canon_optim, canon_sched, t_optim, t_sched, args, step, add_step_to_name=False): ckpt_dict = { "canon": c_module.state_dict(), "t": t_module.state_dict(), "c_ema": c_ema.state_dict(), "t_ema": t_ema.state_dict(), "t_optim": t_optim.state_dict(), "t_sched": t_sched.state_dict(), "canon_optim": canon_optim.state_dict() if canon_optim is not None else None, "canon_sched": canon_sched.state_dict() if canon_sched is not None else None, "args": args, "iter": step } torch.save(ckpt_dict, f'{results_path}/{ckpt_name}.pt') if add_step_to_name: torch.save(ckpt_dict, f'{results_path}/{ckpt_name}_{step:07d}.pt') def count_parameters(model):
def save_state_dict(ckpt_name, c_module, t_module, c_ema, t_ema, canon_optim, canon_sched, t_optim, t_sched, args, step, add_step_to_name=False): ckpt_dict = { "canon": c_module.state_dict(), "t": t_module.state_dict(), "c_ema": c_ema.state_dict(), "t_ema": t_ema.state_dict(), "t_optim": t_optim.state_dict(), "t_sched": t_sched.state_dict(), "canon_optim": canon_optim.state_dict() if canon_optim is not None else None, "canon_sched": canon_sched.state_dict() if canon_sched is not None else None, "args": args, "iter": step } torch.save(ckpt_dict, f'{results_path}/{ckpt_name}.pt') if add_step_to_name: torch.save(ckpt_dict, f'{results_path}/{ckpt_name}_{step:07d}.pt') def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
13
2023-11-14 16:43:16+00:00
16k
doodledood/chat-flock
chatflock/use_cases/bshr.py
[ { "identifier": "InMemoryChatDataBackingStore", "path": "chatflock/backing_stores/in_memory.py", "snippet": "class InMemoryChatDataBackingStore(ChatDataBackingStore):\n messages: List[ChatMessage]\n participants: Dict[str, ChatParticipant]\n last_message_id: Optional[int] = None\n\n def __in...
from typing import Any, Dict, Generator, Generic, List, Optional, Type, TypeVar from functools import partial from halo import Halo from langchain.callbacks.manager import CallbackManagerForToolRun from langchain.chat_models.base import BaseChatModel from langchain.llms.openai import OpenAI from langchain.memory import ConversationSummaryBufferMemory from langchain.tools import BaseTool from pydantic import BaseModel, Field from chatflock.backing_stores import InMemoryChatDataBackingStore from chatflock.backing_stores.langchain import LangChainMemoryBasedChatDataBackingStore from chatflock.base import Chat, ChatDataBackingStore from chatflock.conductors import RoundRobinChatConductor from chatflock.parsing_utils import chat_messages_to_pydantic from chatflock.participants.langchain import LangChainBasedAIChatParticipant from chatflock.participants.user import UserChatParticipant from chatflock.renderers import TerminalChatRenderer from chatflock.sequencial_process import SequentialProcess, Step from chatflock.structured_string import Section, StructuredString from chatflock.use_cases.request_response import get_response from chatflock.web_research import WebSearch from chatflock.web_research.web_research import WebResearchTool import datetime import json import questionary
10,936
class BHSRState(BaseModel): information_need: Optional[str] = None queries_to_run: Optional[List[str]] = None answers_to_queries: Optional[Dict[str, str]] = None current_hypothesis: Optional[str] = None proposed_hypothesis: Optional[str] = None feedback: Optional[str] = None is_satisficed: Optional[bool] = None def save_state(state: BHSRState, state_file: Optional[str]) -> None: if state_file is None: return data = state.model_dump() with open(state_file, "w") as f: json.dump(data, f, indent=2) def load_state(state_file: Optional[str]) -> Optional[BHSRState]: if state_file is None: return None try: with open(state_file) as f: data = json.load(f) return BHSRState.model_validate(data) except FileNotFoundError: return None class QueryGenerationResult(BaseModel): information_need: str = Field(description="Information need as requested by the user.") queries: List[str] = Field(description="Set of queries to run.") class HypothesisGenerationResult(BaseModel): hypothesis: str = Field( description="A new or updated hypothesis based on the materials provided. Rich formatting using Markdown. Should include all relevant citations inline." ) class SatisficationCheckResult(BaseModel): feedback: str = Field( description="If not satisficed yet, feedback on why not satisfied and what to think about next. If satisficed, feedback can be empty." ) is_satisficed: bool = Field(description="Whether or not the information need has been satisficed.") def generate_queries( state: BHSRState, chat_model: BaseChatModel, interactive_user: bool = True, max_queries: int = 5, shared_sections: Optional[List[Section]] = None, web_search_tool: Optional[BaseTool] = None, spinner: Optional[Halo] = None, ) -> None: if state.queries_to_run is not None and len(state.queries_to_run) > 0: # Means we are continuing a previous session return if shared_sections is None: shared_sections = [] query_generator = LangChainBasedAIChatParticipant( name="Search Query Generator", role="Search Query Generator", personal_mission="You will be given a specific query or problem by the user and you are to generate a list of " f"AT MOST {max_queries} search queries that will be used to search the internet. Make sure you " f"generate comprehensive, counterfactual, and maximally orthogonal search queries. " "Employ everything you know about " "information foraging and information literacy to generate the best possible questions. " "Use a step-by-step approach and think about the information need and the information " "domain before generating the queries. Order the queries by their importance and relevance " "to the main information need of the user.", other_prompt_sections=shared_sections + [ Section( name="Unclear Information Need", text=( "If the information need or query are vague and unclear, either perform a web search to " "clarify the information need or ask the user for clarification." if interactive_user else "If the information need or query are vague and unclear, either perform a web search to " "clarify the information need or make a best guess. The user will not be available to " "respond back." ), ), Section( name="Refine Queries", text='You might be given a first-pass information need with "None" previous queries and answers, ' "in which case you will do the best you" 'can to generate "naive queries" (uninformed search queries). However the USER might also ' "give you previous search queries or other background information such as accumulated notes. " 'If these materials are present, you are to generate "informed queries" - more specific ' "search queries that aim to zero in on the correct information domain. Do not duplicate " "previously asked questions. Use the notes and other information presented to create " "targeted queries and/or to cast a wider net.", ), Section( name="Termination", text="Once you generate a new set of queries to run, you should terminate the chat immediately by " "ending your message with TERMINATE", ), ], tools=[web_search_tool] if web_search_tool is not None else None, ignore_group_chat_environment=True, chat_model=chat_model, spinner=spinner, ) user = UserChatParticipant() participants = [user, query_generator] try: memory = ConversationSummaryBufferMemory( llm=chat_model, max_token_limit=OpenAI.modelname_to_contextsize(chat_model.model_name) # type: ignore )
# Based directly on David Shaprio's BSHR Loop: https://github.com/daveshap/BSHR_Loop class BHSRState(BaseModel): information_need: Optional[str] = None queries_to_run: Optional[List[str]] = None answers_to_queries: Optional[Dict[str, str]] = None current_hypothesis: Optional[str] = None proposed_hypothesis: Optional[str] = None feedback: Optional[str] = None is_satisficed: Optional[bool] = None def save_state(state: BHSRState, state_file: Optional[str]) -> None: if state_file is None: return data = state.model_dump() with open(state_file, "w") as f: json.dump(data, f, indent=2) def load_state(state_file: Optional[str]) -> Optional[BHSRState]: if state_file is None: return None try: with open(state_file) as f: data = json.load(f) return BHSRState.model_validate(data) except FileNotFoundError: return None class QueryGenerationResult(BaseModel): information_need: str = Field(description="Information need as requested by the user.") queries: List[str] = Field(description="Set of queries to run.") class HypothesisGenerationResult(BaseModel): hypothesis: str = Field( description="A new or updated hypothesis based on the materials provided. Rich formatting using Markdown. Should include all relevant citations inline." ) class SatisficationCheckResult(BaseModel): feedback: str = Field( description="If not satisficed yet, feedback on why not satisfied and what to think about next. If satisficed, feedback can be empty." ) is_satisficed: bool = Field(description="Whether or not the information need has been satisficed.") def generate_queries( state: BHSRState, chat_model: BaseChatModel, interactive_user: bool = True, max_queries: int = 5, shared_sections: Optional[List[Section]] = None, web_search_tool: Optional[BaseTool] = None, spinner: Optional[Halo] = None, ) -> None: if state.queries_to_run is not None and len(state.queries_to_run) > 0: # Means we are continuing a previous session return if shared_sections is None: shared_sections = [] query_generator = LangChainBasedAIChatParticipant( name="Search Query Generator", role="Search Query Generator", personal_mission="You will be given a specific query or problem by the user and you are to generate a list of " f"AT MOST {max_queries} search queries that will be used to search the internet. Make sure you " f"generate comprehensive, counterfactual, and maximally orthogonal search queries. " "Employ everything you know about " "information foraging and information literacy to generate the best possible questions. " "Use a step-by-step approach and think about the information need and the information " "domain before generating the queries. Order the queries by their importance and relevance " "to the main information need of the user.", other_prompt_sections=shared_sections + [ Section( name="Unclear Information Need", text=( "If the information need or query are vague and unclear, either perform a web search to " "clarify the information need or ask the user for clarification." if interactive_user else "If the information need or query are vague and unclear, either perform a web search to " "clarify the information need or make a best guess. The user will not be available to " "respond back." ), ), Section( name="Refine Queries", text='You might be given a first-pass information need with "None" previous queries and answers, ' "in which case you will do the best you" 'can to generate "naive queries" (uninformed search queries). However the USER might also ' "give you previous search queries or other background information such as accumulated notes. " 'If these materials are present, you are to generate "informed queries" - more specific ' "search queries that aim to zero in on the correct information domain. Do not duplicate " "previously asked questions. Use the notes and other information presented to create " "targeted queries and/or to cast a wider net.", ), Section( name="Termination", text="Once you generate a new set of queries to run, you should terminate the chat immediately by " "ending your message with TERMINATE", ), ], tools=[web_search_tool] if web_search_tool is not None else None, ignore_group_chat_environment=True, chat_model=chat_model, spinner=spinner, ) user = UserChatParticipant() participants = [user, query_generator] try: memory = ConversationSummaryBufferMemory( llm=chat_model, max_token_limit=OpenAI.modelname_to_contextsize(chat_model.model_name) # type: ignore )
backing_store: ChatDataBackingStore = LangChainMemoryBasedChatDataBackingStore(memory=memory)
3
2023-11-12 11:10:58+00:00
16k
atlantic-quantum/Shipyard
shipyard/passes/semantic_analysis/semantic_analyzer.py
[ { "identifier": "ErrorCode", "path": "shipyard/compiler_error.py", "snippet": "class ErrorCode(Enum):\n \"\"\"Class to enumerate error codes of the shipyard\"\"\"\n\n ID_NOT_FOUND = \"Identifier not found\"\n DUPLICATE_ID = \"Duplicate id found\"\n NOT_IN_GLOBAL_SCOPE = \"Not in global scope...
from contextlib import contextmanager from openpulse import ast from ...compiler_error import ErrorCode, SemanticError from ...logger import LOGGER from ...mangle import Mangler from ...utilities import ScopeContext from ...visitors import GenericVisitor, LiteralVisitor, TypeVisitor from .scoped_symbol_table import CalScopedSymbolTable, ScopedSymbolTable from .symbols import ( AliasSymbol, ClassicalSymbol, ConstantSymbol, DefcalSymbol, ExternSymbol, GateSymbol, IOSymbol, LiteralSymbol, QuantumSymbol, SubroutineSymbol, Symbol, )
11,471
""" Module that host the SemanticAnalyser QASMVisitor class that can be used to perform semantic analysis on openQASM Abstract Syntax Trees. """ # pylint: disable=R0904: # Too many public methods class SemanticAnalyzer(TypeVisitor, LiteralVisitor, GenericVisitor): """ QASMVisitor class that peforms semantic analysis on a openQASM Abstract Syntax Tree usage: qasm_ast = openpulse.parse(qasm_program_string) sa = SemanticAnalyser() sa.visit(qasm_ast) """ def __init__(self) -> None:
""" Module that host the SemanticAnalyser QASMVisitor class that can be used to perform semantic analysis on openQASM Abstract Syntax Trees. """ # pylint: disable=R0904: # Too many public methods class SemanticAnalyzer(TypeVisitor, LiteralVisitor, GenericVisitor): """ QASMVisitor class that peforms semantic analysis on a openQASM Abstract Syntax Tree usage: qasm_ast = openpulse.parse(qasm_program_string) sa = SemanticAnalyser() sa.visit(qasm_ast) """ def __init__(self) -> None:
self.current_scope: ScopedSymbolTable = None
9
2023-11-16 17:37:29+00:00
16k
raphaelreme/koft
src/experiments/track.py
[ { "identifier": "FakeDetector", "path": "src/detector.py", "snippet": "class FakeDetector(byotrack.Detector): # TODO: include weight\n def __init__(self, mu: torch.Tensor, noise=1.0, fpr=0.1, fnr=0.2, generate_outside_particles=True):\n self.noise = noise\n self.fpr = fpr\n self...
import dataclasses import enum import pathlib import dacite import torch import tqdm # type: ignore import yaml # type: ignore import byotrack from typing import Collection, List from byotrack.implementation.detector.wavelet import WaveletDetector from byotrack.implementation.linker.icy_emht import EMHTParameters, IcyEMHTLinker, Motion from byotrack.implementation.linker.trackmate.trackmate import TrackMateLinker, TrackMateParameters from byotrack.implementation.refiner.interpolater import ForwardBackwardInterpolater from ..detector import FakeDetector from ..metrics.detections import DetectionMetric from ..metrics.tracking import compute_tracking_metrics from ..skt import constant_kalman_filter, Dist, Method, MatchingConfig, SimpleKalmanTracker, PartialTrack from ..koft import constant_koft_filter, OptFlowExtraction, SingleUpdateKOFTracker, TwoUpdateKOFTracker from ..optical_flow import farneback from ..utils import enforce_all_seeds
10,804
gap_closing_max_distance=thresh * 1.5, kalman_search_radius=thresh if self.tracking_method is TrackingMethod.TRACKMATE_KF else None, ), ) if self.tracking_method is TrackingMethod.SKT: kalman_filter = constant_kalman_filter( torch.tensor(self.kalman.detection_noise), torch.tensor(self.kalman.process_noise), self.kalman.dim, self.kalman.order, ) return SimpleKalmanTracker( kalman_filter, MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method) ) # self.tracking_method is TrackingMethod.KOFT: kalman_filter = constant_koft_filter( torch.tensor(self.kalman.detection_noise), torch.tensor(self.kalman.of_noise), torch.tensor(self.kalman.process_noise), self.kalman.dim, self.kalman.order, ) if self.tracking_method is TrackingMethod.KOFTmm: return SingleUpdateKOFTracker( kalman_filter, farneback, MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method) ) # <=> two updates, without updating vel for all tracks and using OptFlowExtraction at Detected pos # return TwoUpdateKOFTracker( # kalman_filter, # farneback, # MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method), # OptFlowExtraction.DETECTED, # False, # ) PartialTrack.MAX_NON_MEASURE = 5 if self.tracking_method is TrackingMethod.KOFTpp else 3 return TwoUpdateKOFTracker( kalman_filter, farneback, MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method), OptFlowExtraction.POSTERIOR, self.kalman.always_update_velocities, ) def create_thresholds(self) -> List[float]: if self.tracking_method is TrackingMethod.EMHT: # XXX: EMHT struggle to converge in some scenarios with high frp and fnr. # On those where it converges 3.0 is the best, and it converges for 3.0 in all of them # So lets manually select [3.0] in high fpr/fnr. In other cases, let's keep the default grid search # return [3.0] return [3.0, 4.0, 5.0, 6.0] # MAHA if ( self.tracking_method in (TrackingMethod.TRACKMATE, TrackingMethod.TRACKMATE_KF) or self.kalman.dist is Dist.EUCLIDIAN ): return [3.0, 5.0, 7.0, 10.0, 15.0] if self.kalman.dist is Dist.MAHALANOBIS: return [0.5, 1.0, 2.0, 3.0, 4.0] # self.dist is Dist.LIKELIHOOD: return [1e-6, 1e-5, 1e-4, 1e-3, 1e-2] def main(name: str, cfg_data: dict) -> None: print("Running:", name) print(yaml.dump(cfg_data)) cfg = dacite.from_dict(ExperimentConfig, cfg_data, dacite.Config(cast=[pathlib.Path, tuple, enum.Enum])) enforce_all_seeds(cfg.seed) # Read video and ground truth video_path = cfg.simulation_path / "video.mp4" gt_path = cfg.simulation_path / "video_data.pt" video = byotrack.Video(video_path) video.set_transform(byotrack.VideoTransformConfig(aggregate=True, normalize=True, q_min=0.00, q_max=1.0)) ground_truth = torch.load(gt_path) # Detections detector = cfg.detection.create_detector(ground_truth["mu"]) detections_sequence = detector.run(video) # Evaluate detections step performances tp = 0.0 n_pred = 0.0 n_true = 0.0 for detections in detections_sequence: det_metrics = DetectionMetric(1.5).compute_at( detections, ground_truth["mu"][detections.frame_id], ground_truth["weight"][detections.frame_id] ) tp += det_metrics["tp"] n_pred += det_metrics["n_pred"] n_true += det_metrics["n_true"] print("=======Detection======") print("Recall", tp / n_true if n_true else 1.0) print("Precision", tp / n_pred if n_pred else 1.0) print("f1", 2 * tp / (n_true + n_pred) if n_pred + n_true else 1.0) refiner = ForwardBackwardInterpolater() metrics = {} best_thresh = 0.0 best_hota = 0.0 best_tracks: Collection[byotrack.Track] = [] for thresh in tqdm.tqdm(cfg.create_thresholds()): linker = cfg.create_linker(thresh) tracks = linker.run(video, detections_sequence) tracks = refiner.run(video, tracks) tqdm.tqdm.write(f"Built {len(tracks)} tracks") if len(tracks) == 0 or len(tracks) > ground_truth["mu"].shape[1] * 15: tqdm.tqdm.write(f"Threshold: {thresh} => Tracking failed (too few or too many tracks). Continuing...") continue
class DetectionMethod(enum.Enum): WAVELET = "wavelet" FAKE = "fake" @dataclasses.dataclass class WaveletConfig: k: float = 3.0 scale: int = 1 min_area: float = 10.0 @dataclasses.dataclass class FakeConfig: fpr: float = 0.1 # Bad detection rate fnr: float = 0.2 # Miss detection rate measurement_noise: float = 1.0 @dataclasses.dataclass class DetectionConfig: detector: DetectionMethod wavelet: WaveletConfig fake: FakeConfig # interactive = False # Could tweak the detector parameters interactively ? def create_detector(self, mu: torch.Tensor) -> byotrack.Detector: if self.detector == DetectionMethod.WAVELET: return WaveletDetector(self.wavelet.scale, self.wavelet.k, self.wavelet.min_area) return FakeDetector(mu, self.fake.measurement_noise, self.fake.fpr, self.fake.fnr) @dataclasses.dataclass class KalmanConfig: detection_noise: float of_noise: float process_noise: float # Miss evaluation of the process dist: Dist matching_method: Method always_update_velocities: bool = True dim: int = 2 order: int = 1 class TrackingMethod(enum.Enum): SKT = "skt" KOFT = "koft" KOFTmm = "koft--" KOFTpp = "koft++" TRACKMATE = "trackmate" TRACKMATE_KF = "trackmate-kf" EMHT = "emht" @dataclasses.dataclass class ExperimentConfig: seed: int simulation_path: pathlib.Path tracking_method: TrackingMethod detection: DetectionConfig kalman: KalmanConfig icy_path: pathlib.Path fiji_path: pathlib.Path def create_linker(self, thresh: float) -> byotrack.Linker: """Create a linker""" if self.tracking_method is TrackingMethod.EMHT: return IcyEMHTLinker( self.icy_path, EMHTParameters( gate_factor=thresh, motion=Motion.MULTI, tree_depth=2, ), ) if self.tracking_method in (TrackingMethod.TRACKMATE, TrackingMethod.TRACKMATE_KF): # As kalman tracking we let a gap of 2 consecutive miss detections # In that case, we allow 1.5 thresh return TrackMateLinker( self.fiji_path, TrackMateParameters( max_frame_gap=PartialTrack.MAX_NON_MEASURE, linking_max_distance=thresh, gap_closing_max_distance=thresh * 1.5, kalman_search_radius=thresh if self.tracking_method is TrackingMethod.TRACKMATE_KF else None, ), ) if self.tracking_method is TrackingMethod.SKT: kalman_filter = constant_kalman_filter( torch.tensor(self.kalman.detection_noise), torch.tensor(self.kalman.process_noise), self.kalman.dim, self.kalman.order, ) return SimpleKalmanTracker( kalman_filter, MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method) ) # self.tracking_method is TrackingMethod.KOFT: kalman_filter = constant_koft_filter( torch.tensor(self.kalman.detection_noise), torch.tensor(self.kalman.of_noise), torch.tensor(self.kalman.process_noise), self.kalman.dim, self.kalman.order, ) if self.tracking_method is TrackingMethod.KOFTmm: return SingleUpdateKOFTracker( kalman_filter, farneback, MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method) ) # <=> two updates, without updating vel for all tracks and using OptFlowExtraction at Detected pos # return TwoUpdateKOFTracker( # kalman_filter, # farneback, # MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method), # OptFlowExtraction.DETECTED, # False, # ) PartialTrack.MAX_NON_MEASURE = 5 if self.tracking_method is TrackingMethod.KOFTpp else 3 return TwoUpdateKOFTracker( kalman_filter, farneback, MatchingConfig(thresh, self.kalman.dist, self.kalman.matching_method), OptFlowExtraction.POSTERIOR, self.kalman.always_update_velocities, ) def create_thresholds(self) -> List[float]: if self.tracking_method is TrackingMethod.EMHT: # XXX: EMHT struggle to converge in some scenarios with high frp and fnr. # On those where it converges 3.0 is the best, and it converges for 3.0 in all of them # So lets manually select [3.0] in high fpr/fnr. In other cases, let's keep the default grid search # return [3.0] return [3.0, 4.0, 5.0, 6.0] # MAHA if ( self.tracking_method in (TrackingMethod.TRACKMATE, TrackingMethod.TRACKMATE_KF) or self.kalman.dist is Dist.EUCLIDIAN ): return [3.0, 5.0, 7.0, 10.0, 15.0] if self.kalman.dist is Dist.MAHALANOBIS: return [0.5, 1.0, 2.0, 3.0, 4.0] # self.dist is Dist.LIKELIHOOD: return [1e-6, 1e-5, 1e-4, 1e-3, 1e-2] def main(name: str, cfg_data: dict) -> None: print("Running:", name) print(yaml.dump(cfg_data)) cfg = dacite.from_dict(ExperimentConfig, cfg_data, dacite.Config(cast=[pathlib.Path, tuple, enum.Enum])) enforce_all_seeds(cfg.seed) # Read video and ground truth video_path = cfg.simulation_path / "video.mp4" gt_path = cfg.simulation_path / "video_data.pt" video = byotrack.Video(video_path) video.set_transform(byotrack.VideoTransformConfig(aggregate=True, normalize=True, q_min=0.00, q_max=1.0)) ground_truth = torch.load(gt_path) # Detections detector = cfg.detection.create_detector(ground_truth["mu"]) detections_sequence = detector.run(video) # Evaluate detections step performances tp = 0.0 n_pred = 0.0 n_true = 0.0 for detections in detections_sequence: det_metrics = DetectionMetric(1.5).compute_at( detections, ground_truth["mu"][detections.frame_id], ground_truth["weight"][detections.frame_id] ) tp += det_metrics["tp"] n_pred += det_metrics["n_pred"] n_true += det_metrics["n_true"] print("=======Detection======") print("Recall", tp / n_true if n_true else 1.0) print("Precision", tp / n_pred if n_pred else 1.0) print("f1", 2 * tp / (n_true + n_pred) if n_pred + n_true else 1.0) refiner = ForwardBackwardInterpolater() metrics = {} best_thresh = 0.0 best_hota = 0.0 best_tracks: Collection[byotrack.Track] = [] for thresh in tqdm.tqdm(cfg.create_thresholds()): linker = cfg.create_linker(thresh) tracks = linker.run(video, detections_sequence) tracks = refiner.run(video, tracks) tqdm.tqdm.write(f"Built {len(tracks)} tracks") if len(tracks) == 0 or len(tracks) > ground_truth["mu"].shape[1] * 15: tqdm.tqdm.write(f"Threshold: {thresh} => Tracking failed (too few or too many tracks). Continuing...") continue
metrics[thresh] = compute_tracking_metrics(tracks, ground_truth)
2
2023-11-10 10:18:39+00:00
16k
quantuminterface/qiclib
src/qiclib/code/qi_dataflow.py
[ { "identifier": "ForRange", "path": "src/qiclib/code/qi_jobs.py", "snippet": "class ForRange(QiContextManager):\n \"\"\"Adds ForRange to program.\n If multiple cells are used inside body, a synchronisation between the cells is done before the ForRange as well as after the end of the body.\n If ...
from abc import abstractmethod from enum import Enum from typing import Optional, List, Set, Tuple, Union, Dict from copy import copy from qiclib.code.qi_var_definitions import ( _QiVariableBase, QiExpression, ) from .qi_jobs import ( ForRange, If, Parallel, QiCell, QiCommand, QiContextManager, QiJob, )
11,261
succ_neighbor = copy(pred_neighbor) succ_neighbor.node = self self.predecessors.add(pred_neighbor) pred.successors.add(succ_neighbor) class _CFG: """Constructs a control flow graph (CFG) from the commands of a QiJob. The end node does not contain a command, if the last top level command is an If-else or ForRange """ def __init__(self, job: QiJob): self.nodes: Set[_CFGNode] = set() start, end = recursive_build_sub_cfg(job.commands, self.nodes) self.end = _CFGNode(_CFGNode.Type.END, None, None, *end) self.start = _CFGNode(_CFGNode.Type.START, None, None) self.start.connect_successors( _CFGNode.Neighbor(start, _CFGNode.SrcEdgeType.NORMAL) ) def node_iterator(self): visited = set() stack = [self.start] while len(stack) > 0: node = stack.pop() visited.add(node) yield node for successor in node.successors: successor = successor.node if successor not in visited: stack.append(successor) def add_value(self, key, initial): for node in self.node_iterator(): if key not in node.value_map: node.value_map[key] = initial def dump_dot_graph(self, path): """Dump the current cfg topology as a dot file for inspecting and debugging purposes.""" with open(path, "w", encoding="utf-8") as f: f.write("\ndigraph {\n") queue = [self.start] node_visited_or_in_queue = set() node_visited_or_in_queue.add(self.start) while len(queue) > 0: node = queue.pop(0) node_attributes = "\n".join( [f"{name} = {value}" for name, value in node.value_map.items()] ) if node.type == _CFGNode.Type.COMMAND: if isinstance(node.command, QiCommand): node_text = f"{node.command._stringify()}" else: node_text = f"{node.command}" label = f"{node_text}\n{node_attributes}" shape = "box" elif node.type == _CFGNode.Type.START: label = f"start\n{node_attributes}" shape = "oval" elif node.type == _CFGNode.Type.END: label = f"end\n{node_attributes}" shape = "oval" escaped_label = label.translate(str.maketrans({'"': '\\"'})) f.write(f'\t{node.id} [shape={shape}, label="{escaped_label}"];\n') for successor in node.successors: src_edge_type = successor.src_edge_type dest_edge_type = successor.dest_edge_type successor = successor.node assert isinstance(successor, _CFGNode) label = [] if src_edge_type is not _CFGNode.SrcEdgeType.NORMAL: label.append(f"{src_edge_type}") if dest_edge_type is not _CFGNode.DestEdgeType.NORMAL: label.append(f"{dest_edge_type}") label = ", ".join(label) node_label = f'[label="{label}"]' f.write(f"\t{node.id} -> {successor.id} {node_label};\n") if successor not in node_visited_or_in_queue: queue.append(successor) node_visited_or_in_queue.add(successor) f.write("}") def recursive_build_sub_cfg( commands: List[QiCommand], nodes ) -> Tuple[_CFGNode, List[_CFGNode.Neighbor]]: """ Constructs the nodes and edges for a CFG containing provided commands. `nodes` accumulates all nodes of the CFG. """ assert len(commands) > 0 prev: List[_CFGNode.Neighbor] = [] for idx, command in enumerate(commands, 0):
# Copyright © 2017-2023 Quantum Interface (quantuminterface@ipe.kit.edu) # Richard Gebauer, IPE, Karlsruhe Institute of Technology # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """ This module provides basic infrastructure to perform dataflow analyses on qicode programs. Dataflow analyses are computed on the control flow graph (CFG) of a QiJob which should be created when necessary. The dataflow analysis itself is performed in using a standard worklist algorithm. The abstract domain is modeled using DataflowValue. Its merge function represents the supremum calculation. It is recommended to treat DataflowValues as immutable. """ class _CFGNode: class Type(Enum): START = 0 END = 1 COMMAND = 2 class SrcEdgeType(Enum): """CFG Edge information about the source node""" IF_TRUE = 0 IF_FALSE = 1 FOR_BODY = 2 FOR_END = 4 NORMAL = 5 def __str__(self): return { _CFGNode.SrcEdgeType.IF_TRUE: "if_true", _CFGNode.SrcEdgeType.IF_FALSE: "if_false", _CFGNode.SrcEdgeType.FOR_BODY: "for_true", _CFGNode.SrcEdgeType.FOR_END: "for_end", _CFGNode.SrcEdgeType.NORMAL: "normal", }[self] class DestEdgeType(Enum): """CFG Edge information about the destination node""" FOR_BODY_RETURN = 0 FOR_ENTRY = 1 NORMAL = 2 def __str__(self): return { _CFGNode.DestEdgeType.FOR_BODY_RETURN: "for_body_ret", _CFGNode.DestEdgeType.FOR_ENTRY: "for_entry", _CFGNode.DestEdgeType.NORMAL: "normal", }[self] class Neighbor: """Combination of node and both edge types. Each edge in the CFG is represented by an instance of this class""" def __init__( self, neighbor: "_CFGNode", src_edge_type: "_CFGNode.SrcEdgeType", dest_edge_type: Optional["_CFGNode.DestEdgeType"] = None, ): # Default argument didn't work for me in this case. if dest_edge_type is None: dest_edge_type = _CFGNode.DestEdgeType.NORMAL self.node = neighbor # Information about the edge for the src node # (for example, if this edge goes to the 'else' block of an 'if' statement.) self.src_edge_type = src_edge_type # Information about the edge for the destination node # (for example, if the edge loops back from the body of a for statement.) self.dest_edge_type = dest_edge_type _cfg_node_next_id = 1 def __init__( self, type: Union["_CFGNode.Type", QiCommand], instruction_list, index, *predecessors: "Tuple[_CFGNode, _CFGNode.SrcEdgeType]", ): if isinstance(type, QiCommand): self.type = _CFGNode.Type.COMMAND self.command = type else: assert isinstance(type, _CFGNode.Type) self.type = type # This field is used to associated arbitrary data with every node. # For example, a dataflow analysis might use this dictionary to # the nodes current abstract value. self.value_map: Dict[str, CellValues] = {} self.predecessors: Set[_CFGNode.Neighbor] = set() self.successors: Set[_CFGNode.Neighbor] = set() # Used to find commands in job command list, so we can insert new instruction before or after this # command. self.instruction_list = instruction_list self.instruction_index = index self.id = _CFGNode._cfg_node_next_id _CFGNode._cfg_node_next_id += 1 self.connect_predecessors(*predecessors) def connect_successors(self, *successors: "_CFGNode.Neighbor"): assert all(map(lambda x: isinstance(x, _CFGNode.Neighbor), successors)) for succ_neighbor in successors: succ = succ_neighbor.node pred_neighbor = copy(succ_neighbor) pred_neighbor.node = self self.successors.add(succ_neighbor) succ.predecessors.add(pred_neighbor) def connect_predecessors(self, *predecessors: "_CFGNode.Neighbor"): assert all(map(lambda x: isinstance(x, _CFGNode.Neighbor), predecessors)) for pred_neighbor in predecessors: pred = pred_neighbor.node succ_neighbor = copy(pred_neighbor) succ_neighbor.node = self self.predecessors.add(pred_neighbor) pred.successors.add(succ_neighbor) class _CFG: """Constructs a control flow graph (CFG) from the commands of a QiJob. The end node does not contain a command, if the last top level command is an If-else or ForRange """ def __init__(self, job: QiJob): self.nodes: Set[_CFGNode] = set() start, end = recursive_build_sub_cfg(job.commands, self.nodes) self.end = _CFGNode(_CFGNode.Type.END, None, None, *end) self.start = _CFGNode(_CFGNode.Type.START, None, None) self.start.connect_successors( _CFGNode.Neighbor(start, _CFGNode.SrcEdgeType.NORMAL) ) def node_iterator(self): visited = set() stack = [self.start] while len(stack) > 0: node = stack.pop() visited.add(node) yield node for successor in node.successors: successor = successor.node if successor not in visited: stack.append(successor) def add_value(self, key, initial): for node in self.node_iterator(): if key not in node.value_map: node.value_map[key] = initial def dump_dot_graph(self, path): """Dump the current cfg topology as a dot file for inspecting and debugging purposes.""" with open(path, "w", encoding="utf-8") as f: f.write("\ndigraph {\n") queue = [self.start] node_visited_or_in_queue = set() node_visited_or_in_queue.add(self.start) while len(queue) > 0: node = queue.pop(0) node_attributes = "\n".join( [f"{name} = {value}" for name, value in node.value_map.items()] ) if node.type == _CFGNode.Type.COMMAND: if isinstance(node.command, QiCommand): node_text = f"{node.command._stringify()}" else: node_text = f"{node.command}" label = f"{node_text}\n{node_attributes}" shape = "box" elif node.type == _CFGNode.Type.START: label = f"start\n{node_attributes}" shape = "oval" elif node.type == _CFGNode.Type.END: label = f"end\n{node_attributes}" shape = "oval" escaped_label = label.translate(str.maketrans({'"': '\\"'})) f.write(f'\t{node.id} [shape={shape}, label="{escaped_label}"];\n') for successor in node.successors: src_edge_type = successor.src_edge_type dest_edge_type = successor.dest_edge_type successor = successor.node assert isinstance(successor, _CFGNode) label = [] if src_edge_type is not _CFGNode.SrcEdgeType.NORMAL: label.append(f"{src_edge_type}") if dest_edge_type is not _CFGNode.DestEdgeType.NORMAL: label.append(f"{dest_edge_type}") label = ", ".join(label) node_label = f'[label="{label}"]' f.write(f"\t{node.id} -> {successor.id} {node_label};\n") if successor not in node_visited_or_in_queue: queue.append(successor) node_visited_or_in_queue.add(successor) f.write("}") def recursive_build_sub_cfg( commands: List[QiCommand], nodes ) -> Tuple[_CFGNode, List[_CFGNode.Neighbor]]: """ Constructs the nodes and edges for a CFG containing provided commands. `nodes` accumulates all nodes of the CFG. """ assert len(commands) > 0 prev: List[_CFGNode.Neighbor] = [] for idx, command in enumerate(commands, 0):
if isinstance(command, If):
1
2023-11-10 10:26:10+00:00
16k
jpcadena/fastapi-boilerplate
app/api/api_v1/router/auth.py
[ { "identifier": "get_redis_dep", "path": "app/api/deps.py", "snippet": "async def get_redis_dep(\n redis_dependency: Annotated[RedisDependency, Depends()]\n) -> AsyncGenerator[Redis, None]: # type: ignore\n \"\"\"\n Lazy generation of Redis dependency\n :param redis_dependency: The dependen...
import logging from typing import Annotated, Any, Optional from fastapi import ( APIRouter, Body, Depends, Header, HTTPException, Path, Request, status, ) from fastapi.security import OAuth2PasswordRequestForm from pydantic import EmailStr from redis.asyncio import Redis from starlette.datastructures import Address from app.api.deps import get_redis_dep from app.api.oauth2_validation import get_current_user, get_refresh_current_user from app.config.config import ( get_auth_settings, get_init_settings, get_settings, init_setting, ) from app.config.db.auth_settings import AuthSettings from app.config.init_settings import InitSettings from app.config.settings import Settings from app.core.security.password import verify_password from app.exceptions.exceptions import NotFoundException, ServiceException from app.models.sql.user import User as UserDB from app.schemas.external.msg import Msg from app.schemas.external.token import TokenResetPassword, TokenResponse from app.schemas.external.user import ( UserResponse, UserUpdate, UserUpdateResponse, ) from app.schemas.infrastructure.user import UserAuth from app.services.infrastructure.auth import common_auth_procedure from app.services.infrastructure.token import TokenService from app.services.infrastructure.user import UserService, get_user_service from app.tasks.email_tasks.email_tasks import ( send_password_changed_confirmation_email, send_reset_password_email, ) from app.utils.security.password import ( generate_password_reset_token, verify_password_reset_token, )
14,314
UserAuth, Depends(get_refresh_current_user) ], redis: Annotated[Redis, Depends(get_redis_dep)], # type: ignore ) -> TokenResponse: """ Generates a refresh token for the current user and saves it to the database ## Response: - `return:` **Token information with access token, its type and refresh token** - `rtype:` **TokenResponse** \f :param request: The HTTP request on the server :type request: Request :param user_service: Dependency method for User Service :type user_service: UserService :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :param refresh_current_user: The current user dependency for refresh token :type refresh_current_user: UserAuth :param redis: Dependency method for async Redis connection :type redis: Redis """ client: Optional[Address] if not (client := request.client): raise NotFoundException(auth_settings.NO_CLIENT_FOUND) client_ip: str = client.host try: user: UserDB = await user_service.get_login_user( refresh_current_user.username ) except ServiceException as exc: detail: str = "Can not found user information." logger.error(detail) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=detail ) from exc return await common_auth_procedure(user, client_ip, redis, auth_settings) @router.post("/validate-token", response_model=UserAuth) async def validate_token( current_user: Annotated[UserAuth, Depends(get_current_user)] ) -> UserAuth: """ Endpoint to validate an access token. ## Response: - `return:` **The authenticated user instance** - `rtype:` **UserAuth** \f :param current_user: The current user :type current_user: UserAuth """ return current_user @router.post("/recover-password/{email}", response_model=Msg) async def recover_password( settings: Annotated[Settings, Depends(get_settings)], auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], email: Annotated[ EmailStr, Path( ..., title="Email", description="The email used to recover the password", example={"email": "someone@example.com"}, openapi_examples=init_setting.EMAIL_BODY_EXAMPLES, ), ], user_service: Annotated[UserService, Depends(get_user_service)], init_settings: Annotated[InitSettings, Depends(get_init_settings)], ) -> Msg: """ Endpoint to handle password recovery. ## Parameter: - `email:` **Path parameter that references the email used to recover the password** - `type:` **EmailStr** ## Response: - `return:` **Message object** - `rtype:` **Msg** \f :param user_service: Dependency method for User service object :type user_service: UserService :param settings: Dependency method for cached setting object :type settings: config.Settings :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :param init_settings: Dependency method for cached init setting object :type init_settings: InitSettings """ try: user: Optional[UserResponse] = await user_service.get_user_by_email( email ) except ServiceException as exc: logger.error(exc) user = None if user: password_reset_token: str = generate_password_reset_token( email, auth_settings ) await send_reset_password_email( user.email, user.username, password_reset_token, settings, init_settings, auth_settings, ) return Msg(msg="If the email is registered, a reset link will be sent.") @router.post("/reset-password", response_model=Msg) async def reset_password( settings: Annotated[Settings, Depends(get_settings)], auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], user_service: Annotated[UserService, Depends(get_user_service)], token_reset_password: Annotated[
""" Authentication API Router. This module provides login and password recovery functionality. """ logger: logging.Logger = logging.getLogger(__name__) router: APIRouter = APIRouter(prefix="/auth", tags=["auth"]) @router.post("/login", response_model=TokenResponse) async def login( request: Request, auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], user: Annotated[OAuth2PasswordRequestForm, Depends()], user_service: Annotated[UserService, Depends(get_user_service)], redis: Annotated[Redis, Depends(get_redis_dep)], # type: ignore ) -> TokenResponse: """ Endpoint to handle user login with OAuth2 authentication using request form. ## Parameter: - `user:` **Request body with username and password** - `type:` **OAuth2PasswordRequestForm** ## Response: - `return:` **Token information with access token, its type and refresh token** - `rtype:` **TokenResponse** \f :param request: Request object for client host information :type request: Request :param user_service: Dependency method for User Service :type user_service: UserService :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :param redis: Dependency method for async Redis connection :type redis: Redis """ client: Optional[Address] = request.client if not client: raise NotFoundException(auth_settings.NO_CLIENT_FOUND) client_ip: str = client.host try: found_user: UserDB = await user_service.get_login_user(user.username) except ServiceException as exc: logger.error(exc) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Invalid credentials" ) from exc if not verify_password(found_user.password, user.password): detail: str = "Incorrect password" logger.warning(detail) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=detail ) if not found_user.is_active: user_detail: str = "Inactive user" logger.warning(user_detail) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=user_detail ) return await common_auth_procedure( found_user, client_ip, redis, auth_settings ) @router.post( "/refresh", response_model=TokenResponse, status_code=status.HTTP_201_CREATED, ) async def refresh_token( request: Request, user_service: Annotated[UserService, Depends(get_user_service)], auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], refresh_current_user: Annotated[ UserAuth, Depends(get_refresh_current_user) ], redis: Annotated[Redis, Depends(get_redis_dep)], # type: ignore ) -> TokenResponse: """ Generates a refresh token for the current user and saves it to the database ## Response: - `return:` **Token information with access token, its type and refresh token** - `rtype:` **TokenResponse** \f :param request: The HTTP request on the server :type request: Request :param user_service: Dependency method for User Service :type user_service: UserService :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :param refresh_current_user: The current user dependency for refresh token :type refresh_current_user: UserAuth :param redis: Dependency method for async Redis connection :type redis: Redis """ client: Optional[Address] if not (client := request.client): raise NotFoundException(auth_settings.NO_CLIENT_FOUND) client_ip: str = client.host try: user: UserDB = await user_service.get_login_user( refresh_current_user.username ) except ServiceException as exc: detail: str = "Can not found user information." logger.error(detail) raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=detail ) from exc return await common_auth_procedure(user, client_ip, redis, auth_settings) @router.post("/validate-token", response_model=UserAuth) async def validate_token( current_user: Annotated[UserAuth, Depends(get_current_user)] ) -> UserAuth: """ Endpoint to validate an access token. ## Response: - `return:` **The authenticated user instance** - `rtype:` **UserAuth** \f :param current_user: The current user :type current_user: UserAuth """ return current_user @router.post("/recover-password/{email}", response_model=Msg) async def recover_password( settings: Annotated[Settings, Depends(get_settings)], auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], email: Annotated[ EmailStr, Path( ..., title="Email", description="The email used to recover the password", example={"email": "someone@example.com"}, openapi_examples=init_setting.EMAIL_BODY_EXAMPLES, ), ], user_service: Annotated[UserService, Depends(get_user_service)], init_settings: Annotated[InitSettings, Depends(get_init_settings)], ) -> Msg: """ Endpoint to handle password recovery. ## Parameter: - `email:` **Path parameter that references the email used to recover the password** - `type:` **EmailStr** ## Response: - `return:` **Message object** - `rtype:` **Msg** \f :param user_service: Dependency method for User service object :type user_service: UserService :param settings: Dependency method for cached setting object :type settings: config.Settings :param auth_settings: Dependency method for cached setting object :type auth_settings: AuthSettings :param init_settings: Dependency method for cached init setting object :type init_settings: InitSettings """ try: user: Optional[UserResponse] = await user_service.get_user_by_email( email ) except ServiceException as exc: logger.error(exc) user = None if user: password_reset_token: str = generate_password_reset_token( email, auth_settings ) await send_reset_password_email( user.email, user.username, password_reset_token, settings, init_settings, auth_settings, ) return Msg(msg="If the email is registered, a reset link will be sent.") @router.post("/reset-password", response_model=Msg) async def reset_password( settings: Annotated[Settings, Depends(get_settings)], auth_settings: Annotated[AuthSettings, Depends(get_auth_settings)], user_service: Annotated[UserService, Depends(get_user_service)], token_reset_password: Annotated[
TokenResetPassword,
12
2023-11-17 00:32:32+00:00
16k
vitant-lang/CBAM-ASPP
train.py
[ { "identifier": "DeepLab", "path": "nets/deeplabv3_plus.py", "snippet": "class DeepLab(nn.Module):\n\tdef __init__(self, num_classes, backbone=\"mobilenet\", pretrained=True, downsample_factor=16):\n\t\tsuper(DeepLab, self).__init__()\n\t\tif backbone==\"xception\":\n\t\t\t#-----------------------------...
import os import datetime import numpy as np import torch import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim as optim from torch.utils.data import DataLoader from nets.deeplabv3_plus import DeepLab from nets.deeplabv3_training import (get_lr_scheduler, set_optimizer_lr, weights_init) from utils.callbacks import LossHistory, EvalCallback from utils.dataloader import DeeplabDataset, deeplab_dataset_collate from utils.utils import download_weights, show_config from utils.utils_fit import fit_one_epoch from torch.cuda.amp import GradScaler as GradScaler
11,757
#------------------------------------------------------------------# # torch 1.2不支持amp,建议使用torch 1.7.1及以上正确使用fp16 # 因此torch1.2这里显示"could not be resolve" #------------------------------------------------------------------# if fp16: scaler = GradScaler() else: scaler = None model_train = model.train() #----------------------------# # 多卡同步Bn #----------------------------# if sync_bn and ngpus_per_node > 1 and distributed: model_train = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model_train) elif sync_bn: print("Sync_bn is not support in one gpu or not distributed.") if Cuda: if distributed: #----------------------------# # 多卡平行运行 #----------------------------# model_train = model_train.cuda(local_rank) model_train = torch.nn.parallel.DistributedDataParallel(model_train, device_ids=[local_rank], find_unused_parameters=True) else: model_train = torch.nn.DataParallel(model) cudnn.benchmark = True model_train = model_train.cuda() #---------------------------# # 读取数据集对应的txt #---------------------------# with open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Segmentation/train.txt"),"r") as f: train_lines = f.readlines() with open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Segmentation/val.txt"),"r") as f: val_lines = f.readlines() num_train = len(train_lines) num_val = len(val_lines) if local_rank == 0: show_config( num_classes = num_classes, backbone = backbone, model_path = model_path, input_shape = input_shape, \ Init_Epoch = Init_Epoch, Freeze_Epoch = Freeze_Epoch, UnFreeze_Epoch = UnFreeze_Epoch, Freeze_batch_size = Freeze_batch_size, Unfreeze_batch_size = Unfreeze_batch_size, Freeze_Train = Freeze_Train, \ Init_lr = Init_lr, Min_lr = Min_lr, optimizer_type = optimizer_type, momentum = momentum, lr_decay_type = lr_decay_type, \ save_period = save_period, save_dir = save_dir, num_workers = num_workers, num_train = num_train, num_val = num_val ) #---------------------------------------------------------# # 总训练世代指的是遍历全部数据的总次数 # 总训练步长指的是梯度下降的总次数 # 每个训练世代包含若干训练步长,每个训练步长进行一次梯度下降。 # 此处仅建议最低训练世代,上不封顶,计算时只考虑了解冻部分 #----------------------------------------------------------# wanted_step = 1.5e4 if optimizer_type == "sgd" else 0.5e4 total_step = num_train // Unfreeze_batch_size * UnFreeze_Epoch if total_step <= wanted_step: if num_train // Unfreeze_batch_size == 0: raise ValueError('数据集过小,无法进行训练,请扩充数据集。') wanted_epoch = wanted_step // (num_train // Unfreeze_batch_size) + 1 print("\n\033[1;33;44m[Warning] 使用%s优化器时,建议将训练总步长设置到%d以上。\033[0m"%(optimizer_type, wanted_step)) print("\033[1;33;44m[Warning] 本次运行的总训练数据量为%d,Unfreeze_batch_size为%d,共训练%d个Epoch,计算出总训练步长为%d。\033[0m"%(num_train, Unfreeze_batch_size, UnFreeze_Epoch, total_step)) print("\033[1;33;44m[Warning] 由于总训练步长为%d,小于建议总步长%d,建议设置总世代为%d。\033[0m"%(total_step, wanted_step, wanted_epoch)) #------------------------------------------------------# # 主干特征提取网络特征通用,冻结训练可以加快训练速度 # 也可以在训练初期防止权值被破坏。 # Init_Epoch为起始世代 # Interval_Epoch为冻结训练的世代 # Epoch总训练世代 # 提示OOM或者显存不足请调小Batch_size #------------------------------------------------------# if True: UnFreeze_flag = False #------------------------------------# # 冻结一定部分训练 #------------------------------------# if Freeze_Train: for param in model.backbone.parameters(): param.requires_grad = False #-------------------------------------------------------------------# # 如果不冻结训练的话,直接设置batch_size为Unfreeze_batch_size #-------------------------------------------------------------------# batch_size = Freeze_batch_size if Freeze_Train else Unfreeze_batch_size #-------------------------------------------------------------------# # 判断当前batch_size,自适应调整学习率 #-------------------------------------------------------------------# nbs = 16 lr_limit_max = 5e-4 if optimizer_type == 'adam' else 1e-1 lr_limit_min = 3e-4 if optimizer_type == 'adam' else 5e-4 if backbone == "xception": lr_limit_max = 1e-4 if optimizer_type == 'adam' else 1e-1 lr_limit_min = 1e-4 if optimizer_type == 'adam' else 5e-4 Init_lr_fit = min(max(batch_size / nbs * Init_lr, lr_limit_min), lr_limit_max) Min_lr_fit = min(max(batch_size / nbs * Min_lr, lr_limit_min * 1e-2), lr_limit_max * 1e-2) #---------------------------------------# # 根据optimizer_type选择优化器 #---------------------------------------# optimizer = { 'adam' : optim.Adam(model.parameters(), Init_lr_fit, betas = (momentum, 0.999), weight_decay = weight_decay), 'sgd' : optim.SGD(model.parameters(), Init_lr_fit, momentum = momentum, nesterov=True, weight_decay = weight_decay) }[optimizer_type] #---------------------------------------# # 获得学习率下降的公式 #---------------------------------------# lr_scheduler_func = get_lr_scheduler(lr_decay_type, Init_lr_fit, Min_lr_fit, UnFreeze_Epoch) #---------------------------------------# # 判断每一个世代的长度 #---------------------------------------# epoch_step = num_train // batch_size epoch_step_val = num_val // batch_size if epoch_step == 0 or epoch_step_val == 0: raise ValueError("数据集过小,无法继续进行训练,请扩充数据集。")
''' 训练自己的语义分割模型一定需要注意以下几点: 1、训练前仔细检查自己的格式是否满足要求,该库要求数据集格式为VOC格式,需要准备好的内容有输入图片和标签 输入图片为.jpg图片,无需固定大小,传入训练前会自动进行resize。 灰度图会自动转成RGB图片进行训练,无需自己修改。 输入图片如果后缀非jpg,需要自己批量转成jpg后再开始训练。 标签为png图片,无需固定大小,传入训练前会自动进行resize。 由于许多同学的数据集是网络上下载的,标签格式并不符合,需要再度处理。一定要注意!标签的每个像素点的值就是这个像素点所属的种类。 网上常见的数据集总共对输入图片分两类,背景的像素点值为0,目标的像素点值为255。这样的数据集可以正常运行但是预测是没有效果的! 需要改成,背景的像素点值为0,目标的像素点值为1。 如果格式有误,参考:https://github.com/bubbliiiing/segmentation-format-fix 2、损失值的大小用于判断是否收敛,比较重要的是有收敛的趋势,即验证集损失不断下降,如果验证集损失基本上不改变的话,模型基本上就收敛了。 损失值的具体大小并没有什么意义,大和小只在于损失的计算方式,并不是接近于0才好。如果想要让损失好看点,可以直接到对应的损失函数里面除上10000。 训练过程中的损失值会保存在logs文件夹下的loss_%Y_%m_%d_%H_%M_%S文件夹中 3、训练好的权值文件保存在logs文件夹中,每个训练世代(Epoch)包含若干训练步长(Step),每个训练步长(Step)进行一次梯度下降。 如果只是训练了几个Step是不会保存的,Epoch和Step的概念要捋清楚一下。 ''' if __name__ == "__main__": #---------------------------------# # Cuda 是否使用Cuda # 没有GPU可以设置成False #---------------------------------# Cuda = True #---------------------------------------------------------------------# # distributed 用于指定是否使用单机多卡分布式运行 # 终端指令仅支持Ubuntu。CUDA_VISIBLE_DEVICES用于在Ubuntu下指定显卡。 # Windows系统下默认使用DP模式调用所有显卡,不支持DDP。 # DP模式: # 设置 distributed = False # 在终端中输入 CUDA_VISIBLE_DEVICES=0,1 python train.py # DDP模式: # 设置 distributed = True # 在终端中输入 CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch --nproc_per_node=2 train.py #---------------------------------------------------------------------# distributed = False #---------------------------------------------------------------------# # sync_bn 是否使用sync_bn,DDP模式多卡可用 #---------------------------------------------------------------------# sync_bn = False #---------------------------------------------------------------------# # fp16 是否使用混合精度训练 # 可减少约一半的显存、需要pytorch1.7.1以上 #---------------------------------------------------------------------# fp16 = False #-----------------------------------------------------# # num_classes 训练自己的数据集必须要修改的 # 自己需要的分类个数+1,如2+1 #-----------------------------------------------------# num_classes = 3 #---------------------------------# # 所使用的的主干网络: # mobilenet # xception #---------------------------------# backbone = "mobilenet" #----------------------------------------------------------------------------------------------------------------------------# # pretrained 是否使用主干网络的预训练权重,此处使用的是主干的权重,因此是在模型构建的时候进行加载的。 # 如果设置了model_path,则主干的权值无需加载,pretrained的值无意义。 # 如果不设置model_path,pretrained = True,此时仅加载主干开始训练。 # 如果不设置model_path,pretrained = False,Freeze_Train = Fasle,此时从0开始训练,且没有冻结主干的过程。 #----------------------------------------------------------------------------------------------------------------------------# pretrained = False #----------------------------------------------------------------------------------------------------------------------------# # 权值文件的下载请看README,可以通过网盘下载。模型的 预训练权重 对不同数据集是通用的,因为特征是通用的。 # 模型的 预训练权重 比较重要的部分是 主干特征提取网络的权值部分,用于进行特征提取。 # 预训练权重对于99%的情况都必须要用,不用的话主干部分的权值太过随机,特征提取效果不明显,网络训练的结果也不会好 # 训练自己的数据集时提示维度不匹配正常,预测的东西都不一样了自然维度不匹配 # # 如果训练过程中存在中断训练的操作,可以将model_path设置成logs文件夹下的权值文件,将已经训练了一部分的权值再次载入。 # 同时修改下方的 冻结阶段 或者 解冻阶段 的参数,来保证模型epoch的连续性。 # # 当model_path = ''的时候不加载整个模型的权值。 # # 此处使用的是整个模型的权重,因此是在train.py进行加载的,pretrain不影响此处的权值加载。 # 如果想要让模型从主干的预训练权值开始训练,则设置model_path = '',pretrain = True,此时仅加载主干。 # 如果想要让模型从0开始训练,则设置model_path = '',pretrain = Fasle,Freeze_Train = Fasle,此时从0开始训练,且没有冻结主干的过程。 # # 一般来讲,网络从0开始的训练效果会很差,因为权值太过随机,特征提取效果不明显,因此非常、非常、非常不建议大家从0开始训练! # 如果一定要从0开始,可以了解imagenet数据集,首先训练分类模型,获得网络的主干部分权值,分类模型的 主干部分 和该模型通用,基于此进行训练。 #----------------------------------------------------------------------------------------------------------------------------# model_path = "model_data/deeplab_mobilenetv2.pth" #---------------------------------------------------------# # downsample_factor 下采样的倍数8、16 # 8下采样的倍数较小、理论上效果更好。 # 但也要求更大的显存 #---------------------------------------------------------# downsample_factor = 8 #------------------------------# # 输入图片的大小 #------------------------------# input_shape = [512, 512] #----------------------------------------------------------------------------------------------------------------------------# # 训练分为两个阶段,分别是冻结阶段和解冻阶段。设置冻结阶段是为了满足机器性能不足的同学的训练需求。 # 冻结训练需要的显存较小,显卡非常差的情况下,可设置Freeze_Epoch等于UnFreeze_Epoch,此时仅仅进行冻结训练。 # # 在此提供若干参数设置建议,各位训练者根据自己的需求进行灵活调整: # (一)从整个模型的预训练权重开始训练: # Adam: # Init_Epoch = 0,Freeze_Epoch = 50,UnFreeze_Epoch = 100,Freeze_Train = True,optimizer_type = 'adam',Init_lr = 5e-4,weight_decay = 0。(冻结) # Init_Epoch = 0,UnFreeze_Epoch = 100,Freeze_Train = False,optimizer_type = 'adam',Init_lr = 5e-4,weight_decay = 0。(不冻结) # SGD: # Init_Epoch = 0,Freeze_Epoch = 50,UnFreeze_Epoch = 100,Freeze_Train = True,optimizer_type = 'sgd',Init_lr = 7e-3,weight_decay = 1e-4。(冻结) # Init_Epoch = 0,UnFreeze_Epoch = 100,Freeze_Train = False,optimizer_type = 'sgd',Init_lr = 7e-3,weight_decay = 1e-4。(不冻结) # 其中:UnFreeze_Epoch可以在100-300之间调整。 # (二)从主干网络的预训练权重开始训练: # Adam: # Init_Epoch = 0,Freeze_Epoch = 50,UnFreeze_Epoch = 100,Freeze_Train = True,optimizer_type = 'adam',Init_lr = 5e-4,weight_decay = 0。(冻结) # Init_Epoch = 0,UnFreeze_Epoch = 100,Freeze_Train = False,optimizer_type = 'adam',Init_lr = 5e-4,weight_decay = 0。(不冻结) # SGD: # Init_Epoch = 0,Freeze_Epoch = 50,UnFreeze_Epoch = 120,Freeze_Train = True,optimizer_type = 'sgd',Init_lr = 7e-3,weight_decay = 1e-4。(冻结) # Init_Epoch = 0,UnFreeze_Epoch = 120,Freeze_Train = False,optimizer_type = 'sgd',Init_lr = 7e-3,weight_decay = 1e-4。(不冻结) # 其中:由于从主干网络的预训练权重开始训练,主干的权值不一定适合语义分割,需要更多的训练跳出局部最优解。 # UnFreeze_Epoch可以在120-300之间调整。 # Adam相较于SGD收敛的快一些。因此UnFreeze_Epoch理论上可以小一点,但依然推荐更多的Epoch。 # (三)batch_size的设置: # 在显卡能够接受的范围内,以大为好。显存不足与数据集大小无关,提示显存不足(OOM或者CUDA out of memory)请调小batch_size。 # 受到BatchNorm层影响,batch_size最小为2,不能为1。 # 正常情况下Freeze_batch_size建议为Unfreeze_batch_size的1-2倍。不建议设置的差距过大,因为关系到学习率的自动调整。 #----------------------------------------------------------------------------------------------------------------------------# #------------------------------------------------------------------# # 冻结阶段训练参数 # 此时模型的主干被冻结了,特征提取网络不发生改变 # 占用的显存较小,仅对网络进行微调 # Init_Epoch 模型当前开始的训练世代,其值可以大于Freeze_Epoch,如设置: # Init_Epoch = 60、Freeze_Epoch = 50、UnFreeze_Epoch = 100 # 会跳过冻结阶段,直接从60代开始,并调整对应的学习率。 # (断点续练时使用) # Freeze_Epoch 模型冻结训练的Freeze_Epoch # (当Freeze_Train=False时失效) # Freeze_batch_size 模型冻结训练的batch_size # (当Freeze_Train=False时失效) #------------------------------------------------------------------# Init_Epoch = 0 Freeze_Epoch = 10 Freeze_batch_size = 8 #------------------------------------------------------------------# # 解冻阶段训练参数 # 此时模型的主干不被冻结了,特征提取网络会发生改变 # 占用的显存较大,网络所有的参数都会发生改变 # UnFreeze_Epoch 模型总共训练的epoch # Unfreeze_batch_size 模型在解冻后的batch_size #------------------------------------------------------------------# UnFreeze_Epoch = 20 Unfreeze_batch_size = 4 #------------------------------------------------------------------# # Freeze_Train 是否进行冻结训练 # 默认先冻结主干训练后解冻训练。 #------------------------------------------------------------------# Freeze_Train = True #------------------------------------------------------------------# # 其它训练参数:学习率、优化器、学习率下降有关 #------------------------------------------------------------------# #------------------------------------------------------------------# # Init_lr 模型的最大学习率 # 当使用Adam优化器时建议设置 Init_lr=5e-4 # 当使用SGD优化器时建议设置 Init_lr=7e-3 # Min_lr 模型的最小学习率,默认为最大学习率的0.01 #------------------------------------------------------------------# Init_lr = 7e-4 Min_lr = Init_lr * 0.01 #------------------------------------------------------------------# # optimizer_type 使用到的优化器种类,可选的有adam、sgd # 当使用Adam优化器时建议设置 Init_lr=5e-4 # 当使用SGD优化器时建议设置 Init_lr=7e-3 # momentum 优化器内部使用到的momentum参数 # weight_decay 权值衰减,可防止过拟合 # adam会导致weight_decay错误,使用adam时建议设置为0。 #------------------------------------------------------------------# optimizer_type = "sgd" momentum = 0.9 weight_decay = 1e-4 #1e-4 sgd是 #------------------------------------------------------------------# # lr_decay_type 使用到的学习率下降方式,可选的有'step'、'cos' #------------------------------------------------------------------# lr_decay_type = 'cos' #------------------------------------------------------------------# # save_period 多少个epoch保存一次权值 #------------------------------------------------------------------# save_period = 800 #------------------------------------------------------------------# # save_dir 权值与日志文件保存的文件夹 #------------------------------------------------------------------# save_dir = 'logs' #------------------------------------------------------------------# # eval_flag 是否在训练时进行评估,评估对象为验证集 # eval_period 代表多少个epoch评估一次,不建议频繁的评估 # 评估需要消耗较多的时间,频繁评估会导致训练非常慢 # 此处获得的mAP会与get_map.py获得的会有所不同,原因有二: # (一)此处获得的mAP为验证集的mAP。 # (二)此处设置评估参数较为保守,目的是加快评估速度。 #------------------------------------------------------------------# eval_flag = True eval_period = 400 #7.13开始跑 #10点40 #------------------------------------------------------------------# # VOCdevkit_path 数据集路径 #------------------------------------------------------------------# VOCdevkit_path = 'VOCdevkit' #------------------------------------------------------------------# # 建议选项: # 种类少(几类)时,设置为True # 种类多(十几类)时,如果batch_size比较大(10以上),那么设置为True # 种类多(十几类)时,如果batch_size比较小(10以下),那么设置为False #------------------------------------------------------------------# dice_loss = False #------------------------------------------------------------------# # 是否使用focal loss来防止正负样本不平衡 #------------------------------------------------------------------# focal_loss = False #------------------------------------------------------------------# # 是否给不同种类赋予不同的损失权值,默认是平衡的。 # 设置的话,注意设置成numpy形式的,长度和num_classes一样。 # 如: # num_classes = 3 # cls_weights = np.array([1, 2, 3], np.float32) #------------------------------------------------------------------# cls_weights = np.ones([num_classes], np.float32) #------------------------------------------------------------------# # num_workers 用于设置是否使用多线程读取数据,1代表关闭多线程 # 开启后会加快数据读取速度,但是会占用更多内存 # keras里开启多线程有些时候速度反而慢了许多 # 在IO为瓶颈的时候再开启多线程,即GPU运算速度远大于读取图片的速度。 #------------------------------------------------------------------# num_workers = 4 #------------------------------------------------------# # 设置用到的显卡 #------------------------------------------------------# ngpus_per_node = torch.cuda.device_count() if distributed: dist.init_process_group(backend="nccl") local_rank = int(os.environ["LOCAL_RANK"]) rank = int(os.environ["RANK"]) device = torch.device("cuda", local_rank) if local_rank == 0: print(f"[{os.getpid()}] (rank = {rank}, local_rank = {local_rank}) training...") print("Gpu Device Count : ", ngpus_per_node) else: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') local_rank = 0 #----------------------------------------------------# # 下载预训练权重 #----------------------------------------------------# if pretrained: if distributed: if local_rank == 0: download_weights(backbone) dist.barrier() else: download_weights(backbone) model = DeepLab(num_classes=num_classes, backbone=backbone, downsample_factor=downsample_factor, pretrained=pretrained) if not pretrained: weights_init(model) if model_path != '': #------------------------------------------------------# # 权值文件请看README,百度网盘下载 #------------------------------------------------------# if local_rank == 0: print('Load weights {}.'.format(model_path)) #------------------------------------------------------# # 根据预训练权重的Key和模型的Key进行加载 #------------------------------------------------------# model_dict = model.state_dict() pretrained_dict = torch.load(model_path, map_location = device) load_key, no_load_key, temp_dict = [], [], {} for k, v in pretrained_dict.items(): if k in model_dict.keys() and np.shape(model_dict[k]) == np.shape(v): temp_dict[k] = v load_key.append(k) else: no_load_key.append(k) model_dict.update(temp_dict) model.load_state_dict(model_dict) #------------------------------------------------------# # 显示没有匹配上的Key #------------------------------------------------------# if local_rank == 0: print("\nSuccessful Load Key:", str(load_key)[:500], "……\nSuccessful Load Key Num:", len(load_key)) print("\nFail To Load Key:", str(no_load_key)[:500], "……\nFail To Load Key num:", len(no_load_key)) print("\n\033[1;33;44m温馨提示,head部分没有载入是正常现象,Backbone部分没有载入是错误的。\033[0m") #----------------------# # 记录Loss #----------------------# if local_rank == 0: time_str = datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d_%H_%M_%S') log_dir = os.path.join(save_dir, "loss_" + str(time_str)) loss_history = LossHistory(log_dir, model, input_shape=input_shape) else: loss_history = None #------------------------------------------------------------------# # torch 1.2不支持amp,建议使用torch 1.7.1及以上正确使用fp16 # 因此torch1.2这里显示"could not be resolve" #------------------------------------------------------------------# if fp16: scaler = GradScaler() else: scaler = None model_train = model.train() #----------------------------# # 多卡同步Bn #----------------------------# if sync_bn and ngpus_per_node > 1 and distributed: model_train = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model_train) elif sync_bn: print("Sync_bn is not support in one gpu or not distributed.") if Cuda: if distributed: #----------------------------# # 多卡平行运行 #----------------------------# model_train = model_train.cuda(local_rank) model_train = torch.nn.parallel.DistributedDataParallel(model_train, device_ids=[local_rank], find_unused_parameters=True) else: model_train = torch.nn.DataParallel(model) cudnn.benchmark = True model_train = model_train.cuda() #---------------------------# # 读取数据集对应的txt #---------------------------# with open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Segmentation/train.txt"),"r") as f: train_lines = f.readlines() with open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Segmentation/val.txt"),"r") as f: val_lines = f.readlines() num_train = len(train_lines) num_val = len(val_lines) if local_rank == 0: show_config( num_classes = num_classes, backbone = backbone, model_path = model_path, input_shape = input_shape, \ Init_Epoch = Init_Epoch, Freeze_Epoch = Freeze_Epoch, UnFreeze_Epoch = UnFreeze_Epoch, Freeze_batch_size = Freeze_batch_size, Unfreeze_batch_size = Unfreeze_batch_size, Freeze_Train = Freeze_Train, \ Init_lr = Init_lr, Min_lr = Min_lr, optimizer_type = optimizer_type, momentum = momentum, lr_decay_type = lr_decay_type, \ save_period = save_period, save_dir = save_dir, num_workers = num_workers, num_train = num_train, num_val = num_val ) #---------------------------------------------------------# # 总训练世代指的是遍历全部数据的总次数 # 总训练步长指的是梯度下降的总次数 # 每个训练世代包含若干训练步长,每个训练步长进行一次梯度下降。 # 此处仅建议最低训练世代,上不封顶,计算时只考虑了解冻部分 #----------------------------------------------------------# wanted_step = 1.5e4 if optimizer_type == "sgd" else 0.5e4 total_step = num_train // Unfreeze_batch_size * UnFreeze_Epoch if total_step <= wanted_step: if num_train // Unfreeze_batch_size == 0: raise ValueError('数据集过小,无法进行训练,请扩充数据集。') wanted_epoch = wanted_step // (num_train // Unfreeze_batch_size) + 1 print("\n\033[1;33;44m[Warning] 使用%s优化器时,建议将训练总步长设置到%d以上。\033[0m"%(optimizer_type, wanted_step)) print("\033[1;33;44m[Warning] 本次运行的总训练数据量为%d,Unfreeze_batch_size为%d,共训练%d个Epoch,计算出总训练步长为%d。\033[0m"%(num_train, Unfreeze_batch_size, UnFreeze_Epoch, total_step)) print("\033[1;33;44m[Warning] 由于总训练步长为%d,小于建议总步长%d,建议设置总世代为%d。\033[0m"%(total_step, wanted_step, wanted_epoch)) #------------------------------------------------------# # 主干特征提取网络特征通用,冻结训练可以加快训练速度 # 也可以在训练初期防止权值被破坏。 # Init_Epoch为起始世代 # Interval_Epoch为冻结训练的世代 # Epoch总训练世代 # 提示OOM或者显存不足请调小Batch_size #------------------------------------------------------# if True: UnFreeze_flag = False #------------------------------------# # 冻结一定部分训练 #------------------------------------# if Freeze_Train: for param in model.backbone.parameters(): param.requires_grad = False #-------------------------------------------------------------------# # 如果不冻结训练的话,直接设置batch_size为Unfreeze_batch_size #-------------------------------------------------------------------# batch_size = Freeze_batch_size if Freeze_Train else Unfreeze_batch_size #-------------------------------------------------------------------# # 判断当前batch_size,自适应调整学习率 #-------------------------------------------------------------------# nbs = 16 lr_limit_max = 5e-4 if optimizer_type == 'adam' else 1e-1 lr_limit_min = 3e-4 if optimizer_type == 'adam' else 5e-4 if backbone == "xception": lr_limit_max = 1e-4 if optimizer_type == 'adam' else 1e-1 lr_limit_min = 1e-4 if optimizer_type == 'adam' else 5e-4 Init_lr_fit = min(max(batch_size / nbs * Init_lr, lr_limit_min), lr_limit_max) Min_lr_fit = min(max(batch_size / nbs * Min_lr, lr_limit_min * 1e-2), lr_limit_max * 1e-2) #---------------------------------------# # 根据optimizer_type选择优化器 #---------------------------------------# optimizer = { 'adam' : optim.Adam(model.parameters(), Init_lr_fit, betas = (momentum, 0.999), weight_decay = weight_decay), 'sgd' : optim.SGD(model.parameters(), Init_lr_fit, momentum = momentum, nesterov=True, weight_decay = weight_decay) }[optimizer_type] #---------------------------------------# # 获得学习率下降的公式 #---------------------------------------# lr_scheduler_func = get_lr_scheduler(lr_decay_type, Init_lr_fit, Min_lr_fit, UnFreeze_Epoch) #---------------------------------------# # 判断每一个世代的长度 #---------------------------------------# epoch_step = num_train // batch_size epoch_step_val = num_val // batch_size if epoch_step == 0 or epoch_step_val == 0: raise ValueError("数据集过小,无法继续进行训练,请扩充数据集。")
train_dataset = DeeplabDataset(train_lines, input_shape, num_classes, True, VOCdevkit_path)
6
2023-11-17 13:25:28+00:00
16k
CmosWolf1/Code_implementation_for_paper_SKZC
diffusiondet/detector.py
[ { "identifier": "SetCriterionDynamicK", "path": "diffusiondet/loss.py", "snippet": "class SetCriterionDynamicK(nn.Module):\n \"\"\" This class computes the loss for DiffusionDet.\n The process happens in two steps:\n 1) we compute hungarian assignment between ground truth boxes and the outp...
import math import random import torch import torch.nn.functional as F from typing import List from collections import namedtuple from torch import nn from detectron2.layers import batched_nms from detectron2.modeling import META_ARCH_REGISTRY, build_backbone, detector_postprocess from detectron2.structures import Boxes, ImageList, Instances from .loss import SetCriterionDynamicK, HungarianMatcherDynamicK from .head import DynamicHead from .util.box_ops import box_cxcywh_to_xyxy, box_xyxy_to_cxcywh from .util.misc import nested_tensor_from_tensor_list
10,838
return ModelPrediction(pred_noise, x_start), outputs_class, outputs_coord @torch.no_grad() def ddim_sample(self, batched_inputs, backbone_feats, images_whwh, images, clip_denoised=True, do_postprocess=True): batch = images_whwh.shape[0] shape = (batch, self.num_proposals, 4) total_timesteps, sampling_timesteps, eta, objective = self.num_timesteps, self.sampling_timesteps, self.ddim_sampling_eta, self.objective # [-1, 0, 1, 2, ..., T-1] when sampling_timesteps == total_timesteps times = torch.linspace(-1, total_timesteps - 1, steps=sampling_timesteps + 1) times = list(reversed(times.int().tolist())) time_pairs = list(zip(times[:-1], times[1:])) # [(T-1, T-2), (T-2, T-3), ..., (1, 0), (0, -1)] img = torch.randn(shape, device=self.device) ensemble_score, ensemble_label, ensemble_coord = [], [], [] x_start = None for time, time_next in time_pairs: time_cond = torch.full((batch,), time, device=self.device, dtype=torch.long) self_cond = x_start if self.self_condition else None preds, outputs_class, outputs_coord = self.model_predictions(backbone_feats, images_whwh, img, time_cond, self_cond, clip_x_start=clip_denoised) pred_noise, x_start = preds.pred_noise, preds.pred_x_start if self.box_renewal: # filter score_per_image, box_per_image = outputs_class[-1][0], outputs_coord[-1][0] threshold = 0.5 score_per_image = torch.sigmoid(score_per_image) value, _ = torch.max(score_per_image, -1, keepdim=False) keep_idx = value > threshold num_remain = torch.sum(keep_idx) pred_noise = pred_noise[:, keep_idx, :] x_start = x_start[:, keep_idx, :] img = img[:, keep_idx, :] if time_next < 0: img = x_start continue alpha = self.alphas_cumprod[time] alpha_next = self.alphas_cumprod[time_next] sigma = eta * ((1 - alpha / alpha_next) * (1 - alpha_next) / (1 - alpha)).sqrt() c = (1 - alpha_next - sigma ** 2).sqrt() noise = torch.randn_like(img) img = x_start * alpha_next.sqrt() + \ c * pred_noise + \ sigma * noise if self.box_renewal: # filter # replenish with randn boxes img = torch.cat((img, torch.randn(1, self.num_proposals - num_remain, 4, device=img.device)), dim=1) if self.use_ensemble and self.sampling_timesteps > 1: box_pred_per_image, scores_per_image, labels_per_image = self.inference(outputs_class[-1], outputs_coord[-1], images.image_sizes) ensemble_score.append(scores_per_image) ensemble_label.append(labels_per_image) ensemble_coord.append(box_pred_per_image) if self.use_ensemble and self.sampling_timesteps > 1: box_pred_per_image = torch.cat(ensemble_coord, dim=0) scores_per_image = torch.cat(ensemble_score, dim=0) labels_per_image = torch.cat(ensemble_label, dim=0) if self.use_nms: keep = batched_nms(box_pred_per_image, scores_per_image, labels_per_image, 0.5) box_pred_per_image = box_pred_per_image[keep] scores_per_image = scores_per_image[keep] labels_per_image = labels_per_image[keep] result = Instances(images.image_sizes[0]) result.pred_boxes = Boxes(box_pred_per_image) result.scores = scores_per_image result.pred_classes = labels_per_image results = [result] else: output = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1]} box_cls = output["pred_logits"] box_pred = output["pred_boxes"] results = self.inference(box_cls, box_pred, images.image_sizes) if do_postprocess: processed_results = [] for results_per_image, input_per_image, image_size in zip(results, batched_inputs, images.image_sizes): height = input_per_image.get("height", image_size[0]) width = input_per_image.get("width", image_size[1]) r = detector_postprocess(results_per_image, height, width) processed_results.append({"instances": r}) return processed_results # forward diffusion def q_sample(self, x_start, t, noise=None): if noise is None: noise = torch.randn_like(x_start) sqrt_alphas_cumprod_t = extract(self.sqrt_alphas_cumprod, t, x_start.shape) sqrt_one_minus_alphas_cumprod_t = extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise def forward(self, batched_inputs, do_postprocess=True): """ Args: batched_inputs: a list, batched outputs of :class:`DatasetMapper` . Each item in the list contains the inputs for one image. For now, each item in the list is a dict that contains: * image: Tensor, image in (C, H, W) format. * instances: Instances Other information that's included in the original dicts, such as: * "height", "width" (int): the output resolution of the model, used in inference. See :meth:`postprocess` for details. """ images, images_whwh = self.preprocess_image(batched_inputs) if isinstance(images, (list, torch.Tensor)):
# ======================================== # Modified by Shoufa Chen # ======================================== # Modified by Peize Sun, Rufeng Zhang # Contact: {sunpeize, cxrfzhang}@foxmail.com # # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved __all__ = ["DiffusionDet"] ModelPrediction = namedtuple('ModelPrediction', ['pred_noise', 'pred_x_start']) def exists(x): return x is not None def default(val, d): if exists(val): return val return d() if callable(d) else d def extract(a, t, x_shape): """extract the appropriate t index for a batch of indices""" batch_size = t.shape[0] out = a.gather(-1, t) return out.reshape(batch_size, *((1,) * (len(x_shape) - 1))) def cosine_beta_schedule(timesteps, s=0.008): """ cosine schedule as proposed in https://openreview.net/forum?id=-NEXDKk8gZ """ steps = timesteps + 1 x = torch.linspace(0, timesteps, steps, dtype=torch.float64) alphas_cumprod = torch.cos(((x / timesteps) + s) / (1 + s) * math.pi * 0.5) ** 2 alphas_cumprod = alphas_cumprod / alphas_cumprod[0] betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) return torch.clip(betas, 0, 0.999) @META_ARCH_REGISTRY.register() class DiffusionDet(nn.Module): """ Implement DiffusionDet """ def __init__(self, cfg): super().__init__() self.device = torch.device(cfg.MODEL.DEVICE) self.in_features = cfg.MODEL.ROI_HEADS.IN_FEATURES self.num_classes = cfg.MODEL.DiffusionDet.NUM_CLASSES self.num_proposals = cfg.MODEL.DiffusionDet.NUM_PROPOSALS self.hidden_dim = cfg.MODEL.DiffusionDet.HIDDEN_DIM self.num_heads = cfg.MODEL.DiffusionDet.NUM_HEADS # Build Backbone. self.backbone = build_backbone(cfg) self.size_divisibility = self.backbone.size_divisibility # build diffusion timesteps = 1000 sampling_timesteps = cfg.MODEL.DiffusionDet.SAMPLE_STEP self.objective = 'pred_x0' betas = cosine_beta_schedule(timesteps) alphas = 1. - betas alphas_cumprod = torch.cumprod(alphas, dim=0) alphas_cumprod_prev = F.pad(alphas_cumprod[:-1], (1, 0), value=1.) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.sampling_timesteps = default(sampling_timesteps, timesteps) assert self.sampling_timesteps <= timesteps self.is_ddim_sampling = self.sampling_timesteps < timesteps self.ddim_sampling_eta = 1. self.self_condition = False self.scale = cfg.MODEL.DiffusionDet.SNR_SCALE self.box_renewal = True self.use_ensemble = True self.register_buffer('betas', betas) self.register_buffer('alphas_cumprod', alphas_cumprod) self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', torch.sqrt(alphas_cumprod)) self.register_buffer('sqrt_one_minus_alphas_cumprod', torch.sqrt(1. - alphas_cumprod)) self.register_buffer('log_one_minus_alphas_cumprod', torch.log(1. - alphas_cumprod)) self.register_buffer('sqrt_recip_alphas_cumprod', torch.sqrt(1. / alphas_cumprod)) self.register_buffer('sqrt_recipm1_alphas_cumprod', torch.sqrt(1. / alphas_cumprod - 1)) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod) # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', posterior_variance) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', torch.log(posterior_variance.clamp(min=1e-20))) self.register_buffer('posterior_mean_coef1', betas * torch.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)) self.register_buffer('posterior_mean_coef2', (1. - alphas_cumprod_prev) * torch.sqrt(alphas) / (1. - alphas_cumprod)) # Build Dynamic Head. self.head = DynamicHead(cfg=cfg, roi_input_shape=self.backbone.output_shape()) # Loss parameters: class_weight = cfg.MODEL.DiffusionDet.CLASS_WEIGHT giou_weight = cfg.MODEL.DiffusionDet.GIOU_WEIGHT l1_weight = cfg.MODEL.DiffusionDet.L1_WEIGHT no_object_weight = cfg.MODEL.DiffusionDet.NO_OBJECT_WEIGHT self.deep_supervision = cfg.MODEL.DiffusionDet.DEEP_SUPERVISION self.use_focal = cfg.MODEL.DiffusionDet.USE_FOCAL self.use_fed_loss = cfg.MODEL.DiffusionDet.USE_FED_LOSS self.use_nms = cfg.MODEL.DiffusionDet.USE_NMS # Build Criterion. matcher = HungarianMatcherDynamicK( cfg=cfg, cost_class=class_weight, cost_bbox=l1_weight, cost_giou=giou_weight, use_focal=self.use_focal ) weight_dict = {"loss_ce": class_weight, "loss_bbox": l1_weight, "loss_giou": giou_weight} if self.deep_supervision: aux_weight_dict = {} for i in range(self.num_heads - 1): aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()}) weight_dict.update(aux_weight_dict) losses = ["labels", "boxes"] self.criterion = SetCriterionDynamicK( cfg=cfg, num_classes=self.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=no_object_weight, losses=losses, use_focal=self.use_focal,) pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(3, 1, 1) pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(3, 1, 1) self.normalizer = lambda x: (x - pixel_mean) / pixel_std self.to(self.device) def predict_noise_from_start(self, x_t, t, x0): return ( (extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - x0) / extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) ) def model_predictions(self, backbone_feats, images_whwh, x, t, x_self_cond=None, clip_x_start=False): x_boxes = torch.clamp(x, min=-1 * self.scale, max=self.scale) x_boxes = ((x_boxes / self.scale) + 1) / 2 x_boxes = box_cxcywh_to_xyxy(x_boxes) x_boxes = x_boxes * images_whwh[:, None, :] outputs_class, outputs_coord = self.head(backbone_feats, x_boxes, t, None) x_start = outputs_coord[-1] # (batch, num_proposals, 4) predict boxes: absolute coordinates (x1, y1, x2, y2) x_start = x_start / images_whwh[:, None, :] x_start = box_xyxy_to_cxcywh(x_start) x_start = (x_start * 2 - 1.) * self.scale x_start = torch.clamp(x_start, min=-1 * self.scale, max=self.scale) pred_noise = self.predict_noise_from_start(x, t, x_start) return ModelPrediction(pred_noise, x_start), outputs_class, outputs_coord @torch.no_grad() def ddim_sample(self, batched_inputs, backbone_feats, images_whwh, images, clip_denoised=True, do_postprocess=True): batch = images_whwh.shape[0] shape = (batch, self.num_proposals, 4) total_timesteps, sampling_timesteps, eta, objective = self.num_timesteps, self.sampling_timesteps, self.ddim_sampling_eta, self.objective # [-1, 0, 1, 2, ..., T-1] when sampling_timesteps == total_timesteps times = torch.linspace(-1, total_timesteps - 1, steps=sampling_timesteps + 1) times = list(reversed(times.int().tolist())) time_pairs = list(zip(times[:-1], times[1:])) # [(T-1, T-2), (T-2, T-3), ..., (1, 0), (0, -1)] img = torch.randn(shape, device=self.device) ensemble_score, ensemble_label, ensemble_coord = [], [], [] x_start = None for time, time_next in time_pairs: time_cond = torch.full((batch,), time, device=self.device, dtype=torch.long) self_cond = x_start if self.self_condition else None preds, outputs_class, outputs_coord = self.model_predictions(backbone_feats, images_whwh, img, time_cond, self_cond, clip_x_start=clip_denoised) pred_noise, x_start = preds.pred_noise, preds.pred_x_start if self.box_renewal: # filter score_per_image, box_per_image = outputs_class[-1][0], outputs_coord[-1][0] threshold = 0.5 score_per_image = torch.sigmoid(score_per_image) value, _ = torch.max(score_per_image, -1, keepdim=False) keep_idx = value > threshold num_remain = torch.sum(keep_idx) pred_noise = pred_noise[:, keep_idx, :] x_start = x_start[:, keep_idx, :] img = img[:, keep_idx, :] if time_next < 0: img = x_start continue alpha = self.alphas_cumprod[time] alpha_next = self.alphas_cumprod[time_next] sigma = eta * ((1 - alpha / alpha_next) * (1 - alpha_next) / (1 - alpha)).sqrt() c = (1 - alpha_next - sigma ** 2).sqrt() noise = torch.randn_like(img) img = x_start * alpha_next.sqrt() + \ c * pred_noise + \ sigma * noise if self.box_renewal: # filter # replenish with randn boxes img = torch.cat((img, torch.randn(1, self.num_proposals - num_remain, 4, device=img.device)), dim=1) if self.use_ensemble and self.sampling_timesteps > 1: box_pred_per_image, scores_per_image, labels_per_image = self.inference(outputs_class[-1], outputs_coord[-1], images.image_sizes) ensemble_score.append(scores_per_image) ensemble_label.append(labels_per_image) ensemble_coord.append(box_pred_per_image) if self.use_ensemble and self.sampling_timesteps > 1: box_pred_per_image = torch.cat(ensemble_coord, dim=0) scores_per_image = torch.cat(ensemble_score, dim=0) labels_per_image = torch.cat(ensemble_label, dim=0) if self.use_nms: keep = batched_nms(box_pred_per_image, scores_per_image, labels_per_image, 0.5) box_pred_per_image = box_pred_per_image[keep] scores_per_image = scores_per_image[keep] labels_per_image = labels_per_image[keep] result = Instances(images.image_sizes[0]) result.pred_boxes = Boxes(box_pred_per_image) result.scores = scores_per_image result.pred_classes = labels_per_image results = [result] else: output = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1]} box_cls = output["pred_logits"] box_pred = output["pred_boxes"] results = self.inference(box_cls, box_pred, images.image_sizes) if do_postprocess: processed_results = [] for results_per_image, input_per_image, image_size in zip(results, batched_inputs, images.image_sizes): height = input_per_image.get("height", image_size[0]) width = input_per_image.get("width", image_size[1]) r = detector_postprocess(results_per_image, height, width) processed_results.append({"instances": r}) return processed_results # forward diffusion def q_sample(self, x_start, t, noise=None): if noise is None: noise = torch.randn_like(x_start) sqrt_alphas_cumprod_t = extract(self.sqrt_alphas_cumprod, t, x_start.shape) sqrt_one_minus_alphas_cumprod_t = extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise def forward(self, batched_inputs, do_postprocess=True): """ Args: batched_inputs: a list, batched outputs of :class:`DatasetMapper` . Each item in the list contains the inputs for one image. For now, each item in the list is a dict that contains: * image: Tensor, image in (C, H, W) format. * instances: Instances Other information that's included in the original dicts, such as: * "height", "width" (int): the output resolution of the model, used in inference. See :meth:`postprocess` for details. """ images, images_whwh = self.preprocess_image(batched_inputs) if isinstance(images, (list, torch.Tensor)):
images = nested_tensor_from_tensor_list(images)
5
2023-11-17 02:37:37+00:00
16k
fg320/DEASC
examples/11C_3x1_farm_dyn_tuning_wso.py
[ { "identifier": "WfModel", "path": "deasc/wf_model.py", "snippet": "class WfModel:\n \"\"\"\n Class for wind farm modelling (Interface setup but not limited to FLORIS\n framework).\n \"\"\"\n\n def __init__(self, input_file, path):\n \"\"\"\n Initialise wind farm object by p...
import numpy as np from deasc import WfModel from deasc import WSOpt from deasc import GPWrap from deasc import TuningDyn_Turbines from deasc.utils_floris import ( floris_extract_object_dict, floris_param_change_object_dict, floris_param_change_object )
11,610
""" This example shows wake steering optimisation on a 3x1 wind farm of NREL 5 MW turbines. Dynamic parameter tuning is introduced in the optimisation for the wake expansion parameter k of the Jensen wake model. The tuning variables are the yaw angles of the two most upstream turbines. """ # Initialise and set layout for wind farm model path = "./inputs/" input_file = "jensen.yaml" wf_model = WfModel(input_file, path) wf_model.set_aligned_layout(3, 1, 7, 5) # Set kd deflection parameter wf_model_dict = floris_extract_object_dict(wf_model) wf_model_dict = floris_param_change_object_dict(wf_model_dict, 'wake_deflection_parameters', 'kd', 0.3) wf_model = floris_param_change_object(wf_model, wf_model_dict) # Specify atmopheric conditions ws = 8.0 wd = 270 ti = 0.05 shear = 0.0 # Wake steering optimisation inputs yaw_initial = np.full(shape=(3), fill_value=0) inflow = (yaw_initial, wd, ws, ti, shear) variables = [1, 2] var_bounds = (-25, 25) var_initial = np.full(shape=(len(variables)), fill_value=0) # %% Dynamic tuning object # Parameter info parameter_class = 'wake_velocity_parameters' parameter_name = 'we' # Import optimal parameter dataset and extract GP input dataset_path = "./optimal_parameter_datasets/" dataset_import = np.load(dataset_path+'we_3x1_2dim.npy', allow_pickle=True) optimal_parameter_dataset = dataset_import.item() yaw_data = [] param_data = [] for key in optimal_parameter_dataset.keys(): yaw_data.append(key[:-1]) # Last turbine yaw angle is fixed, not a GP dimension param_data.append([optimal_parameter_dataset[key]]) # Construct Gaussian Process (GP) GP_obj = GPWrap(parameter_class=parameter_class, parameter_name=parameter_name, dimensions=2) GP_model = GP_obj.GP_so(yaw_data, param_data, num_restarts=50, noise=0.05) # Tuning object initialisation tuning_dyn_obj = TuningDyn_Turbines(param_class=parameter_class, param_name=parameter_name, tuning_turbines=[1, 2], GP_model=GP_model) # %% Optimisation with dynamic tuning # Initialise wake steering object
""" This example shows wake steering optimisation on a 3x1 wind farm of NREL 5 MW turbines. Dynamic parameter tuning is introduced in the optimisation for the wake expansion parameter k of the Jensen wake model. The tuning variables are the yaw angles of the two most upstream turbines. """ # Initialise and set layout for wind farm model path = "./inputs/" input_file = "jensen.yaml" wf_model = WfModel(input_file, path) wf_model.set_aligned_layout(3, 1, 7, 5) # Set kd deflection parameter wf_model_dict = floris_extract_object_dict(wf_model) wf_model_dict = floris_param_change_object_dict(wf_model_dict, 'wake_deflection_parameters', 'kd', 0.3) wf_model = floris_param_change_object(wf_model, wf_model_dict) # Specify atmopheric conditions ws = 8.0 wd = 270 ti = 0.05 shear = 0.0 # Wake steering optimisation inputs yaw_initial = np.full(shape=(3), fill_value=0) inflow = (yaw_initial, wd, ws, ti, shear) variables = [1, 2] var_bounds = (-25, 25) var_initial = np.full(shape=(len(variables)), fill_value=0) # %% Dynamic tuning object # Parameter info parameter_class = 'wake_velocity_parameters' parameter_name = 'we' # Import optimal parameter dataset and extract GP input dataset_path = "./optimal_parameter_datasets/" dataset_import = np.load(dataset_path+'we_3x1_2dim.npy', allow_pickle=True) optimal_parameter_dataset = dataset_import.item() yaw_data = [] param_data = [] for key in optimal_parameter_dataset.keys(): yaw_data.append(key[:-1]) # Last turbine yaw angle is fixed, not a GP dimension param_data.append([optimal_parameter_dataset[key]]) # Construct Gaussian Process (GP) GP_obj = GPWrap(parameter_class=parameter_class, parameter_name=parameter_name, dimensions=2) GP_model = GP_obj.GP_so(yaw_data, param_data, num_restarts=50, noise=0.05) # Tuning object initialisation tuning_dyn_obj = TuningDyn_Turbines(param_class=parameter_class, param_name=parameter_name, tuning_turbines=[1, 2], GP_model=GP_model) # %% Optimisation with dynamic tuning # Initialise wake steering object
wso_obj_tuning = WSOpt(wf_model=wf_model,
1
2023-11-10 18:13:27+00:00
16k
CPES-Power-and-Energy-Systems/interoperable-recommender-tso
energy_app/packages/forecast-api/forecast_api/models/optimization/opt_algorithms/bayesian_opt/bayesian_optimization.py
[ { "identifier": "GaussianProcess", "path": "energy_app/packages/forecast-api/forecast_api/models/optimization/opt_algorithms/bayesian_opt/helpers.py", "snippet": "class GaussianProcess(BaseEstimator, RegressorMixin):\n \"\"\"The legacy Gaussian Process model class.\n\n .. deprecated:: 0.18\n ...
import numpy as np from .helpers import GaussianProcess from scipy.optimize import minimize from .helpers import UtilityFunction, unique_rows, PrintLog
11,581
# Updates the flag self.initialized = True def explore(self, points_dict): """ Method to explore user defined points :param points_dict: :return: """ # Consistency check param_tup_lens = [] for key in self.keys: param_tup_lens.append(len(list(points_dict[key]))) if all([e == param_tup_lens[0] for e in param_tup_lens]): pass else: raise ValueError('The same number of initialization points ' 'must be entered for every parameter.') # Turn into list of lists all_points = [] for key in self.keys: all_points.append(points_dict[key]) # Take transpose of list self.init_points = list(map(list, zip(*all_points))) def initialize(self, points_dict): """ Method to introduce point for which the target function value is known :param points_dict: :return: """ for target in points_dict: self.y_init.append(target) all_points = [] for key in self.keys: all_points.append(points_dict[target][key]) self.x_init.append(all_points) def set_bounds(self, new_bounds): """ A method that allows changing the lower and upper searching bounds :param new_bounds: A dictionary with the parameter name and its new bounds """ # Update the internal object stored dict self.pbounds.update(new_bounds) # Loop through the all bounds and reset the min-max bound matrix for row, key in enumerate(self.pbounds.keys()): # Reset all entries, even if the same. self.bounds[row] = self.pbounds[key] def maximize(self, init_points=5, n_iter=25, acq='ei', kappa=2.576, xi=0.0, **gp_params): """ Main optimization method. Parameters ---------- :param init_points: Number of randomly chosen points to sample the target function before fitting the gp. :param n_iter: Total number of times the process is to repeated. Note that currently this methods does not have stopping criteria (due to a number of reasons), therefore the total number of points to be sampled must be specified. :param acq: Acquisition function to be used, defaults to Expected Improvement. :param gp_params: Parameters to be passed to the Scikit-learn Gaussian Process object Returns ------- :return: Nothing """ # Reset timer self.plog.reset_timer() # Set acquisition function self.util = UtilityFunction(kind=acq, kappa=kappa, xi=xi) # Initialize x, y and find current y_max if not self.initialized: if self.verbose: self.plog.print_header() self.init(init_points) y_max = self.Y.max() # Set parameters if any was passed self.gp.set_params(**gp_params) # Find unique rows of X to avoid GP from breaking
""" BAYESIAN OPTIMIZATION MODULE - Version 0.1.0 Created by Fernando Nogueira (fmfn). Available in - https://github.com/fmfn/BayesianOptimization """ __author__ = 'fmfn' def acq_max(ac, gp, y_max, bounds): """ A function to find the maximum of the acquisition function using the 'L-BFGS-B' method. Parameters ---------- :param ac: The acquisition function object that return its point-wise value. :param gp: A gaussian process fitted to the relevant data. :param y_max: The current maximum known value of the target function. :param bounds: The variables bounds to limit the search of the acq max. Returns ------- :return: x_max, The arg max of the acquisition function. """ # Start with the lower bound as the argmax x_max = bounds[:, 0] max_acq = None x_tries = np.random.uniform(bounds[:, 0], bounds[:, 1], size=(100, bounds.shape[0])) for x_try in x_tries: # Find the minimum of minus the acquisition function res = minimize(lambda x: -ac(x.reshape(1, -1), gp=gp, y_max=y_max), x_try.reshape(1, -1), bounds=bounds, method="L-BFGS-B") # Store it if better than previous minimum(maximum). if max_acq is None or -res.fun >= max_acq: x_max = res.x max_acq = -res.fun # Clip output to make sure it lies within the bounds. Due to floating # point technicalities this is not always the case. return np.clip(x_max, bounds[:, 0], bounds[:, 1]) def matern52(theta, d): """ Matern 5/2 correlation model.:: theta, d --> r(theta, d) = (1+sqrt(5)*r + 5/3*r^2)*exp(-sqrt(5)*r) n where r = sqrt(sum (d_i)^2 / (theta_i)^2 ) i = 1 Parameters ---------- theta : array_like An array with shape 1 (isotropic) or n (anisotropic) giving the autocorrelation parameter(s). d : array_like An array with shape (n_eval, n_features) giving the componentwise distances between locations x and x' at which the correlation model should be evaluated. Returns ------- r : array_like An array with shape (n_eval, ) containing the values of the autocorrelation modle. """ theta = np.asarray(theta, dtype=np.float) d = np.asarray(d, dtype=np.float) if d.ndim > 1: n_features = d.shape[1] else: n_features = 1 if theta.size == 1: r = np.sqrt(np.sum(d ** 2, axis=1)) / theta[0] elif theta.size != n_features: raise ValueError("Length of theta must be 1 or %s" % n_features) else: r = np.sqrt(np.sum(d ** 2 / theta.reshape(1, n_features) ** 2, axis=1)) return (1 + np.sqrt(5) * r + 5 / 3. * r ** 2) * np.exp(-np.sqrt(5) * r) class BayesianOptimization(object): def __init__(self, f, pbounds, verbose=1): """ :param f: Function to be maximized. :param pbounds: Dictionary with parameters names as keys and a tuple with minimum and maximum values. :param verbose: Whether or not to print progress. """ # Store the original dictionary self.pbounds = pbounds # Get the name of the parameters self.keys = list(pbounds.keys()) # Find number of parameters self.dim = len(pbounds) # Create an array with parameters bounds self.bounds = [] for key in self.pbounds.keys(): self.bounds.append(self.pbounds[key]) self.bounds = np.asarray(self.bounds) # Some function to be optimized self.f = f # Initialization flag self.initialized = False # Initialization lists --- stores starting points before process begins self.init_points = [] self.x_init = [] self.y_init = [] # Numpy array place holders self.X = None self.Y = None # Counter of iterations self.i = 0 # Since scipy 0.16 passing lower and upper bound to theta seems to be # broken. However, there is a lot of development going on around GP # is scikit-learn. So I'll pick the easy route here and simple specify # only theta0. self.gp = GaussianProcess(corr=matern52, theta0=np.random.uniform(0.001, 0.05, self.dim), thetaL=1e-5 * np.ones(self.dim), thetaU=1e0 * np.ones(self.dim), random_start=30) # Utility Function placeholder self.util = None # PrintLog object self.plog = PrintLog(self.keys) # Output dictionary self.res = {} # Output dictionary self.res['max'] = {'max_val': None, 'max_params': None} self.res['all'] = {'values': [], 'params': []} # Verbose self.verbose = verbose def init(self, init_points): """ Initialization method to kick start the optimization process. It is a combination of points passed by the user, and randomly sampled ones. :param init_points: Number of random points to probe. """ # Generate random points rp = [np.random.uniform(x[0], x[1], size=init_points) for x in self.bounds] # Concatenate new random points to possible existing # points from self.explore method. self.init_points += list(map(list, zip(*rp))) # Create empty list to store the new values of the function y_init = [] # Evaluate target function at all initialization # points (random + explore) for x in self.init_points: y_init.append(self.f(**dict(zip(self.keys, x)))) if self.verbose: self.plog.print_step(x, y_init[-1]) # Append any other points passed by the self.initialize method (these # also have a corresponding target value passed by the user). self.init_points += self.x_init # Append the target value of self.initialize method. y_init += self.y_init # Turn it into np array and store. self.X = np.asarray(self.init_points) self.Y = np.asarray(y_init) # Updates the flag self.initialized = True def explore(self, points_dict): """ Method to explore user defined points :param points_dict: :return: """ # Consistency check param_tup_lens = [] for key in self.keys: param_tup_lens.append(len(list(points_dict[key]))) if all([e == param_tup_lens[0] for e in param_tup_lens]): pass else: raise ValueError('The same number of initialization points ' 'must be entered for every parameter.') # Turn into list of lists all_points = [] for key in self.keys: all_points.append(points_dict[key]) # Take transpose of list self.init_points = list(map(list, zip(*all_points))) def initialize(self, points_dict): """ Method to introduce point for which the target function value is known :param points_dict: :return: """ for target in points_dict: self.y_init.append(target) all_points = [] for key in self.keys: all_points.append(points_dict[target][key]) self.x_init.append(all_points) def set_bounds(self, new_bounds): """ A method that allows changing the lower and upper searching bounds :param new_bounds: A dictionary with the parameter name and its new bounds """ # Update the internal object stored dict self.pbounds.update(new_bounds) # Loop through the all bounds and reset the min-max bound matrix for row, key in enumerate(self.pbounds.keys()): # Reset all entries, even if the same. self.bounds[row] = self.pbounds[key] def maximize(self, init_points=5, n_iter=25, acq='ei', kappa=2.576, xi=0.0, **gp_params): """ Main optimization method. Parameters ---------- :param init_points: Number of randomly chosen points to sample the target function before fitting the gp. :param n_iter: Total number of times the process is to repeated. Note that currently this methods does not have stopping criteria (due to a number of reasons), therefore the total number of points to be sampled must be specified. :param acq: Acquisition function to be used, defaults to Expected Improvement. :param gp_params: Parameters to be passed to the Scikit-learn Gaussian Process object Returns ------- :return: Nothing """ # Reset timer self.plog.reset_timer() # Set acquisition function self.util = UtilityFunction(kind=acq, kappa=kappa, xi=xi) # Initialize x, y and find current y_max if not self.initialized: if self.verbose: self.plog.print_header() self.init(init_points) y_max = self.Y.max() # Set parameters if any was passed self.gp.set_params(**gp_params) # Find unique rows of X to avoid GP from breaking
ur = unique_rows(self.X)
2
2023-11-17 09:23:38+00:00
16k
OpenBMB/XAgent
XAgentServer/application/websockets/base.py
[ { "identifier": "XAgentServerEnv", "path": "XAgentServer/application/core/envs.py", "snippet": "class XAgentServerEnv:\n \"\"\"\n XAgentServer environment variables\n if you change value of the environment variable, you need to restart \n the XAgentServer by running the following command:\n ...
import json import os import threading import traceback import uuid from datetime import datetime from urllib.parse import parse_qs from typing import Any from colorama import Fore from fastapi import APIRouter, Depends, WebSocket from sqlalchemy.orm import Session from starlette.endpoints import WebSocketEndpoint from apscheduler.schedulers.asyncio import AsyncIOScheduler from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import WebsocketResponseBody from XAgentServer.exts.exception_ext import XAgentWebSocketConnectError, XAgentError from XAgentServer.interaction import XAgentInteraction from XAgentServer.loggers.logs import Logger from XAgentServer.models.parameter import InteractionParameter from XAgentServer.models.raw import XAgentRaw from XAgentServer.server import XAgentServer from XAgentServer.enums.status import StatusEnum from XAgentServer.application.websockets.common import (check_user, handle_data, handle_workspace_filelist) from XAgentServer.application.global_val import redis
13,417
db=self.db, interaction_id=self.client_id) if interaction.status not in [StatusEnum.FINISHED, StatusEnum.FAILED]: InteractionCRUD.update_interaction_status(db=self.db, interaction_id=self.client_id, status=StatusEnum.CLOSED, message="closed", current_step="0") try: await self.on_disconnect(websocket, close_code) if self.scheduler.running: self.scheduler.shutdown() self.logger.info("shutdown scheduler") if self.db: self.db.close() self.logger.info("close db") finally: # notice the agent stop if user close the websocket redis.set_key(f"{self.client_id}", "close") async def on_connect(self, websocket: WebSocket): """Connect to client Args: websocket (WebSocket): A websocket object Raises: XAgentWebSocketConnectError: If the user is running, it will raise this error. """ self.log_dir = os.path.join(os.path.join(XAgentServerEnv.base_dir, "localstorage", "interact_records"), self.date_str, self.client_id) if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) self.logger = Logger( log_dir=self.log_dir, log_file="interact.log", log_name=f"{self.client_id}_INTERACT") query_string = self.scope.get("query_string", b"").decode() parameters = parse_qs(query_string) user_id = parameters.get("user_id", [""])[0] token = parameters.get("token", [""])[0] description = parameters.get("description", [""])[0] self.logger.typewriter_log( title=f"Receive connection from {self.client_id}: ", title_color=Fore.RED, content=f"user_id: {user_id}, token: {token}, description: {description}") await websocket.accept() try: await check_user(db=self.db, user_id=user_id, token=token) # check running, you can edit it by yourself in envs.py to skip this check if XAgentServerEnv.check_running: if InteractionCRUD.is_running(db=self.db, user_id=user_id): raise XAgentWebSocketConnectError( "You have a running interaction, please wait for it to finish!") base = InteractionCRUD.get_interaction(db=self.db, interaction_id=self.client_id) if base is None: raise XAgentWebSocketConnectError( "init interaction failed, please restart!") InteractionCRUD.update_interaction(db=self.db, base_data={ "interaction_id": self.client_id, "status": "connected", "message": "connected", "current_step": "0", "description": description} ) except XAgentWebSocketConnectError as e: self.logger.error( f"Error in on_connect of {self.client_id}: {e}") await websocket.send_text( WebsocketResponseBody( status="connect", success=False, message=str(e), data=None).to_text()) await websocket.close(code=1000) return await websocket.send_text( WebsocketResponseBody( status="connect", success=True, message="connect success", data=base.to_dict()).to_text()) async def on_disconnect(self, websocket: WebSocket, close_code): """When disconnect with client, it will run this function Override this function to do something when disconnect with client Args: websocket (WebSocket): A websocket object close_code (_type_): The close code, default is 0 """ self.logger.typewriter_log( title=f"Disconnect with client {self.client_id}: ", title_color=Fore.RED) # await websocket.close(code=close_code) async def on_receive(self, websocket: WebSocket, data: Any): """ When receive data from client, it will run this function Args: websocket (WebSocket): A websocket object data (any): The data from client """ data = json.loads(data) if data.get("type", "") != "ping": self.logger.typewriter_log( title=f"Receive data from {self.client_id}: ", title_color=Fore.RED, content=json.dumps(data, indent=4, ensure_ascii=False) ) if data.get("type", "") == "data": args = data.get("args", {}) agent = data.get("agent", "") mode = data.get("mode", "") file_list = data.get("file_list", []) node_id = data.get("node_id", "")
""" Base Websocket Server Note: You can use this websocket to run your interaction. You can modify it by yourself to do something, such as change the way to receive data from client, or use celery to run interaction, or use ThreadPoolExecutor to run interaction and so on. Version: 1.1.0 Attention: Since Version: 1.1.0, Local storage will no longer be supported, replaced by Mysql and only Components: Websocket is a way for long connect with client MySQL to save xagent data Redis to save status of interaction Threading to run interaction APScheduler to send data to client and keep alive FastAPI APIRouter to manage websocket route XAgentError in XAgentServer.exts.exception_ext """ router = APIRouter() # @router.websocket_route("/ws/{client_id}", name="ws") @router.websocket("/ws/base/{client_id}", name="ws") class MainServer(WebSocketEndpoint): """Main Websocket Server Extends: WebSocketEndpoint Description: In this websocket, we will receive the args from user, and you can use it to run the interaction. specifically, the args is a dict, and it must contain a key named "goal" to tell XAgent what do you want to do. """ def __init__(self, websocket: WebSocket, db: Session = Depends(get_db), client_id: str = ""): super().__init__(websocket.scope, websocket.receive, websocket.send) self.db = db self.client_id: str = client_id self.websocket = websocket self.date_str = datetime.now().strftime("%Y-%m-%d") self.log_dir = "" self.logger = None self.scheduler = AsyncIOScheduler() self.continue_flag = True async def dispatch(self) -> None: """XAgent Websocket Server Dispatch Function extend from WebSocketEndpoint override this function block: loop flag and finally block to do something Raises: exc: extend from WebSocketEndpoint """ websocket = WebSocket(self.scope, receive=self.receive, send=self.send) close_code = 1000 await self.on_connect(websocket) redis.set_key(f"{self.client_id}", "alive") try: while self.continue_flag: message = await websocket.receive() if message["type"] == "websocket.receive": data = await self.decode(websocket, message) await self.on_receive(websocket, data) elif message["type"] == "websocket.disconnect": close_code = 1000 break except Exception as exc: close_code = 1011 raise exc finally: interaction = InteractionCRUD.get_interaction( db=self.db, interaction_id=self.client_id) if interaction.status not in [StatusEnum.FINISHED, StatusEnum.FAILED]: InteractionCRUD.update_interaction_status(db=self.db, interaction_id=self.client_id, status=StatusEnum.CLOSED, message="closed", current_step="0") try: await self.on_disconnect(websocket, close_code) if self.scheduler.running: self.scheduler.shutdown() self.logger.info("shutdown scheduler") if self.db: self.db.close() self.logger.info("close db") finally: # notice the agent stop if user close the websocket redis.set_key(f"{self.client_id}", "close") async def on_connect(self, websocket: WebSocket): """Connect to client Args: websocket (WebSocket): A websocket object Raises: XAgentWebSocketConnectError: If the user is running, it will raise this error. """ self.log_dir = os.path.join(os.path.join(XAgentServerEnv.base_dir, "localstorage", "interact_records"), self.date_str, self.client_id) if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) self.logger = Logger( log_dir=self.log_dir, log_file="interact.log", log_name=f"{self.client_id}_INTERACT") query_string = self.scope.get("query_string", b"").decode() parameters = parse_qs(query_string) user_id = parameters.get("user_id", [""])[0] token = parameters.get("token", [""])[0] description = parameters.get("description", [""])[0] self.logger.typewriter_log( title=f"Receive connection from {self.client_id}: ", title_color=Fore.RED, content=f"user_id: {user_id}, token: {token}, description: {description}") await websocket.accept() try: await check_user(db=self.db, user_id=user_id, token=token) # check running, you can edit it by yourself in envs.py to skip this check if XAgentServerEnv.check_running: if InteractionCRUD.is_running(db=self.db, user_id=user_id): raise XAgentWebSocketConnectError( "You have a running interaction, please wait for it to finish!") base = InteractionCRUD.get_interaction(db=self.db, interaction_id=self.client_id) if base is None: raise XAgentWebSocketConnectError( "init interaction failed, please restart!") InteractionCRUD.update_interaction(db=self.db, base_data={ "interaction_id": self.client_id, "status": "connected", "message": "connected", "current_step": "0", "description": description} ) except XAgentWebSocketConnectError as e: self.logger.error( f"Error in on_connect of {self.client_id}: {e}") await websocket.send_text( WebsocketResponseBody( status="connect", success=False, message=str(e), data=None).to_text()) await websocket.close(code=1000) return await websocket.send_text( WebsocketResponseBody( status="connect", success=True, message="connect success", data=base.to_dict()).to_text()) async def on_disconnect(self, websocket: WebSocket, close_code): """When disconnect with client, it will run this function Override this function to do something when disconnect with client Args: websocket (WebSocket): A websocket object close_code (_type_): The close code, default is 0 """ self.logger.typewriter_log( title=f"Disconnect with client {self.client_id}: ", title_color=Fore.RED) # await websocket.close(code=close_code) async def on_receive(self, websocket: WebSocket, data: Any): """ When receive data from client, it will run this function Args: websocket (WebSocket): A websocket object data (any): The data from client """ data = json.loads(data) if data.get("type", "") != "ping": self.logger.typewriter_log( title=f"Receive data from {self.client_id}: ", title_color=Fore.RED, content=json.dumps(data, indent=4, ensure_ascii=False) ) if data.get("type", "") == "data": args = data.get("args", {}) agent = data.get("agent", "") mode = data.get("mode", "") file_list = data.get("file_list", []) node_id = data.get("node_id", "")
parameter = InteractionParameter(
8
2023-10-16 03:44:57+00:00
16k
deepseek-ai/DreamCraft3D
threestudio/models/geometry/tetrahedra_sdf_grid.py
[ { "identifier": "BaseExplicitGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseExplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n\n cfg: Config\n\n def configure(self) -> None:\n self.bbox: Flo...
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio import trimesh from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseExplicitGeometry, BaseGeometry, contract_to_unisphere, ) from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.models.geometry.implicit_volume import ImplicitVolume from threestudio.models.isosurface import MarchingTetrahedraHelper from threestudio.models.mesh import Mesh from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.misc import broadcast from threestudio.utils.ops import scale_tensor from threestudio.utils.typing import * from pysdf import SDF
14,073
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None shape_init_mesh_up: str = "+z" shape_init_mesh_front: str = "+x" force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone())
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None shape_init_mesh_up: str = "+z" shape_init_mesh_front: str = "+x" force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone())
self.isosurface_helper = MarchingTetrahedraHelper(
5
2023-10-23 07:40:20+00:00
16k
zju3dv/4K4D
tests/headless_opengl_tests.py
[ { "identifier": "eglContextManager", "path": "easyvolcap/utils/egl_utils.py", "snippet": "class eglContextManager:\n # Manages the creation and destruction of an EGL context\n # Will resize if the size of the window changes\n # Will also manage gl.Viewport to render different parts of the scree...
from easyvolcap.utils.egl_utils import eglContextManager # must be imported before OpenGL.GL from os.path import join, dirname from easyvolcap.utils.console_utils import * from easyvolcap.utils.gl_utils import Quad, Mesh from easyvolcap.utils.viewer_utils import Camera from easyvolcap.utils.data_utils import save_image from easyvolcap.utils.gl_utils import common_opengl_options, linearize_depth from easyvolcap.utils.test_utils import my_tests import OpenGL.GL as gl import os import cv2 import torch import numpy as np
12,166
from __future__ import absolute_import, division, print_function # fmt: off # fmt: on WIDTH, HEIGHT = 512, 512 eglctx = eglContextManager(HEIGHT, WIDTH) # will create a new context common_opengl_options() # common init def test_gl_context(): # Render triangle gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glBegin(gl.GL_TRIANGLES) gl.glColor3f(1, 0, 0) gl.glVertex2f(0, 1) gl.glColor3f(0, 1, 0) gl.glVertex2f(-1, -1) gl.glColor3f(0, 0, 1) gl.glVertex2f(1, -1) gl.glEnd() # Read result img_buf = gl.glReadPixels(0, 0, WIDTH, HEIGHT, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE) img = np.frombuffer(img_buf, np.uint8).reshape(HEIGHT, WIDTH, 4)[::-1] assert all(img[0, 0, :3] == 0) # black corner assert all(img[0, -1, :3] == 0) # black corner assert img[10, WIDTH // 2, :3].argmax() == 0 # red corner assert img[-1, 10, :3].argmax() == 1 # green corner assert img[-1, -10, :3].argmax() == 2 # blue corner def test_gl_mesh_rast(): gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) mesh_path = 'assets/meshes/bunny.ply' img_path = 'test_gl_mesh_rast.png' camera = Camera(H=HEIGHT, W=WIDTH, K=torch.tensor([[592., 0., 256.], [0., 592., 256.], [0., 0., 1.]]), R=torch.tensor([[0.9908, -0.1353, 0.0000], [-0.1341, -0.9815, -0.1365], [0.0185, 0.1353, -0.9906]]), T=torch.tensor([[0.0178], [0.0953], [0.3137]]) )
from __future__ import absolute_import, division, print_function # fmt: off # fmt: on WIDTH, HEIGHT = 512, 512 eglctx = eglContextManager(HEIGHT, WIDTH) # will create a new context common_opengl_options() # common init def test_gl_context(): # Render triangle gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glBegin(gl.GL_TRIANGLES) gl.glColor3f(1, 0, 0) gl.glVertex2f(0, 1) gl.glColor3f(0, 1, 0) gl.glVertex2f(-1, -1) gl.glColor3f(0, 0, 1) gl.glVertex2f(1, -1) gl.glEnd() # Read result img_buf = gl.glReadPixels(0, 0, WIDTH, HEIGHT, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE) img = np.frombuffer(img_buf, np.uint8).reshape(HEIGHT, WIDTH, 4)[::-1] assert all(img[0, 0, :3] == 0) # black corner assert all(img[0, -1, :3] == 0) # black corner assert img[10, WIDTH // 2, :3].argmax() == 0 # red corner assert img[-1, 10, :3].argmax() == 1 # green corner assert img[-1, -10, :3].argmax() == 2 # blue corner def test_gl_mesh_rast(): gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) mesh_path = 'assets/meshes/bunny.ply' img_path = 'test_gl_mesh_rast.png' camera = Camera(H=HEIGHT, W=WIDTH, K=torch.tensor([[592., 0., 256.], [0., 592., 256.], [0., 0., 1.]]), R=torch.tensor([[0.9908, -0.1353, 0.0000], [-0.1341, -0.9815, -0.1365], [0.0185, 0.1353, -0.9906]]), T=torch.tensor([[0.0178], [0.0953], [0.3137]]) )
mesh = Mesh(filename=mesh_path, shade_flat=False)
2
2023-10-17 04:48:46+00:00
16k
0xbitches/sd-webui-lcm
scripts/main.py
[ { "identifier": "LCMScheduler", "path": "lcm/lcm_scheduler.py", "snippet": "class LCMScheduler(SchedulerMixin, ConfigMixin):\n \"\"\"\n `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with\n non-Markovian guidance.\n\n This model ...
from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Optional from lcm.lcm_scheduler import LCMScheduler from lcm.lcm_pipeline import LatentConsistencyModelPipeline from lcm.lcm_i2i_pipeline import LatentConsistencyModelImg2ImgPipeline from diffusers.image_processor import PipelineImageInput from modules import script_callbacks from PIL import Image, PngImagePlugin import uuid import modules.scripts as scripts import modules.shared import os import random import time import numpy as np import gradio as gr import torch import cv2
11,143
DESCRIPTION = '''# Latent Consistency Model Running [LCM_Dreamshaper_v7](https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7) | [Project Page](https://latent-consistency-models.github.io) | [Extension Page](https://github.com/0xbitches/sd-webui-lcm) ''' MAX_SEED = np.iinfo(np.int32).max MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "768")) class Script(scripts.Script): def __init__(self) -> None: super().__init__() def title(self): return "LCM" def show(self, is_img2img): return scripts.AlwaysVisible def ui(self, is_img2img): return () def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed def save_image(img, metadata: dict): save_dir = os.path.join(scripts.basedir(), "outputs/txt2img-images/LCM/") Path(save_dir).mkdir(exist_ok=True, parents=True) seed = metadata["seed"] unique_id = uuid.uuid4() filename = save_dir + f"{unique_id}-{seed}" + ".png" meta_tuples = [(k, str(v)) for k, v in metadata.items()] png_info = PngImagePlugin.PngInfo() for k, v in meta_tuples: png_info.add_text(k, v) img.save(filename, pnginfo=png_info) return filename def save_images(image_array, metadata: dict): paths = [] with ThreadPoolExecutor() as executor: paths = list(executor.map(save_image, image_array, [metadata]*len(image_array))) return paths def generate( prompt: str, seed: int = 0, width: int = 512, height: int = 512, guidance_scale: float = 8.0, num_inference_steps: int = 4, num_images: int = 4, randomize_seed: bool = False, use_fp16: bool = True, use_torch_compile: bool = False, use_cpu: bool = False, progress=gr.Progress(track_tqdm=True) ) -> Image.Image: seed = randomize_seed_fn(seed, randomize_seed) torch.manual_seed(seed) selected_device = modules.shared.device if use_cpu: selected_device = "cpu" if use_fp16: use_fp16 = False print("LCM warning: running on CPU, overrode FP16 with FP32") scheduler = LCMScheduler.from_pretrained( "SimianLuo/LCM_Dreamshaper_v7", subfolder="scheduler")
DESCRIPTION = '''# Latent Consistency Model Running [LCM_Dreamshaper_v7](https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7) | [Project Page](https://latent-consistency-models.github.io) | [Extension Page](https://github.com/0xbitches/sd-webui-lcm) ''' MAX_SEED = np.iinfo(np.int32).max MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "768")) class Script(scripts.Script): def __init__(self) -> None: super().__init__() def title(self): return "LCM" def show(self, is_img2img): return scripts.AlwaysVisible def ui(self, is_img2img): return () def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed def save_image(img, metadata: dict): save_dir = os.path.join(scripts.basedir(), "outputs/txt2img-images/LCM/") Path(save_dir).mkdir(exist_ok=True, parents=True) seed = metadata["seed"] unique_id = uuid.uuid4() filename = save_dir + f"{unique_id}-{seed}" + ".png" meta_tuples = [(k, str(v)) for k, v in metadata.items()] png_info = PngImagePlugin.PngInfo() for k, v in meta_tuples: png_info.add_text(k, v) img.save(filename, pnginfo=png_info) return filename def save_images(image_array, metadata: dict): paths = [] with ThreadPoolExecutor() as executor: paths = list(executor.map(save_image, image_array, [metadata]*len(image_array))) return paths def generate( prompt: str, seed: int = 0, width: int = 512, height: int = 512, guidance_scale: float = 8.0, num_inference_steps: int = 4, num_images: int = 4, randomize_seed: bool = False, use_fp16: bool = True, use_torch_compile: bool = False, use_cpu: bool = False, progress=gr.Progress(track_tqdm=True) ) -> Image.Image: seed = randomize_seed_fn(seed, randomize_seed) torch.manual_seed(seed) selected_device = modules.shared.device if use_cpu: selected_device = "cpu" if use_fp16: use_fp16 = False print("LCM warning: running on CPU, overrode FP16 with FP32") scheduler = LCMScheduler.from_pretrained( "SimianLuo/LCM_Dreamshaper_v7", subfolder="scheduler")
pipe = LatentConsistencyModelPipeline.from_pretrained(
1
2023-10-22 11:53:48+00:00
16k
kylesargent/ZeroNVS
threestudio/models/geometry/tetrahedra_sdf_grid.py
[ { "identifier": "BaseExplicitGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseExplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n\n cfg: Config\n\n def configure(self) -> None:\n self.bbox: Flo...
from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseExplicitGeometry, BaseGeometry, contract_to_unisphere, ) from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.models.geometry.implicit_volume import ImplicitVolume from threestudio.models.isosurface import MarchingTetrahedraHelper from threestudio.models.mesh import Mesh from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.ops import scale_tensor from threestudio.utils.typing import * import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio
13,640
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone()) self.isosurface_helper = MarchingTetrahedraHelper( self.cfg.isosurface_resolution, f"load/tets/{self.cfg.isosurface_resolution}_tets.npz", ) self.sdf: Float[Tensor, "Nv 1"] self.deformation: Optional[Float[Tensor, "Nv 3"]] if not self.cfg.fix_geometry: self.register_parameter( "sdf", nn.Parameter( torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ) ), ) if self.cfg.isosurface_deformable_grid: self.register_parameter( "deformation", nn.Parameter( torch.zeros_like(self.isosurface_helper.grid_vertices) ), ) else: self.deformation = None else: self.register_buffer( "sdf", torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ), ) if self.cfg.isosurface_deformable_grid: self.register_buffer( "deformation", torch.zeros_like(self.isosurface_helper.grid_vertices), ) else: self.deformation = None if not self.cfg.geometry_only:
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone()) self.isosurface_helper = MarchingTetrahedraHelper( self.cfg.isosurface_resolution, f"load/tets/{self.cfg.isosurface_resolution}_tets.npz", ) self.sdf: Float[Tensor, "Nv 1"] self.deformation: Optional[Float[Tensor, "Nv 3"]] if not self.cfg.fix_geometry: self.register_parameter( "sdf", nn.Parameter( torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ) ), ) if self.cfg.isosurface_deformable_grid: self.register_parameter( "deformation", nn.Parameter( torch.zeros_like(self.isosurface_helper.grid_vertices) ), ) else: self.deformation = None else: self.register_buffer( "sdf", torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ), ) if self.cfg.isosurface_deformable_grid: self.register_buffer( "deformation", torch.zeros_like(self.isosurface_helper.grid_vertices), ) else: self.deformation = None if not self.cfg.geometry_only:
self.encoding = get_encoding(
7
2023-10-24 19:02:44+00:00
16k
princeton-nlp/LLM-Shearing
llmshearing/models/composer_pythia.py
[ { "identifier": "L0Module", "path": "llmshearing/models/l0_module.py", "snippet": "class L0Module(nn.Module):\n def __init__(self, cfg, device):\n super(L0Module, self).__init__()\n\n # base and target model info\n n_matrix_mlp = 2 if \"pythia\" in cfg.name else 3\n self.b...
import math import torch import torch.nn as nn from typing import List, Optional, Tuple from einops import rearrange from omegaconf import DictConfig from torch.nn import functional as F from transformers.pytorch_utils import (find_pruneable_heads_and_indices, prune_linear_layer) from llmshearing.models.l0_module import L0Module from llmshearing.models.composer_llama import ComposerMosaicLlama, prepare_decoder_attention_mask, turn_head_z, turn_mlp_z, normal_attn_fn, flash_attn_fn from transformers.models.gpt_neox.modeling_gpt_neox import apply_rotary_pos_emb
11,070
query_padding_mask = None if key_padding_mask is not None: query_padding_mask = key_padding_mask[:, -query.size(1):] # b, s, d = query.shape new_qkv_shape = qkv.size()[:-1] + (self.n_heads, 3 * self.head_dim) qkv = qkv.view(*new_qkv_shape) # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size] query = qkv[..., : self.head_dim].permute(0, 2, 1, 3) key = qkv[..., self.head_dim : 2 * self.head_dim].permute(0, 2, 1, 3) value = qkv[..., 2 * self.head_dim :].permute(0, 2, 1, 3) query_rot = query[..., : self.rotary_ndims] query_pass = query[..., self.rotary_ndims :] key_rot = key[..., : self.rotary_ndims] key_pass = key[..., self.rotary_ndims :] kv_seq_len = key.size(2) offset = 0 if past_key_value is not None: offset = past_key_value[0].shape[-2] kv_seq_len += offset cos, sin = self.rotary_emb(value, seq_len=kv_seq_len) position_ids = torch.arange(offset, kv_seq_len, dtype=torch.long, device=cos.device) position_ids = position_ids.unsqueeze(0).view(-1, kv_seq_len) query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids) query = torch.cat((query, query_pass), dim=-1) key = torch.cat((key, key_pass), dim=-1) offset = 0 if past_key_value is not None: if len(past_key_value) != 0: offset = past_key_value[0].shape[-2] key = torch.cat([past_key_value[0], key], dim=1) value = torch.cat([past_key_value[1], value], dim=1) past_key_value = (key, value) if self.attn_fn == flash_attn_fn: # TODO: test if it is the same as attn query = rearrange(query, 'b h s d -> b s h d') key = rearrange(key, 'b h s d -> b s h d') value = rearrange(value, 'b h s d -> b s h d') context, attn_weights = self.attn_fn( query, key, value, self.n_heads, softmax_scale=self.softmax_scale, attn_bias=attn_bias, query_padding_mask=query_padding_mask, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, head_z=head_z ) else: context = self.attn_fn( query=query, key=key, value=value, attention_mask=attention_mask, head_z=head_z ) attn_weights = None if retain_grad: self.context = context if self.context.requires_grad: self.context.retain_grad() output = self.out_proj(context) if head_layer_z is not None: output *= head_layer_z if hidden_z is not None: output *= hidden_z if retain_grad: self.output = output if self.output.requires_grad: self.output.retain_grad() return output, attn_weights, past_key_value class PythiaMLP(nn.Module): def __init__(self, cfg: DictConfig, device: Optional[str] = None): super().__init__() self.cfg = cfg self.down_proj = nn.Linear(cfg.intermediate_size, cfg.d_model, bias=True, device=device) self.up_proj = nn.Linear(cfg.d_model, cfg.intermediate_size, bias=True, device=device) def prune_params(self, zs_block): intermediate_z = zs_block.get("intermediate_z", None) mlp_z = zs_block.get("mlp_z", None) hidden_z = zs_block.get("hidden_z", None) # update params # if intermediate_z is not None: self.down_proj.weight.data = self.down_proj.weight.data.mul(intermediate_z.squeeze(0)) if mlp_z is not None: self.down_proj.weight.data = self.down_proj.weight.data.transpose(0, 1).mul(mlp_z).transpose(0, 1) self.down_proj.bias.data = self.down_proj.bias.data.mul(mlp_z) if hidden_z is not None: self.down_proj.weight.data = self.down_proj.weight.data.transpose(0, 1).mul(hidden_z).transpose(0, 1) self.down_proj.bias.data = self.down_proj.bias.data.mul(hidden_z) ################# if hidden_z is not None: remaining_index = torch.where(~hidden_z.eq(0))[0] print(f" FFN hidden dim: {len(hidden_z)} -> {len(remaining_index)}") half = next(self.up_proj.parameters()).dtype self.up_proj = prune_linear_layer(self.up_proj, remaining_index, dim=1) self.down_proj = prune_linear_layer(self.down_proj, remaining_index, dim=0) if half == torch.float16: self.up_proj = self.up_proj.half() self.down_proj = self.down_proj.half()
class ComposerMosaicPythia(ComposerMosaicLlama): def __init__(self, cfg): super().__init__(cfg) self.model = PythiaModel(cfg) class CoFiLayerNorm(torch.nn.LayerNorm): def __init__(self, normalized_shape, eps: float = 1e-5, elementwise_affine: bool = True, device=None) -> None: super().__init__(normalized_shape, eps, elementwise_affine, device) def forward(self, input, hidden_z=None): if hidden_z is not None: remaining_index = torch.where(~hidden_z.eq(0))[0] compressed_input = torch.index_select( input, dim=-1, index=remaining_index) compressed_weight = self.weight[remaining_index] compressed_bias = self.bias[remaining_index] normalized_shape = len(remaining_index) normed_input = F.layer_norm( compressed_input, [normalized_shape], compressed_weight, compressed_bias, self.eps) output = input.clone() normed_input = normed_input.to(output.dtype) output[..., remaining_index] = normed_input else: output = F.layer_norm( input, self.normalized_shape, self.weight, self.bias, self.eps) return output def prune_params(self, hidden_z): remaining_index = torch.where(~hidden_z.eq(0))[0] # self.weight = torch.nn.Parameter(self.weight.data.mul(hidden_z.squeeze())[remaining_index]) self.weight = torch.nn.parameter.Parameter(self.weight.index_select(0, remaining_index)) self.bias = torch.nn.parameter.Parameter(self.bias.index_select(0, remaining_index)) self.normalized_shape = (len(remaining_index),) class PythiaEmbedding(nn.Embedding): def forward(self, input, hidden_z=None): embeddings = super().forward(input) if hidden_z is not None: embeddings = embeddings.mul(hidden_z) return embeddings def prune_params(self, hidden_z): remaining_index = torch.where(~hidden_z.eq(0))[0] self.weight.data = self.weight.data.mul(hidden_z) self.weight = torch.nn.parameter.Parameter(self.weight.index_select(1, remaining_index).clone()) self.embedding_dim = len(remaining_index) print(f" Embedding: {len(hidden_z)} -> {len(remaining_index)}") class PythiaModel(nn.Module): def __init__(self, cfg: DictConfig): super().__init__() print(f'Tried to build Pythia model with cfg.name={cfg.name}') self.cfg = cfg ### added ### self.l0_module = None if getattr(self.cfg, "l0_module", None) is not None: self.l0_module = L0Module(self.cfg, device=cfg.init_device) ############# layernorm_class = CoFiLayerNorm self.attn_impl = cfg.attn_impl self.embedding_fraction = cfg.get('embedding_fraction', 1) assert 0 < self.embedding_fraction <= 1, 'model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!' self.transformer = nn.ModuleDict({ "wte": PythiaEmbedding(cfg.vocab_size, cfg.d_model, device=cfg.init_device), }) self.transformer.update({ 'blocks': nn.ModuleList([ PythiaBlock(cfg, device=cfg.init_device) for _ in range(cfg.n_layers) ]) }) self.transformer.update({ "output": nn.Linear(cfg.d_model, cfg.vocab_size, device=cfg.init_device, bias=False), }) self.transformer.update({ "ln_f": layernorm_class(cfg.d_model, eps=cfg.layer_norm_eps, device=cfg.init_device), # TODO: add to config }) self.is_causal = True if cfg.get('verbose') and cfg.get('verbose') > 2: print(self) def prune_params(self, zs=None): # TODO if zs is None: self.l0_module.eval() zs = self.l0_module(calculate_lagrangian=False) # wte as well :) # ln_f if hidden states are to be pruned if "hidden_z" in zs: hidden_z = zs["hidden_z"] remaining_index = torch.where(~hidden_z.eq(0))[0] self.transformer.ln_f.prune_params(hidden_z) self.transformer.wte.weight.data = self.transformer.wte.weight.data.mul(hidden_z) self.transformer.wte.weight = torch.nn.parameter.Parameter( self.transformer.wte.weight.index_select(1, remaining_index).clone()) self.transformer.wte.embedding_dim = len(remaining_index) # self.transformer.output.weight.data = self.transformer.output.weight.data.mul(hidden_z) half = self.transformer.output.weight.data.dtype == torch.float16 self.transformer.output = prune_linear_layer(self.transformer.output, remaining_index, dim=1) if half: self.transformer.output = self.transformer.output.half() for i, block in enumerate(self.transformer.blocks): zs_block = self.get_zs_block(zs, i) block.prune_params(zs_block) def get_zs_block(self, zs, block_idx): zs_block = {} if zs is not None: for key in zs: if key == "hidden_z": zs_block["hidden_z"] = zs["hidden_z"] else: zs_block[key] = zs[key][block_idx] return zs_block def forward( self, input_ids: torch.LongTensor, key_padding_mask: Optional[torch.ByteTensor] = None, past_key_values: Optional[List[Tuple[torch.FloatTensor]]] = None, pruned_steps: int = 0, retain_grad: bool = False, **zs,): S = input_ids.size(1) assert S <= self.cfg.max_seq_len, f"Sequence length ({S}) exceeds model maximum sequence length ({self.cfg.max_seq_len})!" tok_emb = self.transformer.wte(input_ids) if "hidden_z" in zs: tok_emb = tok_emb.mul(zs["hidden_z"]) x = tok_emb attn_bias = None # only consider the flash attention case attention_mask = prepare_decoder_attention_mask((tok_emb.size(0), tok_emb.size(1)), tok_emb) l0_output = None if self.l0_module is not None: assert zs == {}, "zs should be empty when using L0Module" zs = self.l0_module(calculate_lagrangian=False, pruned_steps=pruned_steps) for b_idx, block in enumerate(self.transformer.blocks): zs_block = self.get_zs_block(zs, b_idx) past_key_value = past_key_values[ b_idx] if past_key_values is not None else None x, past_key_value = block( x, past_key_value=past_key_value, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=self.is_causal, attention_mask=attention_mask, retain_grad=retain_grad, **zs_block ) if past_key_values is not None: past_key_values[b_idx] = past_key_value x = self.transformer.ln_f(x, hidden_z=zs.get("hidden_z", None)) logits = self.transformer.output(x) if self.l0_module is not None: l0_output = self.l0_module(calculate_lagrangian=True, pruned_steps=pruned_steps) return {"logits": logits, "l0_output": l0_output, "zs": zs} def param_init_fn(self, module): pass def fsdp_wrap_fn(self, module): return isinstance(module, PythiaBlock) # Activation Checkpointing def activation_checkpointing_fn(self, module): return isinstance(module, PythiaBlock) class PythiaBlock(nn.Module): def __init__(self, cfg: DictConfig, device: Optional[str] = None): super().__init__() layernorm_class = CoFiLayerNorm # TODO: CoFiLayerNorm,RMSLayerNorm self.ln_1 = layernorm_class(cfg.d_model, eps=cfg.layer_norm_eps, device=device) self.attn = PythiaAttention(cfg, device) self.ln_2 = layernorm_class(cfg.d_model, eps=cfg.layer_norm_eps, device=device) self.mlp = PythiaMLP(cfg, device) self.use_parallel_residual = cfg.get('use_parallel_residual', False) # TODO: add to config def prune_params(self, zs_block): self.attn.prune_params(zs_block) self.mlp.prune_params(zs_block) if self.attn.query_key_value is None: self.ln_1 = None if self.mlp.up_proj is None: self.ln_2 = None if "hidden_z" in zs_block: hidden_z = zs_block["hidden_z"] if self.ln_1 is not None: self.ln_1.prune_params(hidden_z) if self.ln_2 is not None: self.ln_2.prune_params(hidden_z) def forward( self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]] = None, attn_bias: Optional[torch.Tensor] = None, key_padding_mask: Optional[torch.ByteTensor] = None, is_causal: bool = True, attention_mask: Optional[torch.Tensor] = None, retain_grad: bool = False, head_z: Optional[torch.Tensor] = None, head_layer_z: Optional[torch.Tensor] = None, intermediate_z: Optional[torch.Tensor] = None, mlp_z: Optional[torch.Tensor] = None, hidden_z: Optional[torch.Tensor] = None, qk_head_dim_z: Optional[torch.Tensor] = None, vo_head_dim_z: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]: if self.ln_1 is not None: a = self.ln_1(x, hidden_z=hidden_z) attn_output, _, past_key_value = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, attention_mask=attention_mask, retain_grad=retain_grad, head_z=head_z, head_layer_z=head_layer_z, hidden_z=hidden_z, qk_head_dim_z=qk_head_dim_z, vo_head_dim_z=vo_head_dim_z) else: attn_output = 0 if self.use_parallel_residual: # pseudocode: # x = x + attn(ln1(x)) + mlp(ln2(x)) if self.ln_2 is not None: b = self.ln_2(x, hidden_z=hidden_z) mlp_output = self.mlp(b, retain_grad, intermediate_z, mlp_z, hidden_z) x = mlp_output + attn_output + x else: x = attn_output + x else: # pseudocode: # x = x + attn(ln1(x)) # x = x + mlp(ln2(x)) if self.ln_2 is not None: attn_output = x + attn_output hidden_states = self.ln_2(attn_output, hidden_z=hidden_z) mlp_output = self.mlp(hidden_states, retain_grad, intermediate_z, mlp_z, hidden_z) x = mlp_output + attn_output else: x = x + attn_output return x, past_key_value class PythiaAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, cfg: DictConfig, device: Optional[str] = None): super().__init__() self.attn_impl = cfg.get('attn_impl') self.d_model = cfg.d_model self.n_heads = cfg.n_heads self.all_head_size = cfg.d_model self.head_dim = self.d_model // self.n_heads self.pruned_heads = set() self.softmax_scale = cfg.get('softmax_scale') if self.softmax_scale is None: self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads) self.attn_dropout_p = cfg.get('attn_pdrop') # self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device, bias=False) # for param init fn; enables shape based init of fused layers # fuse_splits = (cfg.d_model, 2 * cfg.d_model) # self.Wqkv._fused = (0, fuse_splits) # type: ignore self.query_key_value = nn.Linear(self.d_model, 3 * self.d_model, device=device, bias=True) fuse_splits = (cfg.d_model, 2 * cfg.d_model) self.query_key_value._fused = (0, fuse_splits) self.attn_fn = flash_attn_fn if self.attn_impl == 'flash' else normal_attn_fn self.out_proj = nn.Linear(self.d_model, self.d_model, device=device, bias=True) self.out_proj._is_residual = True # type: ignore self.rotary_ndims = int(self.head_dim * cfg.rotary_pct) self.rotary_emb = RotaryEmbedding(self.rotary_ndims, max_position_embeddings=cfg.max_seq_len, device=device) def prune_params(self, zs_block): head_z = None; head_layer_z = None; hidden_z = None; qk_head_dim_z = None; vo_head_dim_z = None if "head_z" in zs_block: head_z = zs_block["head_z"].squeeze() if "head_layer_z" in zs_block: head_layer_z = zs_block["head_layer_z"].squeeze() if "hidden_z" in zs_block: hidden_z = zs_block["hidden_z"].squeeze() # update params # if head_z is not None: head_z_for_update = torch.repeat_interleave(head_z, self.head_dim) start_index = torch.arange(0, self.n_heads * 3, 3) + 2 end_index = start_index + 1 index = torch.cat([torch.arange(i, j) for i, j in zip(start_index * self.head_dim, end_index * self.head_dim)]) self.query_key_value.weight.data[index, :] = \ self.query_key_value.weight.data.transpose(0, 1)[:, index].mul(head_z_for_update).transpose(0, 1) self.query_key_value.bias.data[index] = \ self.query_key_value.bias.data[index].mul(head_z_for_update) if head_layer_z is not None: self.out_proj.weight.data = self.out_proj.weight.data.transpose(0, 1).mul(head_layer_z).transpose(0, 1) self.out_proj.bias.data = self.out_proj.bias.data.mul(head_layer_z) if hidden_z is not None: self.out_proj.weight.data = self.out_proj.weight.data.transpose(0, 1).mul(hidden_z).transpose(0, 1) self.out_proj.bias.data = self.out_proj.bias.data.mul(hidden_z) ################# if hidden_z is not None: remaining_index = torch.where(~hidden_z.eq(0))[0] print(f" Head hidden: {len(hidden_z)} -> {len(remaining_index)}") half = next(self.query_key_value.parameters()).dtype == torch.float16 self.query_key_value = prune_linear_layer(self.query_key_value, remaining_index, dim=1) self.out_proj = prune_linear_layer(self.out_proj, remaining_index) if half: self.query_key_value.half() self.out_proj.half() to_prune_heads = turn_head_z(head_z, head_layer_z) len_to_prune_heads = len(to_prune_heads) if len_to_prune_heads == 0: print(f" Heads: {self.n_heads} -> {self.n_heads}") return heads, index = find_pruneable_heads_and_indices( to_prune_heads, self.n_heads, self.head_dim, self.pruned_heads ) # Prune linear layers # setting layers to be None if all the heads are pruned if len(index) == 0: self.query_key_value = None self.out_proj = None else: half = next(self.query_key_value.parameters()).dtype == torch.float16 remaining_heads = list(set([i for i in range(self.n_heads)]) - set(to_prune_heads)) qkv_index = torch.cat([torch.arange(i * self.head_dim * 3, (i+1) * self.head_dim * 3).to(index.device) for i in remaining_heads]) self.query_key_value = prune_linear_layer(self.query_key_value, qkv_index) self.out_proj = prune_linear_layer(self.out_proj, index, dim=1) if half: self.query_key_value.half() self.out_proj.half() print(f" Heads: {self.n_heads} -> {self.n_heads - len(heads)}") # Update hyper params and store pruned heads self.n_heads = self.n_heads - len(heads) self.all_head_size = self.head_dim * self.n_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, x, past_key_value=None, attn_bias=None, key_padding_mask=None, is_causal=True, needs_weights=False, attention_mask=None, retain_grad=False, head_z=None, head_layer_z=None, hidden_z=None, qk_head_dim_z=None, vo_head_dim_z=None): if self.query_key_value is None: return None, None, past_key_value qkv = self.query_key_value(x) query_padding_mask = None if key_padding_mask is not None: query_padding_mask = key_padding_mask[:, -query.size(1):] # b, s, d = query.shape new_qkv_shape = qkv.size()[:-1] + (self.n_heads, 3 * self.head_dim) qkv = qkv.view(*new_qkv_shape) # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size] query = qkv[..., : self.head_dim].permute(0, 2, 1, 3) key = qkv[..., self.head_dim : 2 * self.head_dim].permute(0, 2, 1, 3) value = qkv[..., 2 * self.head_dim :].permute(0, 2, 1, 3) query_rot = query[..., : self.rotary_ndims] query_pass = query[..., self.rotary_ndims :] key_rot = key[..., : self.rotary_ndims] key_pass = key[..., self.rotary_ndims :] kv_seq_len = key.size(2) offset = 0 if past_key_value is not None: offset = past_key_value[0].shape[-2] kv_seq_len += offset cos, sin = self.rotary_emb(value, seq_len=kv_seq_len) position_ids = torch.arange(offset, kv_seq_len, dtype=torch.long, device=cos.device) position_ids = position_ids.unsqueeze(0).view(-1, kv_seq_len) query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids) query = torch.cat((query, query_pass), dim=-1) key = torch.cat((key, key_pass), dim=-1) offset = 0 if past_key_value is not None: if len(past_key_value) != 0: offset = past_key_value[0].shape[-2] key = torch.cat([past_key_value[0], key], dim=1) value = torch.cat([past_key_value[1], value], dim=1) past_key_value = (key, value) if self.attn_fn == flash_attn_fn: # TODO: test if it is the same as attn query = rearrange(query, 'b h s d -> b s h d') key = rearrange(key, 'b h s d -> b s h d') value = rearrange(value, 'b h s d -> b s h d') context, attn_weights = self.attn_fn( query, key, value, self.n_heads, softmax_scale=self.softmax_scale, attn_bias=attn_bias, query_padding_mask=query_padding_mask, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, head_z=head_z ) else: context = self.attn_fn( query=query, key=key, value=value, attention_mask=attention_mask, head_z=head_z ) attn_weights = None if retain_grad: self.context = context if self.context.requires_grad: self.context.retain_grad() output = self.out_proj(context) if head_layer_z is not None: output *= head_layer_z if hidden_z is not None: output *= hidden_z if retain_grad: self.output = output if self.output.requires_grad: self.output.retain_grad() return output, attn_weights, past_key_value class PythiaMLP(nn.Module): def __init__(self, cfg: DictConfig, device: Optional[str] = None): super().__init__() self.cfg = cfg self.down_proj = nn.Linear(cfg.intermediate_size, cfg.d_model, bias=True, device=device) self.up_proj = nn.Linear(cfg.d_model, cfg.intermediate_size, bias=True, device=device) def prune_params(self, zs_block): intermediate_z = zs_block.get("intermediate_z", None) mlp_z = zs_block.get("mlp_z", None) hidden_z = zs_block.get("hidden_z", None) # update params # if intermediate_z is not None: self.down_proj.weight.data = self.down_proj.weight.data.mul(intermediate_z.squeeze(0)) if mlp_z is not None: self.down_proj.weight.data = self.down_proj.weight.data.transpose(0, 1).mul(mlp_z).transpose(0, 1) self.down_proj.bias.data = self.down_proj.bias.data.mul(mlp_z) if hidden_z is not None: self.down_proj.weight.data = self.down_proj.weight.data.transpose(0, 1).mul(hidden_z).transpose(0, 1) self.down_proj.bias.data = self.down_proj.bias.data.mul(hidden_z) ################# if hidden_z is not None: remaining_index = torch.where(~hidden_z.eq(0))[0] print(f" FFN hidden dim: {len(hidden_z)} -> {len(remaining_index)}") half = next(self.up_proj.parameters()).dtype self.up_proj = prune_linear_layer(self.up_proj, remaining_index, dim=1) self.down_proj = prune_linear_layer(self.down_proj, remaining_index, dim=0) if half == torch.float16: self.up_proj = self.up_proj.half() self.down_proj = self.down_proj.half()
keep_dim = turn_mlp_z(intermediate_z, mlp_z)
4
2023-10-16 12:26:08+00:00
16k
hkchengrex/Cutie
cutie/inference/inference_core.py
[ { "identifier": "MemoryManager", "path": "cutie/inference/memory_manager.py", "snippet": "class MemoryManager:\n \"\"\"\n Manages all three memory stores and the transition between working/long-term memory\n \"\"\"\n def __init__(self, cfg: DictConfig, object_manager: ObjectManager):\n ...
from typing import List, Optional, Iterable, Dict from omegaconf import DictConfig from cutie.inference.memory_manager import MemoryManager from cutie.inference.object_manager import ObjectManager from cutie.inference.image_feature_store import ImageFeatureStore from cutie.model.cutie import CUTIE from cutie.utils.tensor_utils import pad_divide_by, unpad, aggregate import logging import numpy as np import torch import torch.nn.functional as F
11,894
""" if objects is None and mask is not None: assert not idx_mask objects = list(range(1, mask.shape[0] + 1)) # resize input if needed -- currently only used for the GUI resize_needed = False if self.max_internal_size > 0: h, w = image.shape[-2:] min_side = min(h, w) if min_side > self.max_internal_size: resize_needed = True new_h = int(h / min_side * self.max_internal_size) new_w = int(w / min_side * self.max_internal_size) image = F.interpolate(image.unsqueeze(0), size=(new_h, new_w), mode='bilinear', align_corners=False)[0] if mask is not None: if idx_mask: mask = F.interpolate(mask.unsqueeze(0).unsqueeze(0).float(), size=(new_h, new_w), mode='nearest', align_corners=False)[0, 0].round().long() else: mask = F.interpolate(mask.unsqueeze(0), size=(new_h, new_w), mode='bilinear', align_corners=False)[0] self.curr_ti += 1 image, self.pad = pad_divide_by(image, 16) image = image.unsqueeze(0) # add the batch dimension if self.flip_aug: image = torch.cat([image, torch.flip(image, dims=[-1])], dim=0) # whether to update the working memory is_mem_frame = ((self.curr_ti - self.last_mem_ti >= self.mem_every) or (mask is not None)) and (not end) # segment when there is no input mask or when the input mask is incomplete need_segment = (mask is None) or (self.object_manager.num_obj > 0 and not self.object_manager.has_all(objects)) update_sensory = ((self.curr_ti - self.last_mem_ti) in self.stagger_ti) and (not end) # encoding the image ms_feat, pix_feat = self.image_feature_store.get_features(self.curr_ti, image) key, shrinkage, selection = self.image_feature_store.get_key(self.curr_ti, image) # segmentation from memory if needed if need_segment: pred_prob_with_bg = self._segment(key, selection, pix_feat, ms_feat, update_sensory=update_sensory) # use the input mask if provided if mask is not None: # inform the manager of the new objects, and get a list of temporary id # temporary ids -- indicates the position of objects in the tensor # (starts with 1 due to the background channel) corresponding_tmp_ids, _ = self.object_manager.add_new_objects(objects) mask, _ = pad_divide_by(mask, 16) if need_segment: # merge predicted mask with the incomplete input mask pred_prob_no_bg = pred_prob_with_bg[1:] # use the mutual exclusivity of segmentation if idx_mask: pred_prob_no_bg[:, mask > 0] = 0 else: pred_prob_no_bg[:, mask.max(0) > 0.5] = 0 new_masks = [] for mask_id, tmp_id in enumerate(corresponding_tmp_ids): if idx_mask: this_mask = (mask == objects[mask_id]).type_as(pred_prob_no_bg) else: this_mask = mask[tmp_id] if tmp_id > pred_prob_no_bg.shape[0]: new_masks.append(this_mask.unsqueeze(0)) else: # +1 for padding the background channel pred_prob_no_bg[tmp_id - 1] = this_mask # new_masks are always in the order of tmp_id mask = torch.cat([pred_prob_no_bg, *new_masks], dim=0) elif idx_mask: # simply convert cls to one-hot representation if len(objects) == 0: if delete_buffer: self.image_feature_store.delete(self.curr_ti) log.warn('Trying to insert an empty mask as memory!') return torch.zeros((1, key.shape[-2] * 16, key.shape[-1] * 16), device=key.device, dtype=key.dtype) mask = torch.stack( [mask == objects[mask_id] for mask_id, _ in enumerate(corresponding_tmp_ids)], dim=0) pred_prob_with_bg = aggregate(mask, dim=0) pred_prob_with_bg = torch.softmax(pred_prob_with_bg, dim=0) self.last_mask = pred_prob_with_bg[1:].unsqueeze(0) if self.flip_aug: self.last_mask = torch.cat( [self.last_mask, torch.flip(self.last_mask, dims=[-1])], dim=0) # save as memory if needed if is_mem_frame or force_permanent: self._add_memory(image, pix_feat, self.last_mask, key, shrinkage, selection, force_permanent=force_permanent) if delete_buffer: self.image_feature_store.delete(self.curr_ti)
log = logging.getLogger() class InferenceCore: def __init__(self, network: CUTIE, cfg: DictConfig, *, image_feature_store: ImageFeatureStore = None): self.network = network self.cfg = cfg self.mem_every = cfg.mem_every stagger_updates = cfg.stagger_updates self.chunk_size = cfg.chunk_size self.save_aux = cfg.save_aux self.max_internal_size = cfg.max_internal_size self.flip_aug = cfg.flip_aug self.curr_ti = -1 self.last_mem_ti = 0 # at which time indices should we update the sensory memory if stagger_updates >= self.mem_every: self.stagger_ti = set(range(1, self.mem_every + 1)) else: self.stagger_ti = set( np.round(np.linspace(1, self.mem_every, stagger_updates)).astype(int)) self.object_manager = ObjectManager() self.memory = MemoryManager(cfg=cfg, object_manager=self.object_manager) if image_feature_store is None: self.image_feature_store = ImageFeatureStore(self.network) else: self.image_feature_store = image_feature_store self.last_mask = None def clear_memory(self): self.curr_ti = -1 self.last_mem_ti = 0 self.memory = MemoryManager(cfg=self.cfg, object_manager=self.object_manager) def clear_non_permanent_memory(self): self.curr_ti = -1 self.last_mem_ti = 0 self.memory.clear_non_permanent_memory() def clear_sensory_memory(self): self.curr_ti = -1 self.last_mem_ti = 0 self.memory.clear_sensory_memory() def update_config(self, cfg): self.mem_every = cfg['mem_every'] self.memory.update_config(cfg) def _add_memory(self, image: torch.Tensor, pix_feat: torch.Tensor, prob: torch.Tensor, key: torch.Tensor, shrinkage: torch.Tensor, selection: torch.Tensor, *, is_deep_update: bool = True, force_permanent: bool = False) -> None: """ Memorize the given segmentation in all memory stores. The batch dimension is 1 if flip augmentation is not used. image: RGB image, (1/2)*3*H*W pix_feat: from the key encoder, (1/2)*_*H*W prob: (1/2)*num_objects*H*W, in [0, 1] key/shrinkage/selection: for anisotropic l2, (1/2)*_*H*W selection can be None if not using long-term memory is_deep_update: whether to use deep update (e.g. with the mask encoder) force_permanent: whether to force the memory to be permanent """ if prob.shape[1] == 0: # nothing to add log.warn('Trying to add an empty object mask to memory!') return if force_permanent: as_permanent = 'all' else: as_permanent = 'first' self.memory.initialize_sensory_if_needed(key, self.object_manager.all_obj_ids) msk_value, sensory, obj_value, self.obj_logits = self.network.encode_mask( image, pix_feat, self.memory.get_sensory(self.object_manager.all_obj_ids), prob, deep_update=is_deep_update, chunk_size=self.chunk_size, need_weights=self.save_aux) self.memory.add_memory(key, shrinkage, msk_value, obj_value, self.object_manager.all_obj_ids, selection=selection, as_permanent=as_permanent) self.last_mem_ti = self.curr_ti if is_deep_update: self.memory.update_sensory(sensory, self.object_manager.all_obj_ids) def _segment(self, key: torch.Tensor, selection: torch.Tensor, pix_feat: torch.Tensor, ms_features: Iterable[torch.Tensor], update_sensory: bool = True) -> torch.Tensor: """ Produce a segmentation using the given features and the memory The batch dimension is 1 if flip augmentation is not used. key/selection: for anisotropic l2: (1/2) * _ * H * W pix_feat: from the key encoder, (1/2) * _ * H * W ms_features: an iterable of multiscale features from the encoder, each is (1/2)*_*H*W with strides 16, 8, and 4 respectively update_sensory: whether to update the sensory memory Returns: (num_objects+1)*H*W normalized probability; the first channel is the background """ bs = key.shape[0] if self.flip_aug: assert bs == 2 else: assert bs == 1 if not self.memory.engaged: log.warn('Trying to segment without any memory!') return torch.zeros((1, key.shape[-2] * 16, key.shape[-1] * 16), device=key.device, dtype=key.dtype) memory_readout = self.memory.read(pix_feat, key, selection, self.last_mask, self.network) memory_readout = self.object_manager.realize_dict(memory_readout) sensory, _, pred_prob_with_bg = self.network.segment(ms_features, memory_readout, self.memory.get_sensory( self.object_manager.all_obj_ids), chunk_size=self.chunk_size, update_sensory=update_sensory) # remove batch dim if self.flip_aug: # average predictions of the non-flipped and flipped version pred_prob_with_bg = (pred_prob_with_bg[0] + torch.flip(pred_prob_with_bg[1], dims=[-1])) / 2 else: pred_prob_with_bg = pred_prob_with_bg[0] if update_sensory: self.memory.update_sensory(sensory, self.object_manager.all_obj_ids) return pred_prob_with_bg def step(self, image: torch.Tensor, mask: Optional[torch.Tensor] = None, objects: Optional[List[int]] = None, *, idx_mask: bool = True, end: bool = False, delete_buffer: bool = True, force_permanent: bool = False) -> torch.Tensor: """ Take a step with a new incoming image. If there is an incoming mask with new objects, we will memorize them. If there is no incoming mask, we will segment the image using the memory. In both cases, we will update the memory and return a segmentation. image: 3*H*W mask: H*W (if idx mask) or len(objects)*H*W or None objects: list of object ids that are valid in the mask Tensor. The ids themselves do not need to be consecutive/in order, but they need to be in the same position in the list as the corresponding mask in the tensor in non-idx-mask mode. objects is ignored if the mask is None. If idx_mask is False and objects is None, we sequentially infer the object ids. idx_mask: if True, mask is expected to contain an object id at every pixel. If False, mask should have multiple channels with each channel representing one object. end: if we are at the end of the sequence, we do not need to update memory if unsure just set it to False delete_buffer: whether to delete the image feature buffer after this step force_permanent: the memory recorded this frame will be added to the permanent memory """ if objects is None and mask is not None: assert not idx_mask objects = list(range(1, mask.shape[0] + 1)) # resize input if needed -- currently only used for the GUI resize_needed = False if self.max_internal_size > 0: h, w = image.shape[-2:] min_side = min(h, w) if min_side > self.max_internal_size: resize_needed = True new_h = int(h / min_side * self.max_internal_size) new_w = int(w / min_side * self.max_internal_size) image = F.interpolate(image.unsqueeze(0), size=(new_h, new_w), mode='bilinear', align_corners=False)[0] if mask is not None: if idx_mask: mask = F.interpolate(mask.unsqueeze(0).unsqueeze(0).float(), size=(new_h, new_w), mode='nearest', align_corners=False)[0, 0].round().long() else: mask = F.interpolate(mask.unsqueeze(0), size=(new_h, new_w), mode='bilinear', align_corners=False)[0] self.curr_ti += 1 image, self.pad = pad_divide_by(image, 16) image = image.unsqueeze(0) # add the batch dimension if self.flip_aug: image = torch.cat([image, torch.flip(image, dims=[-1])], dim=0) # whether to update the working memory is_mem_frame = ((self.curr_ti - self.last_mem_ti >= self.mem_every) or (mask is not None)) and (not end) # segment when there is no input mask or when the input mask is incomplete need_segment = (mask is None) or (self.object_manager.num_obj > 0 and not self.object_manager.has_all(objects)) update_sensory = ((self.curr_ti - self.last_mem_ti) in self.stagger_ti) and (not end) # encoding the image ms_feat, pix_feat = self.image_feature_store.get_features(self.curr_ti, image) key, shrinkage, selection = self.image_feature_store.get_key(self.curr_ti, image) # segmentation from memory if needed if need_segment: pred_prob_with_bg = self._segment(key, selection, pix_feat, ms_feat, update_sensory=update_sensory) # use the input mask if provided if mask is not None: # inform the manager of the new objects, and get a list of temporary id # temporary ids -- indicates the position of objects in the tensor # (starts with 1 due to the background channel) corresponding_tmp_ids, _ = self.object_manager.add_new_objects(objects) mask, _ = pad_divide_by(mask, 16) if need_segment: # merge predicted mask with the incomplete input mask pred_prob_no_bg = pred_prob_with_bg[1:] # use the mutual exclusivity of segmentation if idx_mask: pred_prob_no_bg[:, mask > 0] = 0 else: pred_prob_no_bg[:, mask.max(0) > 0.5] = 0 new_masks = [] for mask_id, tmp_id in enumerate(corresponding_tmp_ids): if idx_mask: this_mask = (mask == objects[mask_id]).type_as(pred_prob_no_bg) else: this_mask = mask[tmp_id] if tmp_id > pred_prob_no_bg.shape[0]: new_masks.append(this_mask.unsqueeze(0)) else: # +1 for padding the background channel pred_prob_no_bg[tmp_id - 1] = this_mask # new_masks are always in the order of tmp_id mask = torch.cat([pred_prob_no_bg, *new_masks], dim=0) elif idx_mask: # simply convert cls to one-hot representation if len(objects) == 0: if delete_buffer: self.image_feature_store.delete(self.curr_ti) log.warn('Trying to insert an empty mask as memory!') return torch.zeros((1, key.shape[-2] * 16, key.shape[-1] * 16), device=key.device, dtype=key.dtype) mask = torch.stack( [mask == objects[mask_id] for mask_id, _ in enumerate(corresponding_tmp_ids)], dim=0) pred_prob_with_bg = aggregate(mask, dim=0) pred_prob_with_bg = torch.softmax(pred_prob_with_bg, dim=0) self.last_mask = pred_prob_with_bg[1:].unsqueeze(0) if self.flip_aug: self.last_mask = torch.cat( [self.last_mask, torch.flip(self.last_mask, dims=[-1])], dim=0) # save as memory if needed if is_mem_frame or force_permanent: self._add_memory(image, pix_feat, self.last_mask, key, shrinkage, selection, force_permanent=force_permanent) if delete_buffer: self.image_feature_store.delete(self.curr_ti)
output_prob = unpad(pred_prob_with_bg, self.pad)
5
2023-10-19 17:49:24+00:00
16k
stanford-oval/WikiChat
benchmark/scripts/user_simulator.py
[ { "identifier": "DialogueTurn", "path": "pipelines/dialog_turn.py", "snippet": "class DialogueTurn:\n def __init__(\n self,\n agent_utterance: str = None,\n user_utterance: str = None,\n pipeline: str = None,\n engine: str = None,\n generate_engine: str = Non...
import argparse import logging import json import random import spacy import sys from typing import List from functools import partial from tqdm.contrib.concurrent import thread_map from tqdm.contrib.logging import logging_redirect_tqdm from pipelines.dialog_turn import DialogueTurn from pipelines.chatbot import Chatbot from pipelines.pipeline_arguments import ( add_pipeline_arguments, check_pipeline_arguments, ) from pipelines.utils import make_parent_directories from llm.llm_generate import ( llm_generate, write_prompt_logs_to_file, ) from llm.global_variables import set_debug_mode, get_total_cost
13,156
""" Uses an LLM to talk to our pipelines. Used for evaluation and model distillation. """ sys.path.insert(0, "./") logging.getLogger("openai").setLevel(logging.ERROR) logger = logging.getLogger(__name__) spacy_nlp = spacy.load("en_core_web_sm") user_characteristics = [ "- Ask interesting follow-up questions when needed, and expand on the chatbot's responses using your life experiences.\n- Never volunteer information, and never correct chatbot's mistakes.", # "- You are adversarially stress-testing the chatbot.\n- Never volunteer information, and never correct chatbot's mistakes.", # "- You switch to other topics whenever possible.\n- Keep your inputs short.", # "- Ask interesting follow-up questions when needed.", # "- Ask interesting questions about the recent things that happened about the topic.\n- Never volunteer information, and never correct chatbot's mistakes.", # "- Always disagree with what the chatbot says.", ] def user_simulate_topic( dlg_history, topic, user_character, user_engine, user_temperature ): return llm_generate( template_file="benchmark/prompts/user_with_topic.prompt", prompt_parameter_values={ "dlg": dlg_history, "topic": topic, "user_character": user_character, }, engine=user_engine, max_tokens=60, temperature=user_temperature, stop_tokens=["\n"], top_p=0.5, frequency_penalty=0.0, presence_penalty=0, postprocess=True, ) def user_simulate_passage( dlg_history, title_and_passage, user_character, user_engine, user_temperature ): title, passage = title_and_passage return llm_generate( template_file="benchmark/prompts/user_with_passage.prompt", prompt_parameter_values={ "dlg": dlg_history, "title": title, "passage": passage, "user_character": user_character, }, engine=user_engine, max_tokens=60, temperature=user_temperature, stop_tokens=["\n"], top_p=0.9, frequency_penalty=0.0, presence_penalty=0, postprocess=True, ) def simulate_dialog(dialog_inputs, chatbot, args): """ Simulate one dialog """ dlg_history: List[DialogueTurn] = [] user_character = random.choice(user_characteristics) if args.mode == "topic": user_func = user_simulate_topic elif args.mode == "passage": user_func = user_simulate_passage try: for _ in range(args.num_turns): user_utterance = user_func( dlg_history, dialog_inputs, user_character, args.user_engine, args.user_temperature, ) if user_utterance == "": logger.error("Simulated user utterance is empty.") return None # logger.info('simulate user utterance: %s', user_utterance) new_dlg_turn = chatbot.generate_next_turn( dlg_history, user_utterance, pipeline=args.pipeline ) # logger.info('agent response = %s', new_dlg_turn.agent_utterance) dlg_history.append(new_dlg_turn) return dlg_history except Exception: logger.exception( "Skipping dialog due to exception. dialog_inputs=%s", str(dialog_inputs) ) def repeat_dialog_inputs(dialog_inputs, target_num_dialogs): """ repeats dialog_inputs if we don't have enough of them, truncates if there are too many """ if target_num_dialogs == -1: target_num_dialogs = len(dialog_inputs) full_rounds = target_num_dialogs // len(dialog_inputs) dialog_inputs = ( dialog_inputs * full_rounds + dialog_inputs[: target_num_dialogs % len(dialog_inputs)] ) assert len(dialog_inputs) == target_num_dialogs return dialog_inputs def main(args):
""" Uses an LLM to talk to our pipelines. Used for evaluation and model distillation. """ sys.path.insert(0, "./") logging.getLogger("openai").setLevel(logging.ERROR) logger = logging.getLogger(__name__) spacy_nlp = spacy.load("en_core_web_sm") user_characteristics = [ "- Ask interesting follow-up questions when needed, and expand on the chatbot's responses using your life experiences.\n- Never volunteer information, and never correct chatbot's mistakes.", # "- You are adversarially stress-testing the chatbot.\n- Never volunteer information, and never correct chatbot's mistakes.", # "- You switch to other topics whenever possible.\n- Keep your inputs short.", # "- Ask interesting follow-up questions when needed.", # "- Ask interesting questions about the recent things that happened about the topic.\n- Never volunteer information, and never correct chatbot's mistakes.", # "- Always disagree with what the chatbot says.", ] def user_simulate_topic( dlg_history, topic, user_character, user_engine, user_temperature ): return llm_generate( template_file="benchmark/prompts/user_with_topic.prompt", prompt_parameter_values={ "dlg": dlg_history, "topic": topic, "user_character": user_character, }, engine=user_engine, max_tokens=60, temperature=user_temperature, stop_tokens=["\n"], top_p=0.5, frequency_penalty=0.0, presence_penalty=0, postprocess=True, ) def user_simulate_passage( dlg_history, title_and_passage, user_character, user_engine, user_temperature ): title, passage = title_and_passage return llm_generate( template_file="benchmark/prompts/user_with_passage.prompt", prompt_parameter_values={ "dlg": dlg_history, "title": title, "passage": passage, "user_character": user_character, }, engine=user_engine, max_tokens=60, temperature=user_temperature, stop_tokens=["\n"], top_p=0.9, frequency_penalty=0.0, presence_penalty=0, postprocess=True, ) def simulate_dialog(dialog_inputs, chatbot, args): """ Simulate one dialog """ dlg_history: List[DialogueTurn] = [] user_character = random.choice(user_characteristics) if args.mode == "topic": user_func = user_simulate_topic elif args.mode == "passage": user_func = user_simulate_passage try: for _ in range(args.num_turns): user_utterance = user_func( dlg_history, dialog_inputs, user_character, args.user_engine, args.user_temperature, ) if user_utterance == "": logger.error("Simulated user utterance is empty.") return None # logger.info('simulate user utterance: %s', user_utterance) new_dlg_turn = chatbot.generate_next_turn( dlg_history, user_utterance, pipeline=args.pipeline ) # logger.info('agent response = %s', new_dlg_turn.agent_utterance) dlg_history.append(new_dlg_turn) return dlg_history except Exception: logger.exception( "Skipping dialog due to exception. dialog_inputs=%s", str(dialog_inputs) ) def repeat_dialog_inputs(dialog_inputs, target_num_dialogs): """ repeats dialog_inputs if we don't have enough of them, truncates if there are too many """ if target_num_dialogs == -1: target_num_dialogs = len(dialog_inputs) full_rounds = target_num_dialogs // len(dialog_inputs) dialog_inputs = ( dialog_inputs * full_rounds + dialog_inputs[: target_num_dialogs % len(dialog_inputs)] ) assert len(dialog_inputs) == target_num_dialogs return dialog_inputs def main(args):
chatbot = Chatbot(args)
1
2023-10-19 18:17:25+00:00
16k
jhejna/cpl
research/algs/off_policy_algorithm.py
[ { "identifier": "ReplayBuffer", "path": "research/datasets/replay_buffer/buffer.py", "snippet": "class ReplayBuffer(torch.utils.data.IterableDataset):\n \"\"\"\n Generic Replay Buffer Class.\n\n This class adheres to the following conventions to support multiprocessing:\n 1. Variables/functi...
import datetime import functools import os import sys import tempfile import gym import numpy as np import torch from abc import abstractmethod from typing import Any, Dict, Optional, Union from research.datasets import ReplayBuffer from research.datasets.replay_buffer import storage from research.envs.base import EmptyEnv from research.networks.base import ModuleContainer from research.utils import runners, utils from .base import Algorithm from research.utils.config import Config
12,280
elif isinstance(self.processor.action_space, gym.spaces.Discrete): logits = dist.logits if isinstance(dist, torch.distributions.Categorical) else dist if sample: action = torch.distributions.Categorical(logits=logits / temperature).sample() else: action = logits.argmax(dim=-1) return action else: raise ValueError("Complex action_space incompatible with default _predict.") def _off_policy_collector_subprocess( env_fn, queue, config_path: str, checkpoint_path: str, storage_path: str, exclude_keys: Optional[Optional[list]] = None, device: Union[str, torch.device] = "auto", random_steps: int = 0, total_steps: int = 0, ): """ This subprocess loads a train environemnt. It then collects episodes with a loaded policy and saves them to disk. Afterwards, we check to see if there is an updated policy that we can use. """ try: env = env_fn() # Load the model config = Config.load(config_path) config = config.parse() model = config.get_model(observation_space=env.observation_space, action_space=env.action_space, device=device) model.eval() # Compute the buffer space buffer_space = { "obs": env.observation_space, "action": env.action_space, "reward": 0.0, "done": False, "discount": 1.0, } exclude_keys = [] if exclude_keys is None else exclude_keys flattened_buffer_space = utils.flatten_dict(buffer_space) for k in exclude_keys: del flattened_buffer_space[k] def make_dummy_transition(obs): return { "obs": obs, "action": env.action_space.sample(), "reward": 0.0, "discount": 1.0, "done": False, } # Metrics: num_ep = 0 env_steps = 0 current_checkpoint = None # Get the evaluation function. while True: # First, look for a checkpoint. checkpoints = os.listdir(checkpoint_path) if len(checkpoints) > 0: # Sort the the checkpoints by path checkpoints = sorted(checkpoints, key=lambda x: int(x[:-3])) checkpoints = [os.path.join(checkpoint_path, checkpoint) for checkpoint in checkpoints] if checkpoints[-1] != current_checkpoint and os.path.getsize(checkpoints[-1]) > 0: try: _ = model.load(checkpoints[-1]) # load the most recent one # Remove all checkpoints that are not equal to the current one. current_checkpoint = checkpoints[-1] for checkpoint in checkpoints[:-1]: # Ignore the last checkpoint, we loaded it. os.remove(checkpoint) except (EOFError, RuntimeError): _ = model.load(current_checkpoint) # Then, collect an episode current_ep = {k: list() for k in flattened_buffer_space.keys()} current_ep = utils.nest_dict(current_ep) obs = env.reset() utils.append(current_ep, make_dummy_transition(obs)) done = False while not done: if env_steps < random_steps: action = env.action_space.sample() else: with torch.no_grad(): action = model._get_train_action(obs, env_steps, total_steps) obs, reward, done, info = env.step(action) env_steps += 1 if "discount" in info: discount = info["discount"] elif hasattr(env, "_max_episode_steps") and len(current_ep["done"]) - 1 == env._max_episode_steps: discount = 1.0 else: discount = 1 - float(done) transition = dict(obs=obs, action=action, reward=reward, done=done, discount=discount) utils.append(current_ep, transition) # The episode has terminated. num_ep += 1 metrics = dict( steps=env_steps, reward=np.sum(current_ep["reward"]), length=len(current_ep["done"]) - 1, num_ep=num_ep ) queue.put(metrics) # Timestamp it and add the ep idx (num ep - 1 so we start at zero.) ts = datetime.datetime.now().strftime("%Y%m%dT%H%M%S") ep_len = len(current_ep["done"]) ep_filename = f"{ts}_{num_ep - 1}_{ep_len}.npz"
class OffPolicyAlgorithm(Algorithm): def __init__( self, *args, offline_steps: int = 0, # Run fully offline by setting to -1 random_steps: int = 1000, async_runner_ep_lag: int = 1, **kwargs, ): super().__init__(*args, **kwargs) self.offline_steps = offline_steps self.random_steps = random_steps self.async_runner_ep_lag = async_runner_ep_lag def setup_datasets(self, env: gym.Env, total_steps: int): super().setup_datasets(env, total_steps) # Assign the correct update function based on what is passed in. if env is None or isinstance(env, EmptyEnv) or self.offline_steps < 0: self.env_step = self._empty_step elif isinstance(env, runners.AsyncEnv): self._episode_reward = 0 self._episode_length = 0 self._num_ep = 0 self._env_steps = 0 self._resetting = True env.reset_send() # Ask the env to start resetting. self.env_step = self._async_env_step elif isinstance(env, runners.MPRunner): assert isinstance(self.dataset, ReplayBuffer), "must use replaybuffer for MP RUnner." assert self.dataset.distributed, "ReplayBuffer must be distributed for use with Fully MPRunner." # Launch the runner subprocess. self._eps_since_last_checkpoint = 0 self._checkpoint_dir = tempfile.mkdtemp(prefix="checkpoints_") assert self.offline_steps <= 0, "MPRunner does not currently support offline to online." env.start( fn=_off_policy_collector_subprocess, checkpoint_path=self._checkpoint_dir, storage_path=self.dataset.storage_path, random_steps=self.random_steps, exclude_keys=self.dataset.exclude_keys, total_steps=total_steps, ) self.env_step = self._runner_env_step elif isinstance(env, gym.Env): # Setup Env Metrics self._current_obs = env.reset() self._episode_reward = 0 self._episode_length = 0 self._num_ep = 0 self._env_steps = 0 # Note that currently the very first (s, a) pair is thrown away because # we don't add to the dataset here. # This was done for better compatibility for offline to online learning. self.dataset.add(obs=self._current_obs) # add the first observation. self.env_step = self._env_step else: raise ValueError("Invalid env passed") def _empty_step(self, env: gym.Env, step: int, total_steps: int) -> Dict: return dict() def _env_step(self, env: gym.Env, step: int, total_steps: int) -> Dict: # Return if env is Empty or we we aren't at every env_freq steps if step <= self.offline_steps: # Purposefully set to nan so we write CSV log. return dict(steps=self._env_steps, reward=-np.inf, length=np.inf, num_ep=self._num_ep) if step < self.random_steps: action = env.action_space.sample() else: self.eval() action = self._get_train_action(self._current_obs, step, total_steps) self.train() if isinstance(env.action_space, gym.spaces.Box): action = np.clip(action, env.action_space.low, env.action_space.high) next_obs, reward, done, info = env.step(action) self._env_steps += 1 self._episode_length += 1 self._episode_reward += reward if "discount" in info: discount = info["discount"] elif hasattr(env, "_max_episode_steps") and self._episode_length == env._max_episode_steps: discount = 1.0 else: discount = 1 - float(done) # Store the consequences. self.dataset.add(obs=next_obs, action=action, reward=reward, done=done, discount=discount) if done: self._num_ep += 1 # Compute metrics metrics = dict( steps=self._env_steps, reward=self._episode_reward, length=self._episode_length, num_ep=self._num_ep ) # Reset the environment self._current_obs = env.reset() self.dataset.add(obs=self._current_obs) # Add the first timestep self._episode_length = 0 self._episode_reward = 0 return metrics else: self._current_obs = next_obs return dict(steps=self._env_steps) def _async_env_step(self, env: gym.Env, step: int, total_steps: int) -> Dict: # Recieve Data from the last step and add to buffer. Should only call recv! if self._resetting: self._current_obs = env.reset_recv() self._num_ep += 1 self._episode_length = 0 self._episode_reward = 0 self.dataset.add(obs=self._current_obs) self._resetting = False done = False else: self._current_obs, reward, done, info = env.step_recv() self._env_steps += 1 self._episode_length += 1 self._episode_reward += reward self.dataset.add( obs=self._current_obs, action=self._current_action, reward=reward, done=done, discount=info["discount"] ) # Send data for the next step and return metrics. Should only call send! if done: # If the episode terminated, then we need to reset and send the reset message self._resetting = True env.reset_send() return dict( steps=self._env_steps, reward=self._episode_reward, length=self._episode_length, num_ep=self._num_ep ) else: # Otherwise, compute the action we should take and send it. self._resetting = False if step < self.random_steps: self._current_action = env.action_space.sample() else: self.eval() self._current_action = self._get_train_action(self._current_obs, step, total_steps) self.train() if isinstance(env.action_space, gym.spaces.Box): self._current_action = np.clip(self._current_action, env.action_space.low, env.action_space.high) env.step_send(self._current_action) return dict(steps=self._env_steps) def _runner_env_step(self, env: gym.Env, step: int, total_steps: int) -> Dict: # All we do is check the pipe to see if there is data! metrics = env() if len(metrics) > 0: # If the metrics are non-empty, then it means that we have completed an episode. # As such, decrement the counter self._eps_since_last_checkpoint += 1 if self._eps_since_last_checkpoint == self.async_runner_ep_lag: self.save(self._checkpoint_dir, str(step), dict(step=step)) self._eps_since_last_checkpoint = 0 return metrics @abstractmethod def _get_train_action(self, obs: Any, step: int, total_steps: int) -> np.ndarray: raise NotImplementedError @functools.cached_property def action_range(self): action_range = (self.processor.action_space.low, self.processor.action_space.high) return utils.to_device(utils.to_tensor(action_range), self.device) def _predict( self, batch: Dict, sample: bool = False, noise: float = 0.0, noise_clip: Optional[float] = None, temperature=1.0 ) -> torch.Tensor: with torch.no_grad(): if isinstance(self.network, ModuleContainer) and "encoder" in self.network.CONTAINERS: obs = self.network.encoder(batch["obs"]) else: obs = batch["obs"] # Could be: Logits (discrete), Float (continuous), or torch Dist dist = self.network.actor(obs) if isinstance(self.processor.action_space, gym.spaces.Box): if isinstance(dist, torch.distributions.Independent): # Guassian Distribution action = dist.sample() if sample else dist.base_dist.loc elif isinstance(dist, torch.distributions.MixtureSameFamily): # Mixture of Gaussians. if sample: action = dist.sample() else: # Robomimic always samples from the Categorical, but then does the mixture deterministically. loc = dist.component_distribution.base_dist.loc category = dist.mixture_distribution.sample() # Expand to add Mixture Dim, Action Dim es = dist.component_distribution.event_shape mix_sample_r = category.reshape(category.shape + torch.Size([1] * (len(es) + 1))) mix_sample_r = mix_sample_r.repeat(torch.Size([1] * len(category.shape)) + torch.Size([1]) + es) action = torch.gather(loc, len(dist.batch_shape), mix_sample_r) action = action.squeeze(len(dist.batch_shape)) elif torch.is_tensor(dist): action = dist else: raise ValueError("Model output incompatible with default _predict.") if noise > 0.0: eps = noise * torch.randn_like(action) if noise_clip is not None: eps = torch.clamp(eps, -noise_clip, noise_clip) action = action + eps action = action.clamp(*self.action_range) return action elif isinstance(self.processor.action_space, gym.spaces.Discrete): logits = dist.logits if isinstance(dist, torch.distributions.Categorical) else dist if sample: action = torch.distributions.Categorical(logits=logits / temperature).sample() else: action = logits.argmax(dim=-1) return action else: raise ValueError("Complex action_space incompatible with default _predict.") def _off_policy_collector_subprocess( env_fn, queue, config_path: str, checkpoint_path: str, storage_path: str, exclude_keys: Optional[Optional[list]] = None, device: Union[str, torch.device] = "auto", random_steps: int = 0, total_steps: int = 0, ): """ This subprocess loads a train environemnt. It then collects episodes with a loaded policy and saves them to disk. Afterwards, we check to see if there is an updated policy that we can use. """ try: env = env_fn() # Load the model config = Config.load(config_path) config = config.parse() model = config.get_model(observation_space=env.observation_space, action_space=env.action_space, device=device) model.eval() # Compute the buffer space buffer_space = { "obs": env.observation_space, "action": env.action_space, "reward": 0.0, "done": False, "discount": 1.0, } exclude_keys = [] if exclude_keys is None else exclude_keys flattened_buffer_space = utils.flatten_dict(buffer_space) for k in exclude_keys: del flattened_buffer_space[k] def make_dummy_transition(obs): return { "obs": obs, "action": env.action_space.sample(), "reward": 0.0, "discount": 1.0, "done": False, } # Metrics: num_ep = 0 env_steps = 0 current_checkpoint = None # Get the evaluation function. while True: # First, look for a checkpoint. checkpoints = os.listdir(checkpoint_path) if len(checkpoints) > 0: # Sort the the checkpoints by path checkpoints = sorted(checkpoints, key=lambda x: int(x[:-3])) checkpoints = [os.path.join(checkpoint_path, checkpoint) for checkpoint in checkpoints] if checkpoints[-1] != current_checkpoint and os.path.getsize(checkpoints[-1]) > 0: try: _ = model.load(checkpoints[-1]) # load the most recent one # Remove all checkpoints that are not equal to the current one. current_checkpoint = checkpoints[-1] for checkpoint in checkpoints[:-1]: # Ignore the last checkpoint, we loaded it. os.remove(checkpoint) except (EOFError, RuntimeError): _ = model.load(current_checkpoint) # Then, collect an episode current_ep = {k: list() for k in flattened_buffer_space.keys()} current_ep = utils.nest_dict(current_ep) obs = env.reset() utils.append(current_ep, make_dummy_transition(obs)) done = False while not done: if env_steps < random_steps: action = env.action_space.sample() else: with torch.no_grad(): action = model._get_train_action(obs, env_steps, total_steps) obs, reward, done, info = env.step(action) env_steps += 1 if "discount" in info: discount = info["discount"] elif hasattr(env, "_max_episode_steps") and len(current_ep["done"]) - 1 == env._max_episode_steps: discount = 1.0 else: discount = 1 - float(done) transition = dict(obs=obs, action=action, reward=reward, done=done, discount=discount) utils.append(current_ep, transition) # The episode has terminated. num_ep += 1 metrics = dict( steps=env_steps, reward=np.sum(current_ep["reward"]), length=len(current_ep["done"]) - 1, num_ep=num_ep ) queue.put(metrics) # Timestamp it and add the ep idx (num ep - 1 so we start at zero.) ts = datetime.datetime.now().strftime("%Y%m%dT%H%M%S") ep_len = len(current_ep["done"]) ep_filename = f"{ts}_{num_ep - 1}_{ep_len}.npz"
storage.save_data(current_ep, os.path.join(storage_path, ep_filename))
1
2023-10-19 17:25:45+00:00
16k
nbasyl/LLM-FP4
configs/FPQ_config_llama.py
[ { "identifier": "FPPTQSLBatchingQuantLinear_fpq", "path": "quant_layers/fp_linear.py", "snippet": "class FPPTQSLBatchingQuantLinear_fpq(FPPTQSLQuantLinear):\n def __init__(self, \n in_features: int,\n out_features: int,\n bias: bool = True,\n mode = \"raw\",\n w_bit...
from quant_layers.fp_linear import FPPTQSLBatchingQuantLinear_fpq from quant_layers.fp_embed import FPPTQSLQuantEmbedding_fpq_baseline
11,186
bit = 8 exp_bit = 4 embed_name_list = ["qembedding"] fc_name_list = [ "qlinear_query", "qlinear_key", "qlinear_value", "qlinear_o","qlinear_gate","qlinear_down","qlinear_up","qlinear_score"] matmul_name_list = [ "qmatmul_qk", "qmatmul_scorev"] w_bit = {name: bit for name in fc_name_list} a_bit = {name: bit for name in fc_name_list} embed_bit = {name: bit for name in embed_name_list} A_bit = {name: bit for name in matmul_name_list} B_bit = {name: bit for name in matmul_name_list} w_exp_bit = {name: exp_bit for name in fc_name_list} a_exp_bit = {name: exp_bit for name in fc_name_list} embed_exp_bit = {name: exp_bit for name in embed_name_list} A_exp_bit = {name: exp_bit for name in matmul_name_list} B_exp_bit = {name: exp_bit for name in matmul_name_list} ptqsl_embedding_kwargs = { "metric": "L2_norm", "eq_alpha": 0.01, "eq_beta": 1.2, "eq_n": 100, 'search_round': 3, "n_V": 1, "n_H": 1 } ptqsl_linear_kwargs = { "metric": "L2_norm", "eq_alpha": 0.01, "eq_beta": 1.2, "eq_n": 100, 'search_round': 3, "n_V": 1, "n_H": 1, "n_a": 1, "bias_correction":True # Conventionally I'll not add an actual bias correction in linear } def get_module(module_type, *args, **kwargs): if "embedding" in module_type: kwargs.update(ptqsl_embedding_kwargs)
bit = 8 exp_bit = 4 embed_name_list = ["qembedding"] fc_name_list = [ "qlinear_query", "qlinear_key", "qlinear_value", "qlinear_o","qlinear_gate","qlinear_down","qlinear_up","qlinear_score"] matmul_name_list = [ "qmatmul_qk", "qmatmul_scorev"] w_bit = {name: bit for name in fc_name_list} a_bit = {name: bit for name in fc_name_list} embed_bit = {name: bit for name in embed_name_list} A_bit = {name: bit for name in matmul_name_list} B_bit = {name: bit for name in matmul_name_list} w_exp_bit = {name: exp_bit for name in fc_name_list} a_exp_bit = {name: exp_bit for name in fc_name_list} embed_exp_bit = {name: exp_bit for name in embed_name_list} A_exp_bit = {name: exp_bit for name in matmul_name_list} B_exp_bit = {name: exp_bit for name in matmul_name_list} ptqsl_embedding_kwargs = { "metric": "L2_norm", "eq_alpha": 0.01, "eq_beta": 1.2, "eq_n": 100, 'search_round': 3, "n_V": 1, "n_H": 1 } ptqsl_linear_kwargs = { "metric": "L2_norm", "eq_alpha": 0.01, "eq_beta": 1.2, "eq_n": 100, 'search_round': 3, "n_V": 1, "n_H": 1, "n_a": 1, "bias_correction":True # Conventionally I'll not add an actual bias correction in linear } def get_module(module_type, *args, **kwargs): if "embedding" in module_type: kwargs.update(ptqsl_embedding_kwargs)
module= FPPTQSLQuantEmbedding_fpq_baseline(*args,**kwargs,bit= embed_bit[module_type], exponent_bit=embed_exp_bit[module_type], padding_idx=0)
1
2023-10-15 06:05:13+00:00
16k
bcmi/libcom
libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "libcom/painterly_image_harmonization/source/PHDiffusion/ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n ...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import itertools from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from omegaconf import ListConfig from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.ema import LitEma from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.models.diffusion.ddim import DDIMSampler
12,452
c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out def decode_first_stage_training(self, z, predict_cids=False, force_not_quantize=False): # print('decoding...') # # def print_message(grad): # print('backward decoding') # # z.register_hook(print_message) if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c, **kwargs) return loss def get_time_with_schedule(self, scheduler, bs): if scheduler == 'linear': t = torch.randint(0, self.num_timesteps, (bs,), device=self.device).long() elif scheduler == 'cosine': t = torch.rand((bs, ), device=self.device) t = torch.cos(torch.pi / 2. * t) * self.num_timesteps t = t.long() elif scheduler == 'cubic': t = torch.rand((bs,), device=self.device) t = (1 - t ** 3) * self.num_timesteps t = t.long() else: raise NotImplementedError t = torch.clamp(t, min=0, max=self.num_timesteps-1) return t def forward(self, x,mask, c, *args, **kwargs): if 't' not in kwargs: t = torch.randint(0, self.num_timesteps, (x.shape[0], ), device=self.device).long() else: t = kwargs.pop('t') return self.p_losses(x,mask, c, t, *args, **kwargs) def apply_model(self, x_noisy, mask,t, cond, return_ids=False, **kwargs): if isinstance(cond, dict): # hybrid case, cond is expected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, mask,t, **cond, **kwargs) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=512, channels=3, log_every_t=100, clip_denoised=True, linear_start=0.00085, linear_end=0.012, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization # print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) # count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if reset_ema: assert exists(ckpt_path) if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) if reset_ema: assert self.use_ema print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=0.00085, linear_end=0.012, cosine_s=8e-3): linear_start = 0.00085 linear_end = 0.012 # if exists(given_betas): # betas = given_betas # else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) elif self.parameterization == "v": lvlb_weights = torch.ones_like(self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))) else: raise NotImplementedError("mu not supported") lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") @torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] if self.make_it_fit: n_params = len([name for name, _ in itertools.chain(self.named_parameters(), self.named_buffers())]) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys:\n {missing}") if len(unexpected) > 0: print(f"\nUnexpected Keys:\n {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def predict_start_from_z_and_v(self, x_t, t, v): # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def predict_eps_from_z_and_v(self, x_t, t, v): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_v(self, x, noise, t): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x ) def get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] # if len(x.shape) == 3: # x = x[..., None] # x = rearrange(x, 'b h w c -> b c h w') # x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, *args, **kwargs): self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__': conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) reset_ema = kwargs.pop("reset_ema", False) reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True if reset_ema: assert self.use_ema print( f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() def make_cond_schedule(self, ): self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=0.00085, linear_end=0.012, cosine_s=8e-3): linear_start = 0.00085 linear_end = 0.012 super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append(self.decode_first_stage(zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented") return self.scale_factor * z def get_learned_conditioning(self, c): if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip(L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"]) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox', "txt"]: xc = batch[cond_key] elif cond_key in ['class_label', 'cls']: xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): # import pudb; pudb.set_trace() c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out def decode_first_stage_training(self, z, predict_cids=False, force_not_quantize=False): # print('decoding...') # # def print_message(grad): # print('backward decoding') # # z.register_hook(print_message) if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c, **kwargs) return loss def get_time_with_schedule(self, scheduler, bs): if scheduler == 'linear': t = torch.randint(0, self.num_timesteps, (bs,), device=self.device).long() elif scheduler == 'cosine': t = torch.rand((bs, ), device=self.device) t = torch.cos(torch.pi / 2. * t) * self.num_timesteps t = t.long() elif scheduler == 'cubic': t = torch.rand((bs,), device=self.device) t = (1 - t ** 3) * self.num_timesteps t = t.long() else: raise NotImplementedError t = torch.clamp(t, min=0, max=self.num_timesteps-1) return t def forward(self, x,mask, c, *args, **kwargs): if 't' not in kwargs: t = torch.randint(0, self.num_timesteps, (x.shape[0], ), device=self.device).long() else: t = kwargs.pop('t') return self.p_losses(x,mask, c, t, *args, **kwargs) def apply_model(self, x_noisy, mask,t, cond, return_ids=False, **kwargs): if isinstance(cond, dict): # hybrid case, cond is expected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, mask,t, **cond, **kwargs) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
9
2023-10-19 05:08:12+00:00
16k
e4s2023/E4S2023
training/coach.py
[ { "identifier": "torch_utils", "path": "utils/torch_utils.py", "snippet": "def saveTensorToFile(tensor, save_path):\ndef interpolate(img, size):\ndef readImgAsTensor(img_path, gray=False, to_tensor=True, size=1024):\ndef featMap2im(var):\ndef tensor2im(var, is_zero_center: bool = True, ):\ndef im2tensor...
from utils import torch_utils from datasets.dataset import CelebAHQDataset, get_transforms, TO_TENSOR, NORMALIZE, MASK_CONVERT_TF, FFHQDataset, FFHQ_MASK_CONVERT_TF, MASK_CONVERT_TF_DETAILED, FFHQ_MASK_CONVERT_TF_DETAILED from criteria.w_norm import WNormLoss from criteria.id_loss import IDLoss from criteria.face_parsing.face_parsing_loss import FaceParsingLoss from criteria.lpips.lpips import LPIPS from criteria.adv_loss import AdvDLoss,AdvGLoss,DR1Loss,GPathRegularizer from criteria.style_loss import StyleLoss from training.ranger import Ranger from models.networks import Net, Net2, Net3, NetStage2,MultiScaleNet from tensorboardX import SummaryWriter from torch.utils.data import DataLoader from torch import nn from models.stylegan2.model import Generator,Discriminator from collections import OrderedDict from models.encoder_with_optim import EncoderPlusOptimNet import torchvision.transforms as transforms import torch.nn.functional as F import torch import os import matplotlib import matplotlib.pyplot as plt import torch.distributed as dist import math
11,811
matplotlib.use('Agg') # torch.autograd.set_detect_anomaly(True) ACCUM = 0.5 ** (32 / (100 * 1000)) # 0.9977843871238888 class Coach: def __init__(self, opts): self.opts = opts self.global_step = 0 # 分布式训练 if self.opts.dist_train: self.num_gpus = torch.cuda.device_count() self.rank = int(os.environ["RANK"]) self.world_size = int(os.environ["WORLD_SIZE"]) self.local_rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(self.rank % self.num_gpus) dist.init_process_group( backend='nccl', world_size=self.world_size, rank=self.rank, ) self.device = torch.device("cuda", self.local_rank) else: self.rank=0 # dummy rank self.device = torch.device("cuda", 0) self.opts.device=self.device # ==== Initialize network ==== self.net = Net3(self.opts) # print(self.device) self.net = nn.SyncBatchNorm.convert_sync_batchnorm(self.net) self.net = self.net.to(self.device) self.net_ema = Net3(self.opts).to(self.device).eval() torch_utils.accumulate(self.net_ema,self.net, 0) if self.opts.train_D:
matplotlib.use('Agg') # torch.autograd.set_detect_anomaly(True) ACCUM = 0.5 ** (32 / (100 * 1000)) # 0.9977843871238888 class Coach: def __init__(self, opts): self.opts = opts self.global_step = 0 # 分布式训练 if self.opts.dist_train: self.num_gpus = torch.cuda.device_count() self.rank = int(os.environ["RANK"]) self.world_size = int(os.environ["WORLD_SIZE"]) self.local_rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(self.rank % self.num_gpus) dist.init_process_group( backend='nccl', world_size=self.world_size, rank=self.rank, ) self.device = torch.device("cuda", self.local_rank) else: self.rank=0 # dummy rank self.device = torch.device("cuda", 0) self.opts.device=self.device # ==== Initialize network ==== self.net = Net3(self.opts) # print(self.device) self.net = nn.SyncBatchNorm.convert_sync_batchnorm(self.net) self.net = self.net.to(self.device) self.net_ema = Net3(self.opts).to(self.device).eval() torch_utils.accumulate(self.net_ema,self.net, 0) if self.opts.train_D:
self.D = Discriminator(self.opts.out_size).to(self.device).eval()
22
2023-10-15 12:15:01+00:00
16k
sotopia-lab/sotopia
examples/fix_missing_episodes.py
[ { "identifier": "LLMAgent", "path": "sotopia/agents/llm_agent.py", "snippet": "class LLMAgent(BaseAgent[Observation, AgentAction]):\n def __init__(\n self,\n agent_name: str | None = None,\n uuid_str: str | None = None,\n agent_profile: AgentProfile | None = None,\n ...
import asyncio import logging import gin from collections import Counter, defaultdict from typing import ( Any, Dict, Generator, List, Literal, Optional, Set, cast, ) from absl import flags from absl.flags import FLAGS from rich.logging import RichHandler from rich.terminal_theme import MONOKAI from tqdm import tqdm from sotopia.agents.llm_agent import LLMAgent from sotopia.database.env_agent_combo_storage import ( EnvAgentComboStorage, ) from sotopia.database.logs import EpisodeLog from sotopia.database.persistent_profile import ( AgentProfile, EnvironmentProfile, ) from sotopia.envs.evaluators import ( ReachGoalLLMEvaluator, RuleBasedTerminatedEvaluator, ) from sotopia.envs.parallel import ParallelSotopiaEnv from sotopia.generation_utils.generate import LLM_Name from sotopia.messages.message_classes import AgentAction, Observation from sotopia.samplers.base_sampler import BaseSampler, EnvAgentCombo from sotopia.server import run_async_server from sotopia_conf.gin_utils import parse_gin_flags, run from sotopia_conf.server import _DEFAULT_GIN_SEARCH_PATHS
12,884
bad_rewards_count += 1 if tuple(curr_ep.models) == ("gpt4", "gpt4", "gpt4"): bad_gpt4_rewards_count += 1 continue # find combo pk by env pk and agent ids curr_combo_pk = find_combo_pk( curr_ep.environment, curr_ep.agents[0], curr_ep.agents[1], all_combos_map, ) if curr_combo_pk: model_pair: tuple[LLM_Name, LLM_Name, LLM_Name] = cast( tuple[LLM_Name, LLM_Name, LLM_Name], tuple(curr_ep.models) ) combo_model_map[curr_combo_pk][model_pair] += 1 valid_count += 1 else: bad_combos.append( (curr_ep.environment, curr_ep.agents[0], curr_ep.agents[1]) ) bad_combo_count += 1 print("-" * 20 + "Episode Parsing Summary" + "-" * 20) print(f"valid episodes: {valid_count}") print(f"invalid episodes (missing episode.models): {invalid_count}") print(f"bad combo: {bad_combo_count}") print(f"bad rewards: {bad_rewards_count}") print(f"bad gpt4 rewards: {bad_gpt4_rewards_count}") return combo_model_map def get_all_model_pairs( combo_model_map: Dict[str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]]] ) -> Set[tuple[LLM_Name, LLM_Name, LLM_Name]]: all_model_pairs = set() for key in combo_model_map: for combo in combo_model_map[key]: all_model_pairs.add(combo) # print all model pairs print("-" * 20 + "All Model Pairs" + "-" * 20) for pair in all_model_pairs: print(pair) print() return all_model_pairs def get_all_missing_model_pairs( combo_model_map: Dict[str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]]], all_model_pairs: Set[tuple[LLM_Name, LLM_Name, LLM_Name]], num_required: int, ) -> Dict[str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]]]: combo_missing_model_map: Dict[ str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]] ] = defaultdict(Counter) missing_count = 0 for key in combo_model_map: for model_pair in all_model_pairs: if combo_model_map[key][model_pair] < num_required: combo_missing_model_map[key][model_pair] += ( num_required - combo_model_map[key][model_pair] ) missing_count += ( num_required - combo_model_map[key][model_pair] ) print("-" * 20 + f"Missing {missing_count} Model Pairs" + "-" * 20) print() return combo_missing_model_map # temporally used for making sure unique (env, agents, models) setting; need to change # according to the Counter in the case needing to run multiple experiments for one setting def get_missing_model_combo_map( combo_missing_model_map: Dict[ str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]] ], all_combos_map: Dict[str, EnvAgentComboStorage], ) -> Dict[tuple[LLM_Name, LLM_Name], List[tuple[str, str, str]]]: missing_model_combo_map = defaultdict(list) for combo_pk in combo_missing_model_map: model_counter = combo_missing_model_map[combo_pk] for model_pair in model_counter: model_pair_key = (model_pair[1], model_pair[2]) combo_model = all_combos_map[combo_pk] missing_model_combo_map[model_pair_key].append( ( combo_model.env_id, combo_model.agent_ids[0], combo_model.agent_ids[1], ) ) print("-" * 20 + "Missing Model to Combo Map" + "-" * 20) for key in missing_model_combo_map: print(f"Model pair: {key}") print(f"Number of missing combos: {len(missing_model_combo_map[key])}") return missing_model_combo_map def yield_env_agent_combo( combo_ids: list[tuple[str, str, str]], model_names: dict[str, LLM_Name] ) -> Generator[EnvAgentCombo[Observation, AgentAction], None, None]: for combo_id in combo_ids: env_id, agent_id1, agent_id2 = combo_id env_profile = EnvironmentProfile.get(env_id) env = ParallelSotopiaEnv( env_profile=env_profile, model_name=model_names["env"], action_order="round-robin", evaluators=[ RuleBasedTerminatedEvaluator( max_turn_number=20, max_stale_turn=2 ), ], terminal_evaluators=[ ReachGoalLLMEvaluator(model_names["env"]), ], ) agent_profiles = [
# date and message only FORMAT = "%(asctime)s - %(levelname)s - %(name)s - %(message)s" logging.basicConfig( level=15, format=FORMAT, datefmt="[%X]", handlers=[ RichHandler(), ], ) # get all episode logs def get_all_episodes() -> List[EpisodeLog]: episode_pks: List[str] = list(EpisodeLog.all_pks()) all_episodes = [] for pk in tqdm(episode_pks): try: curr_ep = EpisodeLog.get(pk) except: continue all_episodes.append(curr_ep) print(f"all episodes loaded {len(all_episodes)}") return all_episodes # all env-agent combos def get_all_env_agent_combos( start_combo_idx: int, end_combo_idx: int ) -> Dict[str, EnvAgentComboStorage]: experiment_env_pks = list(EnvironmentProfile.all_pks()) all_combos_map: Dict[str, EnvAgentComboStorage] = {} for env_pk in experiment_env_pks: env_agent_combo_storage_list = list( EnvAgentComboStorage.find( EnvAgentComboStorage.env_id == env_pk ).all() )[start_combo_idx:end_combo_idx] for combo in env_agent_combo_storage_list: all_combos_map[cast(str, combo.pk)] = cast( EnvAgentComboStorage, combo ) print(f"all combos loaded {len(all_combos_map)}") return all_combos_map def find_combo_pk( env_pk: str, agent_id1: str, agent_id2: str, all_combos_map: Dict[str, EnvAgentComboStorage], ) -> str | None: for combo_key in all_combos_map: combo = all_combos_map[combo_key] curr_tuple = (combo.env_id, combo.agent_ids[0], combo.agent_ids[1]) if curr_tuple == (env_pk, agent_id1, agent_id2): return combo_key return None def get_combo_model_map( all_episodes: List[EpisodeLog], all_combos_map: Dict[str, EnvAgentComboStorage], ) -> Dict[str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]]]: combo_model_map: Dict[ str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]] ] = defaultdict(Counter) bad_combos = [] valid_count = 0 invalid_count = 0 bad_rewards_count = 0 bad_gpt4_rewards_count = 0 bad_combo_count = 0 # iterate through episodes for i in tqdm(range(len(all_episodes))): curr_ep = all_episodes[i] bad_rewards = False # check if episode is valid if not curr_ep.models: invalid_count += 1 continue # check if rewards are valid for idx, model in enumerate(curr_ep.models[1:]): if not isinstance(curr_ep.rewards[idx], tuple): bad_rewards = True break if bad_rewards: bad_rewards_count += 1 if tuple(curr_ep.models) == ("gpt4", "gpt4", "gpt4"): bad_gpt4_rewards_count += 1 continue # find combo pk by env pk and agent ids curr_combo_pk = find_combo_pk( curr_ep.environment, curr_ep.agents[0], curr_ep.agents[1], all_combos_map, ) if curr_combo_pk: model_pair: tuple[LLM_Name, LLM_Name, LLM_Name] = cast( tuple[LLM_Name, LLM_Name, LLM_Name], tuple(curr_ep.models) ) combo_model_map[curr_combo_pk][model_pair] += 1 valid_count += 1 else: bad_combos.append( (curr_ep.environment, curr_ep.agents[0], curr_ep.agents[1]) ) bad_combo_count += 1 print("-" * 20 + "Episode Parsing Summary" + "-" * 20) print(f"valid episodes: {valid_count}") print(f"invalid episodes (missing episode.models): {invalid_count}") print(f"bad combo: {bad_combo_count}") print(f"bad rewards: {bad_rewards_count}") print(f"bad gpt4 rewards: {bad_gpt4_rewards_count}") return combo_model_map def get_all_model_pairs( combo_model_map: Dict[str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]]] ) -> Set[tuple[LLM_Name, LLM_Name, LLM_Name]]: all_model_pairs = set() for key in combo_model_map: for combo in combo_model_map[key]: all_model_pairs.add(combo) # print all model pairs print("-" * 20 + "All Model Pairs" + "-" * 20) for pair in all_model_pairs: print(pair) print() return all_model_pairs def get_all_missing_model_pairs( combo_model_map: Dict[str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]]], all_model_pairs: Set[tuple[LLM_Name, LLM_Name, LLM_Name]], num_required: int, ) -> Dict[str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]]]: combo_missing_model_map: Dict[ str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]] ] = defaultdict(Counter) missing_count = 0 for key in combo_model_map: for model_pair in all_model_pairs: if combo_model_map[key][model_pair] < num_required: combo_missing_model_map[key][model_pair] += ( num_required - combo_model_map[key][model_pair] ) missing_count += ( num_required - combo_model_map[key][model_pair] ) print("-" * 20 + f"Missing {missing_count} Model Pairs" + "-" * 20) print() return combo_missing_model_map # temporally used for making sure unique (env, agents, models) setting; need to change # according to the Counter in the case needing to run multiple experiments for one setting def get_missing_model_combo_map( combo_missing_model_map: Dict[ str, Counter[tuple[LLM_Name, LLM_Name, LLM_Name]] ], all_combos_map: Dict[str, EnvAgentComboStorage], ) -> Dict[tuple[LLM_Name, LLM_Name], List[tuple[str, str, str]]]: missing_model_combo_map = defaultdict(list) for combo_pk in combo_missing_model_map: model_counter = combo_missing_model_map[combo_pk] for model_pair in model_counter: model_pair_key = (model_pair[1], model_pair[2]) combo_model = all_combos_map[combo_pk] missing_model_combo_map[model_pair_key].append( ( combo_model.env_id, combo_model.agent_ids[0], combo_model.agent_ids[1], ) ) print("-" * 20 + "Missing Model to Combo Map" + "-" * 20) for key in missing_model_combo_map: print(f"Model pair: {key}") print(f"Number of missing combos: {len(missing_model_combo_map[key])}") return missing_model_combo_map def yield_env_agent_combo( combo_ids: list[tuple[str, str, str]], model_names: dict[str, LLM_Name] ) -> Generator[EnvAgentCombo[Observation, AgentAction], None, None]: for combo_id in combo_ids: env_id, agent_id1, agent_id2 = combo_id env_profile = EnvironmentProfile.get(env_id) env = ParallelSotopiaEnv( env_profile=env_profile, model_name=model_names["env"], action_order="round-robin", evaluators=[ RuleBasedTerminatedEvaluator( max_turn_number=20, max_stale_turn=2 ), ], terminal_evaluators=[ ReachGoalLLMEvaluator(model_names["env"]), ], ) agent_profiles = [
AgentProfile.get(id) for id in (agent_id1, agent_id2)
3
2023-10-23 19:47:26+00:00
16k
uukuguy/multi_loras
multi_loras/slora/router/manager.py
[ { "identifier": "SamplingParams", "path": "multi_loras/slora/sampling_params.py", "snippet": "class SamplingParams:\n\n def __init__(\n self,\n do_sample: bool = False,\n presence_penalty: float = 0.0,\n frequency_penalty: float = 0.0,\n temperature: float = 1.0,\n ...
import uvloop import asyncio import os import pickle import time import torch import zmq import zmq.asyncio import traceback from typing import Dict, List, Optional from rpyc.utils.classic import obtain from slora.utils.infer_utils import calculate_time from ..sampling_params import SamplingParams from ..io_struct import Req, Batch, BatchAbortReq, BatchTokenIdOut, AbortReq from .input_params import InputParams from .model_infer.model_rpc import start_model_process, ModelRpcClient from .req_queue import ReqQueue from .stats import Stats from .profiler import AlphaModel, BetaModel from .pets_req_queue import PETSReqQueue from .peft_req_queue import PEFTReqQueue from .cluster_req_queue import ClusterReqQueue from .abort_req_queue import AbortReqQueue from ..models.peft.lora_adapter import get_lora_config
11,481
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class RouterManager: def __init__(self, weightdir, adapter_dirs, load_way, world_size, eos_id, router_port, detokenization_port, model_rpc_ports, input_params, mode=[], log_stats=True, log_stats_interval=10): self.model_weightdir = weightdir self.adapter_dirs = adapter_dirs self.world_size = world_size self.load_way = load_way self.mode = mode self.input_params = input_params if self.input_params.prefetch: self.prefetch_stream = torch.cuda.Stream() else: self.prefetch_stream = None # get adapter rank self.lora_ranks = {} for lora_dir in adapter_dirs: config, _ = get_lora_config(lora_dir, input_params.dummy) self.lora_ranks[lora_dir] = config["r"] self.lora_ranks[None] = 0 if input_params.scheduler == "pets": self.req_queue = PETSReqQueue(input_params.max_total_token_num, input_params.batch_max_tokens, input_params.running_max_req_size) elif input_params.scheduler == "peft": self.req_queue = PEFTReqQueue(input_params.max_total_token_num, input_params.batch_max_tokens, input_params.running_max_req_size) elif input_params.batch_num_adapters is not None:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) class RouterManager: def __init__(self, weightdir, adapter_dirs, load_way, world_size, eos_id, router_port, detokenization_port, model_rpc_ports, input_params, mode=[], log_stats=True, log_stats_interval=10): self.model_weightdir = weightdir self.adapter_dirs = adapter_dirs self.world_size = world_size self.load_way = load_way self.mode = mode self.input_params = input_params if self.input_params.prefetch: self.prefetch_stream = torch.cuda.Stream() else: self.prefetch_stream = None # get adapter rank self.lora_ranks = {} for lora_dir in adapter_dirs: config, _ = get_lora_config(lora_dir, input_params.dummy) self.lora_ranks[lora_dir] = config["r"] self.lora_ranks[None] = 0 if input_params.scheduler == "pets": self.req_queue = PETSReqQueue(input_params.max_total_token_num, input_params.batch_max_tokens, input_params.running_max_req_size) elif input_params.scheduler == "peft": self.req_queue = PEFTReqQueue(input_params.max_total_token_num, input_params.batch_max_tokens, input_params.running_max_req_size) elif input_params.batch_num_adapters is not None:
self.req_queue = ClusterReqQueue(input_params.max_total_token_num, input_params.batch_max_tokens,
15
2023-10-16 02:39:47+00:00
16k
MobileLLM/AutoDroid
droidbot/input_manager.py
[ { "identifier": "EventLog", "path": "droidbot/input_event.py", "snippet": "class EventLog(object):\n \"\"\"\n save an event to local file system\n \"\"\"\n\n def __init__(self, device, app, event, profiling_method=None, tag=None):\n self.device = device\n self.app = app\n ...
import json import logging import subprocess import time from .input_event import EventLog from .input_policy import UtgBasedInputPolicy, UtgNaiveSearchPolicy, UtgGreedySearchPolicy, \ UtgReplayPolicy, \ ManualPolicy, TaskPolicy, \ POLICY_NAIVE_DFS, POLICY_GREEDY_DFS, \ POLICY_NAIVE_BFS, POLICY_GREEDY_BFS, \ POLICY_REPLAY, POLICY_MEMORY_GUIDED, \ POLICY_MANUAL, POLICY_MONKEY, POLICY_NONE, POLICY_TASK from .input_script import DroidBotScript from .input_policy2 import MemoryGuidedPolicy
13,374
DEFAULT_POLICY = POLICY_GREEDY_DFS DEFAULT_EVENT_INTERVAL = 1 DEFAULT_EVENT_COUNT = 100000000 DEFAULT_TIMEOUT = -1 class UnknownInputException(Exception): pass class InputManager(object): """ This class manages all events to send during app running """ def __init__(self, device, app, task, policy_name, random_input, event_count, event_interval, script_path=None, profiling_method=None, master=None, replay_output=None): """ manage input event sent to the target device :param device: instance of Device :param app: instance of App :param policy_name: policy of generating events, string :return: """ self.logger = logging.getLogger('InputEventManager') self.enabled = True self.device = device self.app = app self.task = task self.policy_name = policy_name self.random_input = random_input self.events = [] self.policy = None self.script = None self.event_count = event_count self.event_interval = event_interval self.replay_output = replay_output self.monkey = None if script_path is not None: f = open(script_path, 'r') script_dict = json.load(f) self.script = DroidBotScript(script_dict) self.policy = self.get_input_policy(device, app, master) self.profiling_method = profiling_method def get_input_policy(self, device, app, master):
DEFAULT_POLICY = POLICY_GREEDY_DFS DEFAULT_EVENT_INTERVAL = 1 DEFAULT_EVENT_COUNT = 100000000 DEFAULT_TIMEOUT = -1 class UnknownInputException(Exception): pass class InputManager(object): """ This class manages all events to send during app running """ def __init__(self, device, app, task, policy_name, random_input, event_count, event_interval, script_path=None, profiling_method=None, master=None, replay_output=None): """ manage input event sent to the target device :param device: instance of Device :param app: instance of App :param policy_name: policy of generating events, string :return: """ self.logger = logging.getLogger('InputEventManager') self.enabled = True self.device = device self.app = app self.task = task self.policy_name = policy_name self.random_input = random_input self.events = [] self.policy = None self.script = None self.event_count = event_count self.event_interval = event_interval self.replay_output = replay_output self.monkey = None if script_path is not None: f = open(script_path, 'r') script_dict = json.load(f) self.script = DroidBotScript(script_dict) self.policy = self.get_input_policy(device, app, master) self.profiling_method = profiling_method def get_input_policy(self, device, app, master):
if self.policy_name == POLICY_NONE:
15
2023-10-23 03:32:58+00:00
16k
f0uriest/interpax
tests/test_interpolate.py
[ { "identifier": "fft_interp1d", "path": "interpax/_fourier.py", "snippet": "@partial(jit, static_argnames=\"n\")\ndef fft_interp1d(f: jax.Array, n: int, sx: jax.Array = None, dx: float = 1.0):\n \"\"\"Interpolation of a 1d periodic function via FFT.\n\n Parameters\n ----------\n f : ndarray,...
import jax import jax.numpy as jnp import numpy as np import pytest from jax import config as jax_config from interpax import ( Interpolator1D, Interpolator2D, Interpolator3D, fft_interp1d, fft_interp2d, interp1d, interp2d, interp3d, )
13,170
"""Tests for interpolation functions.""" jax_config.update("jax_enable_x64", True) class TestInterp1D: """Tests for interp1d function.""" @pytest.mark.unit @pytest.mark.parametrize( "x", [ np.linspace(0, 2 * np.pi, 10000), 0.0, ], ) def test_interp1d(self, x): """Test accuracy of different 1d interpolation methods.""" xp = np.linspace(0, 2 * np.pi, 100) f = lambda x: np.sin(x) fp = f(xp)
"""Tests for interpolation functions.""" jax_config.update("jax_enable_x64", True) class TestInterp1D: """Tests for interp1d function.""" @pytest.mark.unit @pytest.mark.parametrize( "x", [ np.linspace(0, 2 * np.pi, 10000), 0.0, ], ) def test_interp1d(self, x): """Test accuracy of different 1d interpolation methods.""" xp = np.linspace(0, 2 * np.pi, 100) f = lambda x: np.sin(x) fp = f(xp)
interp1 = lambda xq, *args, **kwargs: interp1d(xq, *args, **kwargs)
5
2023-10-18 13:12:20+00:00
16k
apple/ml-nvas3d
demo/generate_demo_video.py
[ { "identifier": "convolve_moving_receiver", "path": "nvas3d/utils/dynamic_utils.py", "snippet": "def convolve_moving_receiver(\n source_audio: np.ndarray,\n rirs: np.ndarray,\n interp_index: T.List[int],\n interp_weight: T.List[float]\n) -> np.ndarray:\n \"\"\"\n Apply convolution betw...
import os import json import argparse import itertools import subprocess import typing as T import torch import imageio import torchaudio import numpy as np import matplotlib.pyplot as plt from moviepy.editor import * from nvas3d.utils.dynamic_utils import convolve_moving_receiver, setup_dynamic_interp from nvas3d.utils.audio_utils import clip_two, clip_all from soundspaces_nvas3d.utils.ss_utils import create_scene, render_rir_parallel from soundspaces_nvas3d.utils.aihabitat_utils import load_room_grid from soundspaces_nvas3d.soundspaces_nvas3d import Receiver, Source, Scene
10,867
def generate_rir_combination( room: str, source_idx_list: T.List[int], grid_points_source: torch.Tensor, receiver_idx_list: T.List[int], receiver_rotation_list: T.List[float], grid_points_receiver: torch.Tensor, channel_type: str = 'Binaural', channel_order: int = 0 ) -> T.List[T.List[torch.Tensor]]: """ Generates room impulse responses (RIR) for given source and receiver combinations. Args: - room: Room object for which RIRs need to be computed. - source_idx_list: List of source indices. - grid_points_source: Grid points for the source. - receiver_idx_list: List of receiver indices. - receiver_rotation_list: List of receiver rotations. - grid_points_receiver: Grid points for the receiver. - channel_type: Type of the channel. Defaults to 'Ambisonics'. - channel_order: Order of the channel for Ambisonics. Defulats to 0, as video usually does not support HOA. Returns: - A 2D list containing RIRs for every source-receiver combination. """ # Set source and receiver points source_point_list = grid_points_source[source_idx_list] receiver_point_list = grid_points_receiver[receiver_idx_list] source_points_pair, receiver_points_pair = all_pairs(source_point_list, receiver_point_list) _, receiver_rotation_pair = all_pairs(source_point_list, receiver_rotation_list) room_list = [room] * len(source_points_pair) filename_list = None # Render RIR for grid points ir_list = render_rir_parallel(room_list, source_points_pair, receiver_points_pair, receiver_rotation_list=receiver_rotation_pair, filename_list=filename_list, channel_type=channel_type, channel_order=channel_order) ir_list = clip_all(ir_list) # make the length consistent num_channel = len(ir_list[0]) # Reshape RIR num_sources = len(source_idx_list) num_receivers = len(receiver_idx_list) ir_output = torch.stack(ir_list).reshape(num_sources, num_receivers, num_channel, -1) # '-1' will infer the remaining dimension based on the size of each tensor in ir_list ir_output /= ir_output.abs().max() return ir_output def interpolate_values( start: float, end: float, interp_weight: float ) -> float: """ Interpolate between two values based on the weight values. Args: - start: Beginning value. - end: Ending value. - interp_weight: Weight for linear interpolation Returns: - Interpolated value. """ return (1 - interp_weight) * start + interp_weight * end def main(args): """ Generate NVAS video from the estimated dry sound. Save: ├── {results_demo} = results/nvas3d_demo/default/demo/{room}/0 │ ├── video/ │ │ ├── moving_audio.wav : Audio interpolated for the moving receiver. │ │ ├── moving_audio_1.wav : Audio interpolated specifically for source 1. │ │ ├── moving_audio_2.wav : Audio interpolated specifically for source 2. │ │ ├── moving_video.mp4 : Video visualization of movement (no audio). │ │ ├── nvas.mp4 : NVAS video results with combined audio. │ │ ├── nvas_source1.mp4 : NVAS video results for only source 1 audio. │ │ ├── nvas_source2.mp4 : NVAS video results for only source 2 audio. │ │ └── rgb_receiver.png : A rendered view from the perspective of the receiver. """ # Constants sample_rate = args.sample_rate sample_rate_video = args.sample_rate_video novel_path_config = args.novel_path_config use_gt_location = args.use_gt_location channel_type = args.channel_type use_placeholder_mesh = args.use_placeholder_mesh # Load data and metadata metadata = torch.load(f'{args.results_dir}/results_detection/metadata.pt') room = metadata['room'][0] grid_points_source = metadata['grid_points'][0] receiver_idx_list_original = torch.tensor(metadata['receiver_idx_list'])[:4] if use_gt_location: # Use estimated dry sound from GT source location source1_idx = metadata['source1_idx'][0].item() source2_idx = metadata['source2_idx'][0].item() source_idx_list = [source1_idx, source2_idx] else: # Use estimated dry sound from detected source location detected_source1_idx = metadata['detected_source_idx'][0] detected_source2_idx = metadata['detected_source_idx'][1] source_idx_list = [detected_source1_idx, detected_source2_idx] # Define receiver path and rotations with open(f'demo/config_demo/{novel_path_config}.json', 'r') as file: json_path = json.load(file) receiver_idx_list = json_path['receiver_idx_list'] receiver_rotation_list = json_path['receiver_rotation_list'] # Load grid points
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # def normalize(input: torch.Tensor) -> torch.Tensor: output = (input - input.min()) / (input.max() - input.min()) output = 2 * output - 1 return output def configure_scene_from_metadata( metadata: T.Dict[str, T.Any], image_size: T.Tuple[int, int] = (1000, 1000), hfov: float = 90.0, use_placeholder_mesh: bool = False ) -> Scene: """ Configures a scene using the provided metadata. Args: - metadata: Dictionary containing room and grid point information. - image_size: The size of the rendered image. - hfov: Horizontal field of view. - use_placeholder_mesh: Flag to determine if placeholder meshes should be used. Returns: - Configured scene object. """ room = metadata['room'][0] grid_points_source = metadata['grid_points'][0] source_idx_list = [metadata['source1_idx'][0].item(), metadata['source2_idx'][0].item()] receiver_idx_list_original = torch.tensor(metadata['receiver_idx_list'])[:4] scene = create_scene(room, image_size=image_size, hfov=hfov) if use_placeholder_mesh: # Add placeholder mesh for sources and receivers to the scene # Download the following mesh objects and locate it under data/objects/{mesh_name}.glb: # - "Bluetooth Speaker" (https://skfb.ly/6VLyL) by Ramanan is licensed under Creative Commons Attribution (http://creativecommons.org/licenses/by/4.0/). # - “Classic Microphone” (https://skfb.ly/6Aryq) by urbanmasque is licensed under Creative Commons Attribution (http://creativecommons.org/licenses/by/4.0/) # - "Standard Drum Set" (https://skfb.ly/owroB) by Heataker is licensed under Creative Commons Attribution (http://creativecommons.org/licenses/by/4.0/). # - "3D Posed People" (https://renderpeople.com/free-3d-people/) by Renderpeople: The licensing for our Renderpeople products includes that customers are allowed to use the data for rendering still images and animations for commercial or private purposes, such as video production, broadcasting, print, movies, advertising, illustrations and presentations (https://renderpeople.com/faq/) ss_source1 = Source( position=grid_points_source[source_idx_list[0]], rotation=0, dry_sound='', mesh='bluetooth_speaker', # Need mesh object device=torch.device('cpu') ) ss_source2 = Source( position=grid_points_source[source_idx_list[1]], rotation=-90, dry_sound='', mesh='bluetooth_speaker', # Need mesh object device=torch.device('cpu') ) ss_mic_list = [ Source( position=grid_points_source[idx], rotation=180, dry_sound='', mesh='classic_microphone', # Need mesh object device=torch.device('cpu') ) for idx in receiver_idx_list_original ] scene.add_source_mesh = True scene.source_list = [None] * (len(source_idx_list) + len(receiver_idx_list_original)) scene.update_source(ss_source1, 0) scene.update_source(ss_source2, 1) for m, mic in enumerate(ss_mic_list): scene.update_source(mic, m + 2) return scene def interpolate_moving_audio( source1_audio: torch.Tensor, source2_audio: torch.Tensor, ir1_list: T.List[torch.Tensor], ir2_list: T.List[torch.Tensor], receiver_position: torch.Tensor ) -> T.Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Interpolates audio for a moving receiver. Args: - source1_audio: First source audio. - source2_audio: Second source audio. - ir1_list: List of impulse responses for source 1. - ir2_list: List of impulse responses for source 2. - receiver_position: Positions of the moving receiver. Returns: - Tuple containing combined audio, interpolated audio from source 1, and interpolated audio from source 2. """ # Prepare for interpolation audio_len = source1_audio.shape[-1] interp_index, interp_weight = setup_dynamic_interp(receiver_position.numpy(), audio_len) # Generate audio for moving receiver receiver_audio_1 = convolve_moving_receiver(source1_audio.numpy()[0], ir1_list.numpy(), interp_index, interp_weight) receiver_audio_2 = convolve_moving_receiver(source2_audio.numpy()[0], ir2_list.numpy(), interp_index, interp_weight) receiver_audio_1 = receiver_audio_1[..., :source1_audio.shape[-1]] receiver_audio_2 = receiver_audio_2[..., :source1_audio.shape[-1]] # Mix and normalize audios receiver_audio = (receiver_audio_1 + receiver_audio_2) scale = np.max(abs(receiver_audio)) receiver_audio /= scale receiver_audio_1 /= scale receiver_audio_2 /= scale return torch.from_numpy(receiver_audio), torch.from_numpy(receiver_audio_1), torch.from_numpy(receiver_audio_2) def interpolate_rgb_images( scene: Scene, receiver_position: torch.Tensor, receiver_rotation_list: T.List[float], video_len: int ) -> T.List[np.ndarray]: """ Interpolates RGB images based on receiver movement and rotation. Args: - scene: Scene object to render the images from. - receiver_position: Positions of the receiver along the path. - receiver_rotation_list: List of rotations for the receiver. - video_len: Number of frames in the video. Returns: - List of interpolated RGB images. """ interp_index, interp_weight = setup_dynamic_interp(receiver_position.numpy(), video_len) interpolated_rgb_list = [] for t in range(len(interp_index)): # Find the positions and rotations between which we're interpolating start_idx = interp_index[t] end_idx = start_idx + 1 start_pos = receiver_position[start_idx] end_pos = receiver_position[end_idx] start_rot = receiver_rotation_list[start_idx] end_rot = receiver_rotation_list[end_idx] # Interpolate position and rotation receiver_position_interp = interpolate_values(start_pos, end_pos, interp_weight[t]) receiver_rotation_interp = interpolate_values(start_rot, end_rot, interp_weight[t]) receiver = Receiver(receiver_position_interp, receiver_rotation_interp) scene.update_receiver(receiver) rgb, _ = scene.render_image() interpolated_rgb_list.append(rgb[..., :3]) return interpolated_rgb_list def all_pairs( list1: T.List[T.Any], list2: T.List[T.Any] ) -> T.Tuple[T.List[T.Any], T.List[T.Any]]: """ Computes all pairs of combinations between two lists. Args: - list1: First list. - list2: Second list. Returns: - Two lists containing paired elements from list1 and list2. """ list_pair = list(itertools.product(list1, list2)) list1_pair, list2_pair = zip(*list_pair) list1_pair = list(list1_pair) list2_pair = list(list2_pair) return list1_pair, list2_pair def generate_rir_combination( room: str, source_idx_list: T.List[int], grid_points_source: torch.Tensor, receiver_idx_list: T.List[int], receiver_rotation_list: T.List[float], grid_points_receiver: torch.Tensor, channel_type: str = 'Binaural', channel_order: int = 0 ) -> T.List[T.List[torch.Tensor]]: """ Generates room impulse responses (RIR) for given source and receiver combinations. Args: - room: Room object for which RIRs need to be computed. - source_idx_list: List of source indices. - grid_points_source: Grid points for the source. - receiver_idx_list: List of receiver indices. - receiver_rotation_list: List of receiver rotations. - grid_points_receiver: Grid points for the receiver. - channel_type: Type of the channel. Defaults to 'Ambisonics'. - channel_order: Order of the channel for Ambisonics. Defulats to 0, as video usually does not support HOA. Returns: - A 2D list containing RIRs for every source-receiver combination. """ # Set source and receiver points source_point_list = grid_points_source[source_idx_list] receiver_point_list = grid_points_receiver[receiver_idx_list] source_points_pair, receiver_points_pair = all_pairs(source_point_list, receiver_point_list) _, receiver_rotation_pair = all_pairs(source_point_list, receiver_rotation_list) room_list = [room] * len(source_points_pair) filename_list = None # Render RIR for grid points ir_list = render_rir_parallel(room_list, source_points_pair, receiver_points_pair, receiver_rotation_list=receiver_rotation_pair, filename_list=filename_list, channel_type=channel_type, channel_order=channel_order) ir_list = clip_all(ir_list) # make the length consistent num_channel = len(ir_list[0]) # Reshape RIR num_sources = len(source_idx_list) num_receivers = len(receiver_idx_list) ir_output = torch.stack(ir_list).reshape(num_sources, num_receivers, num_channel, -1) # '-1' will infer the remaining dimension based on the size of each tensor in ir_list ir_output /= ir_output.abs().max() return ir_output def interpolate_values( start: float, end: float, interp_weight: float ) -> float: """ Interpolate between two values based on the weight values. Args: - start: Beginning value. - end: Ending value. - interp_weight: Weight for linear interpolation Returns: - Interpolated value. """ return (1 - interp_weight) * start + interp_weight * end def main(args): """ Generate NVAS video from the estimated dry sound. Save: ├── {results_demo} = results/nvas3d_demo/default/demo/{room}/0 │ ├── video/ │ │ ├── moving_audio.wav : Audio interpolated for the moving receiver. │ │ ├── moving_audio_1.wav : Audio interpolated specifically for source 1. │ │ ├── moving_audio_2.wav : Audio interpolated specifically for source 2. │ │ ├── moving_video.mp4 : Video visualization of movement (no audio). │ │ ├── nvas.mp4 : NVAS video results with combined audio. │ │ ├── nvas_source1.mp4 : NVAS video results for only source 1 audio. │ │ ├── nvas_source2.mp4 : NVAS video results for only source 2 audio. │ │ └── rgb_receiver.png : A rendered view from the perspective of the receiver. """ # Constants sample_rate = args.sample_rate sample_rate_video = args.sample_rate_video novel_path_config = args.novel_path_config use_gt_location = args.use_gt_location channel_type = args.channel_type use_placeholder_mesh = args.use_placeholder_mesh # Load data and metadata metadata = torch.load(f'{args.results_dir}/results_detection/metadata.pt') room = metadata['room'][0] grid_points_source = metadata['grid_points'][0] receiver_idx_list_original = torch.tensor(metadata['receiver_idx_list'])[:4] if use_gt_location: # Use estimated dry sound from GT source location source1_idx = metadata['source1_idx'][0].item() source2_idx = metadata['source2_idx'][0].item() source_idx_list = [source1_idx, source2_idx] else: # Use estimated dry sound from detected source location detected_source1_idx = metadata['detected_source_idx'][0] detected_source2_idx = metadata['detected_source_idx'][1] source_idx_list = [detected_source1_idx, detected_source2_idx] # Define receiver path and rotations with open(f'demo/config_demo/{novel_path_config}.json', 'r') as file: json_path = json.load(file) receiver_idx_list = json_path['receiver_idx_list'] receiver_rotation_list = json_path['receiver_rotation_list'] # Load grid points
grid_points_receiver = load_room_grid(room, grid_distance=args.grid_distance)['grid_points']
6
2023-10-19 05:35:54+00:00
16k
openvpi/SingingVocoders
training/ddspgan_task_2.py
[ { "identifier": "DDSPgan", "path": "models/ddspgan/ddspgan.py", "snippet": "class DDSPgan(nn.Module):\n def __init__(self,config):\n super().__init__()\n if config['model_args']['type']=='CombSub':\n self.ddsp = CombSub(\n sampling_rate=config['audio_sample_rat...
import logging import os import pathlib import random import sys import lightning.pytorch as pl import matplotlib import numpy as np import torch.utils.data import utils from typing import Dict from lightning.pytorch.utilities.rank_zero import rank_zero_debug, rank_zero_info, rank_zero_only from matplotlib import pyplot as plt from torch import nn from torch.utils.data import Dataset from torchmetrics import Metric, MeanMetric from models.ddspgan.ddspgan import DDSPgan from models.nsf_HiFigan.models import Generator, AttrDict, MultiScaleDiscriminator, MultiPeriodDiscriminator from modules.loss.HiFiloss import HiFiloss from modules.loss.ddsploss import ddsploss from training.base_task_gan import GanBaseTask from utils.training_utils import ( DsBatchSampler, DsEvalBatchSampler, get_latest_checkpoint_path ) from utils.wav2mel import PitchAdjustableMelSpectrogram
13,057
end = start + crop_mel_frames if self.infer: record['spectrogram'] = record['spectrogram'].T record['f0'] = record['f0'] record['uv'] = record['uv'] else: record['spectrogram'] = record['spectrogram'][start:end].T record['f0'] = record['f0'][start:end] record['uv'] = record['uv'][start:end] start *= samples_per_frame end *= samples_per_frame if self.infer: cty = (len(record['spectrogram'].T) * samples_per_frame) record['audio'] = record['audio'][:cty] record['audio'] = np.pad(record['audio'], ( 0, (len(record['spectrogram'].T) * samples_per_frame) - len(record['audio'])), mode='constant') pass else: # record['spectrogram'] = record['spectrogram'][start:end].T record['audio'] = record['audio'][start:end] record['audio'] = np.pad(record['audio'], (0, (end - start) - len(record['audio'])), mode='constant') if self.volume_aug: for record in minibatch: if random.random() < self.volume_aug_prob: audio = record['audio'] audio_mel = record['spectrogram'] max_amp = float(np.max(np.abs(audio))) + 1e-5 max_shift = min(3, np.log(1 / max_amp)) log_mel_shift = random.uniform(-3, max_shift) # audio *= (10 ** log_mel_shift) audio *= np.exp(log_mel_shift) audio_mel += log_mel_shift audio_mel = torch.clamp(torch.from_numpy(audio_mel), min=np.log(1e-5)).numpy() record['audio'] = audio record['spectrogram'] = audio_mel audio = np.stack([record['audio'] for record in minibatch if 'audio' in record]) spectrogram = np.stack([record['spectrogram'] for record in minibatch if 'spectrogram' in record]) f0 = np.stack([record['f0'] for record in minibatch if 'f0' in record]) uv = np.stack([record['uv'] for record in minibatch if 'uv' in record]) return { 'audio': torch.from_numpy(audio).unsqueeze(1), 'mel': torch.from_numpy(spectrogram), 'f0': torch.from_numpy(f0), 'uv': torch.from_numpy(uv) } class stftlog: def __init__(self, n_fft=2048, win_length=2048, hop_length=512, center=False,): self.hop_length=hop_length self.win_size=win_length self.n_fft = n_fft self.win_size = win_length self.center = center self.hann_window = {} def exc(self,y): hann_window_key = f"{y.device}" if hann_window_key not in self.hann_window: self.hann_window[hann_window_key] = torch.hann_window( self.win_size, device=y.device ) y = torch.nn.functional.pad( y.unsqueeze(1), ( int((self.win_size - self.hop_length) // 2), int((self.win_size - self.hop_length+1) // 2), ), mode="reflect", ) y = y.squeeze(1) spec = torch.stft( y, self.n_fft, hop_length=self.hop_length, win_length=self.win_size, window=self.hann_window[hann_window_key], center=self.center, pad_mode="reflect", normalized=False, onesided=True, return_complex=True, ).abs() return spec class ddspgan_task(GanBaseTask): def __init__(self, config): super().__init__(config) self.TF = PitchAdjustableMelSpectrogram( f_min=0, f_max=None, n_mels=256,) self.logged_gt_wav = set() self.stft=stftlog() def build_dataset(self): self.train_dataset = nsf_HiFigan_dataset(config=self.config, data_dir=pathlib.Path(self.config['DataIndexPath']) / self.config[ 'train_set_name']) self.valid_dataset = nsf_HiFigan_dataset(config=self.config, data_dir=pathlib.Path(self.config['DataIndexPath']) / self.config[ 'valid_set_name'], infer=True) def build_model(self): # cfg=self.config['model_args'] # cfg.update({'sampling_rate':self.config['audio_sample_rate'],'num_mels':self.config['audio_num_mel_bins'],'hop_size':self.config['hop_size']}) # h=AttrDict(cfg) self.generator=DDSPgan(self.config)
# from utils.indexed_datasets import IndexedDataset def spec_to_figure(spec, vmin=None, vmax=None): if isinstance(spec, torch.Tensor): spec = spec.cpu().numpy() fig = plt.figure(figsize=(12, 9),dpi=100) plt.pcolor(spec.T, vmin=vmin, vmax=vmax) plt.tight_layout() return fig class nsf_HiFigan_dataset(Dataset): def __init__(self, config: dict, data_dir, infer=False): super().__init__() self.config = config self.data_dir = data_dir if isinstance(data_dir, pathlib.Path) else pathlib.Path(data_dir) with open(self.data_dir, 'r', encoding='utf8') as f: fills = f.read().strip().split('\n') self.data_index = fills self.infer = infer self.volume_aug = self.config['volume_aug'] self.volume_aug_prob = self.config['volume_aug_prob'] if not infer else 0 def __getitem__(self, index): data_path = self.data_index[index] data = np.load(data_path) return {'f0': data['f0'], 'spectrogram': data['mel'], 'audio': data['audio'], 'uv': data['uv']} def __len__(self): return len(self.data_index) def collater(self, minibatch): samples_per_frame = self.config['hop_size'] if self.infer: crop_mel_frames = 0 else: crop_mel_frames = self.config['crop_mel_frames'] for record in minibatch: # Filter out records that aren't long enough. if len(record['spectrogram']) < crop_mel_frames: del record['spectrogram'] del record['audio'] del record['f0'] del record['uv'] continue start = random.randint(0, record['spectrogram'].shape[0] - 1 - crop_mel_frames) end = start + crop_mel_frames if self.infer: record['spectrogram'] = record['spectrogram'].T record['f0'] = record['f0'] record['uv'] = record['uv'] else: record['spectrogram'] = record['spectrogram'][start:end].T record['f0'] = record['f0'][start:end] record['uv'] = record['uv'][start:end] start *= samples_per_frame end *= samples_per_frame if self.infer: cty = (len(record['spectrogram'].T) * samples_per_frame) record['audio'] = record['audio'][:cty] record['audio'] = np.pad(record['audio'], ( 0, (len(record['spectrogram'].T) * samples_per_frame) - len(record['audio'])), mode='constant') pass else: # record['spectrogram'] = record['spectrogram'][start:end].T record['audio'] = record['audio'][start:end] record['audio'] = np.pad(record['audio'], (0, (end - start) - len(record['audio'])), mode='constant') if self.volume_aug: for record in minibatch: if random.random() < self.volume_aug_prob: audio = record['audio'] audio_mel = record['spectrogram'] max_amp = float(np.max(np.abs(audio))) + 1e-5 max_shift = min(3, np.log(1 / max_amp)) log_mel_shift = random.uniform(-3, max_shift) # audio *= (10 ** log_mel_shift) audio *= np.exp(log_mel_shift) audio_mel += log_mel_shift audio_mel = torch.clamp(torch.from_numpy(audio_mel), min=np.log(1e-5)).numpy() record['audio'] = audio record['spectrogram'] = audio_mel audio = np.stack([record['audio'] for record in minibatch if 'audio' in record]) spectrogram = np.stack([record['spectrogram'] for record in minibatch if 'spectrogram' in record]) f0 = np.stack([record['f0'] for record in minibatch if 'f0' in record]) uv = np.stack([record['uv'] for record in minibatch if 'uv' in record]) return { 'audio': torch.from_numpy(audio).unsqueeze(1), 'mel': torch.from_numpy(spectrogram), 'f0': torch.from_numpy(f0), 'uv': torch.from_numpy(uv) } class stftlog: def __init__(self, n_fft=2048, win_length=2048, hop_length=512, center=False,): self.hop_length=hop_length self.win_size=win_length self.n_fft = n_fft self.win_size = win_length self.center = center self.hann_window = {} def exc(self,y): hann_window_key = f"{y.device}" if hann_window_key not in self.hann_window: self.hann_window[hann_window_key] = torch.hann_window( self.win_size, device=y.device ) y = torch.nn.functional.pad( y.unsqueeze(1), ( int((self.win_size - self.hop_length) // 2), int((self.win_size - self.hop_length+1) // 2), ), mode="reflect", ) y = y.squeeze(1) spec = torch.stft( y, self.n_fft, hop_length=self.hop_length, win_length=self.win_size, window=self.hann_window[hann_window_key], center=self.center, pad_mode="reflect", normalized=False, onesided=True, return_complex=True, ).abs() return spec class ddspgan_task(GanBaseTask): def __init__(self, config): super().__init__(config) self.TF = PitchAdjustableMelSpectrogram( f_min=0, f_max=None, n_mels=256,) self.logged_gt_wav = set() self.stft=stftlog() def build_dataset(self): self.train_dataset = nsf_HiFigan_dataset(config=self.config, data_dir=pathlib.Path(self.config['DataIndexPath']) / self.config[ 'train_set_name']) self.valid_dataset = nsf_HiFigan_dataset(config=self.config, data_dir=pathlib.Path(self.config['DataIndexPath']) / self.config[ 'valid_set_name'], infer=True) def build_model(self): # cfg=self.config['model_args'] # cfg.update({'sampling_rate':self.config['audio_sample_rate'],'num_mels':self.config['audio_num_mel_bins'],'hop_size':self.config['hop_size']}) # h=AttrDict(cfg) self.generator=DDSPgan(self.config)
self.discriminator=nn.ModuleDict({'msd':MultiScaleDiscriminator(), 'mpd':MultiPeriodDiscriminator(periods=self.config['model_args']['discriminator_periods'])})
4
2023-10-17 13:45:09+00:00
16k
Jacob-Zhou/gecdi
gec/parser.py
[ { "identifier": "Dataset", "path": "gec/data.py", "snippet": "class Dataset(torch.utils.data.Dataset):\n r\"\"\"\n Dataset that is compatible with :class:`torch.utils.data.Dataset`, serving as a wrapper for manipulating all data fields\n with the operating behaviours defined in :class:`~supar.u...
import os import shutil import tempfile import math import dill import torch import torch.distributed as dist from datetime import datetime, timedelta from typing import Iterable, Union from gec.data import Dataset from gec.fn import map_token_ids from supar.parser import Parser from supar.utils import Config from supar.utils.common import MIN, NUL, UNK from supar.utils.field import RawField from supar.utils.fn import set_rng_state from supar.utils.logging import get_logger, init_logger, progress_bar from supar.utils.metric import Metric from supar.utils.optim import PolynomialLR from supar.utils.parallel import DistributedDataParallel as DDP, gather, is_dist from supar.utils.parallel import is_master from supar.utils.tokenizer import TransformerTokenizer from supar.utils.transform import AttachJuxtaposeTree, Batch from torch.cuda.amp import GradScaler from torch.optim import AdamW from torch.optim.lr_scheduler import ExponentialLR from torch.nn.functional import embedding from .metric import PerplexityMetric, SpanMetric from .model import Seq2SeqDetectModel, Seq2SeqModel from .transform import Field, Text, Tree from torch.distributed.algorithms.ddp_comm_hooks.default_hooks import fp16_compress_hook from torch.distributed.algorithms.ddp_comm_hooks.default_hooks import fp16_compress_hook from transformers import AutoTokenizer, GPT2LMHeadModel
13,666
train.loader.batch_sampler.epoch = self.epoch except AttributeError: logger.warning( "No checkpoint found. Try re-launching the traing procedure instead" ) for epoch in range(self.epoch, args.epochs + 1): start = datetime.now() bar, metric = progress_bar(train.loader), Metric() logger.info(f"Epoch {epoch} / {args.epochs}:") self.model.train() if self.epoch == 1: torch.cuda.empty_cache() with self.join(): # we should zero `step` as the number of batches in different processes is not necessarily equal self.step = 0 for batch in bar: with self.sync(): with torch.autocast(self.device, enabled=self.args.amp): loss = self.train_step(batch) self.backward(loss) if self.sync_grad: self.clip_grad_norm_(self.model.parameters(), self.args.clip) self.scaler.step(self.optimizer) self.scaler.update() self.scheduler.step() self.optimizer.zero_grad(True) bar.set_postfix_str( f"lr: {self.scheduler.get_last_lr()[0]:.4e} - loss: {loss:.4f}" ) self.step += 1 logger.info(f"{bar.postfix}") self.model.eval() with self.join(), torch.autocast(self.device, enabled=self.args.amp): metric = self.reduce( sum([self.eval_step(i) for i in progress_bar(dev.loader)], Metric())) logger.info(f"{'dev:':5} {metric}") if args.test: test_metric = sum( [self.eval_step(i) for i in progress_bar(test.loader)], Metric()) logger.info(f"{'test:':5} {self.reduce(test_metric)}") t = datetime.now() - start self.epoch += 1 self.patience -= 1 self.elapsed += t if metric > self.best_metric: self.best_e, self.patience, self.best_metric = epoch, patience, metric if is_master(): self.save_checkpoint(args.path) logger.info(f"{t}s elapsed (saved)\n") else: logger.info(f"{t}s elapsed\n") if self.patience < 1: break if dist.is_initialized(): dist.barrier() best = self.load(**args) # only allow the master device to save models if is_master(): best.save(args.path) logger.info(f"Epoch {self.best_e} saved") logger.info(f"{'dev:':5} {self.best_metric}") if args.test: best.model.eval() with best.join(): test_metric = sum( [best.eval_step(i) for i in progress_bar(test.loader)], Metric()) logger.info(f"{'test:':5} {best.reduce(test_metric)}") logger.info(f"{self.elapsed}s elapsed, {self.elapsed / epoch}s/epoch") def evaluate(self, data: Union[str, Iterable], batch_size: int = 5000, buckets: int = 8, workers: int = 0, amp: bool = False, cache: bool = False, punct: bool = False, tree: bool = True, proj: bool = False, partial: bool = False, verbose: bool = True, **kwargs): return super().evaluate(**Config().update(locals())) def predict(self, data: Union[str, Iterable], pred: str = None, lang: str = None, prob: bool = False, batch_size: int = 5000, buckets: int = 8, workers: int = 0, amp: bool = False, cache: bool = False, tree: bool = True, proj: bool = False, verbose: bool = True, **kwargs): return super().predict(**Config().update(locals())) def train_step(self, batch: Batch) -> torch.Tensor: src, tgt = batch src_mask, tgt_mask = batch.mask, tgt.ne(self.args.pad_index) x = self.model(src) loss = self.model.loss(x, tgt, src_mask, tgt_mask) return loss @torch.no_grad()
# -*- coding: utf-8 -*- logger = get_logger(__name__) class Seq2SeqParser(Parser): NAME = 'seq2seq' MODEL = Seq2SeqModel def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.SRC = self.transform.SRC self.TGT = self.transform.TGT def train(self, train: Union[str, Iterable], dev: Union[str, Iterable], test: Union[str, Iterable], epochs: int, patience: int, batch_size: int = 5000, update_steps: int = 1, buckets: int = 32, workers: int = 0, clip: float = 5.0, amp: bool = False, cache: bool = False, verbose: bool = True, **kwargs) -> None: args = self.args.update(locals()) init_logger(logger, verbose=args.verbose) self.transform.train() batch_size = batch_size // update_steps if dist.is_initialized(): batch_size = batch_size // dist.get_world_size() logger.info("Loading the data") if args.cache: args.bin = os.path.join(os.path.dirname(args.path), 'bin') train = Dataset(self.transform, args.train, **args).build(batch_size, buckets, True, dist.is_initialized(), workers, chunk_size=args.chunk_size, seed=args.seed) dev = Dataset(self.transform, args.dev, **args).build(batch_size, buckets, False, dist.is_initialized(), workers) logger.info(f"{'train:':6} {train}") if not args.test: logger.info(f"{'dev:':6} {dev}\n") else: test = Dataset(self.transform, args.test, **args).build(batch_size, buckets, False, dist.is_initialized(), workers) logger.info(f"{'dev:':6} {dev}") logger.info(f"{'test:':6} {test}\n") self.optimizer = AdamW(self.model.parameters(), args.lr, (args.mu, args.nu), args.eps, args.weight_decay) steps = len(train.loader) * epochs // args.update_steps self.scheduler = PolynomialLR(self.optimizer, warmup_steps=self.args.warmup_steps, steps=steps) self.scaler = GradScaler(enabled=args.amp) if dist.is_initialized(): self.model = DDP(self.model, device_ids=[args.local_rank], find_unused_parameters=args.get( 'find_unused_parameters', True)) if args.amp: self.model.register_comm_hook(dist.group.WORLD, fp16_compress_hook) self.step, self.epoch, self.best_e, self.patience, self.n_batches = 1, 1, 1, patience, len( train.loader) self.best_metric, self.elapsed = Metric(), timedelta() if self.args.checkpoint: try: self.optimizer.load_state_dict( self.checkpoint_state_dict.pop('optimizer_state_dict')) self.scheduler.load_state_dict( self.checkpoint_state_dict.pop('scheduler_state_dict')) self.scaler.load_state_dict( self.checkpoint_state_dict.pop('scaler_state_dict')) set_rng_state(self.checkpoint_state_dict.pop('rng_state')) for k, v in self.checkpoint_state_dict.items(): setattr(self, k, v) train.loader.batch_sampler.epoch = self.epoch except AttributeError: logger.warning( "No checkpoint found. Try re-launching the traing procedure instead" ) for epoch in range(self.epoch, args.epochs + 1): start = datetime.now() bar, metric = progress_bar(train.loader), Metric() logger.info(f"Epoch {epoch} / {args.epochs}:") self.model.train() if self.epoch == 1: torch.cuda.empty_cache() with self.join(): # we should zero `step` as the number of batches in different processes is not necessarily equal self.step = 0 for batch in bar: with self.sync(): with torch.autocast(self.device, enabled=self.args.amp): loss = self.train_step(batch) self.backward(loss) if self.sync_grad: self.clip_grad_norm_(self.model.parameters(), self.args.clip) self.scaler.step(self.optimizer) self.scaler.update() self.scheduler.step() self.optimizer.zero_grad(True) bar.set_postfix_str( f"lr: {self.scheduler.get_last_lr()[0]:.4e} - loss: {loss:.4f}" ) self.step += 1 logger.info(f"{bar.postfix}") self.model.eval() with self.join(), torch.autocast(self.device, enabled=self.args.amp): metric = self.reduce( sum([self.eval_step(i) for i in progress_bar(dev.loader)], Metric())) logger.info(f"{'dev:':5} {metric}") if args.test: test_metric = sum( [self.eval_step(i) for i in progress_bar(test.loader)], Metric()) logger.info(f"{'test:':5} {self.reduce(test_metric)}") t = datetime.now() - start self.epoch += 1 self.patience -= 1 self.elapsed += t if metric > self.best_metric: self.best_e, self.patience, self.best_metric = epoch, patience, metric if is_master(): self.save_checkpoint(args.path) logger.info(f"{t}s elapsed (saved)\n") else: logger.info(f"{t}s elapsed\n") if self.patience < 1: break if dist.is_initialized(): dist.barrier() best = self.load(**args) # only allow the master device to save models if is_master(): best.save(args.path) logger.info(f"Epoch {self.best_e} saved") logger.info(f"{'dev:':5} {self.best_metric}") if args.test: best.model.eval() with best.join(): test_metric = sum( [best.eval_step(i) for i in progress_bar(test.loader)], Metric()) logger.info(f"{'test:':5} {best.reduce(test_metric)}") logger.info(f"{self.elapsed}s elapsed, {self.elapsed / epoch}s/epoch") def evaluate(self, data: Union[str, Iterable], batch_size: int = 5000, buckets: int = 8, workers: int = 0, amp: bool = False, cache: bool = False, punct: bool = False, tree: bool = True, proj: bool = False, partial: bool = False, verbose: bool = True, **kwargs): return super().evaluate(**Config().update(locals())) def predict(self, data: Union[str, Iterable], pred: str = None, lang: str = None, prob: bool = False, batch_size: int = 5000, buckets: int = 8, workers: int = 0, amp: bool = False, cache: bool = False, tree: bool = True, proj: bool = False, verbose: bool = True, **kwargs): return super().predict(**Config().update(locals())) def train_step(self, batch: Batch) -> torch.Tensor: src, tgt = batch src_mask, tgt_mask = batch.mask, tgt.ne(self.args.pad_index) x = self.model(src) loss = self.model.loss(x, tgt, src_mask, tgt_mask) return loss @torch.no_grad()
def eval_step(self, batch: Batch) -> PerplexityMetric:
2
2023-10-18 10:55:33+00:00
16k
jianlanluo/SAQ
vqn/conservative_sac_main.py
[ { "identifier": "VQN", "path": "vqn/vqn.py", "snippet": "class VQN(object):\n\n @staticmethod\n def get_default_config(updates=None):\n config = ConfigDict()\n config.embedding_dim = 128\n config.codebook_size = 64\n config.commitment_cost = 1.0\n config.quantiza...
import os import time import uuid import numpy as np import pprint import jax import jax.numpy as jnp import flax import gym import d4rl import absl.app import absl.flags from copy import deepcopy from .vqn import VQN from .conservative_sac import ConservativeSAC from .replay_buffer import get_d4rl_dataset, subsample_batch from .jax_utils import batch_to_jax from .model import TanhGaussianPolicy, FullyConnectedQFunction, SamplerPolicy from .sampler import StepSampler, TrajSampler from .robomimic_utils import ( SequenceDataset, make_dataset, process_robomimic_dataset, D4RLDataset, get_robomimic_env, ENV_TO_HORIZON_MAP, OBS_KEYS ) from .utils import ( Timer, define_flags_with_default, set_random_seed, print_flags, get_user_flags, prefix_metrics, WandBLogger ) from viskit.logging import logger, setup_logger
10,811
FLAGS_DEF = define_flags_with_default( env='halfcheetah-medium-v2', algorithm='cql', max_traj_length=200, seed=42, save_model=False, batch_size=256, reward_scale=1.0, reward_bias=0.0, clip_action=0.999, policy_arch='256-256', qf_arch='256-256', orthogonal_init=False, policy_log_std_multiplier=1.0, policy_log_std_offset=-1.0, n_epochs=1000, bc_epochs=1000, n_train_step_per_epoch=1000, eval_period=10, eval_n_trajs=5, cql=ConservativeSAC.get_default_config(), logging=WandBLogger.get_default_config(), ) def main(argv): FLAGS = absl.flags.FLAGS variant = get_user_flags(FLAGS, FLAGS_DEF) wandb_logger = WandBLogger(config=FLAGS.logging, variant=variant) setup_logger( variant=variant, exp_id=wandb_logger.experiment_id, seed=FLAGS.seed, base_log_dir=FLAGS.logging.output_dir, include_exp_prefix_sub_dir=False ) set_random_seed(FLAGS.seed) if FLAGS.env in ENV_TO_HORIZON_MAP: dataset_path = f'./robomimic/datasets/{FLAGS.env}/low_dim_v141.hdf5' seq_dataset = SequenceDataset(hdf5_path=dataset_path, obs_keys=OBS_KEYS, dataset_keys=("actions", "rewards", "dones"), hdf5_cache_mode="all", load_next_obs=True) dataset = process_robomimic_dataset(seq_dataset) dataset = D4RLDataset(env=None, custom_dataset=dataset) example_ob = dataset.dataset_dict['observations'][0][np.newaxis] example_action = dataset.dataset_dict['actions'][0][np.newaxis] env = get_robomimic_env(dataset_path, example_action, FLAGS.env) max_len = ENV_TO_HORIZON_MAP[FLAGS.env] else: env = gym.make(FLAGS.env).unwrapped dataset = get_d4rl_dataset(env) dataset['rewards'] = dataset['rewards'] * FLAGS.reward_scale + FLAGS.reward_bias dataset['actions'] = np.clip(dataset['actions'], -FLAGS.clip_action, FLAGS.clip_action) max_len = FLAGS.max_traj_length example_ob = env.observation_space.sample()[np.newaxis] example_action = env.action_space.sample()[np.newaxis]
FLAGS_DEF = define_flags_with_default( env='halfcheetah-medium-v2', algorithm='cql', max_traj_length=200, seed=42, save_model=False, batch_size=256, reward_scale=1.0, reward_bias=0.0, clip_action=0.999, policy_arch='256-256', qf_arch='256-256', orthogonal_init=False, policy_log_std_multiplier=1.0, policy_log_std_offset=-1.0, n_epochs=1000, bc_epochs=1000, n_train_step_per_epoch=1000, eval_period=10, eval_n_trajs=5, cql=ConservativeSAC.get_default_config(), logging=WandBLogger.get_default_config(), ) def main(argv): FLAGS = absl.flags.FLAGS variant = get_user_flags(FLAGS, FLAGS_DEF) wandb_logger = WandBLogger(config=FLAGS.logging, variant=variant) setup_logger( variant=variant, exp_id=wandb_logger.experiment_id, seed=FLAGS.seed, base_log_dir=FLAGS.logging.output_dir, include_exp_prefix_sub_dir=False ) set_random_seed(FLAGS.seed) if FLAGS.env in ENV_TO_HORIZON_MAP: dataset_path = f'./robomimic/datasets/{FLAGS.env}/low_dim_v141.hdf5' seq_dataset = SequenceDataset(hdf5_path=dataset_path, obs_keys=OBS_KEYS, dataset_keys=("actions", "rewards", "dones"), hdf5_cache_mode="all", load_next_obs=True) dataset = process_robomimic_dataset(seq_dataset) dataset = D4RLDataset(env=None, custom_dataset=dataset) example_ob = dataset.dataset_dict['observations'][0][np.newaxis] example_action = dataset.dataset_dict['actions'][0][np.newaxis] env = get_robomimic_env(dataset_path, example_action, FLAGS.env) max_len = ENV_TO_HORIZON_MAP[FLAGS.env] else: env = gym.make(FLAGS.env).unwrapped dataset = get_d4rl_dataset(env) dataset['rewards'] = dataset['rewards'] * FLAGS.reward_scale + FLAGS.reward_bias dataset['actions'] = np.clip(dataset['actions'], -FLAGS.clip_action, FLAGS.clip_action) max_len = FLAGS.max_traj_length example_ob = env.observation_space.sample()[np.newaxis] example_action = env.action_space.sample()[np.newaxis]
eval_sampler = TrajSampler(env, max_len)
9
2023-10-18 06:31:20+00:00
16k
SLDGroup/G-CASCADE
lib/networks.py
[ { "identifier": "pvt_v2_b2", "path": "lib/pvtv2.py", "snippet": "class pvt_v2_b2(PyramidVisionTransformerImpr):\n def __init__(self, **kwargs):\n super(pvt_v2_b2, self).__init__(\n patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],\n ...
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import timm import logging from scipy import ndimage from lib.pvtv2 import pvt_v2_b2, pvt_v2_b5, pvt_v2_b0 from lib.decoders import CUP, CASCADE, CASCADE_Cat, GCUP, GCUP_Cat, GCASCADE, GCASCADE_Cat from lib.pyramid_vig import pvig_ti_224_gelu, pvig_s_224_gelu, pvig_m_224_gelu, pvig_b_224_gelu from lib.maxxvit_4out import maxvit_tiny_rw_224 as maxvit_tiny_rw_224_4out from lib.maxxvit_4out import maxvit_rmlp_tiny_rw_256 as maxvit_rmlp_tiny_rw_256_4out from lib.maxxvit_4out import maxxvit_rmlp_small_rw_256 as maxxvit_rmlp_small_rw_256_4out from lib.maxxvit_4out import maxvit_rmlp_small_rw_224 as maxvit_rmlp_small_rw_224_4out
12,026
self.decoder = CASCADE(channels=[512, 320, 128, 64]) print('Model %s created, param count: %d' % ('CASCADE decoder: ', sum([m.numel() for m in self.decoder.parameters()]))) # Prediction heads initialization self.out_head1 = nn.Conv2d(512, n_class, 1) self.out_head2 = nn.Conv2d(320, n_class, 1) self.out_head3 = nn.Conv2d(128, n_class, 1) self.out_head4 = nn.Conv2d(64, n_class, 1) def forward(self, x): # if grayscale input, convert to 3 channels if x.size()[1] == 1: x = self.conv(x) # transformer backbone as encoder x1, x2, x3, x4 = self.backbone(x) # decoder x1_o, x2_o, x3_o, x4_o = self.decoder(x4, [x3, x2, x1]) # prediction heads p1 = self.out_head1(x1_o) p2 = self.out_head2(x2_o) p3 = self.out_head3(x3_o) p4 = self.out_head4(x4_o) p1 = F.interpolate(p1, scale_factor=32, mode='bilinear') p2 = F.interpolate(p2, scale_factor=16, mode='bilinear') p3 = F.interpolate(p3, scale_factor=8, mode='bilinear') p4 = F.interpolate(p4, scale_factor=4, mode='bilinear') return p1, p2, p3, p4 class PVT_CASCADE_Cat(nn.Module): def __init__(self, n_class=1): super(PVT_CASCADE_Cat, self).__init__() # conv block to convert single channel to 3 channels self.conv = nn.Sequential( nn.Conv2d(1, 3, kernel_size=1), nn.BatchNorm2d(3), nn.ReLU(inplace=True) ) # backbone network initialization with pretrained weight self.backbone = pvt_v2_b2() # [64, 128, 320, 512] path = './pretrained_pth/pvt/pvt_v2_b2.pth' save_model = torch.load(path) model_dict = self.backbone.state_dict() state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()} model_dict.update(state_dict) self.backbone.load_state_dict(model_dict) print('Model %s created, param count: %d' % ('PVT backbone: ', sum([m.numel() for m in self.backbone.parameters()]))) # decoder initialization self.decoder = CASCADE_Cat(channels=[512, 320, 128, 64]) print('Model %s created, param count: %d' % ('CASCADE_Cat decoder: ', sum([m.numel() for m in self.decoder.parameters()]))) # Prediction heads initialization self.out_head1 = nn.Conv2d(512, n_class, 1) self.out_head2 = nn.Conv2d(320, n_class, 1) self.out_head3 = nn.Conv2d(128, n_class, 1) self.out_head4 = nn.Conv2d(64, n_class, 1) def forward(self, x): # if grayscale input, convert to 3 channels if x.size()[1] == 1: x = self.conv(x) # transformer backbone as encoder x1, x2, x3, x4 = self.backbone(x) # decoder x1_o, x2_o, x3_o, x4_o = self.decoder(x4, [x3, x2, x1]) # prediction heads p1 = self.out_head1(x1_o) p2 = self.out_head2(x2_o) p3 = self.out_head3(x3_o) p4 = self.out_head4(x4_o) p1 = F.interpolate(p1, scale_factor=32, mode='bilinear') p2 = F.interpolate(p2, scale_factor=16, mode='bilinear') p3 = F.interpolate(p3, scale_factor=8, mode='bilinear') p4 = F.interpolate(p4, scale_factor=4, mode='bilinear') return p1, p2, p3, p4 class PVT_GCUP(nn.Module): def __init__(self, n_class=1, img_size=224, k=11, padding=5, conv='mr', gcb_act='gelu', activation='relu', skip_aggregation='additive'): super(PVT_GCUP, self).__init__() self.skip_aggregation = skip_aggregation self.n_class = n_class # conv block to convert single channel to 3 channels self.conv_1cto3c = nn.Sequential( nn.Conv2d(1, 3, kernel_size=1), nn.BatchNorm2d(3), nn.ReLU(inplace=True) ) # backbone network initialization with pretrained weight self.backbone = pvt_v2_b2() # [64, 128, 320, 512] path = './pretrained_pth/pvt/pvt_v2_b2.pth' save_model = torch.load(path) model_dict = self.backbone.state_dict() state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()} model_dict.update(state_dict) self.backbone.load_state_dict(model_dict) self.channels = [512, 320, 128, 64] # decoder initialization if self.skip_aggregation == 'additive':
logger = logging.getLogger(__name__) def np2th(weights, conv=False): """Possibly convert HWIO to OIHW.""" if conv: weights = weights.transpose([3, 2, 0, 1]) return torch.from_numpy(weights) class PVT_CUP(nn.Module): def __init__(self, n_class=1): super(PVT_CUP, self).__init__() # conv block to convert single channel to 3 channels self.conv = nn.Sequential( nn.Conv2d(1, 3, kernel_size=1), nn.BatchNorm2d(3), nn.ReLU(inplace=True) ) # backbone network initialization with pretrained weight self.backbone = pvt_v2_b2() # [64, 128, 320, 512] path = './pretrained_pth/pvt/pvt_v2_b2.pth' save_model = torch.load(path) model_dict = self.backbone.state_dict() state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()} model_dict.update(state_dict) self.backbone.load_state_dict(model_dict) # decoder initialization self.decoder = CUP(channels=[512, 320, 128, 64]) print('Model %s created, param count: %d' % ('CUP decoder: ', sum([m.numel() for m in self.decoder.parameters()]))) # Prediction heads initialization self.out_head1 = nn.Conv2d(512, n_class, 1) self.out_head2 = nn.Conv2d(320, n_class, 1) self.out_head3 = nn.Conv2d(128, n_class, 1) self.out_head4 = nn.Conv2d(64, n_class, 1) def forward(self, x): # if grayscale input, convert to 3 channels if x.size()[1] == 1: x = self.conv(x) # transformer backbone as encoder x1, x2, x3, x4 = self.backbone(x) # decoder x1_o, x2_o, x3_o, x4_o = self.decoder(x4, [x3, x2, x1]) # prediction heads p1 = self.out_head1(x1_o) p2 = self.out_head2(x2_o) p3 = self.out_head3(x3_o) p4 = self.out_head4(x4_o) p1 = F.interpolate(p1, scale_factor=32, mode='bilinear') p2 = F.interpolate(p2, scale_factor=16, mode='bilinear') p3 = F.interpolate(p3, scale_factor=8, mode='bilinear') p4 = F.interpolate(p4, scale_factor=4, mode='bilinear') return p1, p2, p3, p4 class PVT_CASCADE(nn.Module): def __init__(self, n_class=1): super(PVT_CASCADE, self).__init__() # conv block to convert single channel to 3 channels self.conv = nn.Sequential( nn.Conv2d(1, 3, kernel_size=1), nn.BatchNorm2d(3), nn.ReLU(inplace=True) ) # backbone network initialization with pretrained weight self.backbone = pvt_v2_b2() # [64, 128, 320, 512] path = './pretrained_pth/pvt/pvt_v2_b2.pth' save_model = torch.load(path) model_dict = self.backbone.state_dict() state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()} model_dict.update(state_dict) self.backbone.load_state_dict(model_dict) # decoder initialization self.decoder = CASCADE(channels=[512, 320, 128, 64]) print('Model %s created, param count: %d' % ('CASCADE decoder: ', sum([m.numel() for m in self.decoder.parameters()]))) # Prediction heads initialization self.out_head1 = nn.Conv2d(512, n_class, 1) self.out_head2 = nn.Conv2d(320, n_class, 1) self.out_head3 = nn.Conv2d(128, n_class, 1) self.out_head4 = nn.Conv2d(64, n_class, 1) def forward(self, x): # if grayscale input, convert to 3 channels if x.size()[1] == 1: x = self.conv(x) # transformer backbone as encoder x1, x2, x3, x4 = self.backbone(x) # decoder x1_o, x2_o, x3_o, x4_o = self.decoder(x4, [x3, x2, x1]) # prediction heads p1 = self.out_head1(x1_o) p2 = self.out_head2(x2_o) p3 = self.out_head3(x3_o) p4 = self.out_head4(x4_o) p1 = F.interpolate(p1, scale_factor=32, mode='bilinear') p2 = F.interpolate(p2, scale_factor=16, mode='bilinear') p3 = F.interpolate(p3, scale_factor=8, mode='bilinear') p4 = F.interpolate(p4, scale_factor=4, mode='bilinear') return p1, p2, p3, p4 class PVT_CASCADE_Cat(nn.Module): def __init__(self, n_class=1): super(PVT_CASCADE_Cat, self).__init__() # conv block to convert single channel to 3 channels self.conv = nn.Sequential( nn.Conv2d(1, 3, kernel_size=1), nn.BatchNorm2d(3), nn.ReLU(inplace=True) ) # backbone network initialization with pretrained weight self.backbone = pvt_v2_b2() # [64, 128, 320, 512] path = './pretrained_pth/pvt/pvt_v2_b2.pth' save_model = torch.load(path) model_dict = self.backbone.state_dict() state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()} model_dict.update(state_dict) self.backbone.load_state_dict(model_dict) print('Model %s created, param count: %d' % ('PVT backbone: ', sum([m.numel() for m in self.backbone.parameters()]))) # decoder initialization self.decoder = CASCADE_Cat(channels=[512, 320, 128, 64]) print('Model %s created, param count: %d' % ('CASCADE_Cat decoder: ', sum([m.numel() for m in self.decoder.parameters()]))) # Prediction heads initialization self.out_head1 = nn.Conv2d(512, n_class, 1) self.out_head2 = nn.Conv2d(320, n_class, 1) self.out_head3 = nn.Conv2d(128, n_class, 1) self.out_head4 = nn.Conv2d(64, n_class, 1) def forward(self, x): # if grayscale input, convert to 3 channels if x.size()[1] == 1: x = self.conv(x) # transformer backbone as encoder x1, x2, x3, x4 = self.backbone(x) # decoder x1_o, x2_o, x3_o, x4_o = self.decoder(x4, [x3, x2, x1]) # prediction heads p1 = self.out_head1(x1_o) p2 = self.out_head2(x2_o) p3 = self.out_head3(x3_o) p4 = self.out_head4(x4_o) p1 = F.interpolate(p1, scale_factor=32, mode='bilinear') p2 = F.interpolate(p2, scale_factor=16, mode='bilinear') p3 = F.interpolate(p3, scale_factor=8, mode='bilinear') p4 = F.interpolate(p4, scale_factor=4, mode='bilinear') return p1, p2, p3, p4 class PVT_GCUP(nn.Module): def __init__(self, n_class=1, img_size=224, k=11, padding=5, conv='mr', gcb_act='gelu', activation='relu', skip_aggregation='additive'): super(PVT_GCUP, self).__init__() self.skip_aggregation = skip_aggregation self.n_class = n_class # conv block to convert single channel to 3 channels self.conv_1cto3c = nn.Sequential( nn.Conv2d(1, 3, kernel_size=1), nn.BatchNorm2d(3), nn.ReLU(inplace=True) ) # backbone network initialization with pretrained weight self.backbone = pvt_v2_b2() # [64, 128, 320, 512] path = './pretrained_pth/pvt/pvt_v2_b2.pth' save_model = torch.load(path) model_dict = self.backbone.state_dict() state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()} model_dict.update(state_dict) self.backbone.load_state_dict(model_dict) self.channels = [512, 320, 128, 64] # decoder initialization if self.skip_aggregation == 'additive':
self.decoder = GCUP(channels=self.channels, img_size=img_size, k=k, padding=padding, conv=conv, gcb_act=gcb_act, activation=activation)
6
2023-10-24 17:49:10+00:00
16k
boppreh/hello_tls
src/hello_tls/scan.py
[ { "identifier": "ClientHello", "path": "src/hello_tls/protocol.py", "snippet": "class ScanError(Exception):\nclass ServerAlertError(ScanError):\nclass BadServerResponse(ScanError):\nclass ServerHello:\nclass ClientHello:\n def __init__(self, level: AlertLevel, description: AlertDescription):\ndef _ma...
from enum import Enum from multiprocessing.pool import ThreadPool from typing import Iterable, Union, List, Optional, Iterator, Callable, Any from urllib.parse import urlparse from datetime import datetime, timezone from .protocol import ClientHello, ScanError, make_client_hello, parse_server_hello, ServerAlertError, BadServerResponse, ServerHello, logger from .names_and_numbers import AlertDescription, CipherSuite, Group, Protocol, CompressionMethod from OpenSSL import SSL, crypto import socket import re import dataclasses import ssl, select
14,182
# Default number of workers/threads/concurrent connections to use. DEFAULT_MAX_WORKERS: int = 6 # Default socket connection timeout, in seconds. DEFAULT_TIMEOUT: float = 2 class DowngradeError(ScanError): """ Error for servers that attempt to downgrade beyond supported versions. """ pass class ConnectionError(ScanError): """ Class for error in resolving or connecting to a server. """ pass class ProxyError(ConnectionError): """ Class for errors in connecting through a proxy. """ pass @dataclasses.dataclass class ConnectionSettings: """ Settings for a connection to a server, including the host, port, and proxy. """ host: str port: int = 443 proxy: Optional[str] = None timeout_in_seconds: Optional[float] = DEFAULT_TIMEOUT date: datetime = dataclasses.field(default_factory=lambda: datetime.now(tz=timezone.utc).replace(microsecond=0)) def make_socket(settings: ConnectionSettings) -> socket.socket: """ Creates and connects a socket to the target server, through the chosen proxy if any. """ socket_host, socket_port = None, None # To appease the type checker. try: if not settings.proxy: socket_host, socket_port = settings.host, settings.port return socket.create_connection((socket_host, socket_port), timeout=settings.timeout_in_seconds) if not settings.proxy.startswith('http://'): raise ProxyError("Only HTTP proxies are supported at the moment.", settings.proxy) socket_host, socket_port = parse_target(settings.proxy, 80) sock = socket.create_connection((socket_host, socket_port), timeout=settings.timeout_in_seconds) sock.send(f"CONNECT {settings.host}:{settings.port} HTTP/1.1\r\nhost:{socket_host}\r\n\r\n".encode('utf-8')) sock_file = sock.makefile('r', newline='\r\n') line = sock_file.readline() if not re.fullmatch(r'HTTP/1\.[01] 200 Connection [Ee]stablished\r\n', line): sock_file.close() sock.close() raise ProxyError("Proxy refused the connection: ", line) while True: if sock_file.readline() == '\r\n': break return sock except TimeoutError as e: raise ConnectionError(f"Connection to {socket_host}:{socket_port} timed out after {settings.timeout_in_seconds} seconds") from e except socket.gaierror as e: raise ConnectionError(f"Could not resolve host {socket_host}") from e except socket.error as e: raise ConnectionError(f"Could not connect to {socket_host}:{socket_port}") from e
# Default number of workers/threads/concurrent connections to use. DEFAULT_MAX_WORKERS: int = 6 # Default socket connection timeout, in seconds. DEFAULT_TIMEOUT: float = 2 class DowngradeError(ScanError): """ Error for servers that attempt to downgrade beyond supported versions. """ pass class ConnectionError(ScanError): """ Class for error in resolving or connecting to a server. """ pass class ProxyError(ConnectionError): """ Class for errors in connecting through a proxy. """ pass @dataclasses.dataclass class ConnectionSettings: """ Settings for a connection to a server, including the host, port, and proxy. """ host: str port: int = 443 proxy: Optional[str] = None timeout_in_seconds: Optional[float] = DEFAULT_TIMEOUT date: datetime = dataclasses.field(default_factory=lambda: datetime.now(tz=timezone.utc).replace(microsecond=0)) def make_socket(settings: ConnectionSettings) -> socket.socket: """ Creates and connects a socket to the target server, through the chosen proxy if any. """ socket_host, socket_port = None, None # To appease the type checker. try: if not settings.proxy: socket_host, socket_port = settings.host, settings.port return socket.create_connection((socket_host, socket_port), timeout=settings.timeout_in_seconds) if not settings.proxy.startswith('http://'): raise ProxyError("Only HTTP proxies are supported at the moment.", settings.proxy) socket_host, socket_port = parse_target(settings.proxy, 80) sock = socket.create_connection((socket_host, socket_port), timeout=settings.timeout_in_seconds) sock.send(f"CONNECT {settings.host}:{settings.port} HTTP/1.1\r\nhost:{socket_host}\r\n\r\n".encode('utf-8')) sock_file = sock.makefile('r', newline='\r\n') line = sock_file.readline() if not re.fullmatch(r'HTTP/1\.[01] 200 Connection [Ee]stablished\r\n', line): sock_file.close() sock.close() raise ProxyError("Proxy refused the connection: ", line) while True: if sock_file.readline() == '\r\n': break return sock except TimeoutError as e: raise ConnectionError(f"Connection to {socket_host}:{socket_port} timed out after {settings.timeout_in_seconds} seconds") from e except socket.gaierror as e: raise ConnectionError(f"Could not resolve host {socket_host}") from e except socket.error as e: raise ConnectionError(f"Could not connect to {socket_host}:{socket_port}") from e
def send_hello(connection_settings: ConnectionSettings, client_hello: ClientHello) -> ServerHello:
0
2023-10-21 02:00:13+00:00
16k
YefanZhou/TempBalance
object_detection/src/YOLOv8/ultralytics/vit/sam/modules/mask_generator.py
[ { "identifier": "MaskData", "path": "object_detection/src/YOLOv8/ultralytics/vit/sam/amg.py", "snippet": "class MaskData:\n \"\"\"\n A structure for storing masks and their related data in batched format.\n Implements basic filtering and concatenation.\n \"\"\"\n\n def __init__(self, **kw...
from typing import Any, Dict, List, Optional, Tuple from torchvision.ops.boxes import batched_nms, box_area # type: ignore from ..amg import (MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh, build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes, is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy, uncrop_masks, uncrop_points) from .prompt_predictor import PromptPredictor from .sam import Sam from pycocotools import mask as mask_utils # type: ignore # noqa: F401 import numpy as np import torch import cv2 # type: ignore # noqa: F401
11,245
'predicted_iou': mask_data['iou_preds'][idx].item(), 'point_coords': [mask_data['points'][idx].tolist()], 'stability_score': mask_data['stability_score'][idx].item(), 'crop_box': box_xyxy_to_xywh(mask_data['crop_boxes'][idx]).tolist(), } curr_anns.append(ann) return curr_anns def _generate_masks(self, image: np.ndarray) -> MaskData: orig_size = image.shape[:2] crop_boxes, layer_idxs = generate_crop_boxes(orig_size, self.crop_n_layers, self.crop_overlap_ratio) # Iterate over image crops data = MaskData() for crop_box, layer_idx in zip(crop_boxes, layer_idxs): crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) data.cat(crop_data) # Remove duplicate masks between crops if len(crop_boxes) > 1: # Prefer masks from smaller crops scores = 1 / box_area(data['crop_boxes']) scores = scores.to(data['boxes'].device) keep_by_nms = batched_nms( data['boxes'].float(), scores, torch.zeros_like(data['boxes'][:, 0]), # categories iou_threshold=self.crop_nms_thresh, ) data.filter(keep_by_nms) data.to_numpy() return data def _process_crop( self, image: np.ndarray, crop_box: List[int], crop_layer_idx: int, orig_size: Tuple[int, ...], ) -> MaskData: # Crop the image and calculate embeddings x0, y0, x1, y1 = crop_box cropped_im = image[y0:y1, x0:x1, :] cropped_im_size = cropped_im.shape[:2] self.predictor.set_image(cropped_im) # Get points for this crop points_scale = np.array(cropped_im_size)[None, ::-1] points_for_image = self.point_grids[crop_layer_idx] * points_scale # Generate masks for this crop in batches data = MaskData() for (points, ) in batch_iterator(self.points_per_batch, points_for_image): batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size) data.cat(batch_data) del batch_data self.predictor.reset_image() # Remove duplicates within this crop. keep_by_nms = batched_nms( data['boxes'].float(), data['iou_preds'], torch.zeros_like(data['boxes'][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Return to the original image frame data['boxes'] = uncrop_boxes_xyxy(data['boxes'], crop_box) data['points'] = uncrop_points(data['points'], crop_box) data['crop_boxes'] = torch.tensor([crop_box for _ in range(len(data['rles']))]) return data def _process_batch( self, points: np.ndarray, im_size: Tuple[int, ...], crop_box: List[int], orig_size: Tuple[int, ...], ) -> MaskData: orig_h, orig_w = orig_size # Run model on this batch transformed_points = self.predictor.transform.apply_coords(points, im_size) in_points = torch.as_tensor(transformed_points, device=self.predictor.device) in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device) masks, iou_preds, _ = self.predictor.predict_torch( in_points[:, None, :], in_labels[:, None], multimask_output=True, return_logits=True, ) # Serialize predictions and store in MaskData data = MaskData( masks=masks.flatten(0, 1), iou_preds=iou_preds.flatten(0, 1), points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), ) del masks # Filter by predicted IoU if self.pred_iou_thresh > 0.0: keep_mask = data['iou_preds'] > self.pred_iou_thresh data.filter(keep_mask) # Calculate stability score data['stability_score'] = calculate_stability_score(data['masks'], self.predictor.model.mask_threshold, self.stability_score_offset) if self.stability_score_thresh > 0.0: keep_mask = data['stability_score'] >= self.stability_score_thresh data.filter(keep_mask) # Threshold masks and calculate boxes data['masks'] = data['masks'] > self.predictor.model.mask_threshold data['boxes'] = batched_mask_to_box(data['masks']) # Filter boxes that touch crop boundaries
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class SamAutomaticMaskGenerator: def __init__( self, model: Sam, points_per_side: Optional[int] = 32, points_per_batch: int = 64, pred_iou_thresh: float = 0.88, stability_score_thresh: float = 0.95, stability_score_offset: float = 1.0, box_nms_thresh: float = 0.7, crop_n_layers: int = 0, crop_nms_thresh: float = 0.7, crop_overlap_ratio: float = 512 / 1500, crop_n_points_downscale_factor: int = 1, point_grids: Optional[List[np.ndarray]] = None, min_mask_region_area: int = 0, output_mode: str = 'binary_mask', ) -> None: """ Using a SAM model, generates masks for the entire image. Generates a grid of point prompts over the image, then filters low quality and duplicate masks. The default settings are chosen for SAM with a ViT-H backbone. Arguments: model (Sam): The SAM model to use for mask prediction. points_per_side (int, None): The number of points to be sampled along one side of the image. The total number of points is points_per_side**2. If None, 'point_grids' must provide explicit point sampling. points_per_batch (int): Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. pred_iou_thresh (float): A filtering threshold in [0,1], using the model's predicted mask quality. stability_score_thresh (float): A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (float): The amount to shift the cutoff when calculated the stability score. box_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks. crop_n_layers (int): If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crop_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. crop_overlap_ratio (float): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (int): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. point_grids (list(np.ndarray), None): A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. min_mask_region_area (int): If >0, postprocessing will be applied to remove disconnected regions and holes in masks with area smaller than min_mask_region_area. Requires opencv. output_mode (str): The form masks are returned in. Can be 'binary_mask', 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. For large resolutions, 'binary_mask' may consume large amounts of memory. """ assert (points_per_side is None) != (point_grids is None), \ 'Exactly one of points_per_side or point_grid must be provided.' if points_per_side is not None: self.point_grids = build_all_layer_point_grids( points_per_side, crop_n_layers, crop_n_points_downscale_factor, ) elif point_grids is not None: self.point_grids = point_grids else: raise ValueError("Can't have both points_per_side and point_grid be None.") assert output_mode in {'binary_mask', 'uncompressed_rle', 'coco_rle'}, f'Unknown output_mode {output_mode}.' if output_mode == 'coco_rle': if min_mask_region_area > 0: self.predictor = PromptPredictor(model) self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.stability_score_thresh = stability_score_thresh self.stability_score_offset = stability_score_offset self.box_nms_thresh = box_nms_thresh self.crop_n_layers = crop_n_layers self.crop_nms_thresh = crop_nms_thresh self.crop_overlap_ratio = crop_overlap_ratio self.crop_n_points_downscale_factor = crop_n_points_downscale_factor self.min_mask_region_area = min_mask_region_area self.output_mode = output_mode # TODO: Temporary implementation for compatibility def __call__(self, image: np.ndarray, augment=False, visualize=False) -> List[Dict[str, Any]]: return self.generate(image) @torch.no_grad() def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: """ Generates masks for the given image. Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any), np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == 'coco_rle': mask_data['segmentations'] = [coco_encode_rle(rle) for rle in mask_data['rles']] elif self.output_mode == 'binary_mask': mask_data['segmentations'] = [rle_to_mask(rle) for rle in mask_data['rles']] else: mask_data['segmentations'] = mask_data['rles'] # Write mask records curr_anns = [] for idx in range(len(mask_data['segmentations'])): ann = { 'segmentation': mask_data['segmentations'][idx], 'area': area_from_rle(mask_data['rles'][idx]), 'bbox': box_xyxy_to_xywh(mask_data['boxes'][idx]).tolist(), 'predicted_iou': mask_data['iou_preds'][idx].item(), 'point_coords': [mask_data['points'][idx].tolist()], 'stability_score': mask_data['stability_score'][idx].item(), 'crop_box': box_xyxy_to_xywh(mask_data['crop_boxes'][idx]).tolist(), } curr_anns.append(ann) return curr_anns def _generate_masks(self, image: np.ndarray) -> MaskData: orig_size = image.shape[:2] crop_boxes, layer_idxs = generate_crop_boxes(orig_size, self.crop_n_layers, self.crop_overlap_ratio) # Iterate over image crops data = MaskData() for crop_box, layer_idx in zip(crop_boxes, layer_idxs): crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) data.cat(crop_data) # Remove duplicate masks between crops if len(crop_boxes) > 1: # Prefer masks from smaller crops scores = 1 / box_area(data['crop_boxes']) scores = scores.to(data['boxes'].device) keep_by_nms = batched_nms( data['boxes'].float(), scores, torch.zeros_like(data['boxes'][:, 0]), # categories iou_threshold=self.crop_nms_thresh, ) data.filter(keep_by_nms) data.to_numpy() return data def _process_crop( self, image: np.ndarray, crop_box: List[int], crop_layer_idx: int, orig_size: Tuple[int, ...], ) -> MaskData: # Crop the image and calculate embeddings x0, y0, x1, y1 = crop_box cropped_im = image[y0:y1, x0:x1, :] cropped_im_size = cropped_im.shape[:2] self.predictor.set_image(cropped_im) # Get points for this crop points_scale = np.array(cropped_im_size)[None, ::-1] points_for_image = self.point_grids[crop_layer_idx] * points_scale # Generate masks for this crop in batches data = MaskData() for (points, ) in batch_iterator(self.points_per_batch, points_for_image): batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size) data.cat(batch_data) del batch_data self.predictor.reset_image() # Remove duplicates within this crop. keep_by_nms = batched_nms( data['boxes'].float(), data['iou_preds'], torch.zeros_like(data['boxes'][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Return to the original image frame data['boxes'] = uncrop_boxes_xyxy(data['boxes'], crop_box) data['points'] = uncrop_points(data['points'], crop_box) data['crop_boxes'] = torch.tensor([crop_box for _ in range(len(data['rles']))]) return data def _process_batch( self, points: np.ndarray, im_size: Tuple[int, ...], crop_box: List[int], orig_size: Tuple[int, ...], ) -> MaskData: orig_h, orig_w = orig_size # Run model on this batch transformed_points = self.predictor.transform.apply_coords(points, im_size) in_points = torch.as_tensor(transformed_points, device=self.predictor.device) in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device) masks, iou_preds, _ = self.predictor.predict_torch( in_points[:, None, :], in_labels[:, None], multimask_output=True, return_logits=True, ) # Serialize predictions and store in MaskData data = MaskData( masks=masks.flatten(0, 1), iou_preds=iou_preds.flatten(0, 1), points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), ) del masks # Filter by predicted IoU if self.pred_iou_thresh > 0.0: keep_mask = data['iou_preds'] > self.pred_iou_thresh data.filter(keep_mask) # Calculate stability score data['stability_score'] = calculate_stability_score(data['masks'], self.predictor.model.mask_threshold, self.stability_score_offset) if self.stability_score_thresh > 0.0: keep_mask = data['stability_score'] >= self.stability_score_thresh data.filter(keep_mask) # Threshold masks and calculate boxes data['masks'] = data['masks'] > self.predictor.model.mask_threshold data['boxes'] = batched_mask_to_box(data['masks']) # Filter boxes that touch crop boundaries
keep_mask = ~is_box_near_crop_edge(data['boxes'], crop_box, [0, 0, orig_w, orig_h])
9
2023-10-24 00:45:55+00:00
16k
bytedance/ColTrack
models/dino/dino.py
[ { "identifier": "box_ops", "path": "util/box_ops.py", "snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef box_iou_pairwise(boxes1, boxes2):\ndef generalized_box_iou_pairwise(boxes1, boxes2):\ndef masks_to_boxes(m...
import copy import math import torch import torch.nn.functional as F from typing import List from torch import nn from torchvision.ops.boxes import nms from util import box_ops from util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_dist_avail_and_initialized, inverse_sigmoid, scale_sigmoid) from .backbone import build_backbone from .matcher import build_matcher from .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm, dice_loss) from .deformable_transformer import build_deformable_transformer from .utils import sigmoid_focal_loss, MLP from ..registry import MODULE_BUILD_FUNCS from .dn_components import prepare_for_cdn,dn_post_process
10,846
bias_value = -math.log((1 - prior_prob) / prior_prob) _class_embed.bias.data = torch.ones(self.num_classes) * bias_value nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0) nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0) if dec_pred_bbox_embed_share: box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)] else: box_embed_layerlist = [copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers)] if dec_pred_class_embed_share: class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)] else: class_embed_layerlist = [copy.deepcopy(_class_embed) for i in range(transformer.num_decoder_layers)] self.bbox_embed = nn.ModuleList(box_embed_layerlist) self.class_embed = nn.ModuleList(class_embed_layerlist) self.transformer.decoder.bbox_embed = self.bbox_embed self.transformer.decoder.class_embed = self.class_embed # two stage self.two_stage_type = two_stage_type self.two_stage_add_query_num = two_stage_add_query_num assert two_stage_type in ['no', 'standard'], "unknown param {} of two_stage_type".format(two_stage_type) if two_stage_type != 'no': if two_stage_bbox_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_bbox_embed = _bbox_embed else: self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed) if two_stage_class_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_class_embed = _class_embed else: self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed) self.refpoint_embed = None if self.two_stage_add_query_num > 0: self.init_ref_points(two_stage_add_query_num) self.decoder_sa_type = decoder_sa_type assert decoder_sa_type in ['sa', 'ca_label', 'ca_content'] # self.replace_sa_with_double_ca = replace_sa_with_double_ca if decoder_sa_type == 'ca_label': self.label_embedding = nn.Embedding(num_classes, hidden_dim) for layer in self.transformer.decoder.layers: layer.label_embedding = self.label_embedding else: for layer in self.transformer.decoder.layers: layer.label_embedding = None self.label_embedding = None self._reset_parameters() def _reset_parameters(self): # init input_proj for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) def init_ref_points(self, use_num_queries): raise NotImplementedError def forward(self, samples: NestedTensor, targets:List=None): """ The forward expects a NestedTensor, which consists of: - samples.tensor: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x num_classes] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if isinstance(samples, (list, torch.Tensor)): samples = nested_tensor_from_tensor_list(samples) features, poss = self.backbone(samples) srcs = [] masks = [] for l, feat in enumerate(features): src, mask = feat.decompose() srcs.append(self.input_proj[l](src)) masks.append(mask) assert mask is not None if self.num_feature_levels > len(srcs): _len_srcs = len(srcs) for l in range(_len_srcs, self.num_feature_levels): if l == _len_srcs: src = self.input_proj[l](features[-1].tensors) else: src = self.input_proj[l](srcs[-1]) m = samples.mask mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0] pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype) srcs.append(src) masks.append(mask) poss.append(pos_l) if self.dn_number > 0 or targets is not None: input_query_label, input_query_bbox, attn_mask, dn_meta =\ prepare_for_cdn(dn_args=(targets, self.dn_number, self.dn_label_noise_ratio, self.dn_box_noise_scale), training=self.training,num_queries=self.num_queries,num_classes=self.num_classes, hidden_dim=self.hidden_dim,label_enc=self.label_enc) else: assert targets is None input_query_bbox = input_query_label = attn_mask = dn_meta = None hs, reference, hs_enc, ref_enc, init_box_proposal = self.transformer(srcs, masks, input_query_bbox, poss,input_query_label,attn_mask) # In case num object=0 hs[0]+=self.label_enc.weight[0,0]*0.0 outputs_coord_list = [] for dec_lid, (layer_ref_sig, layer_bbox_embed, layer_hs) in enumerate(zip(reference[:-1], self.bbox_embed, hs)): layer_delta_unsig = layer_bbox_embed(layer_hs) layer_outputs_unsig = layer_delta_unsig + inverse_sigmoid(layer_ref_sig)
# ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR model and criterion classes. # 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. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ class DINO(nn.Module): """ This is the Cross-Attention Detector module that performs object detection """ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False, iter_update=False, query_dim=2, random_refpoints_xy=False, fix_refpoints_hw=-1, num_feature_levels=1, nheads=8, # two stage two_stage_type='no', # ['no', 'standard'] two_stage_add_query_num=0, dec_pred_class_embed_share=True, dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, decoder_sa_type = 'sa', num_patterns = 0, dn_number = 100, dn_box_noise_scale = 0.4, dn_label_noise_ratio = 0.5, dn_labelbook_size = 100, ): """ Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_classes: number of object classes num_queries: number of object queries, ie detection slot. This is the maximal number of objects Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. fix_refpoints_hw: -1(default): learn w and h for each box seperately >0 : given fixed number -2 : learn a shared w and h """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.num_classes = num_classes self.hidden_dim = hidden_dim = transformer.d_model self.num_feature_levels = num_feature_levels self.nheads = nheads self.label_enc = nn.Embedding(dn_labelbook_size + 1, hidden_dim) # setting query dim self.query_dim = query_dim assert query_dim == 4 self.random_refpoints_xy = random_refpoints_xy self.fix_refpoints_hw = fix_refpoints_hw # for dn training self.num_patterns = num_patterns self.dn_number = dn_number self.dn_box_noise_scale = dn_box_noise_scale self.dn_label_noise_ratio = dn_label_noise_ratio self.dn_labelbook_size = dn_labelbook_size # prepare input projection layers if num_feature_levels > 1: num_backbone_outs = len(backbone.num_channels) input_proj_list = [] for _ in range(num_backbone_outs): in_channels = backbone.num_channels[_] input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, hidden_dim), )) in_channels = hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: assert two_stage_type == 'no', "two_stage_type should be no if num_feature_levels=1 !!!" self.input_proj = nn.ModuleList([ nn.Sequential( nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )]) self.backbone = backbone self.aux_loss = aux_loss self.box_pred_damping = box_pred_damping = None self.iter_update = iter_update assert iter_update, "Why not iter_update?" # prepare pred layers self.dec_pred_class_embed_share = dec_pred_class_embed_share self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share # prepare class & box embed _class_embed = nn.Linear(hidden_dim, num_classes) _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3) # init the two embed layers prior_prob = 0.01 bias_value = -math.log((1 - prior_prob) / prior_prob) _class_embed.bias.data = torch.ones(self.num_classes) * bias_value nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0) nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0) if dec_pred_bbox_embed_share: box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)] else: box_embed_layerlist = [copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers)] if dec_pred_class_embed_share: class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)] else: class_embed_layerlist = [copy.deepcopy(_class_embed) for i in range(transformer.num_decoder_layers)] self.bbox_embed = nn.ModuleList(box_embed_layerlist) self.class_embed = nn.ModuleList(class_embed_layerlist) self.transformer.decoder.bbox_embed = self.bbox_embed self.transformer.decoder.class_embed = self.class_embed # two stage self.two_stage_type = two_stage_type self.two_stage_add_query_num = two_stage_add_query_num assert two_stage_type in ['no', 'standard'], "unknown param {} of two_stage_type".format(two_stage_type) if two_stage_type != 'no': if two_stage_bbox_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_bbox_embed = _bbox_embed else: self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed) if two_stage_class_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_class_embed = _class_embed else: self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed) self.refpoint_embed = None if self.two_stage_add_query_num > 0: self.init_ref_points(two_stage_add_query_num) self.decoder_sa_type = decoder_sa_type assert decoder_sa_type in ['sa', 'ca_label', 'ca_content'] # self.replace_sa_with_double_ca = replace_sa_with_double_ca if decoder_sa_type == 'ca_label': self.label_embedding = nn.Embedding(num_classes, hidden_dim) for layer in self.transformer.decoder.layers: layer.label_embedding = self.label_embedding else: for layer in self.transformer.decoder.layers: layer.label_embedding = None self.label_embedding = None self._reset_parameters() def _reset_parameters(self): # init input_proj for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) def init_ref_points(self, use_num_queries): raise NotImplementedError def forward(self, samples: NestedTensor, targets:List=None): """ The forward expects a NestedTensor, which consists of: - samples.tensor: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x num_classes] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if isinstance(samples, (list, torch.Tensor)): samples = nested_tensor_from_tensor_list(samples) features, poss = self.backbone(samples) srcs = [] masks = [] for l, feat in enumerate(features): src, mask = feat.decompose() srcs.append(self.input_proj[l](src)) masks.append(mask) assert mask is not None if self.num_feature_levels > len(srcs): _len_srcs = len(srcs) for l in range(_len_srcs, self.num_feature_levels): if l == _len_srcs: src = self.input_proj[l](features[-1].tensors) else: src = self.input_proj[l](srcs[-1]) m = samples.mask mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0] pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype) srcs.append(src) masks.append(mask) poss.append(pos_l) if self.dn_number > 0 or targets is not None: input_query_label, input_query_bbox, attn_mask, dn_meta =\ prepare_for_cdn(dn_args=(targets, self.dn_number, self.dn_label_noise_ratio, self.dn_box_noise_scale), training=self.training,num_queries=self.num_queries,num_classes=self.num_classes, hidden_dim=self.hidden_dim,label_enc=self.label_enc) else: assert targets is None input_query_bbox = input_query_label = attn_mask = dn_meta = None hs, reference, hs_enc, ref_enc, init_box_proposal = self.transformer(srcs, masks, input_query_bbox, poss,input_query_label,attn_mask) # In case num object=0 hs[0]+=self.label_enc.weight[0,0]*0.0 outputs_coord_list = [] for dec_lid, (layer_ref_sig, layer_bbox_embed, layer_hs) in enumerate(zip(reference[:-1], self.bbox_embed, hs)): layer_delta_unsig = layer_bbox_embed(layer_hs) layer_outputs_unsig = layer_delta_unsig + inverse_sigmoid(layer_ref_sig)
layer_outputs_unsig = scale_sigmoid(layer_outputs_unsig.sigmoid())
8
2023-10-16 02:18:33+00:00
16k
YuroFR/freqtrade-modded-crypto-trading-bot
freqtrade/data/history/idatahandler.py
[ { "identifier": "misc", "path": "freqtrade/misc.py", "snippet": "def decimals_per_coin(coin: str):\ndef round_coin_value(\n value: float, coin: str, show_coin_name=True, keep_trailing_zeros=False) -> str:\ndef file_dump_json(filename: Path, data: Any, is_zip: bool = False, log: bool = True) -> No...
import logging import re from abc import ABC, abstractmethod from copy import deepcopy from datetime import datetime, timezone from pathlib import Path from typing import List, Optional, Tuple, Type from pandas import DataFrame from freqtrade import misc from freqtrade.configuration import TimeRange from freqtrade.constants import DEFAULT_TRADES_COLUMNS, ListPairsWithTimeframes from freqtrade.data.converter import (clean_ohlcv_dataframe, trades_convert_types, trades_df_remove_duplicates, trim_dataframe) from freqtrade.enums import CandleType, TradingMode from freqtrade.exchange import timeframe_to_seconds from .jsondatahandler import JsonDataHandler from .jsondatahandler import JsonGzDataHandler from .hdf5datahandler import HDF5DataHandler from .featherdatahandler import FeatherDataHandler from .parquetdatahandler import ParquetDataHandler
10,948
""" Abstract datahandler interface. It's subclasses handle and storing data from disk. """ logger = logging.getLogger(__name__) class IDataHandler(ABC): _OHLCV_REGEX = r'^([a-zA-Z_\d-]+)\-(\d+[a-zA-Z]{1,2})\-?([a-zA-Z_]*)?(?=\.)' def __init__(self, datadir: Path) -> None: self._datadir = datadir @classmethod def _get_file_extension(cls) -> str: """ Get file extension for this particular datahandler """ raise NotImplementedError() @classmethod def ohlcv_get_available_data( cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes: """ Returns a list of all pairs with ohlcv data available in this datadir :param datadir: Directory to search for ohlcv files :param trading_mode: trading-mode to be used :return: List of Tuples of (pair, timeframe, CandleType) """ if trading_mode == TradingMode.FUTURES: datadir = datadir.joinpath('futures') _tmp = [ re.search( cls._OHLCV_REGEX, p.name ) for p in datadir.glob(f"*.{cls._get_file_extension()}")] return [ ( cls.rebuild_pair_from_filename(match[1]), cls.rebuild_timeframe_from_filename(match[2]),
""" Abstract datahandler interface. It's subclasses handle and storing data from disk. """ logger = logging.getLogger(__name__) class IDataHandler(ABC): _OHLCV_REGEX = r'^([a-zA-Z_\d-]+)\-(\d+[a-zA-Z]{1,2})\-?([a-zA-Z_]*)?(?=\.)' def __init__(self, datadir: Path) -> None: self._datadir = datadir @classmethod def _get_file_extension(cls) -> str: """ Get file extension for this particular datahandler """ raise NotImplementedError() @classmethod def ohlcv_get_available_data( cls, datadir: Path, trading_mode: TradingMode) -> ListPairsWithTimeframes: """ Returns a list of all pairs with ohlcv data available in this datadir :param datadir: Directory to search for ohlcv files :param trading_mode: trading-mode to be used :return: List of Tuples of (pair, timeframe, CandleType) """ if trading_mode == TradingMode.FUTURES: datadir = datadir.joinpath('futures') _tmp = [ re.search( cls._OHLCV_REGEX, p.name ) for p in datadir.glob(f"*.{cls._get_file_extension()}")] return [ ( cls.rebuild_pair_from_filename(match[1]), cls.rebuild_timeframe_from_filename(match[2]),
CandleType.from_string(match[3])
7
2023-10-21 10:02:05+00:00
16k
yanzhh/HGERE
transformers/src/transformers/modeling_roberta.py
[ { "identifier": "RobertaConfig", "path": "transformers/src/transformers/configuration_roberta.py", "snippet": "class RobertaConfig(BertConfig):\n r\"\"\"\n This is the configuration class to store the configuration of an :class:`~transformers.RobertaModel`.\n It is used to instantiate a...
import logging import torch import torch.nn as nn from torch.nn import CrossEntropyLoss, MSELoss from .configuration_roberta import RobertaConfig from .file_utils import add_start_docstrings, add_start_docstrings_to_callable from .modeling_bert import BertEmbeddings, BertLayerNorm, BertModel, BertPreTrainedModel, gelu, BertModel from .modeling_utils import create_position_ids_from_input_ids
10,831
config_class = RobertaConfig pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP base_model_prefix = "roberta" def __init__(self, config): super().__init__(config) self.embeddings = RobertaEmbeddings(config) self.init_weights() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value @add_start_docstrings("""RoBERTa Model with a `language modeling` head on top. """, ROBERTA_START_DOCSTRING) class RobertaForMaskedLM(BertPreTrainedModel): config_class = RobertaConfig pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP base_model_prefix = "roberta" def __init__(self, config): super().__init__(config) self.roberta = RobertaModel(config) self.lm_head = RobertaLMHead(config) self.init_weights() def get_output_embeddings(self): return self.lm_head.decoder @add_start_docstrings_to_callable(ROBERTA_INPUTS_DOCSTRING) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, masked_lm_labels=None, ): r""" masked_lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` Returns: :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.RobertaConfig`) and inputs: masked_lm_loss (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: Masked language modeling loss. prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`) Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: from transformers import RobertaTokenizer, RobertaForMaskedLM import torch tokenizer = RobertaTokenizer.from_pretrained('roberta-base') model = RobertaForMaskedLM.from_pretrained('roberta-base') input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 outputs = model(input_ids, masked_lm_labels=input_ids) loss, prediction_scores = outputs[:2] """ outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, ) sequence_output = outputs[0] prediction_scores = self.lm_head(sequence_output) outputs = (prediction_scores,) + outputs[2:] # Add hidden states and attention if they are here if masked_lm_labels is not None: loss_fct = CrossEntropyLoss() masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1)) outputs = (masked_lm_loss,) + outputs return outputs # (masked_lm_loss), prediction_scores, (hidden_states), (attentions) class RobertaLMHead(nn.Module): """Roberta Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, features, **kwargs): x = self.dense(features)
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """PyTorch RoBERTa model. """ # from .modeling_ensemblebert import EnsembleBertModel logger = logging.getLogger(__name__) ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP = { "roberta-base": "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-pytorch_model.bin", "roberta-large": "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-pytorch_model.bin", "roberta-large-mnli": "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-mnli-pytorch_model.bin", "distilroberta-base": "https://s3.amazonaws.com/models.huggingface.co/bert/distilroberta-base-pytorch_model.bin", "roberta-base-openai-detector": "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-openai-detector-pytorch_model.bin", "roberta-large-openai-detector": "https://s3.amazonaws.com/models.huggingface.co/bert/roberta-large-openai-detector-pytorch_model.bin", } class RobertaEmbeddings(BertEmbeddings): """ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing. """ def __init__(self, config): super().__init__(config) self.padding_idx = 1 self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=self.padding_idx) self.position_embeddings = nn.Embedding( config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx ) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): if position_ids is None: if input_ids is not None: # Create the position ids from the input token ids. Any padded tokens remain padded. position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx).to(input_ids.device) else: position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds) return super().forward( input_ids, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds ) def create_position_ids_from_inputs_embeds(self, inputs_embeds): """ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. :param torch.Tensor inputs_embeds: :return torch.Tensor: """ input_shape = inputs_embeds.size()[:-1] sequence_length = input_shape[1] position_ids = torch.arange( self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device ) return position_ids.unsqueeze(0).expand(input_shape) ROBERTA_START_DOCSTRING = r""" This model is a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`_ sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config (:class:`~transformers.RobertaConfig`): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights. """ ROBERTA_INPUTS_DOCSTRING = r""" Args: input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using :class:`transformers.RobertaTokenizer`. See :func:`transformers.PreTrainedTokenizer.encode` and :func:`transformers.PreTrainedTokenizer.encode_plus` for details. `What are input IDs? <../glossary.html#input-ids>`__ attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`): Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens. `What are attention masks? <../glossary.html#attention-mask>`__ token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`): Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1`` corresponds to a `sentence B` token `What are token type IDs? <../glossary.html#token-type-ids>`_ position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0, config.max_position_embeddings - 1]``. `What are position IDs? <../glossary.html#position-ids>`_ head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`): Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``: :obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**. inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`): Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. """ @add_start_docstrings( "The bare RoBERTa Model transformer outputting raw hidden-states without any specific head on top.", ROBERTA_START_DOCSTRING, ) class RobertaModel(BertModel): """ This class overrides :class:`~transformers.BertModel`. Please check the superclass for the appropriate documentation alongside usage examples. """ config_class = RobertaConfig pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP base_model_prefix = "roberta" def __init__(self, config): super().__init__(config) self.embeddings = RobertaEmbeddings(config) self.init_weights() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value @add_start_docstrings("""RoBERTa Model with a `language modeling` head on top. """, ROBERTA_START_DOCSTRING) class RobertaForMaskedLM(BertPreTrainedModel): config_class = RobertaConfig pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP base_model_prefix = "roberta" def __init__(self, config): super().__init__(config) self.roberta = RobertaModel(config) self.lm_head = RobertaLMHead(config) self.init_weights() def get_output_embeddings(self): return self.lm_head.decoder @add_start_docstrings_to_callable(ROBERTA_INPUTS_DOCSTRING) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, masked_lm_labels=None, ): r""" masked_lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` Returns: :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.RobertaConfig`) and inputs: masked_lm_loss (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``: Masked language modeling loss. prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`) Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: from transformers import RobertaTokenizer, RobertaForMaskedLM import torch tokenizer = RobertaTokenizer.from_pretrained('roberta-base') model = RobertaForMaskedLM.from_pretrained('roberta-base') input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 outputs = model(input_ids, masked_lm_labels=input_ids) loss, prediction_scores = outputs[:2] """ outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, ) sequence_output = outputs[0] prediction_scores = self.lm_head(sequence_output) outputs = (prediction_scores,) + outputs[2:] # Add hidden states and attention if they are here if masked_lm_labels is not None: loss_fct = CrossEntropyLoss() masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1)) outputs = (masked_lm_loss,) + outputs return outputs # (masked_lm_loss), prediction_scores, (hidden_states), (attentions) class RobertaLMHead(nn.Module): """Roberta Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, features, **kwargs): x = self.dense(features)
x = gelu(x)
3
2023-10-15 02:31:09+00:00
16k
generative-skill-chaining/gsc-code
generative_skill_chaining/envs/pybullet/table/primitives.py
[ { "identifier": "base", "path": "generative_skill_chaining/envs/base.py", "snippet": "class Primitive:\nclass Env(gym.Env[np.ndarray, np.ndarray]):\nclass PrimitiveEnv(Env):\n class Scope:\n def __init__(self, env: \"Env\", idx_policy: int):\n def env(self) -> \"Env\":\n def idx_policy(self)...
import abc import random import gym import numpy as np import symbolic from typing import Callable, Dict, List, Optional, NamedTuple, Type from ctrlutils import eigen from generative_skill_chaining.envs import base as envs from generative_skill_chaining.envs.pybullet.sim import math from generative_skill_chaining.envs.pybullet.sim.robot import ControlException, Robot from generative_skill_chaining.envs.pybullet.table.objects import Box, Hook, Rack, Null, Object from generative_skill_chaining.envs.pybullet.table import ( object_state, utils, primitive_actions, ) from generative_skill_chaining.envs.pybullet.table_env import TableEnv from generative_skill_chaining.envs.pybullet.table_env import TableEnv from generative_skill_chaining.envs.pybullet.table_env import TableEnv from generative_skill_chaining.envs.pybullet.table_env import TableEnv from generative_skill_chaining.envs.pybullet.table_env import TableEnv from generative_skill_chaining.envs.pybullet.table_env import TableEnv
11,174
dbprint = lambda *args: None # noqa # dbprint = print ACTION_CONSTRAINTS = {"max_lift_height": 0.4, "max_lift_radius": 0.7} def compute_top_down_orientation( theta: float, quat_obj: eigen.Quaterniond = eigen.Quaterniond.identity() ) -> eigen.Quaterniond: """Computes the top-down orientation of the end-effector with respect to a target object. Args: theta: Angle of the gripper about the world z-axis wrt the target object. quat_obj: Orientation of the target object. """ command_aa = eigen.AngleAxisd(theta, np.array([0.0, 0.0, 1.0])) command_quat = quat_obj * eigen.Quaterniond(command_aa) return command_quat def did_object_move( obj: Object, old_pose: math.Pose, max_delta_xyz: float = 0.05, max_delta_theta: float = 5.0 * np.pi / 180, ) -> bool: """Checks if the object has moved significantly from its old pose.""" new_pose = obj.pose() T_old_to_world = old_pose.to_eigen() T_new_to_world = new_pose.to_eigen() T_new_to_old = T_old_to_world.inverse() * T_new_to_world delta_xyz = float(np.linalg.norm(T_new_to_old.translation)) delta_theta = eigen.AngleAxisd(eigen.Quaterniond(T_new_to_old.linear)).angle return delta_xyz >= max_delta_xyz or delta_theta >= max_delta_theta def initialize_robot_pose(robot: Robot) -> bool: x_min, x_max = ( utils.TABLE_CONSTRAINTS["table_x_min"], ACTION_CONSTRAINTS["max_lift_radius"], ) y_min = utils.TABLE_CONSTRAINTS["table_y_min"] y_max = utils.TABLE_CONSTRAINTS["table_y_max"] xy_min = np.array([x_min, y_min]) xy_max = np.array([x_max, y_max]) while True: xy = np.random.uniform(xy_min, xy_max) if np.linalg.norm(xy) < ACTION_CONSTRAINTS["max_lift_radius"]: break theta = np.random.uniform(*object_state.ObjectState.RANGES["wz"]) pos = np.append(xy, ACTION_CONSTRAINTS["max_lift_height"]) aa = eigen.AngleAxisd(theta, np.array([0.0, 0.0, 1.0])) quat = eigen.Quaterniond(aa) try: robot.goto_pose(pos, quat)
dbprint = lambda *args: None # noqa # dbprint = print ACTION_CONSTRAINTS = {"max_lift_height": 0.4, "max_lift_radius": 0.7} def compute_top_down_orientation( theta: float, quat_obj: eigen.Quaterniond = eigen.Quaterniond.identity() ) -> eigen.Quaterniond: """Computes the top-down orientation of the end-effector with respect to a target object. Args: theta: Angle of the gripper about the world z-axis wrt the target object. quat_obj: Orientation of the target object. """ command_aa = eigen.AngleAxisd(theta, np.array([0.0, 0.0, 1.0])) command_quat = quat_obj * eigen.Quaterniond(command_aa) return command_quat def did_object_move( obj: Object, old_pose: math.Pose, max_delta_xyz: float = 0.05, max_delta_theta: float = 5.0 * np.pi / 180, ) -> bool: """Checks if the object has moved significantly from its old pose.""" new_pose = obj.pose() T_old_to_world = old_pose.to_eigen() T_new_to_world = new_pose.to_eigen() T_new_to_old = T_old_to_world.inverse() * T_new_to_world delta_xyz = float(np.linalg.norm(T_new_to_old.translation)) delta_theta = eigen.AngleAxisd(eigen.Quaterniond(T_new_to_old.linear)).angle return delta_xyz >= max_delta_xyz or delta_theta >= max_delta_theta def initialize_robot_pose(robot: Robot) -> bool: x_min, x_max = ( utils.TABLE_CONSTRAINTS["table_x_min"], ACTION_CONSTRAINTS["max_lift_radius"], ) y_min = utils.TABLE_CONSTRAINTS["table_y_min"] y_max = utils.TABLE_CONSTRAINTS["table_y_max"] xy_min = np.array([x_min, y_min]) xy_max = np.array([x_max, y_max]) while True: xy = np.random.uniform(xy_min, xy_max) if np.linalg.norm(xy) < ACTION_CONSTRAINTS["max_lift_radius"]: break theta = np.random.uniform(*object_state.ObjectState.RANGES["wz"]) pos = np.append(xy, ACTION_CONSTRAINTS["max_lift_height"]) aa = eigen.AngleAxisd(theta, np.array([0.0, 0.0, 1.0])) quat = eigen.Quaterniond(aa) try: robot.goto_pose(pos, quat)
except ControlException as e:
2
2023-10-16 00:22:40+00:00
16k
akashgreninja/GreSec
backend/venv/lib/python3.10/site-packages/pydantic/dataclasses.py
[ { "identifier": "_config", "path": "backend/venv/lib/python3.10/site-packages/pydantic/_internal/_config.py", "snippet": "DEPRECATION_MESSAGE = 'Support for class-based `config` is deprecated, use ConfigDict instead.'\nV2_REMOVED_KEYS = {\n 'allow_mutation',\n 'error_msg_templates',\n 'fields',...
import dataclasses import sys import types from typing import TYPE_CHECKING, Any, Callable, Generic, NoReturn, TypeVar, overload from typing_extensions import Literal, TypeGuard, dataclass_transform from ._internal import _config, _decorators, _typing_extra from ._internal import _dataclasses as _pydantic_dataclasses from ._migration import getattr_migration from .config import ConfigDict from .fields import Field from ._internal._dataclasses import PydanticDataclass
11,981
"""Provide an enhanced dataclass that performs validation.""" from __future__ import annotations as _annotations if TYPE_CHECKING: __all__ = 'dataclass', 'rebuild_dataclass' _T = TypeVar('_T') if sys.version_info >= (3, 10):
"""Provide an enhanced dataclass that performs validation.""" from __future__ import annotations as _annotations if TYPE_CHECKING: __all__ = 'dataclass', 'rebuild_dataclass' _T = TypeVar('_T') if sys.version_info >= (3, 10):
@dataclass_transform(field_specifiers=(dataclasses.field, Field))
6
2023-10-23 18:09:28+00:00
16k
zju3dv/nr_in_a_room
data_gen/batch_real_scene_neural_render.py
[ { "identifier": "read_json", "path": "utils/util.py", "snippet": "def read_json(fname):\n fname = Path(fname)\n with fname.open(\"rt\") as handle:\n return json.load(handle, object_hook=OrderedDict)" }, { "identifier": "read_yaml", "path": "utils/util.py", "snippet": "def re...
import sys import os import torch import numpy as np import imageio import time import cv2 from tqdm import tqdm from argparse import ArgumentParser from utils.util import read_json, read_yaml from optim.room_optimizer import RoomOptimizer from optim.misc_utils import read_real_scene_localization, read_testing_config from scipy.spatial.transform import Rotation
14,238
os.environ["OMP_NUM_THREADS"] = "1" # noqa os.environ["MKL_NUM_THREADS"] = "1" # noqa sys.path.append(".") # noqa def render_frame(config, target_dir): # or load from config active_instance_id = config.active_instance_id dataset_config = config.dataset_config["dataset"] scene_info_json_path = config.scene_info_json active_instance_id = [0] for obj_info in read_json(scene_info_json_path)["objs"]: active_instance_id += [obj_info["id"]] bg_scale_factor = 1 bg_scene_center = [0, 0, 0] if config.bg_dataset_config != "": bg_dataset_config = config.bg_dataset_config["dataset"] bg_scale_factor = bg_dataset_config["scale_factor"] bg_scene_center = bg_dataset_config["scene_center"] # intialize room optimizer
os.environ["OMP_NUM_THREADS"] = "1" # noqa os.environ["MKL_NUM_THREADS"] = "1" # noqa sys.path.append(".") # noqa def render_frame(config, target_dir): # or load from config active_instance_id = config.active_instance_id dataset_config = config.dataset_config["dataset"] scene_info_json_path = config.scene_info_json active_instance_id = [0] for obj_info in read_json(scene_info_json_path)["objs"]: active_instance_id += [obj_info["id"]] bg_scale_factor = 1 bg_scene_center = [0, 0, 0] if config.bg_dataset_config != "": bg_dataset_config = config.bg_dataset_config["dataset"] bg_scale_factor = bg_dataset_config["scale_factor"] bg_scene_center = bg_dataset_config["scene_center"] # intialize room optimizer
room_optimizer = RoomOptimizer(
2
2023-10-15 08:41:29+00:00
16k
WenzhengZhang/Seq2seqCoref
trainer.py
[ { "identifier": "CorefAllMetrics", "path": "metrics.py", "snippet": "class CorefAllMetrics(object):\n \"\"\"\n Wrapper for coreference resolution metrics.\n \"\"\"\n\n @staticmethod\n def _get_mention_to_x(clusters: List[list]) -> dict:\n mention_to_x = {}\n for cluster in c...
import time import torch.distributed as dist import sys import numpy as np import os import json import re import torch.nn as nn import torch import shutil import math import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met import torch_xla.distributed.parallel_loader as pl import smdistributed.modelparallel.torch as smp import safetensors.torch from tqdm.auto import tqdm from transformers.trainer_utils import HPSearchBackend, speed_metrics, \ TrainOutput from pathlib import Path from torch.utils.data import RandomSampler from torch.utils.data.distributed import DistributedSampler from transformers.trainer_callback import TrainerState from transformers.trainer import TRAINER_STATE_NAME, OptimizerNames from transformers.utils import is_apex_available from transformers.integrations import hp_params from transformers import Seq2SeqTrainer from packaging import version from collections import defaultdict from metrics import CorefAllMetrics from typing import Dict, Union, Any, Optional, Tuple, List from transformers.debug_utils import DebugOption, DebugUnderflowOverflow from transformers.pytorch_utils import is_torch_less_than_1_11 from torch.utils.data import DataLoader from transformers.trainer_utils import EvalLoopOutput, has_length, \ denumpify_detensorize, ShardedDDPOption from data import get_document_predicts, parse_int_output_tokens, \ parse_short_target_tokens, parse_nonint_output_tokens from constants import SPECIAL_IDS, MARK_SPECIAL_IDS, NON_INT_SPECIAL_IDS, \ MENTION_END_NON_INT_SPECIAL_IDS from transformers.deepspeed import deepspeed_init from transformers.trainer_pt_utils import find_batch_size, nested_concat, \ nested_numpify, IterableDatasetShard, nested_truncate, get_parameter_names from transformers.modeling_utils import PreTrainedModel, unwrap_model, \ load_sharded_checkpoint from transformers.utils import logging, is_torch_tpu_available, \ is_sagemaker_mp_enabled, is_safetensors_available, SAFE_WEIGHTS_NAME, \ WEIGHTS_NAME, WEIGHTS_INDEX_NAME from transformers.integrations import is_fairscale_available from transformers.dependency_versions_check import dep_version_check from smdistributed.modelparallel import __version__ as SMP_VERSION from apex import amp from transformers import LogitsProcessorList from logits_processor import ShortSeqProcessor, IntProcessor, NonIntProcessor from transformers.trainer_seq2seq import is_deepspeed_zero3_enabled
10,939
logger.info( "\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: # Wait for everyone to get here so we are sur the model has been saved by process 0. if is_torch_tpu_available(): xm.rendezvous("load_best_model_at_end") elif args.local_rank != -1: dist.barrier() elif is_sagemaker_mp_enabled(): smp.barrier() self._load_best_model() # add remaining tr_loss self._total_loss_scalar += tr_loss.item() train_loss = self._total_loss_scalar / self.state.global_step metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) self.store_flos() metrics["total_flos"] = self.state.total_flos metrics["train_loss"] = train_loss self.is_in_train = False self._memory_tracker.stop_and_update_metrics(metrics) self.log(metrics) run_dir = self._get_output_dir(trial) checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint. if self.state.best_model_checkpoint is not None and \ self.args.save_total_limit == 1 and self.is_world_process_zero(): for checkpoint in checkpoints_sorted: if checkpoint != self.state.best_model_checkpoint: logger.info( f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") shutil.rmtree(checkpoint) self.control = self.callback_handler.on_train_end(args, self.state, self.control) return TrainOutput(self.state.global_step, train_loss, metrics) def my_compute_metrics(self, doc_labels: Dict[str, List[List]], predicts: Any, samples: List, split: str, id_to_name: Dict = None ) -> Dict: if self.args.joint_train: data_names = self.args.joint_data_names.split(',') joint_threds = [ int(t) for t in self.args.joint_min_num_mentions.split(',')] name_to_threds = {n: t for n, t in zip(data_names, joint_threds)} documents_to_chunk_data = defaultdict(list) documents_to_chunk_gold = defaultdict(list) predictions = {} golds = {} assert len(samples) == len(predicts) out_sents = [] last_doc_id = re.sub(r'_\d+$', '', samples[0]['doc_key']) for sample, predict in zip(samples, predicts): doc_key = sample['doc_key'] doc_id = re.sub(r'_\d+$', '', doc_key) # require convert to ids first input_ids = sample['sentence'] subtoken_map = sample['subtoken_map'] offset = sample['offset'] # remove bos predict_ids = predict[1:].tolist() gold_data = sample['seg_clusters'] if self.args.joint_train: thred = name_to_threds[id_to_name[doc_id]] else: thred = self.args.min_num_mentions if self.args.seq2seq_type == "short_seq": special_ids = MARK_SPECIAL_IDS if self.args.mark_sentence \ else SPECIAL_IDS pred_data, aligned_input_ids, aligned_pred_ids = \ parse_short_target_tokens(input_ids, predict_ids, special_ids, subtoken_map, self.tokenizer, self.args.align_mode, thred, self.args.mark_sentence ) pred_tokens = self.tokenizer.convert_ids_to_tokens( predict_ids) out_predict = { 'doc_key': doc_key, 'pred_tokens': pred_tokens, 'pred_text': self.tokenizer.convert_tokens_to_string( pred_tokens), 'pred_aligned_text': self.tokenizer.convert_ids_to_tokens( aligned_pred_ids ), 'input_aligned_text': self.tokenizer.convert_ids_to_tokens( aligned_input_ids ) } else: is_tagging = (self.args.seq2seq_type == 'tagging') if self.args.action_type == 'integer': pred_data, pred_token_mentions, predict_ids = \ parse_int_output_tokens( input_ids, predict_ids, SPECIAL_IDS, subtoken_map, self.tokenizer, thred, is_tagging) else: special_ids = MENTION_END_NON_INT_SPECIAL_IDS if \
if is_torch_tpu_available(check_device=False): if is_fairscale_available(): dep_version_check("fairscale") if is_sagemaker_mp_enabled(): IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse( "1.10") else: IS_SAGEMAKER_MP_POST_1_10 = False if is_safetensors_available(): if is_apex_available(): logger = logging.get_logger(__name__) TRAINING_ARGS_NAME = "training_args.bin" TRAINER_STATE_NAME = "trainer_state.json" OPTIMIZER_NAME = "optimizer.pt" SCHEDULER_NAME = "scheduler.pt" SCALER_NAME = "scaler.pt" class CorefTrainer(Seq2SeqTrainer): def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None: if self.args.save_total_limit is None or self.args.save_total_limit <= 0: return # Check if we should delete older checkpoint(s) checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir) if self.args.val_after_train and self.args.eval_delay < \ self.state.global_step: for checkpoint in checkpoints_sorted[:-1]: states_dir = [str(x) for x in Path( checkpoint).glob(f'global_step*') if os.path.isdir(x)] for state_dir in states_dir: logger.info(f"Deleting optimizer states of saved " f"checkpoint {checkpoint}") if os.path.exists(state_dir) and os.path.isdir( state_dir): shutil.rmtree(state_dir) else: if len(checkpoints_sorted) <= self.args.save_total_limit: return # If save_total_limit=1 with load_best_model_at_end=True, we could end up deleting the last checkpoint, which # we don't do to allow resuming. save_total_limit = self.args.save_total_limit if ( self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1 and checkpoints_sorted[ -1] != self.state.best_model_checkpoint ): save_total_limit = 2 number_of_checkpoints_to_delete = max(0, len( checkpoints_sorted) - save_total_limit) checkpoints_to_be_deleted = checkpoints_sorted[ :number_of_checkpoints_to_delete] for checkpoint in checkpoints_to_be_deleted: logger.info( f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") shutil.rmtree(checkpoint) def _save(self, output_dir: Optional[str] = None, state_dict=None): # If we are executing this function, we are the process zero, so we don't check for that. output_dir = output_dir if output_dir is not None else self.args.output_dir os.makedirs(output_dir, exist_ok=True) logger.info(f"Saving model checkpoint to {output_dir}") # Save a trained model and configuration using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` if not isinstance(self.model, PreTrainedModel) and not hasattr( self.model, 'save_pretrained'): if state_dict is None: state_dict = self.model.state_dict() if isinstance(unwrap_model(self.model), PreTrainedModel): unwrap_model(self.model).save_pretrained( output_dir, state_dict=state_dict, # safe_serialization=self.args.save_safetensors ) else: logger.info( "Trainer.model is not a `PreTrainedModel`, only saving its state dict.") # if self.args.save_safetensors: # safetensors.torch.save_file(state_dict, # os.path.join(output_dir, # SAFE_WEIGHTS_NAME)) # else: torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME)) else: self.model.save_pretrained( output_dir, state_dict=state_dict, # safe_serialization=self.args.save_safetensors ) if self.tokenizer is not None: self.tokenizer.save_pretrained(output_dir) # Good practice: save your training arguments together with the trained model torch.save(self.args, os.path.join(output_dir, TRAINING_ARGS_NAME)) def _inner_training_loop( self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None ): self._train_batch_size = batch_size # Data loader and number of training steps train_dataloader = self.get_train_dataloader() # Setting up training control variables: # number of training epochs: num_train_epochs # number of training steps per epoch: num_update_steps_per_epoch # total number of training steps to execute: max_steps total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size len_dataloader = None if has_length(train_dataloader): len_dataloader = len(train_dataloader) num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) num_examples = self.num_examples(train_dataloader) if args.max_steps > 0: max_steps = args.max_steps num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( args.max_steps % num_update_steps_per_epoch > 0 ) # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's # the best we can do. num_train_samples = args.max_steps * total_train_batch_size else: max_steps = math.ceil( args.num_train_epochs * num_update_steps_per_epoch) num_train_epochs = math.ceil(args.num_train_epochs) num_train_samples = self.num_examples( train_dataloader) * args.num_train_epochs elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size max_steps = args.max_steps # Setting a very large number of epochs so we go as many times as necessary over the iterator. num_train_epochs = sys.maxsize num_update_steps_per_epoch = max_steps num_examples = total_train_batch_size * args.max_steps num_train_samples = args.max_steps * total_train_batch_size else: raise ValueError( "args.max_steps must be set to a positive value if dataloader does not have a length, was" f" {args.max_steps}" ) if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: if self.args.n_gpu > 1: # nn.DataParallel(model) replicates the model, creating new variables and module # references registered here no longer work on other gpus, breaking the module raise ValueError( "Currently --debug underflow_overflow is not supported under DP. Please use DDP" " (torch.distributed.launch)." ) else: debug_overflow = DebugUnderflowOverflow(self.model) # noqa delay_optimizer_creation = ( self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE or is_sagemaker_mp_enabled() or self.fsdp is not None ) if args.deepspeed: deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint ) self.model = deepspeed_engine.module self.model_wrapped = deepspeed_engine self.deepspeed = deepspeed_engine self.optimizer = optimizer self.lr_scheduler = lr_scheduler elif not delay_optimizer_creation: self.create_optimizer_and_scheduler(num_training_steps=max_steps) self.state = TrainerState() self.state.is_hyper_param_search = trial is not None # Activate gradient checkpointing if needed if args.gradient_checkpointing: self.model.gradient_checkpointing_enable() model = self._wrap_model(self.model_wrapped) if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None: self._load_from_checkpoint(resume_from_checkpoint, model) # for the rest of this function `model` is the outside model, whether it was wrapped or not if model is not self.model: self.model_wrapped = model if delay_optimizer_creation: self.create_optimizer_and_scheduler(num_training_steps=max_steps) # Check if saved optimizer or scheduler states exist self._load_optimizer_and_scheduler(resume_from_checkpoint) # important: at this point: # self.model is the Transformers Model # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. # Train! logger.info("***** Running training *****") logger.info(f" Num examples = {num_examples}") logger.info(f" Num Epochs = {num_train_epochs}") logger.info( f" Instantaneous batch size per device = {args.per_device_train_batch_size}") logger.info( f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") logger.info( f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") logger.info(f" Total optimization steps = {max_steps}") logger.info( f" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}" ) self.state.epoch = 0 start_time = time.time() epochs_trained = 0 steps_trained_in_current_epoch = 0 steps_trained_progress_bar = None # Check if continuing training from a checkpoint if resume_from_checkpoint is not None and os.path.isfile( os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME) ): self.state = TrainerState.load_from_json( os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)) epochs_trained = self.state.global_step // num_update_steps_per_epoch if not args.ignore_data_skip: steps_trained_in_current_epoch = self.state.global_step % ( num_update_steps_per_epoch) steps_trained_in_current_epoch *= args.gradient_accumulation_steps else: steps_trained_in_current_epoch = 0 logger.info( " Continuing training from checkpoint, will skip to saved global_step") logger.info(f" Continuing training from epoch {epochs_trained}") logger.info( f" Continuing training from global step {self.state.global_step}") if not args.ignore_data_skip: logger.info( f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " "flag to your launch command, but you will resume the training on data already seen by your model." ) if self.is_local_process_zero() and not args.disable_tqdm: steps_trained_progress_bar = tqdm( total=steps_trained_in_current_epoch) steps_trained_progress_bar.set_description( "Skipping the first batches") # Update the references self.callback_handler.model = self.model self.callback_handler.optimizer = self.optimizer self.callback_handler.lr_scheduler = self.lr_scheduler self.callback_handler.train_dataloader = train_dataloader if self.hp_name is not None and self._trial is not None: # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial # parameter to Train when using DDP. self.state.trial_name = self.hp_name(self._trial) if trial is not None: assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial self.state.trial_params = hp_params(assignments) else: self.state.trial_params = None # This should be the same if the state has been saved but in case the training arguments changed, it's safer # to set this after the load. self.state.max_steps = max_steps self.state.num_train_epochs = num_train_epochs self.state.is_local_process_zero = self.is_local_process_zero() self.state.is_world_process_zero = self.is_world_process_zero() # tr_loss is a tensor to avoid synchronization of TPUs through .item() tr_loss = torch.tensor(0.0).to(args.device) # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses self._total_loss_scalar = 0.0 self._globalstep_last_logged = self.state.global_step model.zero_grad() self.control = self.callback_handler.on_train_begin(args, self.state, self.control) # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. if not args.ignore_data_skip: for epoch in range(epochs_trained): is_random_sampler = hasattr(train_dataloader, "sampler") and isinstance( train_dataloader.sampler, RandomSampler ) if is_torch_less_than_1_11 or not is_random_sampler: # We just need to begin an iteration to create the randomization of the sampler. # That was before PyTorch 1.11 however... if self.args.joint_train: train_dataloader.dataset.set_samples(epoch) for _ in train_dataloader: break else: # Otherwise we need to call the whooooole sampler cause there is some random operation added # AT THE VERY END! _ = list(train_dataloader.sampler) if args.manual_empty_cache: torch.cuda.empty_cache() for epoch in range(epochs_trained, num_train_epochs): if self.args.joint_train: train_dataloader.dataset.set_samples(epoch) if isinstance(train_dataloader, DataLoader) and isinstance( train_dataloader.sampler, DistributedSampler): train_dataloader.sampler.set_epoch(epoch) elif hasattr(train_dataloader, "dataset") and isinstance( train_dataloader.dataset, IterableDatasetShard): train_dataloader.dataset.set_epoch(epoch) if is_torch_tpu_available(): parallel_loader = pl.ParallelLoader(train_dataloader, [ args.device]).per_device_loader(args.device) epoch_iterator = parallel_loader else: epoch_iterator = train_dataloader # Reset the past mems state at the beginning of each epoch if necessary. if args.past_index >= 0: self._past = None steps_in_epoch = ( len(epoch_iterator) if len_dataloader is not None else args.max_steps * args.gradient_accumulation_steps ) self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0: self._load_rng_state(resume_from_checkpoint) step = -1 if args.manual_empty_cache: torch.cuda.empty_cache() for step, inputs in enumerate(epoch_iterator): # Skip past any already trained steps if resuming training if args.manual_empty_cache: torch.cuda.empty_cache() if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 if steps_trained_progress_bar is not None: steps_trained_progress_bar.update(1) if steps_trained_in_current_epoch == 0: self._load_rng_state(resume_from_checkpoint) continue elif steps_trained_progress_bar is not None: steps_trained_progress_bar.close() steps_trained_progress_bar = None if step % args.gradient_accumulation_steps == 0: self.control = self.callback_handler.on_step_begin(args, self.state, self.control) # if args.manual_empty_cache: # torch.cuda.empty_cache() if ( ((step + 1) % args.gradient_accumulation_steps != 0) and args.local_rank != -1 and args._no_sync_in_gradient_accumulation ): # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. with model.no_sync(): tr_loss_step = self.training_step(model, inputs) else: tr_loss_step = self.training_step(model, inputs) if ( args.logging_nan_inf_filter and not is_torch_tpu_available() and ( torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)) ): # if loss is nan or inf simply add the average of previous logged losses tr_loss += tr_loss / ( 1 + self.state.global_step - self._globalstep_last_logged) else: tr_loss += tr_loss_step self.current_flos += float(self.floating_point_ops(inputs)) # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps if self.deepspeed: if args.manual_empty_cache: torch.cuda.empty_cache() self.deepspeed.step() if (step + 1) % args.gradient_accumulation_steps == 0 or ( # last step in epoch but step is always smaller than gradient_accumulation_steps steps_in_epoch <= args.gradient_accumulation_steps and (step + 1) == steps_in_epoch ): # Gradient clipping if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: # deepspeed does its own clipping if self.do_grad_scaling: # Reduce gradients first for XLA if is_torch_tpu_available(): gradients = xm._fetch_gradients(self.optimizer) xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size()) # AMP: gradients need unscaling self.scaler.unscale_(self.optimizer) if is_sagemaker_mp_enabled() and args.fp16: self.optimizer.clip_master_grads(args.max_grad_norm) elif hasattr(self.optimizer, "clip_grad_norm"): # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping self.optimizer.clip_grad_norm(args.max_grad_norm) elif hasattr(model, "clip_grad_norm_"): # Some models (like FullyShardedDDP) have a specific way to do gradient clipping model.clip_grad_norm_(args.max_grad_norm) else: # Revert to normal clipping otherwise, handling Apex or full precision nn.utils.clip_grad_norm_( amp.master_params( self.optimizer) if self.use_apex else model.parameters(), args.max_grad_norm, ) # Optimizer step optimizer_was_run = True if self.deepspeed: pass # called outside the loop elif is_torch_tpu_available(): if self.do_grad_scaling: self.scaler.step(self.optimizer) self.scaler.update() else: xm.optimizer_step(self.optimizer) elif self.do_grad_scaling: scale_before = self.scaler.get_scale() self.scaler.step(self.optimizer) self.scaler.update() scale_after = self.scaler.get_scale() optimizer_was_run = scale_before <= scale_after else: self.optimizer.step() if optimizer_was_run and not self.deepspeed: self.lr_scheduler.step() model.zero_grad() self.state.global_step += 1 self.state.epoch = epoch + (step + 1) / steps_in_epoch if args.manual_empty_cache: torch.cuda.empty_cache() self.control = self.callback_handler.on_step_end(args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) else: self.control = self.callback_handler.on_substep_end(args, self.state, self.control) if self.control.should_epoch_stop or self.control.should_training_stop: break if step < 0: logger.warning( "There seems to be not a single sample in your epoch_iterator, stopping training at step" f" {self.state.global_step}! This is expected if you're using an IterableDataset and set" f" num_steps ({max_steps}) higher than the number of available samples." ) self.control.should_training_stop = True self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) if DebugOption.TPU_METRICS_DEBUG in self.args.debug: if is_torch_tpu_available(): # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) else: logger.warning( "You enabled PyTorch/XLA debug metrics but you don't have a TPU " "configured. Check your training configuration if this is unexpected." ) if self.control.should_training_stop: break if args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") logger.info( "\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: # Wait for everyone to get here so we are sur the model has been saved by process 0. if is_torch_tpu_available(): xm.rendezvous("load_best_model_at_end") elif args.local_rank != -1: dist.barrier() elif is_sagemaker_mp_enabled(): smp.barrier() self._load_best_model() # add remaining tr_loss self._total_loss_scalar += tr_loss.item() train_loss = self._total_loss_scalar / self.state.global_step metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) self.store_flos() metrics["total_flos"] = self.state.total_flos metrics["train_loss"] = train_loss self.is_in_train = False self._memory_tracker.stop_and_update_metrics(metrics) self.log(metrics) run_dir = self._get_output_dir(trial) checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint. if self.state.best_model_checkpoint is not None and \ self.args.save_total_limit == 1 and self.is_world_process_zero(): for checkpoint in checkpoints_sorted: if checkpoint != self.state.best_model_checkpoint: logger.info( f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") shutil.rmtree(checkpoint) self.control = self.callback_handler.on_train_end(args, self.state, self.control) return TrainOutput(self.state.global_step, train_loss, metrics) def my_compute_metrics(self, doc_labels: Dict[str, List[List]], predicts: Any, samples: List, split: str, id_to_name: Dict = None ) -> Dict: if self.args.joint_train: data_names = self.args.joint_data_names.split(',') joint_threds = [ int(t) for t in self.args.joint_min_num_mentions.split(',')] name_to_threds = {n: t for n, t in zip(data_names, joint_threds)} documents_to_chunk_data = defaultdict(list) documents_to_chunk_gold = defaultdict(list) predictions = {} golds = {} assert len(samples) == len(predicts) out_sents = [] last_doc_id = re.sub(r'_\d+$', '', samples[0]['doc_key']) for sample, predict in zip(samples, predicts): doc_key = sample['doc_key'] doc_id = re.sub(r'_\d+$', '', doc_key) # require convert to ids first input_ids = sample['sentence'] subtoken_map = sample['subtoken_map'] offset = sample['offset'] # remove bos predict_ids = predict[1:].tolist() gold_data = sample['seg_clusters'] if self.args.joint_train: thred = name_to_threds[id_to_name[doc_id]] else: thred = self.args.min_num_mentions if self.args.seq2seq_type == "short_seq": special_ids = MARK_SPECIAL_IDS if self.args.mark_sentence \ else SPECIAL_IDS pred_data, aligned_input_ids, aligned_pred_ids = \ parse_short_target_tokens(input_ids, predict_ids, special_ids, subtoken_map, self.tokenizer, self.args.align_mode, thred, self.args.mark_sentence ) pred_tokens = self.tokenizer.convert_ids_to_tokens( predict_ids) out_predict = { 'doc_key': doc_key, 'pred_tokens': pred_tokens, 'pred_text': self.tokenizer.convert_tokens_to_string( pred_tokens), 'pred_aligned_text': self.tokenizer.convert_ids_to_tokens( aligned_pred_ids ), 'input_aligned_text': self.tokenizer.convert_ids_to_tokens( aligned_input_ids ) } else: is_tagging = (self.args.seq2seq_type == 'tagging') if self.args.action_type == 'integer': pred_data, pred_token_mentions, predict_ids = \ parse_int_output_tokens( input_ids, predict_ids, SPECIAL_IDS, subtoken_map, self.tokenizer, thred, is_tagging) else: special_ids = MENTION_END_NON_INT_SPECIAL_IDS if \
self.args.add_mention_end else NON_INT_SPECIAL_IDS
7
2023-10-17 17:39:16+00:00
16k
chenxn2020/GOSE
GOSEfinetune/models/LiLTRobertaLike/modeling_LiLTRobertaLike.py
[ { "identifier": "LiLTRobertaLikeConfig", "path": "GOSEfinetune/models/LiLTRobertaLike/configuration_LiLTRobertaLike.py", "snippet": "class LiLTRobertaLikeConfig(RobertaConfig):\n model_type = \"liltrobertalike\"\n\n def __init__(\n self,\n channel_shrink_ratio=4,\n max_2d_posi...
import math import torch import torch.nn as nn import torch.utils.checkpoint import os from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN, gelu from transformers.file_utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from transformers.modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPoolingAndCrossAttentions, CausalLMOutputWithCrossAttentions, MaskedLMOutput, MultipleChoiceModelOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from transformers.modeling_utils import ( PreTrainedModel, apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer, ) from transformers.utils import logging from .configuration_LiLTRobertaLike import LiLTRobertaLikeConfig from dataclasses import dataclass from typing import Dict, Optional, Tuple from transformers.file_utils import ModelOutput from ...modules.decoders.RE import RE from ...modules.decoders.gose import GOSE from ...utils import ReOutput
12,148
output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] sequence_output = torch.cat([sequence_output, layout_outputs], -1) sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) class LiLTRobertaLikeForRelationExtraction(LiLTRobertaLikePreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config): super().__init__(config) self.lilt = LiLTRobertaLikeModel(config, add_pooling_layer=False) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.input_type = config.input_type self.freeze_model = config.freeze_model print(f'=============model freeze {self.freeze_model}===============') #from IPython import embed;embed() self.decoder = config.decoder_name if self.decoder == 're': self.extractor = REDecoder(config, config.hidden_size + config.hidden_size // config.channel_shrink_ratio) elif self.decoder == 'gose': self.extractor = GOSE(config) self.init_weights() def forward( self, input_ids=None, bbox=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, entities=None, relations=None, ): if self.input_type == 'bbox': input_mask = input_ids != 1 input_ids[input_mask] = 3 elif self.input_type == 'text': bbox[:,:,:] = 0 if self.freeze_model: with torch.no_grad(): outputs, layout_outputs = self.lilt( input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) else: outputs, layout_outputs = self.lilt( input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) seq_length = input_ids.size(1) sequence_output = outputs[0] sequence_output = torch.cat([sequence_output, layout_outputs], -1) sequence_output = self.dropout(sequence_output) loss, pred_relations = self.extractor(sequence_output, entities, relations, bbox)
# coding=utf-8 logger = logging.get_logger(__name__) class LiLTRobertaLikeTextEmbeddings(nn.Module): def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load # any TensorFlow checkpoint file self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") # End copy self.padding_idx = config.pad_token_id self.position_embeddings = nn.Embedding( config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx ) def forward( self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 ): if position_ids is None: if input_ids is not None: # Create the position ids from the input token ids. Any padded tokens remain padded. position_ids = create_position_ids_from_input_ids( input_ids, self.padding_idx, past_key_values_length ).to(input_ids.device) else: position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds) if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = inputs_embeds + token_type_embeddings if self.position_embedding_type == "absolute": position_embeddings = self.position_embeddings(position_ids) embeddings += position_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings, position_ids def create_position_ids_from_inputs_embeds(self, inputs_embeds): """ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. Args: inputs_embeds: torch.Tensor Returns: torch.Tensor """ input_shape = inputs_embeds.size()[:-1] sequence_length = input_shape[1] position_ids = torch.arange( self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device ) return position_ids.unsqueeze(0).expand(input_shape) class LiLTRobertaLikeLayoutEmbeddings(nn.Module): def __init__(self, config): super(LiLTRobertaLikeLayoutEmbeddings, self).__init__() self.x_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6) self.y_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6) self.h_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6) self.w_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.hidden_size // 6) self.padding_idx = config.pad_token_id self.box_position_embeddings = nn.Embedding( config.max_position_embeddings, config.hidden_size//config.channel_shrink_ratio, padding_idx=self.padding_idx ) self.box_linear_embeddings = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size//config.channel_shrink_ratio) self.LayerNorm = nn.LayerNorm(config.hidden_size//config.channel_shrink_ratio, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward( self, bbox=None, position_ids=None, ): try: left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0]) upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1]) right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2]) lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3]) except IndexError as e: raise IndexError("The :obj:`bbox`coordinate values should be within 0-1000 range.") from e h_position_embeddings = self.h_position_embeddings(bbox[:, :, 3] - bbox[:, :, 1]) w_position_embeddings = self.w_position_embeddings(bbox[:, :, 2] - bbox[:, :, 0]) spatial_position_embeddings = torch.cat( [ left_position_embeddings, upper_position_embeddings, right_position_embeddings, lower_position_embeddings, h_position_embeddings, w_position_embeddings, ], dim=-1, ) spatial_position_embeddings = self.box_linear_embeddings(spatial_position_embeddings) box_position_embeddings = self.box_position_embeddings(position_ids) spatial_position_embeddings = spatial_position_embeddings + box_position_embeddings spatial_position_embeddings = self.LayerNorm(spatial_position_embeddings) spatial_position_embeddings = self.dropout(spatial_position_embeddings) return spatial_position_embeddings class LiLTRobertaLikeSelfAttention(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.layout_query = nn.Linear(config.hidden_size // config.channel_shrink_ratio, self.all_head_size // config.channel_shrink_ratio) self.layout_key = nn.Linear(config.hidden_size // config.channel_shrink_ratio, self.all_head_size // config.channel_shrink_ratio) self.layout_value = nn.Linear(config.hidden_size // config.channel_shrink_ratio, self.all_head_size // config.channel_shrink_ratio) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": self.max_position_embeddings = config.max_position_embeddings self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) self.is_decoder = config.is_decoder self.channel_shrink_ratio = config.channel_shrink_ratio def transpose_for_scores(self, x, r=1): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size//r) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states, layout_inputs, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): layout_value_layer = self.transpose_for_scores(self.layout_value(layout_inputs), r=self.channel_shrink_ratio) layout_key_layer = self.transpose_for_scores(self.layout_key(layout_inputs), r=self.channel_shrink_ratio) layout_query_layer = self.transpose_for_scores(self.layout_query(layout_inputs), r=self.channel_shrink_ratio) mixed_query_layer = self.query(hidden_states) # If this is instantiated as a cross-attention module, the keys # and values come from an encoder; the attention mask needs to be # such that the encoder's padding tokens are not attended to. is_cross_attention = encoder_hidden_states is not None if is_cross_attention and past_key_value is not None: # reuse k,v, cross_attentions key_layer = past_key_value[0] value_layer = past_key_value[1] attention_mask = encoder_attention_mask elif is_cross_attention: key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) attention_mask = encoder_attention_mask elif past_key_value is not None: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) key_layer = torch.cat([past_key_value[0], key_layer], dim=2) value_layer = torch.cat([past_key_value[1], value_layer], dim=2) else: key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) query_layer = self.transpose_for_scores(mixed_query_layer) if self.is_decoder: # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_layer, value_layer) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) layout_attention_scores = torch.matmul(layout_query_layer, layout_key_layer.transpose(-1, -2)) if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": seq_length = hidden_states.size()[1] position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) distance = position_ids_l - position_ids_r positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility if self.position_embedding_type == "relative_key": relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores elif self.position_embedding_type == "relative_key_query": relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key tmp_attention_scores = attention_scores / math.sqrt(self.attention_head_size) tmp_layout_attention_scores = layout_attention_scores / math.sqrt(self.attention_head_size//self.channel_shrink_ratio) attention_scores = tmp_attention_scores + tmp_layout_attention_scores layout_attention_scores = tmp_layout_attention_scores + tmp_attention_scores if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) layout_attention_scores = layout_attention_scores + attention_mask # Normalize the attention scores to probabilities. layout_attention_probs = nn.Softmax(dim=-1)(layout_attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. layout_attention_probs = self.dropout(layout_attention_probs) # Mask heads if we want to if head_mask is not None: layout_attention_probs = layout_attention_probs * head_mask layout_context_layer = torch.matmul(layout_attention_probs, layout_value_layer) layout_context_layer = layout_context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = layout_context_layer.size()[:-2] + (self.all_head_size//self.channel_shrink_ratio,) layout_context_layer = layout_context_layer.view(*new_context_layer_shape) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.Softmax(dim=-1)(attention_scores) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = ((context_layer, layout_context_layer), attention_probs) if output_attentions else ((context_layer, layout_context_layer),) if self.is_decoder: outputs = outputs + (past_key_value,) return outputs class LiLTRobertaLikeSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class LiLTRobertaLikeAttention(nn.Module): def __init__(self, config): super().__init__() self.self = LiLTRobertaLikeSelfAttention(config) self.output = LiLTRobertaLikeSelfOutput(config) self.pruned_heads = set() ori_hidden_size = config.hidden_size config.hidden_size = config.hidden_size // config.channel_shrink_ratio self.layout_output = LiLTRobertaLikeSelfOutput(config) config.hidden_size = ori_hidden_size def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads ) # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, hidden_states, layout_inputs, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): self_outputs = self.self( hidden_states, layout_inputs, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) attention_output = self.output(self_outputs[0][0], hidden_states) layout_attention_output = self.layout_output(self_outputs[0][1], layout_inputs) outputs = ((attention_output, layout_attention_output),) + self_outputs[1:] # add attentions if we output them return outputs class LiLTRobertaLikeIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class LiLTRobertaLikeOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class LiLTRobertaLikeLayer(nn.Module): def __init__(self, config): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = LiLTRobertaLikeAttention(config) self.is_decoder = config.is_decoder self.add_cross_attention = config.add_cross_attention if self.add_cross_attention: assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added" self.crossattention = LiLTRobertaLikeAttention(config) self.intermediate = LiLTRobertaLikeIntermediate(config) self.output = LiLTRobertaLikeOutput(config) ori_hidden_size = config.hidden_size ori_intermediate_size = config.intermediate_size config.hidden_size = config.hidden_size // config.channel_shrink_ratio config.intermediate_size = config.intermediate_size // config.channel_shrink_ratio self.layout_intermediate = LiLTRobertaLikeIntermediate(config) self.layout_output = LiLTRobertaLikeOutput(config) config.hidden_size = ori_hidden_size config.intermediate_size = ori_intermediate_size def forward( self, hidden_states, layout_inputs, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_value=None, output_attentions=False, ): # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None self_attention_outputs = self.attention( hidden_states, layout_inputs, attention_mask, head_mask, output_attentions=output_attentions, past_key_value=self_attn_past_key_value, ) attention_output = self_attention_outputs[0][0] layout_attention_output = self_attention_outputs[0][1] # if decoder, the last output is tuple of self-attn cache if self.is_decoder: outputs = self_attention_outputs[1:-1] present_key_value = self_attention_outputs[-1] else: outputs = self_attention_outputs[1:] # add self attentions if we output attention weights cross_attn_present_key_value = None if self.is_decoder and encoder_hidden_states is not None: assert hasattr( self, "crossattention" ), f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`" # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None cross_attention_outputs = self.crossattention( attention_output, attention_mask, head_mask, encoder_hidden_states, encoder_attention_mask, cross_attn_past_key_value, output_attentions, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights # add cross-attn cache to positions 3,4 of present_key_value tuple cross_attn_present_key_value = cross_attention_outputs[-1] present_key_value = present_key_value + cross_attn_present_key_value layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) layout_layer_output = apply_chunking_to_forward( self.layout_feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, layout_attention_output ) outputs = ((layer_output, layout_layer_output),) + outputs # if decoder, return the attn key/values as the last output if self.is_decoder: outputs = outputs + (present_key_value,) return outputs def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output def layout_feed_forward_chunk(self, attention_output): intermediate_output = self.layout_intermediate(attention_output) layer_output = self.layout_output(intermediate_output, attention_output) return layer_output class LiLTRobertaLikeEncoder(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([LiLTRobertaLikeLayer(config) for _ in range(config.num_hidden_layers)]) def forward( self, hidden_states, layout_inputs, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=False, output_hidden_states=False, return_dict=True, ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None next_decoder_cache = () if use_cache else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_head_mask = head_mask[i] if head_mask is not None else None past_key_value = past_key_values[i] if past_key_values is not None else None if getattr(self.config, "gradient_checkpointing", False) and self.training: if use_cache: logger.warning( "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting " "`use_cache=False`..." ) use_cache = False def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs, past_key_value, output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, layout_inputs, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, ) else: layer_outputs = layer_module( hidden_states, layout_inputs, attention_mask, layer_head_mask, encoder_hidden_states, encoder_attention_mask, past_key_value, output_attentions, ) hidden_states = layer_outputs[0][0] layout_inputs = layer_outputs[0][1] if use_cache: next_decoder_cache += (layer_outputs[-1],) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if self.config.add_cross_attention: all_cross_attentions = all_cross_attentions + (layer_outputs[2],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [ hidden_states, next_decoder_cache, all_hidden_states, all_self_attentions, all_cross_attentions, ] if v is not None ), layout_inputs return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ), layout_inputs class LiLTRobertaLikePooler(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output class LiLTRobertaLikePreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = LiLTRobertaLikeConfig base_model_prefix = "liltrobertalike" def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) class LiLTRobertaLikeModel(LiLTRobertaLikePreTrainedModel): _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.embeddings = LiLTRobertaLikeTextEmbeddings(config) self.layout_embeddings = LiLTRobertaLikeLayoutEmbeddings(config) self.encoder = LiLTRobertaLikeEncoder(config) self.pooler = LiLTRobertaLikePooler(config) if add_pooling_layer else None self.init_weights() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) def forward( self, input_ids=None, bbox=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if self.config.is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() batch_size, seq_length = input_shape elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] batch_size, seq_length = input_shape else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device # past_key_values_length past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) if bbox is None: bbox = torch.zeros(tuple(list(input_shape) + [4]), dtype=torch.long, device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, device) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) embedding_output, position_ids = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) layout_embedding_output = self.layout_embeddings( bbox=bbox, position_ids=position_ids, ) encoder_outputs, layout_encoder_outputs = self.encoder( embedding_output, layout_embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = encoder_outputs[0] pooled_output = self.pooler(sequence_output) if self.pooler is not None else None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, ), layout_encoder_outputs class LiLTRobertaLikeForTokenClassification(LiLTRobertaLikePreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.lilt = LiLTRobertaLikeModel(config, add_pooling_layer=False) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size + config.hidden_size//config.channel_shrink_ratio, config.num_labels) self.init_weights() def forward( self, input_ids=None, bbox=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs, layout_outputs = self.lilt( input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] sequence_output = torch.cat([sequence_output, layout_outputs], -1) sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) class LiLTRobertaLikeForRelationExtraction(LiLTRobertaLikePreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] _keys_to_ignore_on_load_missing = [r"position_ids"] def __init__(self, config): super().__init__(config) self.lilt = LiLTRobertaLikeModel(config, add_pooling_layer=False) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.input_type = config.input_type self.freeze_model = config.freeze_model print(f'=============model freeze {self.freeze_model}===============') #from IPython import embed;embed() self.decoder = config.decoder_name if self.decoder == 're': self.extractor = REDecoder(config, config.hidden_size + config.hidden_size // config.channel_shrink_ratio) elif self.decoder == 'gose': self.extractor = GOSE(config) self.init_weights() def forward( self, input_ids=None, bbox=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, entities=None, relations=None, ): if self.input_type == 'bbox': input_mask = input_ids != 1 input_ids[input_mask] = 3 elif self.input_type == 'text': bbox[:,:,:] = 0 if self.freeze_model: with torch.no_grad(): outputs, layout_outputs = self.lilt( input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) else: outputs, layout_outputs = self.lilt( input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) seq_length = input_ids.size(1) sequence_output = outputs[0] sequence_output = torch.cat([sequence_output, layout_outputs], -1) sequence_output = self.dropout(sequence_output) loss, pred_relations = self.extractor(sequence_output, entities, relations, bbox)
return ReOutput(
3
2023-10-19 14:36:32+00:00
16k
BurgerBurgerBurger/AA
run.py
[ { "identifier": "add_args", "path": "args.py", "snippet": "def add_args(parser):\n parser.add_argument(\"--do_train\", action=\"store_true\")\n parser.add_argument(\"--data_dir\", default=\"./dataset/docred\", type=str)\n parser.add_argument(\"--transformer_type\", default=\"bert\", type=str)\n...
import argparse import os import numpy as np import torch import ujson as json import pandas as pd import pickle from torch.cuda.amp import GradScaler from torch.utils.data import DataLoader from transformers import AutoConfig, AutoModel, AutoTokenizer from transformers.optimization import AdamW, get_linear_schedule_with_warmup from args import add_args from model import DocREModel from utils import set_seed, collate_fn, create_directory from prepro import read_docred from evaluation import to_official, official_evaluate, merge_results from tqdm import tqdm
11,387
dump_to_file(best_offi_results, pred_file, best_output, score_file, best_results, results_file) return num_steps new_layer = ["extractor", "bilinear", "graph"] optimizer_grouped_parameters = [ {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in new_layer)], }, {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in new_layer)], "lr": args.lr_added}, ] optimizer = AdamW(optimizer_grouped_parameters, lr=args.lr_transformer, eps=args.adam_epsilon) num_steps = 0 set_seed(args) model.zero_grad() finetune(train_features, optimizer, args.num_train_epochs, num_steps) def evaluate(args, model, features, tag="dev"): dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False) preds, evi_preds = [], [] scores, topks = [], [] attns = [] for batch in dataloader: model.eval() if args.save_attn: tag = "infer" inputs = load_input(batch, args.device, tag) with torch.no_grad(): outputs = model(**inputs) pred = outputs["rel_pred"] pred = pred.cpu().numpy() pred[np.isnan(pred)] = 0 preds.append(pred) if "scores" in outputs: scores.append(outputs["scores"].cpu().numpy()) topks.append(outputs["topks"].cpu().numpy()) if "evi_pred" in outputs: # relation extraction and evidence extraction evi_pred = outputs["evi_pred"] evi_pred = evi_pred.cpu().numpy() evi_preds.append(evi_pred) if "attns" in outputs: # attention recorded attn = outputs["attns"] attns.extend([a.cpu().numpy() for a in attn]) preds = np.concatenate(preds, axis=0) if scores: scores = np.concatenate(scores, axis=0) topks = np.concatenate(topks, axis=0) if evi_preds: evi_preds = np.concatenate(evi_preds, axis=0) official_results, results = to_official(preds, features, evi_preds=evi_preds, scores=scores, topks=topks) if len(official_results) > 0: if tag == "test": best_re, best_evi, best_re_ign, _ = official_evaluate(official_results, args.data_dir, args.train_file, args.test_file) else: best_re, best_evi, best_re_ign, _ = official_evaluate(official_results, args.data_dir, args.train_file, args.dev_file) else: best_re = best_evi = best_re_ign = [-1, -1, -1] output = { tag + "_rel": [i * 100 for i in best_re], tag + "_rel_ign": [i * 100 for i in best_re_ign], tag + "_evi": [i * 100 for i in best_evi], } scores = {"dev_F1": best_re[-1] * 100, "dev_evi_F1": best_evi[-1] * 100, "dev_F1_ign": best_re_ign[-1] * 100} if args.save_attn: attns_path = os.path.join(args.load_path, f"{os.path.splitext(args.test_file)[0]}.attns") print(f"saving attentions into {attns_path} ...") with open(attns_path, "wb") as f: pickle.dump(attns, f) return scores, output, official_results, results def dump_to_file(offi: list, offi_path: str, scores: list, score_path: str, results: list = [], res_path: str = "", thresh: float = None): ''' dump scores and (top-k) predictions to file. ''' print(f"saving official predictions into {offi_path} ...") json.dump(offi, open(offi_path, "w")) print(f"saving evaluations into {score_path} ...") headers = ["precision", "recall", "F1"] scores_pd = pd.DataFrame.from_dict(scores, orient="index", columns=headers) print(scores_pd) scores_pd.to_csv(score_path, sep='\t') if len(results) != 0: assert res_path != "" print(f"saving topk results into {res_path} ...") json.dump(results, open(res_path, "w")) if thresh is not None: thresh_path = os.path.join(os.path.dirname(offi_path), "thresh") if not os.path.exists(thresh_path): print(f"saving threshold into {thresh_path} ...") json.dump(thresh, open(thresh_path, "w")) return def main(): parser = argparse.ArgumentParser()
def load_input(batch, device, tag="dev"): input = {'input_ids': batch[0].to(device), 'attention_mask': batch[1].to(device), 'labels': batch[2].to(device), 'entity_pos': batch[3], 'hts': batch[4], 'sent_pos': batch[5], 'sent_labels': batch[6].to(device) if (not batch[6] is None) and (batch[7] is None) else None, 'teacher_attns': batch[7].to(device) if not batch[7] is None else None, 'graph': batch[8], 'tag': tag } return input def train(args, model, train_features, dev_features): def finetune(features, optimizer, num_epoch, num_steps): best_score = -1 train_dataloader = DataLoader(features, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True) train_iterator = range(int(num_epoch)) total_steps = int(len(train_dataloader) * num_epoch // args.gradient_accumulation_steps) warmup_steps = int(total_steps * args.warmup_ratio) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=total_steps) scaler = GradScaler() print("Total steps: {}".format(total_steps)) print("Warmup steps: {}".format(warmup_steps)) for epoch in tqdm(train_iterator, desc='Train epoch'): for step, batch in enumerate(train_dataloader): model.zero_grad() optimizer.zero_grad() model.train() inputs = load_input(batch, args.device) outputs = model(**inputs) loss = [outputs["loss"]["rel_loss"]] if inputs["sent_labels"] is not None: loss.append(outputs["loss"]["evi_loss"] * args.evi_lambda) if inputs["teacher_attns"] is not None: loss.append(outputs["loss"]["attn_loss"] * args.attn_lambda) loss = sum(loss) / args.gradient_accumulation_steps scaler.scale(loss).backward() if step % args.gradient_accumulation_steps == 0: if args.max_grad_norm > 0: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) scaler.step(optimizer) scaler.update() scheduler.step() model.zero_grad() num_steps += 1 if (step + 1) == len(train_dataloader) or ( args.evaluation_steps > 0 and num_steps % args.evaluation_steps == 0 and step % args.gradient_accumulation_steps == 0): dev_scores, dev_output, official_results, results = evaluate(args, model, dev_features, tag="dev") print(dev_output) if dev_scores["dev_F1_ign"] > best_score: best_score = dev_scores["dev_F1_ign"] best_offi_results = official_results best_results = results best_output = dev_output ckpt_file = os.path.join(args.save_path, "best.ckpt") print(f"saving model checkpoint into {ckpt_file} ...") torch.save(model.state_dict(), ckpt_file) if epoch == train_iterator[-1]: # last epoch ckpt_file = os.path.join(args.save_path, "last.ckpt") print(f"saving model checkpoint into {ckpt_file} ...") torch.save(model.state_dict(), ckpt_file) pred_file = os.path.join(args.save_path, args.pred_file) score_file = os.path.join(args.save_path, "scores.csv") results_file = os.path.join(args.save_path, f"topk_{args.pred_file}") dump_to_file(best_offi_results, pred_file, best_output, score_file, best_results, results_file) return num_steps new_layer = ["extractor", "bilinear", "graph"] optimizer_grouped_parameters = [ {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in new_layer)], }, {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in new_layer)], "lr": args.lr_added}, ] optimizer = AdamW(optimizer_grouped_parameters, lr=args.lr_transformer, eps=args.adam_epsilon) num_steps = 0 set_seed(args) model.zero_grad() finetune(train_features, optimizer, args.num_train_epochs, num_steps) def evaluate(args, model, features, tag="dev"): dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False) preds, evi_preds = [], [] scores, topks = [], [] attns = [] for batch in dataloader: model.eval() if args.save_attn: tag = "infer" inputs = load_input(batch, args.device, tag) with torch.no_grad(): outputs = model(**inputs) pred = outputs["rel_pred"] pred = pred.cpu().numpy() pred[np.isnan(pred)] = 0 preds.append(pred) if "scores" in outputs: scores.append(outputs["scores"].cpu().numpy()) topks.append(outputs["topks"].cpu().numpy()) if "evi_pred" in outputs: # relation extraction and evidence extraction evi_pred = outputs["evi_pred"] evi_pred = evi_pred.cpu().numpy() evi_preds.append(evi_pred) if "attns" in outputs: # attention recorded attn = outputs["attns"] attns.extend([a.cpu().numpy() for a in attn]) preds = np.concatenate(preds, axis=0) if scores: scores = np.concatenate(scores, axis=0) topks = np.concatenate(topks, axis=0) if evi_preds: evi_preds = np.concatenate(evi_preds, axis=0) official_results, results = to_official(preds, features, evi_preds=evi_preds, scores=scores, topks=topks) if len(official_results) > 0: if tag == "test": best_re, best_evi, best_re_ign, _ = official_evaluate(official_results, args.data_dir, args.train_file, args.test_file) else: best_re, best_evi, best_re_ign, _ = official_evaluate(official_results, args.data_dir, args.train_file, args.dev_file) else: best_re = best_evi = best_re_ign = [-1, -1, -1] output = { tag + "_rel": [i * 100 for i in best_re], tag + "_rel_ign": [i * 100 for i in best_re_ign], tag + "_evi": [i * 100 for i in best_evi], } scores = {"dev_F1": best_re[-1] * 100, "dev_evi_F1": best_evi[-1] * 100, "dev_F1_ign": best_re_ign[-1] * 100} if args.save_attn: attns_path = os.path.join(args.load_path, f"{os.path.splitext(args.test_file)[0]}.attns") print(f"saving attentions into {attns_path} ...") with open(attns_path, "wb") as f: pickle.dump(attns, f) return scores, output, official_results, results def dump_to_file(offi: list, offi_path: str, scores: list, score_path: str, results: list = [], res_path: str = "", thresh: float = None): ''' dump scores and (top-k) predictions to file. ''' print(f"saving official predictions into {offi_path} ...") json.dump(offi, open(offi_path, "w")) print(f"saving evaluations into {score_path} ...") headers = ["precision", "recall", "F1"] scores_pd = pd.DataFrame.from_dict(scores, orient="index", columns=headers) print(scores_pd) scores_pd.to_csv(score_path, sep='\t') if len(results) != 0: assert res_path != "" print(f"saving topk results into {res_path} ...") json.dump(results, open(res_path, "w")) if thresh is not None: thresh_path = os.path.join(os.path.dirname(offi_path), "thresh") if not os.path.exists(thresh_path): print(f"saving threshold into {thresh_path} ...") json.dump(thresh, open(thresh_path, "w")) return def main(): parser = argparse.ArgumentParser()
parser = add_args(parser)
0
2023-10-20 05:53:25+00:00
16k
xingchenshanyao/YOLOP-E
lib/core/function.py
[ { "identifier": "ConfusionMatrix", "path": "lib/core/evaluate.py", "snippet": "class ConfusionMatrix:\n # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix\n def __init__(self, nc=1, conf=0.25, iou_thres=0.45):\n nc = 10 # 20230904 nc是类别数\n self.matrix ...
import time import torch import numpy as np import json import random import cv2 import os import math import wandb from lib.core.evaluate import ConfusionMatrix,SegmentationMetric from lib.core.general import non_max_suppression,check_img_size,scale_coords,xyxy2xywh,xywh2xyxy,box_iou,coco80_to_coco91_class,plot_images,ap_per_class,output_to_target from lib.utils.utils import time_synchronized from lib.utils import plot_img_and_mask,plot_one_box,show_seg_result from threading import Thread from PIL import Image from torchvision import transforms from pathlib import Path from torch.cuda import amp from tqdm import tqdm from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval
11,836
if not config.DEBUG: img = img.to(device, non_blocking=True) assign_target = [] for tgt in target: assign_target.append(tgt.to(device)) target = assign_target nb, _, height, width = img.shape #batch size, channel, height, width with torch.no_grad(): pad_w, pad_h = shapes[0][1][1] pad_w = int(pad_w) pad_h = int(pad_h) ratio = shapes[0][1][0][0] t = time_synchronized() det_out, da_seg_out, ll_seg_out= model(img) # 检测图片? t_inf = time_synchronized() - t if batch_i > 0: T_inf.update(t_inf/img.size(0),img.size(0)) inf_out,train_out = det_out #driving area segment evaluation # 可驾驶区域分割评估 _,da_predict=torch.max(da_seg_out, 1) _,da_gt=torch.max(target[1], 1) da_predict = da_predict[:, pad_h:height-pad_h, pad_w:width-pad_w] da_gt = da_gt[:, pad_h:height-pad_h, pad_w:width-pad_w] da_metric.reset() da_metric.addBatch(da_predict.cpu(), da_gt.cpu()) da_acc = da_metric.pixelAccuracy() da_IoU = da_metric.IntersectionOverUnion() da_mIoU = da_metric.meanIntersectionOverUnion() da_acc_seg.update(da_acc,img.size(0)) da_IoU_seg.update(da_IoU,img.size(0)) da_mIoU_seg.update(da_mIoU,img.size(0)) #lane line segment evaluation # 车道线分割评估 _,ll_predict=torch.max(ll_seg_out, 1) _,ll_gt=torch.max(target[2], 1) ll_predict = ll_predict[:, pad_h:height-pad_h, pad_w:width-pad_w] ll_gt = ll_gt[:, pad_h:height-pad_h, pad_w:width-pad_w] ll_metric.reset() ll_metric.addBatch(ll_predict.cpu(), ll_gt.cpu()) ll_acc = ll_metric.lineAccuracy() ll_IoU = ll_metric.IntersectionOverUnion() ll_mIoU = ll_metric.meanIntersectionOverUnion() ll_acc_seg.update(ll_acc,img.size(0)) ll_IoU_seg.update(ll_IoU,img.size(0)) ll_mIoU_seg.update(ll_mIoU,img.size(0)) total_loss, head_losses = criterion((train_out,da_seg_out, ll_seg_out), target, shapes,model) #Compute loss losses.update(total_loss.item(), img.size(0)) #NMS # 非极大值抑制 t = time_synchronized() target[0][:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels lb = [target[0][target[0][:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling output = non_max_suppression(inf_out, conf_thres= config.TEST.NMS_CONF_THRESHOLD, iou_thres=config.TEST.NMS_IOU_THRESHOLD, labels=lb) #output = non_max_suppression(inf_out, conf_thres=0.001, iou_thres=0.6) #output = non_max_suppression(inf_out, conf_thres=config.TEST.NMS_CONF_THRES, iou_thres=config.TEST.NMS_IOU_THRES) t_nms = time_synchronized() - t if batch_i > 0: T_nms.update(t_nms/img.size(0),img.size(0)) if config.TEST.PLOTS: if batch_i == 0: for i in range(test_batch_size): img_test = cv2.imread(paths[i]) da_seg_mask = da_seg_out[i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) da_seg_mask = torch.nn.functional.interpolate(da_seg_mask, scale_factor=int(1/ratio), mode='bilinear') _, da_seg_mask = torch.max(da_seg_mask, 1) da_gt_mask = target[1][i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) da_gt_mask = torch.nn.functional.interpolate(da_gt_mask, scale_factor=int(1/ratio), mode='bilinear') _, da_gt_mask = torch.max(da_gt_mask, 1) da_seg_mask = da_seg_mask.int().squeeze().cpu().numpy() da_gt_mask = da_gt_mask.int().squeeze().cpu().numpy() # seg_mask = seg_mask > 0.5 # plot_img_and_mask(img_test, seg_mask, i,epoch,save_dir) img_test1 = img_test.copy() _ = show_seg_result(img_test, da_seg_mask, i,epoch,save_dir) _ = show_seg_result(img_test1, da_gt_mask, i, epoch, save_dir, is_gt=True) img_ll = cv2.imread(paths[i]) ll_seg_mask = ll_seg_out[i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) ll_seg_mask = torch.nn.functional.interpolate(ll_seg_mask, scale_factor=int(1/ratio), mode='bilinear') _, ll_seg_mask = torch.max(ll_seg_mask, 1) ll_gt_mask = target[2][i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) ll_gt_mask = torch.nn.functional.interpolate(ll_gt_mask, scale_factor=int(1/ratio), mode='bilinear') _, ll_gt_mask = torch.max(ll_gt_mask, 1) ll_seg_mask = ll_seg_mask.int().squeeze().cpu().numpy() ll_gt_mask = ll_gt_mask.int().squeeze().cpu().numpy() # seg_mask = seg_mask > 0.5 # plot_img_and_mask(img_test, seg_mask, i,epoch,save_dir) img_ll1 = img_ll.copy() _ = show_seg_result(img_ll, ll_seg_mask, i,epoch,save_dir, is_ll=True) _ = show_seg_result(img_ll1, ll_gt_mask, i, epoch, save_dir, is_ll=True, is_gt=True) img_det = cv2.imread(paths[i]) img_gt = img_det.copy() det = output[i].clone() if len(det): det[:,:4] = scale_coords(img[i].shape[1:],det[:,:4],img_det.shape).round() for *xyxy,conf,cls in reversed(det): #print(cls) # import pdb;pdb.set_trace() label_det_pred = f'{names[int(cls)]} {conf:.3f}' plot_one_box(xyxy, img_det , label=label_det_pred, color=colors[int(cls)], line_thickness=3) cv2.imwrite(save_dir+"/batch_{}_{}_det_pred.png".format(epoch,i),img_det) labels = target[0][target[0][:, 0] == i, 1:] # print(labels)
id_dict_SDExpressway = { 0:'Car', 1:'Truck', 2:'Guidance Sign', 3:'Warning Sign', 4:'Pending Sign', 5:'Speed Limit Sign', 6:'Emergency Telephone Sign', 7:'Directional Sign', 8:'Straight Ahead Arrow', 9:'Straight or Right Turn Arrow'} def train(cfg, train_loader, model, criterion, optimizer, scaler, epoch, num_batch, num_warmup, writer_dict, logger, device, rank=-1): """ train for one epoch Inputs: - config: configurations - train_loader: loder for data - model: - criterion: (function) calculate all the loss, return total_loss, head_losses - writer_dict: outputs(2,) output[0] len:3, [1,3,32,32,85], [1,3,16,16,85], [1,3,8,8,85] output[1] len:1, [2,256,256] output[2] len:1, [2,256,256] target(2,) target[0] [1,n,5] target[1] [2,256,256] target[2] [2,256,256] Returns: None """ batch_time = AverageMeter() # batch_time = <lib.core.function.AverageMeter object at 0x7f0255618970> data_time = AverageMeter() # data_time = <lib.core.function.AverageMeter object at 0x7f025561a4f0> losses = AverageMeter() # losses = <lib.core.function.AverageMeter object at 0x7f02402e7cd0> # switch to train mode model.train() start = time.time() # start = 1688805138.6791408 for i, (input, target, paths, shapes) in enumerate(train_loader): # i=0 # target = [tensor([[0.0000e+00,...335e-01]]), tensor([[[[1., 1., 1...., 0.]]]]), tensor([[[[1., 1., 1...., 0.]]]])] # paths = ('/home/xingchen/Study...3225df.jpg', '/home/xingchen/Study...49926c.jpg', ...) # shapes = (((720, 1280), ((0.5, 0.5), (0.0, 12.0))), ((...), (...)), ...) intermediate = time.time() # intermediate = 1688805496.5324085 #print('tims:{}'.format(intermediate-start)) num_iter = i + num_batch * (epoch - 1) # num_iter = 0 # num_batch = 4375 if num_iter < num_warmup: # warm up lf = lambda x: ((1 + math.cos(x * math.pi / cfg.TRAIN.END_EPOCH)) / 2) * \ (1 - cfg.TRAIN.LRF) + cfg.TRAIN.LRF # cosine xi = [0, num_warmup] # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou) for j, x in enumerate(optimizer.param_groups): # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 # 偏置lr从0.1下降到lr0,所有其他lr从0.0上升到lr0 x['lr'] = np.interp(num_iter, xi, [cfg.TRAIN.WARMUP_BIASE_LR if j == 2 else 0.0, x['initial_lr'] * lf(epoch)]) if 'momentum' in x: x['momentum'] = np.interp(num_iter, xi, [cfg.TRAIN.WARMUP_MOMENTUM, cfg.TRAIN.MOMENTUM]) data_time.update(time.time() - start) if not cfg.DEBUG: input = input.to(device, non_blocking=True) assign_target = [] for tgt in target: assign_target.append(tgt.to(device)) target = assign_target with amp.autocast(enabled=device.type != 'cpu'): outputs = model(input) # outputs = [[tensor([[[[[ 8.8806e...ackward0>), tensor([[[[[ 4.6631e...ackward0>), tensor([[[[[ 1.4758e...ackward0>)], tensor([[[[0.5151, 0...ackward0>), tensor([[[[0.4868, 0...ackward0>)] total_loss, head_losses = criterion(outputs, target, shapes,model) # print(head_losses) # compute gradient and do update step optimizer.zero_grad() scaler.scale(total_loss).backward() scaler.step(optimizer) scaler.update() if rank in [-1, 0]: # measure accuracy and record loss losses.update(total_loss.item(), input.size(0)) # _, avg_acc, cnt, pred = accuracy(output.detach().cpu().numpy(), # target.detach().cpu().numpy()) # acc.update(avg_acc, cnt) # measure elapsed time batch_time.update(time.time() - start) end = time.time() if i % cfg.PRINT_FREQ == 0: msg = 'Epoch: [{0}][{1}/{2}]\t' \ 'Time {batch_time.val:.3f}s ({batch_time.avg:.3f}s)\t' \ 'Speed {speed:.1f} samples/s\t' \ 'Data {data_time.val:.3f}s ({data_time.avg:.3f}s)\t' \ 'Loss {loss.val:.5f} ({loss.avg:.5f})'.format( epoch, i, len(train_loader), batch_time=batch_time, speed=input.size(0)/batch_time.val, data_time=data_time, loss=losses) logger.info(msg) writer = writer_dict['writer'] global_steps = writer_dict['train_global_steps'] writer.add_scalar('train_loss', losses.val, global_steps) # writer.add_scalar('train_acc', acc.val, global_steps) writer_dict['train_global_steps'] = global_steps + 1 def validate(epoch,config, val_loader, val_dataset, model, criterion, output_dir, tb_log_dir, writer_dict=None, logger=None, device='cpu', rank=-1,nc = 1): """ validata Inputs: - config: configurations - train_loader: loder for data - model: - criterion: (function) calculate all the loss, return - writer_dict: Return: None """ # setting max_stride = 32 weights = None save_dir = output_dir + os.path.sep + 'visualization' # save_dir = 'runs/BddDataset/_2023-07-09-09-50/visualization' if not os.path.exists(save_dir): os.mkdir(save_dir) # print(save_dir) _, imgsz = [check_img_size(x, s=max_stride) for x in config.MODEL.IMAGE_SIZE] #imgsz is multiple of max_stride batch_size = config.TRAIN.BATCH_SIZE_PER_GPU * len(config.GPUS) # batch_size = 16 test_batch_size = config.TEST.BATCH_SIZE_PER_GPU * len(config.GPUS) # test_batch_size = 16 training = False is_coco = False #is coco dataset save_conf=False # save auto-label confidences verbose=False save_hybrid=False log_imgs,wandb = min(16,100), None nc = 10 #20230904 iouv = torch.linspace(0.5,0.95,10).to(device) #iou vector for mAP@0.5:0.95 niou = iouv.numel() # niou = 10 try: except ImportError: wandb = None log_imgs = 0 seen = 0 # import pdb;pdb.set_trace() confusion_matrix = ConfusionMatrix(nc=model.nc) #detector confusion matrix # confusion matrix 混合矩阵 da_metric = SegmentationMetric(config.num_seg_class) #segment confusion matrix ll_metric = SegmentationMetric(2) #segment confusion matrix # names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)} # names = {'0':0} names = id_dict_SDExpressway #20230904 colors = [[random.randint(0, 255) for _ in range(3)] for _ in names] # colors = [[191, 83, 111]] coco91class = coco80_to_coco91_class() s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95') # s = ' Class Images Targets P R mAP@.5 mAP@.5:.95' p, r, f1, mp, mr, map50, map, t_inf, t_nms = 0., 0., 0., 0., 0., 0., 0., 0., 0. losses = AverageMeter() da_acc_seg = AverageMeter() da_IoU_seg = AverageMeter() da_mIoU_seg = AverageMeter() ll_acc_seg = AverageMeter() ll_IoU_seg = AverageMeter() ll_mIoU_seg = AverageMeter() T_inf = AverageMeter() T_nms = AverageMeter() # switch to train mode model.eval() jdict, stats, ap, ap_class, wandb_images = [], [], [], [], [] for batch_i, (img, target, paths, shapes) in tqdm(enumerate(val_loader), total=len(val_loader)): if not config.DEBUG: img = img.to(device, non_blocking=True) assign_target = [] for tgt in target: assign_target.append(tgt.to(device)) target = assign_target nb, _, height, width = img.shape #batch size, channel, height, width with torch.no_grad(): pad_w, pad_h = shapes[0][1][1] pad_w = int(pad_w) pad_h = int(pad_h) ratio = shapes[0][1][0][0] t = time_synchronized() det_out, da_seg_out, ll_seg_out= model(img) # 检测图片? t_inf = time_synchronized() - t if batch_i > 0: T_inf.update(t_inf/img.size(0),img.size(0)) inf_out,train_out = det_out #driving area segment evaluation # 可驾驶区域分割评估 _,da_predict=torch.max(da_seg_out, 1) _,da_gt=torch.max(target[1], 1) da_predict = da_predict[:, pad_h:height-pad_h, pad_w:width-pad_w] da_gt = da_gt[:, pad_h:height-pad_h, pad_w:width-pad_w] da_metric.reset() da_metric.addBatch(da_predict.cpu(), da_gt.cpu()) da_acc = da_metric.pixelAccuracy() da_IoU = da_metric.IntersectionOverUnion() da_mIoU = da_metric.meanIntersectionOverUnion() da_acc_seg.update(da_acc,img.size(0)) da_IoU_seg.update(da_IoU,img.size(0)) da_mIoU_seg.update(da_mIoU,img.size(0)) #lane line segment evaluation # 车道线分割评估 _,ll_predict=torch.max(ll_seg_out, 1) _,ll_gt=torch.max(target[2], 1) ll_predict = ll_predict[:, pad_h:height-pad_h, pad_w:width-pad_w] ll_gt = ll_gt[:, pad_h:height-pad_h, pad_w:width-pad_w] ll_metric.reset() ll_metric.addBatch(ll_predict.cpu(), ll_gt.cpu()) ll_acc = ll_metric.lineAccuracy() ll_IoU = ll_metric.IntersectionOverUnion() ll_mIoU = ll_metric.meanIntersectionOverUnion() ll_acc_seg.update(ll_acc,img.size(0)) ll_IoU_seg.update(ll_IoU,img.size(0)) ll_mIoU_seg.update(ll_mIoU,img.size(0)) total_loss, head_losses = criterion((train_out,da_seg_out, ll_seg_out), target, shapes,model) #Compute loss losses.update(total_loss.item(), img.size(0)) #NMS # 非极大值抑制 t = time_synchronized() target[0][:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels lb = [target[0][target[0][:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling output = non_max_suppression(inf_out, conf_thres= config.TEST.NMS_CONF_THRESHOLD, iou_thres=config.TEST.NMS_IOU_THRESHOLD, labels=lb) #output = non_max_suppression(inf_out, conf_thres=0.001, iou_thres=0.6) #output = non_max_suppression(inf_out, conf_thres=config.TEST.NMS_CONF_THRES, iou_thres=config.TEST.NMS_IOU_THRES) t_nms = time_synchronized() - t if batch_i > 0: T_nms.update(t_nms/img.size(0),img.size(0)) if config.TEST.PLOTS: if batch_i == 0: for i in range(test_batch_size): img_test = cv2.imread(paths[i]) da_seg_mask = da_seg_out[i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) da_seg_mask = torch.nn.functional.interpolate(da_seg_mask, scale_factor=int(1/ratio), mode='bilinear') _, da_seg_mask = torch.max(da_seg_mask, 1) da_gt_mask = target[1][i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) da_gt_mask = torch.nn.functional.interpolate(da_gt_mask, scale_factor=int(1/ratio), mode='bilinear') _, da_gt_mask = torch.max(da_gt_mask, 1) da_seg_mask = da_seg_mask.int().squeeze().cpu().numpy() da_gt_mask = da_gt_mask.int().squeeze().cpu().numpy() # seg_mask = seg_mask > 0.5 # plot_img_and_mask(img_test, seg_mask, i,epoch,save_dir) img_test1 = img_test.copy() _ = show_seg_result(img_test, da_seg_mask, i,epoch,save_dir) _ = show_seg_result(img_test1, da_gt_mask, i, epoch, save_dir, is_gt=True) img_ll = cv2.imread(paths[i]) ll_seg_mask = ll_seg_out[i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) ll_seg_mask = torch.nn.functional.interpolate(ll_seg_mask, scale_factor=int(1/ratio), mode='bilinear') _, ll_seg_mask = torch.max(ll_seg_mask, 1) ll_gt_mask = target[2][i][:, pad_h:height-pad_h, pad_w:width-pad_w].unsqueeze(0) ll_gt_mask = torch.nn.functional.interpolate(ll_gt_mask, scale_factor=int(1/ratio), mode='bilinear') _, ll_gt_mask = torch.max(ll_gt_mask, 1) ll_seg_mask = ll_seg_mask.int().squeeze().cpu().numpy() ll_gt_mask = ll_gt_mask.int().squeeze().cpu().numpy() # seg_mask = seg_mask > 0.5 # plot_img_and_mask(img_test, seg_mask, i,epoch,save_dir) img_ll1 = img_ll.copy() _ = show_seg_result(img_ll, ll_seg_mask, i,epoch,save_dir, is_ll=True) _ = show_seg_result(img_ll1, ll_gt_mask, i, epoch, save_dir, is_ll=True, is_gt=True) img_det = cv2.imread(paths[i]) img_gt = img_det.copy() det = output[i].clone() if len(det): det[:,:4] = scale_coords(img[i].shape[1:],det[:,:4],img_det.shape).round() for *xyxy,conf,cls in reversed(det): #print(cls) # import pdb;pdb.set_trace() label_det_pred = f'{names[int(cls)]} {conf:.3f}' plot_one_box(xyxy, img_det , label=label_det_pred, color=colors[int(cls)], line_thickness=3) cv2.imwrite(save_dir+"/batch_{}_{}_det_pred.png".format(epoch,i),img_det) labels = target[0][target[0][:, 0] == i, 1:] # print(labels)
labels[:,1:5]=xywh2xyxy(labels[:,1:5])
6
2023-10-24 02:08:25+00:00
16k
giulio98/functional-diffusion-processes
src/functional_diffusion_processes/trainers/trainer.py
[ { "identifier": "AudioDataset", "path": "src/functional_diffusion_processes/datasets/audio_dataset.py", "snippet": "class AudioDataset(BaseDataset, abc.ABC):\n \"\"\"Base class for defining audio datasets.\n\n This class serves as the foundation for defining datasets containing audio data.\n It...
import abc import gc import io import logging import os import flax import flax.jax_utils as flax_utils import hydra.utils import jax import numpy as np import tensorflow as tf import wandb from typing import Any, Callable, Tuple, Union from cleanfid import fid from flax import linen, traverse_util from flax.training import checkpoints from flax.training.checkpoints import restore_checkpoint from jax import numpy as jnp from omegaconf import DictConfig, OmegaConf from tqdm.auto import tqdm from wandb.sdk.lib import RunDisabled from wandb.sdk.wandb_run import Run from ..datasets import AudioDataset, ImageDataset from ..datasets.base_dataset import BaseDataset from ..losses.base_loss import Loss from ..metrics import FIDMetric from ..samplers import Sampler from ..sdetools.base_sde import SDE from ..utils.common import filter_mask, make_grid_image, process_images, save_samples, to_grayscale from ..utils.scaler import get_data_inverse_scaler, get_data_scaler from ..utils.training_state import TrainState from .helpers import colorizing_fn, construct_sampling_fn, construct_train_step, inpainting_fn, sampling_fn
13,980
# Resume training when intermediate checkpoints are detected if self.training_config.resume_training: pylogger.warning("Resuming training from the latest checkpoint.") if self.logging.use_wandb and self.model_name != "local": model_file = wandb.use_artifact(self.model_name).download() state = restore_checkpoint(ckpt_dir=model_file, prefix="checkpoint_", target=state) else: state = checkpoints.restore_checkpoint(ckpt_dir=self.checkpoint_dir, target=state) return run, scaler, inverse_scaler, rng, state, train_step_fn, sample_fn, batch_input def train_step( self, train_step_fn: Callable, carry_state: Tuple, batch: jnp.ndarray, batch_input: jnp.ndarray, ) -> Tuple: """Perform a single training step, updating the model parameters. Args: train_step_fn (Callable): The train step function. carry_state (Tuple): The current state of the model and optimizer. batch (jnp.ndarray): The batch of data used for training. batch_input (jnp.ndarray): The input data to the model. Returns: Tuple: The updated state after performing the training step. """ (rng, state) = carry_state ( new_rng, loss, loss_inner, new_params, new_optim_state, batch_reconstructed, batch_corrupted, target, ) = train_step_fn( rng, state.params, state.opt_state_params, state.step, batch_input, batch, ) ema_rate = self.training_config.ema_rate new_params_ema = jax.tree_map( lambda p_ema, p: p_ema * ema_rate + p * (1.0 - ema_rate), state.ema_params, new_params, ) # update the state new_state = state.replace( rng=flax.jax_utils.unreplicate(new_rng), step=state.step + 1, opt_state_params=new_optim_state, params=new_params, ema_params=new_params_ema, ) new_carry_state = (new_rng, new_state) loss = flax.jax_utils.unreplicate(loss) step = int(flax_utils.unreplicate(state.step)) # Log the training progress if jax.host_id() == 0 and step % self.training_config.log_freq == 0: pylogger.info("step: %d, training_loss: %.5e" % (step, loss)) if self.logging.use_wandb: wandb.log({"step": step, "loss": loss}, step=step) if loss_inner is not None: loss_inner = flax.jax_utils.unreplicate(loss_inner) for inner_step, loss in enumerate(loss_inner): pylogger.info("step: %d, training_loss_inner: %.5e" % (step, loss)) if self.logging.use_wandb: wandb.log({"step": step, f"loss inner step {inner_step}": loss}, step=step) return new_carry_state, batch_reconstructed, batch_corrupted, target def save_checkpoint(self, step, run, state): pylogger.info("Saving the model at step %d." % (step,)) # Log the evaluation progress # Save the model parameters ( params, opt_state_params, step_, ema_params, ) = flax_utils.unreplicate( ( state.params, state.opt_state_params, state.step, state.ema_params, ) ) saved_state = state.replace( step=step_, opt_state_params=opt_state_params, params=params, ema_params=ema_params, ) checkpoint_file = checkpoints.save_checkpoint( self.checkpoint_dir, saved_state, step=step_ // self.training_config.eval_freq, keep=np.inf, ) if self.logging.use_wandb: wandb_model_artifact_name = str(step_) + "_" + run.id wandb_model = wandb.Artifact(wandb_model_artifact_name, type="model") wandb_model.add_file(checkpoint_file) run.log_artifact(wandb_model) # noinspection PyProtectedMember
# import imageio # import imageio pylogger = logging.getLogger(__name__) class Trainer(abc.ABC): """Class for training a model.""" def __init__( self, mode: str, model_name: str, training_config: DictConfig, optimizer, evaluation_config: DictConfig, trainer_logging: DictConfig, sampler: Sampler, loss_obj: Loss, ) -> None: """Initialize a Trainer instance with configurations and core components. Args: mode (str): Specifies the mode of the trainer which can be either "train" or "eval". model_name (str): The name identifier for the model. training_config (DictConfig): A configuration dictionary for training settings. optimizer: The optimizer instance used for training. evaluation_config (DictConfig): A configuration dictionary for evaluation settings. trainer_logging (DictConfig): A configuration dictionary for logging settings. sampler (Sampler): A sampler instance for sampling from the model. loss_obj (Loss): A loss object used for computing the loss during training. """ self.mode = mode self.model_name = model_name self.training_config = training_config self.optimizer = hydra.utils.instantiate(optimizer) self.evaluation_config = evaluation_config self.logging = trainer_logging self.sampler = sampler self.loss_obj = loss_obj self.checkpoint_dir = os.path.join(self.training_config.save_dir, self.training_config.checkpoint_dir) self.sample_dir = os.path.join(self.training_config.save_dir, self.training_config.sample_dir) self.eval_dir = os.path.join(self.training_config.save_dir, self.evaluation_config.eval_dir) # Create the directories for saving samples and checkpoints tf.io.gfile.makedirs(self.checkpoint_dir) tf.io.gfile.makedirs(self.sample_dir) tf.io.gfile.makedirs(self.eval_dir) tf.io.gfile.makedirs(os.path.join(self.eval_dir, "clean")) def initialize_wandb( self, dataset_config: DictConfig, sde_config: DictConfig, model_config: DictConfig ) -> Union[Run, RunDisabled, None]: """Initialize wandb if logging is enabled.""" if self.logging.use_wandb: run = wandb.init( name=os.path.basename(self.logging.wandb_init.name), project=self.logging.wandb_init.project, entity=self.logging.wandb_init.entity, save_code=self.logging.wandb_init.save_code, config={ **self.training_config, **dataset_config, **sde_config, **model_config, }, ) else: run = None return run def initialize_run(self, model, ds_train, sde): """Perform all initialization steps required for training.""" run = self.initialize_wandb(ds_train.data_config, sde.sde_config, model.model_config) scaler = get_data_scaler(is_centered=ds_train.data_config.data_centered) inverse_scaler = get_data_inverse_scaler(is_centered=ds_train.data_config.data_centered) rng = jax.random.PRNGKey(seed=self.training_config.seed) rng, step_rng = jax.random.split(rng) batch_input = model.initialize_input( (ds_train.data_config.batch_size, *sde.sde_config.shape, ds_train.data_config.output_size) ) params = jax.jit(model.initialize_model, backend="cpu")(step_rng, batch_input) flat_params = traverse_util.flatten_dict(params).values() tot_params = sum([jnp.size(p) for p in flat_params]) pylogger.info("Total number of parameters: {:.2f}M".format(tot_params / 1e6)) state = TrainState.create( apply_fn=model.apply, params=params, tx=self.optimizer, opt_state_params=self.optimizer.init(params), rng=rng, ema_params=params, ) train_step_fn = construct_train_step(self.optimizer, self.loss_obj.construct_loss_fn(model)) sample_fn = construct_sampling_fn(model, self.sampler) # Resume training when intermediate checkpoints are detected if self.training_config.resume_training: pylogger.warning("Resuming training from the latest checkpoint.") if self.logging.use_wandb and self.model_name != "local": model_file = wandb.use_artifact(self.model_name).download() state = restore_checkpoint(ckpt_dir=model_file, prefix="checkpoint_", target=state) else: state = checkpoints.restore_checkpoint(ckpt_dir=self.checkpoint_dir, target=state) return run, scaler, inverse_scaler, rng, state, train_step_fn, sample_fn, batch_input def train_step( self, train_step_fn: Callable, carry_state: Tuple, batch: jnp.ndarray, batch_input: jnp.ndarray, ) -> Tuple: """Perform a single training step, updating the model parameters. Args: train_step_fn (Callable): The train step function. carry_state (Tuple): The current state of the model and optimizer. batch (jnp.ndarray): The batch of data used for training. batch_input (jnp.ndarray): The input data to the model. Returns: Tuple: The updated state after performing the training step. """ (rng, state) = carry_state ( new_rng, loss, loss_inner, new_params, new_optim_state, batch_reconstructed, batch_corrupted, target, ) = train_step_fn( rng, state.params, state.opt_state_params, state.step, batch_input, batch, ) ema_rate = self.training_config.ema_rate new_params_ema = jax.tree_map( lambda p_ema, p: p_ema * ema_rate + p * (1.0 - ema_rate), state.ema_params, new_params, ) # update the state new_state = state.replace( rng=flax.jax_utils.unreplicate(new_rng), step=state.step + 1, opt_state_params=new_optim_state, params=new_params, ema_params=new_params_ema, ) new_carry_state = (new_rng, new_state) loss = flax.jax_utils.unreplicate(loss) step = int(flax_utils.unreplicate(state.step)) # Log the training progress if jax.host_id() == 0 and step % self.training_config.log_freq == 0: pylogger.info("step: %d, training_loss: %.5e" % (step, loss)) if self.logging.use_wandb: wandb.log({"step": step, "loss": loss}, step=step) if loss_inner is not None: loss_inner = flax.jax_utils.unreplicate(loss_inner) for inner_step, loss in enumerate(loss_inner): pylogger.info("step: %d, training_loss_inner: %.5e" % (step, loss)) if self.logging.use_wandb: wandb.log({"step": step, f"loss inner step {inner_step}": loss}, step=step) return new_carry_state, batch_reconstructed, batch_corrupted, target def save_checkpoint(self, step, run, state): pylogger.info("Saving the model at step %d." % (step,)) # Log the evaluation progress # Save the model parameters ( params, opt_state_params, step_, ema_params, ) = flax_utils.unreplicate( ( state.params, state.opt_state_params, state.step, state.ema_params, ) ) saved_state = state.replace( step=step_, opt_state_params=opt_state_params, params=params, ema_params=ema_params, ) checkpoint_file = checkpoints.save_checkpoint( self.checkpoint_dir, saved_state, step=step_ // self.training_config.eval_freq, keep=np.inf, ) if self.logging.use_wandb: wandb_model_artifact_name = str(step_) + "_" + run.id wandb_model = wandb.Artifact(wandb_model_artifact_name, type="model") wandb_model.add_file(checkpoint_file) run.log_artifact(wandb_model) # noinspection PyProtectedMember
def train(self, model: linen.Module, ds_train: BaseDataset, sde: SDE) -> None:
2
2023-10-24 22:01:35+00:00
16k
KosinskiLab/pyTME
tme/tests/test_structure.py
[ { "identifier": "Structure", "path": "tme/structure.py", "snippet": "class Structure:\n \"\"\"Represents atomic structures in accordance with the Protein Data Bank (PDB)\n format specification.\n\n Attributes\n ----------\n record_type : NDArray\n Type of the record, e.g., ATOM, HE...
from tempfile import mkstemp from os import remove from tme import Structure from tme.matching_utils import euler_to_rotationmatrix, minimum_enclosing_box import pytest import numpy as np
12,964
else: assert value == value_comparison @pytest.mark.parametrize( "modified_attribute", [ ("record_type"), ("atom_serial_number"), ("atom_name"), ("atom_coordinate"), ("alternate_location_indicator"), ("residue_name"), ("chain_identifier"), ("residue_sequence_number"), ("code_for_residue_insertion"), ("occupancy"), ("temperature_factor"), ("segment_identifier"), ("element_symbol"), ], ) def test_initialization_errors(self, modified_attribute): kwargs = { attribute: getattr(self.structure, attribute) for attribute in STRUCTURE_ATTRIBUTES if attribute != modified_attribute } kwargs[modified_attribute] = getattr(self.structure, modified_attribute)[:1] with pytest.raises(ValueError): Structure(**kwargs) def test__getitem__(self): ret_single_index = self.structure[1] ret = self.structure[[1]] self.compare_structures(ret_single_index, ret) ret = self.structure[self.structure.record_type == "ATOM"] assert np.all(ret.record_type == "ATOM") ret = self.structure[self.structure.element_symbol == "C"] assert np.all(ret.element_symbol == "C") def test__repr__(self): unique_chains = "-".join( [ ",".join([str(x) for x in entity]) for entity in self.structure.details["unique_chains"] ] ) min_atom = np.min(self.structure.atom_serial_number) max_atom = np.max(self.structure.atom_serial_number) n_atom = self.structure.atom_serial_number.size min_residue = np.min(self.structure.residue_sequence_number) max_residue = np.max(self.structure.residue_sequence_number) n_residue = self.structure.residue_sequence_number.size repr_str = ( f"Structure object at {id(self.structure)}\n" f"Unique Chains: {unique_chains}, " f"Atom Range: {min_atom}-{max_atom} [N = {n_atom}], " f"Residue Range: {min_residue}-{max_residue} [N = {n_residue}]" ) assert repr_str == self.structure.__repr__() @pytest.mark.parametrize( "path", [ ("./tme/tests/data/Structures/5khe.cif"), ("./tme/tests/data/Structures/5khe.pdb"), ], ) def test_fromfile(self, path): _ = Structure.from_file(path) def test_fromfile_error(self): with pytest.raises(NotImplementedError): _ = Structure.from_file("madeup.extension") @pytest.mark.parametrize("file_format", [("cif"), ("pdb")]) def test_to_file(self, file_format): _, path = mkstemp() path = f"{path}.{file_format}" self.structure.to_file(path) read = self.structure.from_file(path) comparison = self.structure.copy() self.compare_structures(comparison, read, exclude_attributes=["details"]) def test_to_file_error(self): _, path = mkstemp() path = f"{path}.RAISERROR" with pytest.raises(NotImplementedError): self.structure.to_file(path) def test_subset_by_chain(self): chain = "A" ret = self.structure.subset_by_chain(chain=chain) assert np.all(ret.chain_identifier == chain) def test_subset_by_chain_range(self): chain, start, stop = "A", 0, 20 ret = self.structure.subset_by_range(chain=chain, start=start, stop=stop) assert np.all(ret.chain_identifier == chain) assert np.all( np.logical_and( ret.residue_sequence_number >= start, ret.residue_sequence_number <= stop, ) ) def test_center_of_mass(self): center_of_mass = self.structure.center_of_mass() assert center_of_mass.shape[0] == self.structure.atom_coordinate.shape[1] assert np.allclose(center_of_mass, [-0.89391639, 29.94908928, -2.64736741]) def test_centered(self): ret, translation = self.structure.centered()
STRUCTURE_ATTRIBUTES = [ "record_type", "atom_serial_number", "atom_name", "atom_coordinate", "alternate_location_indicator", "residue_name", "chain_identifier", "residue_sequence_number", "code_for_residue_insertion", "occupancy", "temperature_factor", "segment_identifier", "element_symbol", "charge", "details", ] class TestStructure: def setup_method(self): self.structure = Structure.from_file("./tme/tests/data/Structures/5khe.cif") _, self.path = mkstemp() def teardown_method(self): del self.structure remove(self.path) def compare_structures(self, structure1, structure2, exclude_attributes=[]): for attribute in STRUCTURE_ATTRIBUTES: if attribute in exclude_attributes: continue value = getattr(structure1, attribute) value_comparison = getattr(structure2, attribute) if type(value) == np.ndarray: assert np.all(value_comparison == value) else: assert value == value_comparison def test_initialization(self): structure = Structure( record_type=self.structure.record_type, atom_serial_number=self.structure.atom_serial_number, atom_name=self.structure.atom_name, atom_coordinate=self.structure.atom_coordinate, alternate_location_indicator=self.structure.alternate_location_indicator, residue_name=self.structure.residue_name, chain_identifier=self.structure.chain_identifier, residue_sequence_number=self.structure.residue_sequence_number, code_for_residue_insertion=self.structure.code_for_residue_insertion, occupancy=self.structure.occupancy, temperature_factor=self.structure.temperature_factor, segment_identifier=self.structure.segment_identifier, element_symbol=self.structure.element_symbol, charge=self.structure.charge, details=self.structure.details, ) for attribute in STRUCTURE_ATTRIBUTES: value = getattr(self.structure, attribute) value_comparison = getattr(structure, attribute) if type(value) == np.ndarray: assert np.all(value_comparison == value) else: assert value == value_comparison @pytest.mark.parametrize( "modified_attribute", [ ("record_type"), ("atom_serial_number"), ("atom_name"), ("atom_coordinate"), ("alternate_location_indicator"), ("residue_name"), ("chain_identifier"), ("residue_sequence_number"), ("code_for_residue_insertion"), ("occupancy"), ("temperature_factor"), ("segment_identifier"), ("element_symbol"), ], ) def test_initialization_errors(self, modified_attribute): kwargs = { attribute: getattr(self.structure, attribute) for attribute in STRUCTURE_ATTRIBUTES if attribute != modified_attribute } kwargs[modified_attribute] = getattr(self.structure, modified_attribute)[:1] with pytest.raises(ValueError): Structure(**kwargs) def test__getitem__(self): ret_single_index = self.structure[1] ret = self.structure[[1]] self.compare_structures(ret_single_index, ret) ret = self.structure[self.structure.record_type == "ATOM"] assert np.all(ret.record_type == "ATOM") ret = self.structure[self.structure.element_symbol == "C"] assert np.all(ret.element_symbol == "C") def test__repr__(self): unique_chains = "-".join( [ ",".join([str(x) for x in entity]) for entity in self.structure.details["unique_chains"] ] ) min_atom = np.min(self.structure.atom_serial_number) max_atom = np.max(self.structure.atom_serial_number) n_atom = self.structure.atom_serial_number.size min_residue = np.min(self.structure.residue_sequence_number) max_residue = np.max(self.structure.residue_sequence_number) n_residue = self.structure.residue_sequence_number.size repr_str = ( f"Structure object at {id(self.structure)}\n" f"Unique Chains: {unique_chains}, " f"Atom Range: {min_atom}-{max_atom} [N = {n_atom}], " f"Residue Range: {min_residue}-{max_residue} [N = {n_residue}]" ) assert repr_str == self.structure.__repr__() @pytest.mark.parametrize( "path", [ ("./tme/tests/data/Structures/5khe.cif"), ("./tme/tests/data/Structures/5khe.pdb"), ], ) def test_fromfile(self, path): _ = Structure.from_file(path) def test_fromfile_error(self): with pytest.raises(NotImplementedError): _ = Structure.from_file("madeup.extension") @pytest.mark.parametrize("file_format", [("cif"), ("pdb")]) def test_to_file(self, file_format): _, path = mkstemp() path = f"{path}.{file_format}" self.structure.to_file(path) read = self.structure.from_file(path) comparison = self.structure.copy() self.compare_structures(comparison, read, exclude_attributes=["details"]) def test_to_file_error(self): _, path = mkstemp() path = f"{path}.RAISERROR" with pytest.raises(NotImplementedError): self.structure.to_file(path) def test_subset_by_chain(self): chain = "A" ret = self.structure.subset_by_chain(chain=chain) assert np.all(ret.chain_identifier == chain) def test_subset_by_chain_range(self): chain, start, stop = "A", 0, 20 ret = self.structure.subset_by_range(chain=chain, start=start, stop=stop) assert np.all(ret.chain_identifier == chain) assert np.all( np.logical_and( ret.residue_sequence_number >= start, ret.residue_sequence_number <= stop, ) ) def test_center_of_mass(self): center_of_mass = self.structure.center_of_mass() assert center_of_mass.shape[0] == self.structure.atom_coordinate.shape[1] assert np.allclose(center_of_mass, [-0.89391639, 29.94908928, -2.64736741]) def test_centered(self): ret, translation = self.structure.centered()
box = minimum_enclosing_box(coordinates=self.structure.atom_coordinate.T)
2
2023-10-20 13:46:01+00:00
16k
tonnetonne814/MB-iSTFT-BERT-VITS2-44100-Ja
train_ms.py
[ { "identifier": "TextAudioSpeakerLoader", "path": "data_utils.py", "snippet": "class TextAudioSpeakerLoader(torch.utils.data.Dataset):\n \"\"\"\n 1) loads audio, speaker_id, text pairs\n 2) normalizes text and converts them to sequences of integers\n 3) computes spectrograms from audio files...
import os import torch import torch.distributed as dist import logging import commons import utils from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from data_utils import ( TextAudioSpeakerLoader, TextAudioSpeakerCollate, DistributedBucketSampler, ) from models import ( SynthesizerTrn, MultiPeriodDiscriminator, DurationDiscriminator, ) from losses import generator_loss, discriminator_loss, feature_loss, kl_loss from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols
11,120
for batch_idx, ( x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert, ja_bert, ) in tqdm(enumerate(train_loader)): if net_g.use_noise_scaled_mas: current_mas_noise_scale = ( net_g.mas_noise_scale_initial - net_g.noise_scale_delta * global_step ) net_g.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda( rank, non_blocking=True ) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda( rank, non_blocking=True ) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda( rank, non_blocking=True ) speakers = speakers.cuda(rank, non_blocking=True) tone = tone.cuda(rank, non_blocking=True) language = language.cuda(rank, non_blocking=True) bert = bert.cuda(rank, non_blocking=True) ja_bert = ja_bert.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): ( y_hat, l_length, attn, ids_slice, x_mask, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_), ) = net_g( x, x_lengths, spec, spec_lengths, speakers, tone, language, bert, ja_bert, ) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax, ) y_mel = commons.slice_segments( mel, ids_slice, hps.train.segment_size // hps.data.hop_length ) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax, ) y = commons.slice_segments( y, ids_slice * hps.data.hop_length, hps.train.segment_size ) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( y_d_hat_r, y_d_hat_g ) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc( hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach() ) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all ( loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g, ) = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cudnn.benchmark = True torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 torch.backends.cuda.enable_math_sdp(True) global_step = 0 def run(): #dist.init_process_group( # backend="gloo", # init_method="env://", # Due to some training problem,we proposed to use gloo instead of nccl. #) # Use torchrun instead of mp.spawn #rank = dist.get_rank() #n_gpus = dist.get_world_size() rank = 0 n_gpus = 1 hps = utils.get_hparams() torch.manual_seed(hps.train.seed) torch.cuda.set_device(rank) global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) writer = SummaryWriter(log_dir=hps.model_dir) writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, ) collate_fn = TextAudioSpeakerCollate() train_loader = DataLoader( train_dataset, num_workers=16, shuffle=False, pin_memory=True, collate_fn=collate_fn, batch_sampler=train_sampler, persistent_workers=True, prefetch_factor=4, ) # DataLoader config could be adjusted. if rank == 0: eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) eval_loader = DataLoader( eval_dataset, num_workers=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False, collate_fn=collate_fn, ) if ( "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas is True ): print("Using noise scaled MAS for VITS2") mas_noise_scale_initial = 0.01 noise_scale_delta = 2e-6 else: print("Using normal MAS for VITS1") mas_noise_scale_initial = 0.0 noise_scale_delta = 0.0 if ( "use_duration_discriminator" in hps.model.keys() and hps.model.use_duration_discriminator is True ): print("Using duration discriminator for VITS2") net_dur_disc = DurationDiscriminator( hps.model.hidden_channels, hps.model.hidden_channels, 3, 0.1, gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, ).cuda(rank) if ( "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder is True ): if hps.data.n_speakers == 0: raise ValueError( "n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model" ) else: print("Using normal encoder for VITS1") net_g = SynthesizerTrn( len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, mas_noise_scale_initial=mas_noise_scale_initial, noise_scale_delta=noise_scale_delta, **hps.model, ).cuda(rank) net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) optim_g = torch.optim.AdamW( filter(lambda p: p.requires_grad, net_g.parameters()), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) optim_d = torch.optim.AdamW( net_d.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) if net_dur_disc is not None: optim_dur_disc = torch.optim.AdamW( net_dur_disc.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) else: optim_dur_disc = None # net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True) # net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True) # if net_dur_disc is not None: # net_dur_disc = DDP(net_dur_disc, device_ids=[rank], find_unused_parameters=True) try: if net_dur_disc is not None: _, _, dur_resume_lr, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, skip_optimizer=hps.train.skip_optimizer if "skip_optimizer" in hps.train else True, ) _, optim_g, g_resume_lr, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g, skip_optimizer=hps.train.skip_optimizer if "skip_optimizer" in hps.train else True, ) _, optim_d, d_resume_lr, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d, skip_optimizer=hps.train.skip_optimizer if "skip_optimizer" in hps.train else True, ) if not optim_g.param_groups[0].get("initial_lr"): optim_g.param_groups[0]["initial_lr"] = g_resume_lr if not optim_d.param_groups[0].get("initial_lr"): optim_d.param_groups[0]["initial_lr"] = d_resume_lr if not optim_dur_disc.param_groups[0].get("initial_lr"): optim_dur_disc.param_groups[0]["initial_lr"] = dur_resume_lr epoch_str = max(epoch_str, 1) global_step = (epoch_str - 1) * len(train_loader) except Exception as e: print(e) epoch_str = 1 global_step = 0 scheduler_g = torch.optim.lr_scheduler.ExponentialLR( optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) scheduler_d = torch.optim.lr_scheduler.ExponentialLR( optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) if net_dur_disc is not None: # if not optim_dur_disc.param_groups[0].get("initial_lr"): # optim_dur_disc.param_groups[0]["initial_lr"] = dur_resume_lr scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR( optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) else: scheduler_dur_disc = None scaler = GradScaler(enabled=hps.train.fp16_run) for epoch in range(epoch_str, hps.train.epochs + 1): if rank == 0: train_and_evaluate( rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval], ) else: train_and_evaluate( rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None, ) scheduler_g.step() scheduler_d.step() if net_dur_disc is not None: scheduler_dur_disc.step() def train_and_evaluate( rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers ): net_g, net_d, net_dur_disc = nets optim_g, optim_d, optim_dur_disc = optims scheduler_g, scheduler_d, scheduler_dur_disc = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() if net_dur_disc is not None: net_dur_disc.train() for batch_idx, ( x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert, ja_bert, ) in tqdm(enumerate(train_loader)): if net_g.use_noise_scaled_mas: current_mas_noise_scale = ( net_g.mas_noise_scale_initial - net_g.noise_scale_delta * global_step ) net_g.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda( rank, non_blocking=True ) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda( rank, non_blocking=True ) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda( rank, non_blocking=True ) speakers = speakers.cuda(rank, non_blocking=True) tone = tone.cuda(rank, non_blocking=True) language = language.cuda(rank, non_blocking=True) bert = bert.cuda(rank, non_blocking=True) ja_bert = ja_bert.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): ( y_hat, l_length, attn, ids_slice, x_mask, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_), ) = net_g( x, x_lengths, spec, spec_lengths, speakers, tone, language, bert, ja_bert, ) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax, ) y_mel = commons.slice_segments( mel, ids_slice, hps.train.segment_size // hps.data.hop_length ) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax, ) y = commons.slice_segments( y, ids_slice * hps.data.hop_length, hps.train.segment_size ) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( y_d_hat_r, y_d_hat_g ) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc( hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach() ) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all ( loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g, ) = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
9
2023-10-16 10:04:32+00:00
16k
violet-sto/HN-GFN
main.py
[ { "identifier": "Dataset", "path": "dataset.py", "snippet": "class Dataset:\n\n def __init__(self, args, bpath, oracle, device):\n self.test_split_rng = np.random.RandomState(142857)\n self.train_rng = np.random.RandomState(int(time.time()))\n self.train_mols = []\n self.t...
from curses import raw from dataset import Dataset from mol_mdp_ext import MolMDPExtended, BlockMoleculeDataExtended from oracle.oracle import Oracle from proxy import get_proxy from generator import TBGFlowNet, FMGFlowNet from utils.metrics import circle_points, compute_success, compute_diversity, compute_novelty, evaluate, compute_correlation from utils.utils import set_random_seed from utils.logging import get_logger from datetime import datetime from botorch.utils.multi_objective.hypervolume import Hypervolume from botorch.utils.sampling import sample_simplex from botorch.utils.transforms import normalize, unnormalize from torch.distributions.dirichlet import Dirichlet from rdkit.Chem import AllChem from rdkit import DataStructs from pymoo.util.ref_dirs import get_reference_directions import os import argparse import json import time import threading import pdb import pickle import gzip import warnings import torch.multiprocessing as mp import torch.nn.functional as F import torch import pandas as pd import numpy as np
12,247
args.logger.add_scalar( 'Loss/train', train_loss[0], use_context=False) print('Iter {}: Loss {}, Time {}'.format( i, train_loss, round(time.time() - time_last_check, 3))) time_last_check = time.time() last_losses = [] if not i % args.sample_iterations and i != 0: volume, diversity = evaluate(args, generator, rollout_worker, 100) corrs = compute_correlation(args, generator, rollout_worker, rollout_worker.test_mols) args.logger.add_scalar( 'Top-100-sampled/volumes', volume, use_context=False) args.logger.add_scalar( 'Top-100-sampled/dists', diversity, use_context=False) args.logger.add_scalar( 'Top-100-sampled/corr', np.mean(corrs), use_context=False) if do_save: save_stuff(i) if volume > best_hv: best_hv = volume if do_save: save_stuff('volume') if np.mean(corrs) > best_corr: best_corr = np.mean(corrs) if do_save: save_stuff('corr') stop_everything() if do_save: save_stuff(i) return rollout_worker, {'train_losses': train_losses, 'test_losses': test_losses, 'test_infos': test_infos, 'train_infos': train_infos} def get_test_mols(args, mdp, num): samples = [] fps = [] early_stops = [] while len(samples) < num: if len(samples) % 5000 == 0: print(f'{len(samples)}/{num} mols have been sampled') m = BlockMoleculeDataExtended() min_blocks = args.min_blocks max_blocks = args.max_blocks early_stop_at = np.random.randint(min_blocks, max_blocks + 1) early_stops.append(early_stop_at) for t in range(max_blocks): if t == 0: length = mdp.num_blocks+1 else: length = len(m.stems)*mdp.num_blocks+1 action = np.random.randint(1, length) if t == early_stop_at: action = 0 if t >= min_blocks and action == 0: fp = AllChem.GetMorganFingerprintAsBitVect(m.mol, 3, 2048) if len(samples)==0: samples.append(m) fps.append(fp) else: sims = DataStructs.BulkTanimotoSimilarity(fp, fps) if max(sims) < 0.7: samples.append(m) fps.append(fp) break else: action = max(0, action-1) action = (action % mdp.num_blocks, action // mdp.num_blocks) #print('..', action) m = mdp.add_block_to(m, *action) if len(m.blocks) and not len(m.stems) or t == max_blocks - 1: # can't add anything more to this mol so let's make it # terminal. Note that this node's parent isn't just m, # because this is a sink for all parent transitions fp = AllChem.GetMorganFingerprintAsBitVect(m.mol, 3, 2048) if len(samples)==0: samples.append(m) fps.append(fp) else: sims = DataStructs.BulkTanimotoSimilarity(fp, fps) if max(sims) < 0.7: samples.append(m) fps.append(fp) break return samples def get_test_rays(): if args.n_objectives == 3: n_partitions = 6 elif args.n_objectives == 4: n_partitions = 7 test_rays = get_reference_directions("das-dennis", args.n_objectives, n_partitions=n_partitions).astype(np.float32) test_rays = test_rays[[(r > 0).all() for r in test_rays]] print(f"initialize {len(test_rays)} test rays") return test_rays def main(args): set_random_seed(args.seed) args.logger.set_context('iter_0') bpath = "./data/blocks_105.json" # Initialization: oracle and dataset oracle = Oracle(args) args.n_objectives = len(args.objectives) if args.n_objectives == 2: test_weights = circle_points(K=5, min_angle=0.1, max_angle=np.pi/2-0.1) else: test_weights = get_test_rays() if args.criterion == 'TB': generator = TBGFlowNet(args, bpath) elif args.criterion == 'FM':
warnings.filterwarnings('ignore') def arg_parse(): parser = argparse.ArgumentParser() parser.add_argument("--device", type=str, default='cuda') parser.add_argument('--seed', type=int, default=42, help='seed') parser.add_argument("--run", default=0, help="run", type=int) parser.add_argument('--save', action='store_true', default=False, help='Save model.') parser.add_argument('--debug', action='store_true', default=False, help='debug mode, no multi thread') parser.add_argument("--enable_tensorboard", action='store_true', default=False) parser.add_argument("--log_dir", default='runs/synthetic') parser.add_argument("--include_nblocks", default=False) parser.add_argument("--num_samples", default=1000, type=int) parser.add_argument("--floatX", default='float32') parser.add_argument('--sample_iterations', type=int, default=1000, help='sample mols and compute metrics') # objectives parser.add_argument("--objectives", type=str, default='gsk3b,jnk3') parser.add_argument("--scalar", default='WeightedSum', type=str) #TODO: other scalars parser.add_argument("--alpha", default=1., type=float, help='dirichlet distribution') parser.add_argument("--alpha_vector", default='1,1', type=str) # GFlowNet parser.add_argument("--min_blocks", default=2, type=int) parser.add_argument("--max_blocks", default=8, type=int) parser.add_argument("--num_iterations", default=30000, type=int) # 30k parser.add_argument("--criterion", default="FM", type=str) parser.add_argument("--learning_rate", default=5e-4, help="Learning rate", type=float) parser.add_argument("--Z_learning_rate", default=5e-3, help="Learning rate", type=float) parser.add_argument("--clip_grad", default=0, type=float) parser.add_argument("--trajectories_mbsize", default=16, type=int) parser.add_argument("--offline_mbsize", default=0, type=int) parser.add_argument("--hindsight_mbsize", default=0, type=int) parser.add_argument("--reward_min", default=1e-2, type=float) parser.add_argument("--reward_norm", default=0.8, type=float) parser.add_argument("--reward_exp", default=6, type=float) parser.add_argument("--reward_exp_ramping", default=0, type=float) # Hyperparameters for TB parser.add_argument("--partition_init", default=30, type=float) # Hyperparameters for FM parser.add_argument("--log_reg_c", default=(0.1/8) ** 4, type=float) # (0.1/8)**8 parser.add_argument("--balanced_loss", default=True) parser.add_argument("--leaf_coef", default=10, type=float) # Architecture parser.add_argument("--repr_type", default='block_graph') parser.add_argument("--model_version", default='v4') parser.add_argument("--condition_type", default='HN', type=str) # 'HN', 'FiLM', 'concat' parser.add_argument("--num_conv_steps", default=10, type=int) parser.add_argument("--nemb", default=256, help="#hidden", type=int) parser.add_argument("--weight_decay", default=0, type=float) parser.add_argument("--random_action_prob", default=0.05, type=float) parser.add_argument("--bootstrap_tau", default=0, type=float) parser.add_argument("--ray_hidden_dim", default=100, type=int) parser.add_argument("--logit_clipping", default=0., type=float) return parser.parse_args() class RolloutWorker: def __init__(self, args, bpath, proxy, device): self.args = args self.test_split_rng = np.random.RandomState(142857) self.train_rng = np.random.RandomState(int(time.time())) self.mdp = MolMDPExtended(bpath) self.mdp.post_init(device, args.repr_type, include_nblocks=args.include_nblocks) self.mdp.build_translation_table() if args.floatX == 'float64': self.mdp.floatX = self.floatX = torch.double else: self.mdp.floatX = self.floatX = torch.float self.proxy = proxy self._device = device self.seen_molecules = set() self.stop_event = threading.Event() ####### # This is the "result", here a list of (reward, BlockMolDataExt, info...) tuples self.sampled_mols = [] self.online_mols = [] self.hindsight_mols = [] self.max_online_mols = 1000 self.max_hindsight_mols = 1000 self.min_blocks = args.min_blocks self.max_blocks = args.max_blocks self.mdp._cue_max_blocks = self.max_blocks self.reward_exp = args.reward_exp self.reward_min = args.reward_min self.reward_norm = args.reward_norm self.reward_exp_ramping = args.reward_exp_ramping self.random_action_prob = args.random_action_prob # If True this basically implements Buesing et al's TreeSample Q, # samples uniformly from it though, no MTCS involved if args.criterion == 'TB' or args.criterion == "Reinforce": self.ignore_parents = True elif args.criterion == 'FM': self.ignore_parents = False def rollout(self, generator, use_rand_policy=True, weights=None, replay=False): weights = Dirichlet(torch.ones(len(self.args.objectives))*self.args.alpha).sample_n(1).to( self.args.device) if weights is None else weights m = BlockMoleculeDataExtended() samples = [] max_blocks = self.max_blocks trajectory_stats = [] for t in range(max_blocks): s = self.mdp.mols2batch([self.mdp.mol2repr(m)]) s_o, m_o = generator(s, vec_data=weights, do_stems=True) # fix from run 330 onwards if t < self.min_blocks: m_o = m_o*0 - 1000 # prevent assigning prob to stop # when we can't stop ## logits = torch.cat([m_o.reshape(-1), s_o.reshape(-1)]) cat = torch.distributions.Categorical( logits=logits) action = cat.sample().item() if use_rand_policy and self.random_action_prob > 0: # just for training if self.train_rng.uniform() < self.random_action_prob: action = self.train_rng.randint( int(t < self.min_blocks), logits.shape[0]) q = torch.cat([m_o.reshape(-1), s_o.reshape(-1)]) trajectory_stats.append( (q[action].item(), action, torch.logsumexp(q, 0).item())) if t >= self.min_blocks and action == 0: r, raw_r = self._get_reward(m, weights) # r: reward, raw_r: scores for the objectives samples.append(((m,), ((-1, 0),), weights, weights, r, m, 1)) break else: action = max(0, action-1) action = (action % self.mdp.num_blocks, action // self.mdp.num_blocks) m_old = m m = self.mdp.add_block_to(m, *action) if len(m.blocks) and not len(m.stems) or t == max_blocks - 1: # can't add anything more to this mol so let's make it # terminal. Note that this node's parent isn't just m, # because this is a sink for all parent transitions r, raw_r = self._get_reward(m, weights) if self.ignore_parents: samples.append( ((m_old,), (action,), weights, weights, r, m, 1)) else: parents, actions = zip(*self.mdp.parents(m)) samples.append((parents, actions, weights.repeat( len(parents), 1), weights, r, m, 1)) break else: if self.ignore_parents: samples.append( ((m_old,), (action,), weights, weights, 0, m, 0)) else: parents, actions = zip(*self.mdp.parents(m)) samples.append( (parents, actions, weights.repeat(len(parents), 1), weights, 0, m, 0)) p = self.mdp.mols2batch([self.mdp.mol2repr(i) for i in samples[-1][0]]) qp = generator(p, weights.repeat(p.num_graphs, 1)) qsa_p = generator.model.index_output_by_action( p, qp[0], qp[1][:, 0], torch.tensor(samples[-1][1], device=self._device).long()) inflow = torch.logsumexp(qsa_p.flatten(), 0).item() self.sampled_mols.append( ([i.cpu().numpy() for i in raw_r], weights.cpu().numpy(), m, trajectory_stats, inflow)) if replay and self.args.hindsight_prob > 0.0: self._add_mol_to_replay(m) return samples def _get_reward(self, m, weights=None): rdmol = m.mol if rdmol is None: return self.reward_min # get scores from oracle score = self.proxy.get_score([m]) score = torch.tensor(list(score.values())).to(self.args.device) if self.args.scalar == 'WeightedSum': raw_reward = (weights*score).sum() elif self.args.scalar == 'Tchebycheff': raw_reward = (weights*score).min() + 0.1 * (weights*score).sum() reward = self.l2r(raw_reward.clip(self.reward_min)) return reward, (raw_reward, score) def execute_train_episode_batch(self, generator, dataset=None, use_rand_policy=True): if self.args.condition_type is None: weights = self.test_weights # train specific model else: weights = Dirichlet(torch.tensor(self.args.alpha_vector)*self.args.alpha).sample_n(1).to(self.args.device) #* sample weights per batch, seem better samples = sum((self.rollout(generator, use_rand_policy, weights) for i in range(self.args.trajectories_mbsize)), []) return zip(*samples) def sample2batch(self, mb): p, a, p_weights, weights, r, s, d, *o = mb mols = (p, s) # The batch index of each parent p_batch = torch.tensor(sum([[i]*len(p) for i, p in enumerate(p)], []), device=self._device).long() # Convert all parents and states to repr. Note that this # concatenates all the parent lists, which is why we need # p_batch p = self.mdp.mols2batch(list(map(self.mdp.mol2repr, sum(p, ())))) s = self.mdp.mols2batch([self.mdp.mol2repr(i) for i in s]) # Concatenate all the actions (one per parent per sample) a = torch.tensor(sum(a, ()), device=self._device).long() # rewards and dones r = torch.tensor(r, device=self._device).to(self.floatX) d = torch.tensor(d, device=self._device).to(self.floatX) # weights p_w = torch.cat(p_weights, 0) w = torch.cat(weights, 0) return (p, p_batch, a, p_w, w, r, s, d, mols, *o) def l2r(self, raw_reward, t=0): if self.reward_exp_ramping > 0: reward_exp = 1 + (self.reward_exp - 1) * \ (1 - 1/(1 + t / self.reward_exp_ramping)) # when t=0, exp = 1; t->∞, exp = self.reward_exp else: reward_exp = self.reward_exp reward = (raw_reward/self.reward_norm)**reward_exp return reward def start_samplers(self, generator, n, dataset): self.ready_events = [threading.Event() for i in range(n)] self.resume_events = [threading.Event() for i in range(n)] self.results = [None] * n def f(idx): while not self.stop_event.is_set(): try: self.results[idx] = self.sample2batch( self.execute_train_episode_batch(generator, dataset, use_rand_policy=True)) except Exception as e: print("Exception while sampling:") print(e) self.sampler_threads[idx].failed = True self.sampler_threads[idx].exception = e self.ready_events[idx].set() break self.ready_events[idx].set() self.resume_events[idx].clear() self.resume_events[idx].wait() self.sampler_threads = [threading.Thread( target=f, args=(i,)) for i in range(n)] [setattr(i, 'failed', False) for i in self.sampler_threads] [i.start() for i in self.sampler_threads] round_robin_idx = [0] def get(): while True: idx = round_robin_idx[0] round_robin_idx[0] = (round_robin_idx[0] + 1) % n if self.ready_events[idx].is_set(): r = self.results[idx] self.ready_events[idx].clear() self.resume_events[idx].set() return r elif round_robin_idx[0] == 0: time.sleep(0.001) return get def stop_samplers_and_join(self): self.stop_event.set() if hasattr(self, 'sampler_threads'): while any([i.is_alive() for i in self.sampler_threads]): [i.set() for i in self.resume_events] [i.join(0.05) for i in self.sampler_threads] def train_generative_model_with_oracle(args, generator, bpath, oracle, test_weights, dataset=None, do_save=False): print("Training generator...") device = args.device rollout_worker = RolloutWorker(args, bpath, oracle, device) if args.condition_type is None: rollout_worker.test_weights = torch.tensor(test_weights).to(device)[args.run :args.run+1] else: rollout_worker.test_weights = torch.tensor(test_weights).to(device) rollout_worker.test_mols = pickle.load(gzip.open('./data/test_mols_6062.pkl.gz', 'rb')) def save_stuff(iter): torch.save(generator.state_dict(), os.path.join( args.log_dir, '{}_generator_checkpoint.pth'.format(iter))) pickle.dump(rollout_worker.sampled_mols, gzip.open(f'{args.log_dir}/sampled_mols.pkl.gz', 'wb')) multi_thread = not args.debug if multi_thread: sampler = rollout_worker.start_samplers(generator, 8, dataset) def stop_everything(): print('joining') rollout_worker.stop_samplers_and_join() last_losses = [] train_losses = [] test_losses = [] test_infos = [] train_infos = [] best_hv = 0 best_corr = 0 time_last_check = time.time() for i in range(args.num_iterations + 1): rollout_worker.reward_exp = 1 + (args.reward_exp-1) * (1-1/(1+i/20)) if multi_thread: r = sampler() for thread in rollout_worker.sampler_threads: if thread.failed: stop_everything() pdb.post_mortem(thread.exception.__traceback__) return p, pb, a, pw, w, r, s, d, mols = r else: p, pb, a, pw, w, r, s, d, mols = rollout_worker.sample2batch( rollout_worker.execute_train_episode_batch(generator, dataset, use_rand_policy=True)) loss = generator.train_step(p, pb, a, pw, w, r, s, d, mols, i) last_losses.append(loss) if not i % 100: train_loss = [np.round(np.mean(loss), 3) for loss in zip(*last_losses)] train_losses.append(train_loss) args.logger.add_scalar( 'Loss/train', train_loss[0], use_context=False) print('Iter {}: Loss {}, Time {}'.format( i, train_loss, round(time.time() - time_last_check, 3))) time_last_check = time.time() last_losses = [] if not i % args.sample_iterations and i != 0: volume, diversity = evaluate(args, generator, rollout_worker, 100) corrs = compute_correlation(args, generator, rollout_worker, rollout_worker.test_mols) args.logger.add_scalar( 'Top-100-sampled/volumes', volume, use_context=False) args.logger.add_scalar( 'Top-100-sampled/dists', diversity, use_context=False) args.logger.add_scalar( 'Top-100-sampled/corr', np.mean(corrs), use_context=False) if do_save: save_stuff(i) if volume > best_hv: best_hv = volume if do_save: save_stuff('volume') if np.mean(corrs) > best_corr: best_corr = np.mean(corrs) if do_save: save_stuff('corr') stop_everything() if do_save: save_stuff(i) return rollout_worker, {'train_losses': train_losses, 'test_losses': test_losses, 'test_infos': test_infos, 'train_infos': train_infos} def get_test_mols(args, mdp, num): samples = [] fps = [] early_stops = [] while len(samples) < num: if len(samples) % 5000 == 0: print(f'{len(samples)}/{num} mols have been sampled') m = BlockMoleculeDataExtended() min_blocks = args.min_blocks max_blocks = args.max_blocks early_stop_at = np.random.randint(min_blocks, max_blocks + 1) early_stops.append(early_stop_at) for t in range(max_blocks): if t == 0: length = mdp.num_blocks+1 else: length = len(m.stems)*mdp.num_blocks+1 action = np.random.randint(1, length) if t == early_stop_at: action = 0 if t >= min_blocks and action == 0: fp = AllChem.GetMorganFingerprintAsBitVect(m.mol, 3, 2048) if len(samples)==0: samples.append(m) fps.append(fp) else: sims = DataStructs.BulkTanimotoSimilarity(fp, fps) if max(sims) < 0.7: samples.append(m) fps.append(fp) break else: action = max(0, action-1) action = (action % mdp.num_blocks, action // mdp.num_blocks) #print('..', action) m = mdp.add_block_to(m, *action) if len(m.blocks) and not len(m.stems) or t == max_blocks - 1: # can't add anything more to this mol so let's make it # terminal. Note that this node's parent isn't just m, # because this is a sink for all parent transitions fp = AllChem.GetMorganFingerprintAsBitVect(m.mol, 3, 2048) if len(samples)==0: samples.append(m) fps.append(fp) else: sims = DataStructs.BulkTanimotoSimilarity(fp, fps) if max(sims) < 0.7: samples.append(m) fps.append(fp) break return samples def get_test_rays(): if args.n_objectives == 3: n_partitions = 6 elif args.n_objectives == 4: n_partitions = 7 test_rays = get_reference_directions("das-dennis", args.n_objectives, n_partitions=n_partitions).astype(np.float32) test_rays = test_rays[[(r > 0).all() for r in test_rays]] print(f"initialize {len(test_rays)} test rays") return test_rays def main(args): set_random_seed(args.seed) args.logger.set_context('iter_0') bpath = "./data/blocks_105.json" # Initialization: oracle and dataset oracle = Oracle(args) args.n_objectives = len(args.objectives) if args.n_objectives == 2: test_weights = circle_points(K=5, min_angle=0.1, max_angle=np.pi/2-0.1) else: test_weights = get_test_rays() if args.criterion == 'TB': generator = TBGFlowNet(args, bpath) elif args.criterion == 'FM':
generator = FMGFlowNet(args, bpath)
5
2023-10-24 14:10:35+00:00
16k
SALT-NLP/Efficient_Unlearning
src/models/transformers/parameter-efficient-finetuning/heads/base.py
[ { "identifier": "ImageClassifierOutput", "path": "src/models/transformers/modeling_outputs.py", "snippet": "class ImageClassifierOutput(ModelOutput):\n \"\"\"\n Base class for outputs of image classification models.\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, retur...
import logging import torch from dataclasses import dataclass from typing import List, Optional, Union from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...modeling_outputs import ( ImageClassifierOutput, MultipleChoiceModelOutput, QuestionAnsweringModelOutput, Seq2SeqModelOutput, Seq2SeqQuestionAnsweringModelOutput, Seq2SeqSequenceClassifierOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...utils import ModelOutput from ..composition import AdapterCompositionBlock, BatchSplit, Parallel, parse_heads_from_composition from ..context import AdapterSetup, ForwardContext from ..model_mixin import ModelWithHeadsAdaptersMixin from ..modeling import Activation_Function_Class
11,320
# with number indices the head output at that position is accessed # e.g output[1] is equivalent to output.head_outputs[1] if isinstance(k, int): return self.head_outputs[k] # with strings the attribute in the underlying dict can be adressed # e.g output["loss"] is equivalent to output.loss else: return super().__getitem__(k) def __setitem__(self, k, v): if isinstance(k, int): self.head_outputs[k] = v else: return super().__setitem__(k, v) def __iter__(self): # iterates over the head outputs return iter(self.head_outputs) def __len__(self): return len(self.head_outputs) # Let this class inherit from nn.Sequential to provide iterable access as before class PredictionHead(nn.Sequential): def __init__(self, name): super().__init__() self.config = {} self.name = name def build(self, model): model_config = model.config pred_head = [] dropout_prob = self.config.get("dropout_prob", model_config.hidden_dropout_prob) bias = self.config.get("bias", True) for l_id in range(self.config["layers"]): if dropout_prob > 0: pred_head.append(nn.Dropout(dropout_prob)) if l_id < self.config["layers"] - 1: pred_head.append(nn.Linear(model_config.hidden_size, model_config.hidden_size)) if self.config["activation_function"]: pred_head.append(Activation_Function_Class(self.config["activation_function"])) else: if "num_labels" in self.config: pred_head.append(nn.Linear(model_config.hidden_size, self.config["num_labels"], bias=bias)) elif "num_choices" in self.config: # used for multiple_choice head pred_head.append(nn.Linear(model_config.hidden_size, 1, bias=bias)) else: pred_head.append(nn.Linear(model_config.hidden_size, model_config.hidden_size, bias=bias)) if self.config["activation_function"]: pred_head.append(Activation_Function_Class(self.config["activation_function"])) for i, module in enumerate(pred_head): self.add_module(str(i), module) self.apply(model._init_weights) self.train(model.training) # make sure training mode is consistent def get_output_embeddings(self): return None # override for heads with output embeddings def get_label_names(self): return ["labels"] class ClassificationHead(PredictionHead): def __init__( self, model, head_name, num_labels=2, layers=2, activation_function="tanh", id2label=None, use_pooler=False, bias=True, ): super().__init__(head_name) self.config = { "head_type": "classification", "num_labels": num_labels, "layers": layers, "activation_function": activation_function, "label2id": {label: id_ for id_, label in id2label.items()} if id2label is not None else None, "use_pooler": use_pooler, "bias": bias, } self.build(model) def forward(self, outputs, cls_output=None, attention_mask=None, return_dict=False, **kwargs): if cls_output is None: if self.config["use_pooler"]: cls_output = kwargs.pop("pooled_output") else: cls_output = outputs[0][:, 0] logits = super().forward(cls_output) loss = None labels = kwargs.pop("labels", None) if labels is not None: if self.config["num_labels"] == 1: # We are doing regression loss_fct = MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.config["num_labels"]), labels.view(-1)) if return_dict: if isinstance(outputs, Seq2SeqModelOutput): return Seq2SeqSequenceClassifierOutput( loss=loss, logits=logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) else:
logger = logging.getLogger(__name__) @dataclass class MultiHeadOutput(ModelOutput): head_outputs: List[ModelOutput] = None loss: Optional[torch.FloatTensor] = None @property def logits(self): return torch.vstack([outputs["logits"] for outputs in self.head_outputs]) def __getitem__(self, k): # with number indices the head output at that position is accessed # e.g output[1] is equivalent to output.head_outputs[1] if isinstance(k, int): return self.head_outputs[k] # with strings the attribute in the underlying dict can be adressed # e.g output["loss"] is equivalent to output.loss else: return super().__getitem__(k) def __setitem__(self, k, v): if isinstance(k, int): self.head_outputs[k] = v else: return super().__setitem__(k, v) def __iter__(self): # iterates over the head outputs return iter(self.head_outputs) def __len__(self): return len(self.head_outputs) # Let this class inherit from nn.Sequential to provide iterable access as before class PredictionHead(nn.Sequential): def __init__(self, name): super().__init__() self.config = {} self.name = name def build(self, model): model_config = model.config pred_head = [] dropout_prob = self.config.get("dropout_prob", model_config.hidden_dropout_prob) bias = self.config.get("bias", True) for l_id in range(self.config["layers"]): if dropout_prob > 0: pred_head.append(nn.Dropout(dropout_prob)) if l_id < self.config["layers"] - 1: pred_head.append(nn.Linear(model_config.hidden_size, model_config.hidden_size)) if self.config["activation_function"]: pred_head.append(Activation_Function_Class(self.config["activation_function"])) else: if "num_labels" in self.config: pred_head.append(nn.Linear(model_config.hidden_size, self.config["num_labels"], bias=bias)) elif "num_choices" in self.config: # used for multiple_choice head pred_head.append(nn.Linear(model_config.hidden_size, 1, bias=bias)) else: pred_head.append(nn.Linear(model_config.hidden_size, model_config.hidden_size, bias=bias)) if self.config["activation_function"]: pred_head.append(Activation_Function_Class(self.config["activation_function"])) for i, module in enumerate(pred_head): self.add_module(str(i), module) self.apply(model._init_weights) self.train(model.training) # make sure training mode is consistent def get_output_embeddings(self): return None # override for heads with output embeddings def get_label_names(self): return ["labels"] class ClassificationHead(PredictionHead): def __init__( self, model, head_name, num_labels=2, layers=2, activation_function="tanh", id2label=None, use_pooler=False, bias=True, ): super().__init__(head_name) self.config = { "head_type": "classification", "num_labels": num_labels, "layers": layers, "activation_function": activation_function, "label2id": {label: id_ for id_, label in id2label.items()} if id2label is not None else None, "use_pooler": use_pooler, "bias": bias, } self.build(model) def forward(self, outputs, cls_output=None, attention_mask=None, return_dict=False, **kwargs): if cls_output is None: if self.config["use_pooler"]: cls_output = kwargs.pop("pooled_output") else: cls_output = outputs[0][:, 0] logits = super().forward(cls_output) loss = None labels = kwargs.pop("labels", None) if labels is not None: if self.config["num_labels"] == 1: # We are doing regression loss_fct = MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.config["num_labels"]), labels.view(-1)) if return_dict: if isinstance(outputs, Seq2SeqModelOutput): return Seq2SeqSequenceClassifierOutput( loss=loss, logits=logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) else:
return SequenceClassifierOutput(
6
2023-10-18 18:05:54+00:00
16k
upiterbarg/hihack
models/utils.py
[ { "identifier": "CDGPT5", "path": "models/cdgpt5.py", "snippet": "class CDGPT5(nn.Module):\n def __init__(self, shape, action_space, flags, device):\n super(CDGPT5, self).__init__()\n\n self.flags = flags\n self.num_actions = len(action_space)\n self.use_prev_action = flag...
import omegaconf import os import pathlib import pdb import sys import torch from .cdgpt5 import CDGPT5 from .cleaved_hierarchical_policy import CleavedHierarchicalPolicy from .flat_transformer import FlatTransformer from .hierarchical_lstm import HierarchicalLSTM from .hierarchical_transformer_lstm import HierarchicalTransformerLSTM from .transformer_lstm import TransformerLSTM from nle.env.base import DUNGEON_SHAPE from omegaconf import OmegaConf from tasks import ENVS
11,179
base_path = str(pathlib.Path().resolve()) hihack_path = os.path.join(base_path[:base_path.find('hihack')], 'hihack') sys.path.insert(0, os.path.join(hihack_path, 'dungeonsdata-neurips2022/experiment_code/hackrl')) MODELS = [ CDGPT5, HierarchicalLSTM, HierarchicalTransformerLSTM, TransformerLSTM, FlatTransformer ] MODELS_LOOKUP = {c.__name__: c for c in MODELS} def initialize_weights(flags, model): def _initialize_weights(layer): if hasattr(layer, "bias") and isinstance( layer.bias, torch.nn.parameter.Parameter ): layer.bias.data.fill_(0) if flags.initialisation == "orthogonal": if type(layer) in [torch.nn.Conv2d, torch.nn.Linear]: torch.nn.init.orthogonal_(layer.weight.data, gain=1.0) elif flags.initialisation == "xavier_uniform": if type(layer) in [torch.nn.Conv2d, torch.nn.Linear]: torch.nn.init.xavier_uniform_(layer.weight.data, gain=1.0) else: pass else: pass model.apply(_initialize_weights) def load_flags(load_path): out = torch.load(load_path) return omegaconf.OmegaConf.create(out['flags']) def create_model(flags, device, model_type=None): model_type = model_type if not model_type is None else flags.model try: model_cls = MODELS_LOOKUP[model_type] except KeyError: raise NotImplementedError("model=%s" % flags.model) from None action_space = ENVS[flags.env.name](savedir=None).actions model = model_cls(DUNGEON_SHAPE, action_space, flags, device) model.to(device=device) initialize_weights(flags, model) return model def load_pt_model_and_flags(load_path, device): out = torch.load(load_path, map_location=device) flags = omegaconf.OmegaConf.create(out['flags']) if flags.model == 'CleavedHierarchicalPolicy': assert len(out['submodule_flags']) > 0 submodule_flags = omegaconf.OmegaConf.create(out['submodule_flags']) high_level_model = create_model(submodule_flags, device, model_type=flags.high_level_model) low_level_model = create_model(flags, device, model_type=flags.low_level_model)
base_path = str(pathlib.Path().resolve()) hihack_path = os.path.join(base_path[:base_path.find('hihack')], 'hihack') sys.path.insert(0, os.path.join(hihack_path, 'dungeonsdata-neurips2022/experiment_code/hackrl')) MODELS = [ CDGPT5, HierarchicalLSTM, HierarchicalTransformerLSTM, TransformerLSTM, FlatTransformer ] MODELS_LOOKUP = {c.__name__: c for c in MODELS} def initialize_weights(flags, model): def _initialize_weights(layer): if hasattr(layer, "bias") and isinstance( layer.bias, torch.nn.parameter.Parameter ): layer.bias.data.fill_(0) if flags.initialisation == "orthogonal": if type(layer) in [torch.nn.Conv2d, torch.nn.Linear]: torch.nn.init.orthogonal_(layer.weight.data, gain=1.0) elif flags.initialisation == "xavier_uniform": if type(layer) in [torch.nn.Conv2d, torch.nn.Linear]: torch.nn.init.xavier_uniform_(layer.weight.data, gain=1.0) else: pass else: pass model.apply(_initialize_weights) def load_flags(load_path): out = torch.load(load_path) return omegaconf.OmegaConf.create(out['flags']) def create_model(flags, device, model_type=None): model_type = model_type if not model_type is None else flags.model try: model_cls = MODELS_LOOKUP[model_type] except KeyError: raise NotImplementedError("model=%s" % flags.model) from None action_space = ENVS[flags.env.name](savedir=None).actions model = model_cls(DUNGEON_SHAPE, action_space, flags, device) model.to(device=device) initialize_weights(flags, model) return model def load_pt_model_and_flags(load_path, device): out = torch.load(load_path, map_location=device) flags = omegaconf.OmegaConf.create(out['flags']) if flags.model == 'CleavedHierarchicalPolicy': assert len(out['submodule_flags']) > 0 submodule_flags = omegaconf.OmegaConf.create(out['submodule_flags']) high_level_model = create_model(submodule_flags, device, model_type=flags.high_level_model) low_level_model = create_model(flags, device, model_type=flags.low_level_model)
model = CleavedHierarchicalPolicy(flags, high_level_model, low_level_model)
1
2023-10-23 15:44:32+00:00
16k
nchen909/Pass-Tuning
main.py
[ { "identifier": "add_args", "path": "configs.py", "snippet": "def add_args(parser):\n parser.add_argument(\"--task\", type=str, required=True,\n choices=['summarize', 'translate', 'refine', 'generate', 'defect', 'clone'])# without complete\n parser.add_argument(\"--sub_task\...
import logging import torch import argparse import time import multiprocessing import os import numpy as np import math import sys from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader, SequentialSampler, RandomSampler from torch.utils.data.distributed import DistributedSampler from transformers import AdamW, get_linear_schedule_with_warmup from tqdm import tqdm from configs import add_args, set_dist, set_seed, set_hyperparas from models import bulid_or_load_gen_model,bulid_or_load_cls_model from utils import get_filenames, get_elapse_time, load_and_cache_gen_data, load_and_cache_defect_data,load_and_cache_clone_data, get_lang_by_task from evaluator import smooth_bleu from evaluator.CodeBLEU import calc_code_bleu from evaluator.bleu import _bleu from sklearn.metrics import recall_score, precision_score, f1_score from tree_sitter import Language, Parser from utils import retrieve2file
13,043
elif args.model_name in ['unixcoder']: preds = model(source_ids=source_ids) # preds shape: [batch_size, self.beam_size, max_target_len] top_preds = [pred[0].cpu().numpy() for pred in preds]# top_preds shape: batch_size * [max_target_len] else: preds = model.generate(source_ids, attention_mask=source_mask, use_cache=True, num_beams=args.beam_size, early_stopping=args.task == 'summarize', max_length=args.max_target_length) top_preds = list(preds.cpu().numpy()) pred_ids.extend(top_preds) # pdb.set_trace() pred_nls = [tokenizer.decode( id, skip_special_tokens=True, clean_up_tokenization_spaces=False) for id in pred_ids] # unixcoder in fewshot will generate '\n' in small batch, and gradually disappear if args.model_name in ['unixcoder']: pred_nls = [id.replace('\n',' ').replace(" "," ").replace(" "," ").replace("\t"," ") for id in pred_nls] output_fn = os.path.join(args.res_dir, "test_{}.output".format(criteria)) gold_fn = os.path.join(args.res_dir, "test_{}.gold".format(criteria)) src_fn = os.path.join(args.res_dir, "test_{}.src".format(criteria)) if args.task in ['defect']: target_dict = {0: 'false', 1: 'true'} golds = [target_dict[ex.target] for ex in eval_examples] eval_acc = np.mean([int(p == g) for p, g in zip(pred_nls, golds)]) result = {'em': eval_acc, 'bleu': 0, 'codebleu': 0} with open(output_fn, 'w',encoding='utf-8') as f, open(gold_fn, 'w',encoding='utf-8') as f1, open(src_fn, 'w',encoding='utf-8') as f2: for pred_nl, gold in zip(pred_nls, eval_examples): f.write(pred_nl.strip() + '\n') f1.write(target_dict[gold.target] + '\n') f2.write(gold.source.strip() + '\n') logger.info("Save the predictions into %s", output_fn) else: dev_accs, predictions = [], [] with open(output_fn, 'w',encoding='utf-8') as f, open(gold_fn, 'w',encoding='utf-8') as f1, open(src_fn, 'w',encoding='utf-8') as f2: for pred_nl, gold in zip(pred_nls, eval_examples): dev_accs.append(pred_nl.strip() == gold.target.strip()) if args.task in ['summarize']: predictions.append(str(gold.idx) + '\t' + pred_nl) f.write(str(gold.idx) + '\t' + pred_nl.strip().encode('utf8').decode() + '\n') f1.write(str(gold.idx) + '\t' + gold.target.strip().encode('utf8').decode() + '\n') f2.write(str(gold.idx) + '\t' + gold.source.strip().encode('utf8').decode() + '\n') else: f.write(pred_nl.strip().encode('utf8').decode() + '\n') f1.write(gold.target.strip().encode( 'utf8').decode() + '\n') f2.write(gold.source.strip().encode( 'utf8').decode() + '\n') if args.task in ['summarize']: (goldMap, predictionMap) = smooth_bleu.computeMaps(predictions, gold_fn) bleu = round(smooth_bleu.bleuFromMaps( goldMap, predictionMap)[0], 2) else: bleu = round(_bleu(gold_fn, output_fn), 2) if split_tag == 'test' and args.task in ['refine', 'translate', 'generate' , 'clone']: args.lang = get_lang_by_task(args.task, args.sub_task) codebleu = calc_code_bleu.get_codebleu( gold_fn, output_fn, args.lang,args=args) # except: # bleu = 0.0 # codebleu = 0.0 em = np.mean(dev_accs) * 100 result = {'em': em, 'bleu': bleu} if not args.task == 'summarize' and split_tag == 'test': result['codebleu'] = codebleu * 100 logger.info("***** Eval results *****") for key in sorted(result.keys()): logger.info(" %s = %s", key, str(round(result[key], 4))) return result def main(): parser = argparse.ArgumentParser() args = add_args(parser) t0 = time.time() set_dist(args) set_seed(args) set_hyperparas(args) logger.info(args) logger.info("************* args: *************") logger.info("args.model_name: "+str(args.model_name)) logger.info("args.few_shot: "+str(args.few_shot)) logger.info("args.task: "+str(args.task)) logger.info("args.sub_task: "+str(args.sub_task)) logger.info("*********************************") if args.task in ['summarize', 'translate', 'refine', 'generate','complete']: config, model, tokenizer = bulid_or_load_gen_model(args) elif args.task in ['defect','clone']: config, model, tokenizer = bulid_or_load_cls_model(args) model.to(args.device) if args.n_gpu > 1: model = torch.nn.DataParallel(model) pool = multiprocessing.Pool(args.cpu_count) args.train_filename, args.dev_filename, args.test_filename = get_filenames( args.data_dir, args.task, args.sub_task) fa = open(os.path.join(args.output_dir, 'summary.log'), 'a+',encoding='utf-8') if args.do_train: if args.local_rank in [-1, 0] and args.data_num == -1: summary_fn = '{}/{}'.format(args.summary_dir, '/'.join(args.output_dir.split('/')[1:])) tb_writer = SummaryWriter(summary_fn) # Prepare training data loader if args.task in ['summarize', 'translate', 'refine', 'generate','complete']: train_examples, train_data = load_and_cache_gen_data( args, args.train_filename, pool, tokenizer, 'train') elif args.task in ['defect']: train_examples, train_data = load_and_cache_defect_data(args, args.train_filename, pool, tokenizer, 'train') elif args.task in ['clone']:
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) def evaluate_cls(args, model, eval_examples, eval_data, write_to_pred=False): eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.dev_batch_size) # Eval! if write_to_pred == False: logger.info("***** Running evaluation *****") logger.info(" Num examples = %d", len(eval_examples)) logger.info(" Num batches = %d", len(eval_dataloader)) logger.info(" Batch size = %d", args.dev_batch_size) eval_loss = 0.0 nb_eval_steps = 0 model.eval() logits = [] labels = [] for batch in tqdm(eval_dataloader, total=len(eval_dataloader), desc="Evaluating"): if args.sub_task == "POJ": inputs = batch[0].to(args.device) p_inputs = batch[1].to(args.device) n_inputs = batch[2].to(args.device) label = batch[3].to(args.device) else: inputs = batch[0].to(args.device) # inputs shape: [batch_size, args.max_source_length+args.max_target_length] label = batch[1].to(args.device) # label shape: [batch_size] with torch.no_grad(): if args.sub_task == "POJ": lm_loss, logit = model(inputs,p_inputs,n_inputs,label) else: lm_loss, logit = model(inputs, label) # logit shape:[batch_size] eval_loss += lm_loss.mean().item() logits.append(logit.cpu().numpy())#logit shape: [batch_size] labels.append(label.cpu().numpy())#label shape: [batch_size] nb_eval_steps += 1 logits = np.concatenate(logits, 0) labels = np.concatenate(labels, 0) if args.model_name == "unixcoder" and args.task == "clone": preds = logits > 0.5 else: preds = logits[:, 1] > 0.5 if args.task == 'defect': eval_acc = np.mean(labels == preds) eval_loss = eval_loss / nb_eval_steps perplexity = torch.tensor(eval_loss) result = { "eval_loss": float(perplexity), "eval_acc": round(eval_acc, 4) * 100, } elif args.task == 'clone': recall = recall_score(labels, preds) precision = precision_score(labels, preds) f1 = f1_score(labels, preds) result = { "eval_recall": float(recall) * 100, "eval_precision": float(precision) * 100, "eval_f1": float(f1) * 100, "eval_threshold": 0.5, } if write_to_pred == False: logger.info("***** Eval results *****") for key in sorted(result.keys()): logger.info(" %s = %s", key, str(round(result[key], 4))) if write_to_pred: with open(os.path.join(args.output_dir, "predictions.txt"), 'w') as f: for example, pred in zip(eval_examples, preds): if args.task == 'defect': if args.model_name == "unixcoder": if pred: f.write(str(example.idx) + '\t1\n') else: f.write(str(example.idx) + '\t0\n') else: if pred: f.write(str(example.idx) + '\t1\n') else: f.write(str(example.idx) + '\t0\n') elif args.task == 'clone': if pred: f.write(example.url1 + '\t' + example.url2 + '\t' + '1' + '\n') else: f.write(example.url1 + '\t' + example.url2 + '\t' + '0' + '\n') return result def eval_ppl_epoch(args, eval_data, eval_examples, model, tokenizer): eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.dev_batch_size, num_workers=4, pin_memory=True) # Start evaluating model logger.info(" " + "***** Running ppl evaluation *****") logger.info(" Num examples = %d", len(eval_examples)) logger.info(" Batch size = %d", args.dev_batch_size) model.eval() eval_loss, batch_num = 0, 0 for batch in tqdm(eval_dataloader, total=len(eval_dataloader), desc="Eval ppl"): batch = tuple(t.to(args.device) for t in batch) source_ids, target_ids = batch source_mask = source_ids.ne(tokenizer.pad_token_id) target_mask = target_ids.ne(tokenizer.pad_token_id) with torch.no_grad(): if args.model_name in ['roberta', 'codebert', 'graphcodebert']: # loss, _, _, attention = model(source_ids=source_ids, source_mask=source_mask, # target_ids=target_ids, target_mask=target_mask) loss, _, _, _ = model(source_ids=source_ids, source_mask=source_mask, target_ids=target_ids, target_mask=target_mask) if args.n_gpu > 1: loss = loss.mean() eval_loss += loss.item() batch_num += 1 elif args.model_name in ['unixcoder']: _,loss,num = model(source_ids=source_ids,target_ids=target_ids) if args.n_gpu > 1: loss = loss.mean() eval_loss += loss.sum().item() batch_num += num.sum().item() else: outputs = model(input_ids=source_ids, attention_mask=source_mask, labels=target_ids, decoder_attention_mask=target_mask) if isinstance(outputs,dict): loss=outputs['loss'] else: loss = outputs.loss if args.n_gpu > 1: loss = loss.mean() eval_loss += loss.item() batch_num += 1 eval_loss = eval_loss / batch_num eval_ppl = round(np.exp(eval_loss), 5) return eval_ppl def eval_bleu_epoch(args, eval_data, eval_examples, model, tokenizer, split_tag, criteria): logger.info( " ***** Running bleu evaluation on {} data*****".format(split_tag)) logger.info(" Num examples = %d", len(eval_examples)) if split_tag == 'dev': batch_size = args.dev_batch_size elif split_tag == 'test': batch_size = args.test_batch_size else: batch_size = args.batch_size logger.info(" Batch size = %d", batch_size) eval_sampler = SequentialSampler(eval_data) if args.data_num == -1: eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=batch_size, num_workers=4, pin_memory=True) else: eval_dataloader = DataLoader( eval_data, sampler=eval_sampler, batch_size=batch_size) model.eval() pred_ids = [] bleu, codebleu = 0.0, 0.0 for batch in tqdm(eval_dataloader, total=len(eval_dataloader), desc="Eval bleu for {} set".format(split_tag)): source_ids = batch[0].to(args.device) #shape: (batch_size, max_source_len) source_mask = source_ids.ne(tokenizer.pad_token_id) if hasattr(model, 'module'): model = model.module # extract the model from the DataParallel wrapper with torch.no_grad(): if args.model_name in ['roberta', 'codebert', 'graphcodebert']: preds, _ = model(source_ids=source_ids, source_mask=source_mask) top_preds = [pred[0].cpu().numpy() for pred in preds] elif args.model_name in ['unixcoder']: preds = model(source_ids=source_ids) # preds shape: [batch_size, self.beam_size, max_target_len] top_preds = [pred[0].cpu().numpy() for pred in preds]# top_preds shape: batch_size * [max_target_len] else: preds = model.generate(source_ids, attention_mask=source_mask, use_cache=True, num_beams=args.beam_size, early_stopping=args.task == 'summarize', max_length=args.max_target_length) top_preds = list(preds.cpu().numpy()) pred_ids.extend(top_preds) # pdb.set_trace() pred_nls = [tokenizer.decode( id, skip_special_tokens=True, clean_up_tokenization_spaces=False) for id in pred_ids] # unixcoder in fewshot will generate '\n' in small batch, and gradually disappear if args.model_name in ['unixcoder']: pred_nls = [id.replace('\n',' ').replace(" "," ").replace(" "," ").replace("\t"," ") for id in pred_nls] output_fn = os.path.join(args.res_dir, "test_{}.output".format(criteria)) gold_fn = os.path.join(args.res_dir, "test_{}.gold".format(criteria)) src_fn = os.path.join(args.res_dir, "test_{}.src".format(criteria)) if args.task in ['defect']: target_dict = {0: 'false', 1: 'true'} golds = [target_dict[ex.target] for ex in eval_examples] eval_acc = np.mean([int(p == g) for p, g in zip(pred_nls, golds)]) result = {'em': eval_acc, 'bleu': 0, 'codebleu': 0} with open(output_fn, 'w',encoding='utf-8') as f, open(gold_fn, 'w',encoding='utf-8') as f1, open(src_fn, 'w',encoding='utf-8') as f2: for pred_nl, gold in zip(pred_nls, eval_examples): f.write(pred_nl.strip() + '\n') f1.write(target_dict[gold.target] + '\n') f2.write(gold.source.strip() + '\n') logger.info("Save the predictions into %s", output_fn) else: dev_accs, predictions = [], [] with open(output_fn, 'w',encoding='utf-8') as f, open(gold_fn, 'w',encoding='utf-8') as f1, open(src_fn, 'w',encoding='utf-8') as f2: for pred_nl, gold in zip(pred_nls, eval_examples): dev_accs.append(pred_nl.strip() == gold.target.strip()) if args.task in ['summarize']: predictions.append(str(gold.idx) + '\t' + pred_nl) f.write(str(gold.idx) + '\t' + pred_nl.strip().encode('utf8').decode() + '\n') f1.write(str(gold.idx) + '\t' + gold.target.strip().encode('utf8').decode() + '\n') f2.write(str(gold.idx) + '\t' + gold.source.strip().encode('utf8').decode() + '\n') else: f.write(pred_nl.strip().encode('utf8').decode() + '\n') f1.write(gold.target.strip().encode( 'utf8').decode() + '\n') f2.write(gold.source.strip().encode( 'utf8').decode() + '\n') if args.task in ['summarize']: (goldMap, predictionMap) = smooth_bleu.computeMaps(predictions, gold_fn) bleu = round(smooth_bleu.bleuFromMaps( goldMap, predictionMap)[0], 2) else: bleu = round(_bleu(gold_fn, output_fn), 2) if split_tag == 'test' and args.task in ['refine', 'translate', 'generate' , 'clone']: args.lang = get_lang_by_task(args.task, args.sub_task) codebleu = calc_code_bleu.get_codebleu( gold_fn, output_fn, args.lang,args=args) # except: # bleu = 0.0 # codebleu = 0.0 em = np.mean(dev_accs) * 100 result = {'em': em, 'bleu': bleu} if not args.task == 'summarize' and split_tag == 'test': result['codebleu'] = codebleu * 100 logger.info("***** Eval results *****") for key in sorted(result.keys()): logger.info(" %s = %s", key, str(round(result[key], 4))) return result def main(): parser = argparse.ArgumentParser() args = add_args(parser) t0 = time.time() set_dist(args) set_seed(args) set_hyperparas(args) logger.info(args) logger.info("************* args: *************") logger.info("args.model_name: "+str(args.model_name)) logger.info("args.few_shot: "+str(args.few_shot)) logger.info("args.task: "+str(args.task)) logger.info("args.sub_task: "+str(args.sub_task)) logger.info("*********************************") if args.task in ['summarize', 'translate', 'refine', 'generate','complete']: config, model, tokenizer = bulid_or_load_gen_model(args) elif args.task in ['defect','clone']: config, model, tokenizer = bulid_or_load_cls_model(args) model.to(args.device) if args.n_gpu > 1: model = torch.nn.DataParallel(model) pool = multiprocessing.Pool(args.cpu_count) args.train_filename, args.dev_filename, args.test_filename = get_filenames( args.data_dir, args.task, args.sub_task) fa = open(os.path.join(args.output_dir, 'summary.log'), 'a+',encoding='utf-8') if args.do_train: if args.local_rank in [-1, 0] and args.data_num == -1: summary_fn = '{}/{}'.format(args.summary_dir, '/'.join(args.output_dir.split('/')[1:])) tb_writer = SummaryWriter(summary_fn) # Prepare training data loader if args.task in ['summarize', 'translate', 'refine', 'generate','complete']: train_examples, train_data = load_and_cache_gen_data( args, args.train_filename, pool, tokenizer, 'train') elif args.task in ['defect']: train_examples, train_data = load_and_cache_defect_data(args, args.train_filename, pool, tokenizer, 'train') elif args.task in ['clone']:
train_examples, train_data = load_and_cache_clone_data(args, args.train_filename, pool, tokenizer, 'train')
10
2023-10-20 09:24:44+00:00
16k
JoaoPedro9674/django-ledger
django_ledger/io/io_mixin.py
[ { "identifier": "settings", "path": "django_ledger/settings.py", "snippet": " DJANGO_LEDGER_GRAPHQL_SUPPORT_ENABLED = True\n DJANGO_LEDGER_GRAPHQL_SUPPORT_ENABLED = False\n DJANGO_LEDGER_PDF_SUPPORT_ENABLED = True\n DJANGO_LEDGER_PDF_SUPPORT_ENABLED = False\nDJANGO_LEDGER_USE_CLOSING_ENTRIES...
from collections import defaultdict, namedtuple from datetime import datetime, date from itertools import groupby from pathlib import Path from random import choice from typing import List, Set, Union, Tuple, Optional, Dict from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.db.models import Sum, QuerySet from django.db.models.functions import TruncMonth from django.http import Http404 from django.utils.dateparse import parse_date, parse_datetime from django.utils.timezone import make_aware, is_naive, localtime from django.utils.translation import gettext_lazy as _ from django_ledger import settings from django_ledger.exceptions import InvalidDateInputError, TransactionNotInBalanceError from django_ledger.io import roles as roles_module from django_ledger.io.io_context import (RoleContextManager, GroupContextManager, ActivityContextManager, BalanceSheetStatementContextManager, IncomeStatementContextManager, CashFlowStatementContextManager) from django_ledger.io.io_digest import IODigestContextManager from django_ledger.io.ratios import FinancialRatioManager from django_ledger.models.utils import lazy_loader
13,645
""" Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement. Contributions to this module: * Miguel Sanda <msanda@arrobalytics.com> """ UserModel = get_user_model() def diff_tx_data(tx_data: list, raise_exception: bool = True): IS_TX_MODEL = False TransactionModel = lazy_loader.get_txs_model() if isinstance(tx_data[0], TransactionModel): CREDITS = sum(tx.amount for tx in tx_data if tx.tx_type == 'credit') DEBITS = sum(tx.amount for tx in tx_data if tx.tx_type == 'debit') IS_TX_MODEL = True elif isinstance(tx_data[0], dict): CREDITS = sum(tx['amount'] for tx in tx_data if tx['tx_type'] == 'credit') DEBITS = sum(tx['amount'] for tx in tx_data if tx['tx_type'] == 'debit') else: raise ValidationError('Only Dictionary or TransactionModel allowed.') is_valid = (CREDITS == DEBITS) diff = CREDITS - DEBITS
""" Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement. Contributions to this module: * Miguel Sanda <msanda@arrobalytics.com> """ UserModel = get_user_model() def diff_tx_data(tx_data: list, raise_exception: bool = True): IS_TX_MODEL = False TransactionModel = lazy_loader.get_txs_model() if isinstance(tx_data[0], TransactionModel): CREDITS = sum(tx.amount for tx in tx_data if tx.tx_type == 'credit') DEBITS = sum(tx.amount for tx in tx_data if tx.tx_type == 'debit') IS_TX_MODEL = True elif isinstance(tx_data[0], dict): CREDITS = sum(tx['amount'] for tx in tx_data if tx['tx_type'] == 'credit') DEBITS = sum(tx['amount'] for tx in tx_data if tx['tx_type'] == 'debit') else: raise ValidationError('Only Dictionary or TransactionModel allowed.') is_valid = (CREDITS == DEBITS) diff = CREDITS - DEBITS
if not is_valid and abs(diff) > settings.DJANGO_LEDGER_TRANSACTION_MAX_TOLERANCE:
0
2023-10-20 01:07:20+00:00
16k
hitz-zentroa/This-is-not-a-Dataset
run.py
[ { "identifier": "load_model", "path": "load_model.py", "snippet": "def load_model(\n inference: bool,\n model_weights_name_or_path: str,\n quantization: Optional[int] = None,\n use_lora: bool = False,\n lora_weights_name_or_path: Optional[str] = None,\n lora_target_modules: Optional[Li...
from load_model import load_model from dataset import get_dataloader from evaluate import evaluate from config import DataTrainingArguments, ModelArguments from transformers import ( HfArgumentParser, Seq2SeqTrainingArguments, set_seed, get_scheduler, ) from tqdm import tqdm from accelerate import Accelerator, find_executable_batch_size from typing import List from optimizer import get_optimizer from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from transformers.modeling_utils import unwrap_model import torch import os import wandb import gc import json import math import sys import logging
10,966
# Remove duplicated in last batch if we are in a distributed setting if step == len(dataloader) - 1: preds = preds[: (len(dataloader.dataset) - samples_seen)] else: samples_seen += len(batch) preds = tokenizer.batch_decode(preds, skip_special_tokens=True) # print(preds) for pred in preds: pred = pred.lower() if "true" in pred: all_preds.append(True) else: all_preds.append(False) if accelerator.is_local_main_process: with open(output_path, "w", encoding="utf8") as f: for pred in all_preds if not return_scores else all_scores: print(pred, file=f) if not return_scores: json_dataset = dataloader.dataset.get_jsonl() assert len(json_dataset) == len(all_preds) with open( os.path.splitext(output_path)[0] + ".jsonl", "w", encoding="utf8" ) as f: for json_line, pred in zip(json_dataset, all_preds): json_line["prediction"] = bool(pred) print(json.dumps(json_line, ensure_ascii=False), file=f) model.train() def main( model_args: ModelArguments, data_args: DataTrainingArguments, training_args: Seq2SeqTrainingArguments, ): assert ( training_args.do_train or training_args.do_predict ), "You must specify do_train or do_predict" assert not (training_args.do_train and data_args.do_predict_full_dataset), ( "You cannot do both training and predict_full_dataset, " "as the model will be evaluated on the full dataset, which" " includes the training set." ) logging.basicConfig(level=logging.INFO) accelerator = Accelerator() print(f"Accelerator State: {accelerator.state}") set_seed(training_args.seed) if training_args.do_train: model, tokenizer = load_model( inference=False, model_weights_name_or_path=model_args.model_name_or_path, lora_weights_name_or_path=model_args.lora_weights_name_or_path, quantization=model_args.quantization, use_lora=model_args.use_lora, lora_target_modules=model_args.lora_target_modules, torch_dtype=model_args.torch_dtype, force_auto_device_map=data_args.force_auto_device_map, use_flash_attention=model_args.use_flash_attention, use_gradient_checkpointing=model_args.use_lora, ) true_tokens_ids = tokenizer.encode("True", add_special_tokens=False) false_tokens_ids = tokenizer.encode("False", add_special_tokens=False) train_dataloader = get_dataloader( tokenizer=tokenizer, split="train", is_encoder_decoder=model.config.is_encoder_decoder, max_length=data_args.max_seq_length, conv_template=model_args.conversation_template, batch_size=training_args.per_device_train_batch_size, prompt_loss_weight=data_args.prompt_loss_weight, add_bos_token=model_args.add_bos_token, pattern=data_args.pattern, only_negative=data_args.only_negative, only_affirmative=data_args.only_affirmative, only_distractor=data_args.only_non_distractor, only_non_distractor=data_args.only_non_distractor, ) dev_dataloader = None if training_args.do_eval: dev_dataloader = get_dataloader( tokenizer=tokenizer, split="validation", is_encoder_decoder=model.config.is_encoder_decoder, max_length=data_args.max_seq_length, conv_template=model_args.conversation_template, batch_size=training_args.per_device_train_batch_size, prompt_loss_weight=data_args.prompt_loss_weight, add_bos_token=model_args.add_bos_token, pattern=data_args.pattern, only_negative=data_args.only_negative, only_affirmative=data_args.only_affirmative, only_distractor=data_args.only_non_distractor, only_non_distractor=data_args.only_non_distractor, ) if accelerator.is_main_process: wandb.init( project="ThisIsNotADataset", name=f"{os.path.basename(training_args.output_dir)}", config=vars(training_args), ) num_update_steps_per_epoch = math.ceil( len(train_dataloader) / training_args.gradient_accumulation_steps ) max_train_steps = int( training_args.num_train_epochs * num_update_steps_per_epoch )
def clean_cache(): """Clean cache to avoid memory leak. This fixes this issue: https://github.com/huggingface/transformers/issues/22801""" print(f"Cleaning GPU memory. Current memory usage: {torch.cuda.memory_allocated()}") torch.cuda.empty_cache() gc.collect() torch.cuda.empty_cache() print(f"GPU memory usage after cleaning: {torch.cuda.memory_allocated()}") def compute_loss(model, inputs, return_outputs=False): """ How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. """ if "labels" in inputs: labels = inputs.pop("labels") else: raise ValueError("You should supply a labels key to compute the loss") if "loss_weight_mask" in inputs: loss_weight_mask = inputs.pop("loss_weight_mask") else: raise ValueError("You should supply a loss_weight_mask key to compute the loss") if unwrap_model(model).config.is_encoder_decoder: outputs = model(labels=labels, **inputs) else: outputs = model(**inputs) logits = outputs["logits"] if isinstance(outputs, dict) else outputs[0] model_name = unwrap_model(model)._get_name() if ( model_name in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values() or model_name == "PeftModelForCausalLM" ): logits = logits[..., :-1, :].contiguous() labels = labels[..., 1:].contiguous() loss_weight_mask = loss_weight_mask[..., 1:].contiguous() logits = logits.view(-1, logits.size(-1)) labels = labels.view(-1) loss_weight_mask = loss_weight_mask.view(-1) loss_fct = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=-100) loss = loss_fct(logits, labels) loss = torch.sum(loss * loss_weight_mask) / torch.sum(loss_weight_mask) return (loss, outputs) if return_outputs else loss def gen_predictions( model, tokenizer, true_tokens_ids: List[int], false_tokens_ids: List[int], dataloader, output_path, accelerator, print_first=False, predict_with_generate=False, return_scores=False, ): if predict_with_generate and return_scores: raise ValueError( "return_scores is not supported when predict_with_generate is True" ) model.eval() with torch.no_grad(): samples_seen: int = 0 yes_id = true_tokens_ids[0] no_id = false_tokens_ids[0] all_preds = [] all_scores = [] first = True for step, batch in enumerate( tqdm(dataloader, f"Inference on {os.path.basename(output_path)}") ): if print_first and accelerator.is_local_main_process: ### DEBUG ### if print_first and first and accelerator.is_main_process: decodeable_inputs = batch.input_ids.clone() decodeable_inputs[ decodeable_inputs == -100 ] = tokenizer.pad_token_id model_inputs = "\n".join( tokenizer.batch_decode( decodeable_inputs, skip_special_tokens=False, clean_up_tokenization_spaces=False, ) ) print(f"*** Sample of batch 0 ***") print(f"-- Model inputs --\n{model_inputs}") print(f"*** End of sample ***\n") first = False if not predict_with_generate: if not model.config.is_encoder_decoder: logits = model( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], ).logits else: encoder_output = model.get_encoder()( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], ) decoder_args = { "attention_mask": batch["attention_mask"], "use_cache": False, "encoder_outputs": encoder_output, } gen_inputs = model.prepare_inputs_for_generation( input_ids=torch.tensor( [[tokenizer.pad_token_id]] * len(batch["input_ids"]) ).to(batch["input_ids"].device), **decoder_args, ) logits = model( **gen_inputs, ).logits logits = logits[:, -1, :] logits = torch.nn.functional.softmax(logits, dim=-1) logits = logits[:, [yes_id, no_id]] logits = logits[:, 0] / (logits[:, 0] + logits[:, 1]) preds = logits > 0.5 preds = accelerator.gather(preds).cpu().tolist() logits = accelerator.gather(logits).cpu().tolist() if accelerator.is_local_main_process: if accelerator.num_processes > 1: # Remove duplicated in last batch if we are in a distributed setting if step == len(dataloader) - 1: preds = preds[: (len(dataloader.dataset) - samples_seen)] logits = logits[: (len(dataloader.dataset) - samples_seen)] else: samples_seen += len(batch) all_preds.extend(preds) all_scores.extend(logits) else: preds = model.generate( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], max_new_tokens=6, ) preds = accelerator.gather( accelerator.pad_across_processes( preds, dim=1, pad_index=tokenizer.pad_token_id, ) ).cpu() inputs_ids = accelerator.gather( accelerator.pad_across_processes( batch["input_ids"], dim=1, pad_index=tokenizer.pad_token_id, ) ).cpu() preds = preds[:, len(inputs_ids[0]) :] if accelerator.is_local_main_process: if accelerator.num_processes > 1: # Remove duplicated in last batch if we are in a distributed setting if step == len(dataloader) - 1: preds = preds[: (len(dataloader.dataset) - samples_seen)] else: samples_seen += len(batch) preds = tokenizer.batch_decode(preds, skip_special_tokens=True) # print(preds) for pred in preds: pred = pred.lower() if "true" in pred: all_preds.append(True) else: all_preds.append(False) if accelerator.is_local_main_process: with open(output_path, "w", encoding="utf8") as f: for pred in all_preds if not return_scores else all_scores: print(pred, file=f) if not return_scores: json_dataset = dataloader.dataset.get_jsonl() assert len(json_dataset) == len(all_preds) with open( os.path.splitext(output_path)[0] + ".jsonl", "w", encoding="utf8" ) as f: for json_line, pred in zip(json_dataset, all_preds): json_line["prediction"] = bool(pred) print(json.dumps(json_line, ensure_ascii=False), file=f) model.train() def main( model_args: ModelArguments, data_args: DataTrainingArguments, training_args: Seq2SeqTrainingArguments, ): assert ( training_args.do_train or training_args.do_predict ), "You must specify do_train or do_predict" assert not (training_args.do_train and data_args.do_predict_full_dataset), ( "You cannot do both training and predict_full_dataset, " "as the model will be evaluated on the full dataset, which" " includes the training set." ) logging.basicConfig(level=logging.INFO) accelerator = Accelerator() print(f"Accelerator State: {accelerator.state}") set_seed(training_args.seed) if training_args.do_train: model, tokenizer = load_model( inference=False, model_weights_name_or_path=model_args.model_name_or_path, lora_weights_name_or_path=model_args.lora_weights_name_or_path, quantization=model_args.quantization, use_lora=model_args.use_lora, lora_target_modules=model_args.lora_target_modules, torch_dtype=model_args.torch_dtype, force_auto_device_map=data_args.force_auto_device_map, use_flash_attention=model_args.use_flash_attention, use_gradient_checkpointing=model_args.use_lora, ) true_tokens_ids = tokenizer.encode("True", add_special_tokens=False) false_tokens_ids = tokenizer.encode("False", add_special_tokens=False) train_dataloader = get_dataloader( tokenizer=tokenizer, split="train", is_encoder_decoder=model.config.is_encoder_decoder, max_length=data_args.max_seq_length, conv_template=model_args.conversation_template, batch_size=training_args.per_device_train_batch_size, prompt_loss_weight=data_args.prompt_loss_weight, add_bos_token=model_args.add_bos_token, pattern=data_args.pattern, only_negative=data_args.only_negative, only_affirmative=data_args.only_affirmative, only_distractor=data_args.only_non_distractor, only_non_distractor=data_args.only_non_distractor, ) dev_dataloader = None if training_args.do_eval: dev_dataloader = get_dataloader( tokenizer=tokenizer, split="validation", is_encoder_decoder=model.config.is_encoder_decoder, max_length=data_args.max_seq_length, conv_template=model_args.conversation_template, batch_size=training_args.per_device_train_batch_size, prompt_loss_weight=data_args.prompt_loss_weight, add_bos_token=model_args.add_bos_token, pattern=data_args.pattern, only_negative=data_args.only_negative, only_affirmative=data_args.only_affirmative, only_distractor=data_args.only_non_distractor, only_non_distractor=data_args.only_non_distractor, ) if accelerator.is_main_process: wandb.init( project="ThisIsNotADataset", name=f"{os.path.basename(training_args.output_dir)}", config=vars(training_args), ) num_update_steps_per_epoch = math.ceil( len(train_dataloader) / training_args.gradient_accumulation_steps ) max_train_steps = int( training_args.num_train_epochs * num_update_steps_per_epoch )
optimizer = get_optimizer(training_args=training_args, model=model)
5
2023-10-18 10:24:48+00:00
16k
Glasgow-AI4BioMed/GenKIE
tasks/pretrain_tasks/unify_task.py
[ { "identifier": "OFATask", "path": "tasks/ofa_task.py", "snippet": "class OFATask(FairseqTask):\n def __init__(self, cfg: OFAConfig, src_dict, tgt_dict):\n super().__init__(cfg)\n self.src_dict = src_dict\n self.tgt_dict = tgt_dict\n\n @classmethod\n def setup_task(cls, cfg...
from dataclasses import dataclass, field from typing import Optional from fairseq.tasks import register_task from fairseq.data import FairseqDataset, iterators from tasks.ofa_task import OFATask, OFAConfig from data.pretrain_data.unify_dataset import UnifyDataset from data.file_dataset import FileDataset import json import logging import os import math
11,519
# Copyright 2022 The OFA-Sys Team. # All rights reserved. # This source code is licensed under the Apache 2.0 license # found in the LICENSE file in the root directory. logger = logging.getLogger(__name__) @dataclass class UnifyConfig(OFAConfig): max_image_size: int = field( default=512, metadata={"help": ""} ) text_data: Optional[str] = field( default=None, metadata={"help": "pure text data"}, ) image_data: Optional[str] = field( default=None, metadata={"help": "pure image data"}, ) detection_data: Optional[str] = field( default=None, metadata={"help": "detection data"}, ) text_selected_cols: Optional[str] = field( default=None, metadata={"help": "pure text data selected cols"}, ) image_selected_cols: Optional[str] = field( default=None, metadata={"help": "pure image data selected cols"}, ) detection_selected_cols: Optional[str] = field( default=None, metadata={"help": "detection data selected cols"}, ) neg_sample_dir: Optional[str] = field( default=None, metadata={"help": "negative sample directory, which contains captions (taken from all image-text pairs), " "answers (taken from VQA), " "objects (taken form OpenImages) "}, ) code_image_size: int = field( default=128, metadata={"help": "the resolution of the generated image in the image infilling task"} ) pretrain_seed: int = field( default=7, metadata={"help": "pretrain seed"}, ) mask_ratio: float = field( default=0.3, metadata={"help": "fraction of words/subwords that will be masked"}, ) random_ratio: float = field( default=0.0, metadata={"help": "instead of using [MASK], use random token this often"}, ) keep_ratio: float = field( default=0.0, metadata={"help": "instead of using [MASK], keep original token this often"}, ) mask_length: str = field( default="span-poisson", metadata={"help": "mask length to choose ['subword', 'word', 'span-poisson']"}, ) poisson_lambda: float = field( default=3.0, metadata={"help": "randomly shuffle sentences for this proportion of inputs"}, ) replace_length: int = field( default=1, metadata={"help": "when masking N tokens, replace with 0, 1, or N tokens (use -1 for N)"}, ) @register_task("unify_task", dataclass=UnifyConfig) class UnifyTask(OFATask): def __init__(self, cfg: UnifyConfig, src_dict, tgt_dict): super().__init__(cfg, src_dict, tgt_dict) self.type2ans_dict = json.load(open(os.path.join(self.cfg.neg_sample_dir, 'type2ans.json'))) self.ans2type_dict = {} for type, answer_list in self.type2ans_dict.items(): if type == 'other': continue for answer in answer_list: self.ans2type_dict[answer] = type self.all_object_list = [ row.strip() for row in open(os.path.join(self.cfg.neg_sample_dir, 'object.txt')) if row.strip() != '' ] self.all_caption_list = [ row.strip() for row in open(os.path.join(self.cfg.neg_sample_dir, 'all_captions.txt')) if row.strip() != '' ] self.pure_text_dataset = None self.pure_image_dataset = None self.detection_dataset = None if self.cfg.text_data is not None: self.pure_text_dataset = FileDataset(self.cfg.text_data, self.cfg.text_selected_cols) if self.cfg.image_data is not None: self.pure_image_dataset = FileDataset(self.cfg.image_data, self.cfg.image_selected_cols) if self.cfg.detection_data is not None: self.detection_dataset = FileDataset(self.cfg.detection_data, self.cfg.detection_selected_cols) def load_dataset(self, split, epoch=1, combine=False, **kwargs): paths = self.cfg.data.split(',') assert len(paths) > 0 file_path = paths[(epoch - 1) % (len(paths))] dataset = FileDataset(file_path, self.cfg.selected_cols)
# Copyright 2022 The OFA-Sys Team. # All rights reserved. # This source code is licensed under the Apache 2.0 license # found in the LICENSE file in the root directory. logger = logging.getLogger(__name__) @dataclass class UnifyConfig(OFAConfig): max_image_size: int = field( default=512, metadata={"help": ""} ) text_data: Optional[str] = field( default=None, metadata={"help": "pure text data"}, ) image_data: Optional[str] = field( default=None, metadata={"help": "pure image data"}, ) detection_data: Optional[str] = field( default=None, metadata={"help": "detection data"}, ) text_selected_cols: Optional[str] = field( default=None, metadata={"help": "pure text data selected cols"}, ) image_selected_cols: Optional[str] = field( default=None, metadata={"help": "pure image data selected cols"}, ) detection_selected_cols: Optional[str] = field( default=None, metadata={"help": "detection data selected cols"}, ) neg_sample_dir: Optional[str] = field( default=None, metadata={"help": "negative sample directory, which contains captions (taken from all image-text pairs), " "answers (taken from VQA), " "objects (taken form OpenImages) "}, ) code_image_size: int = field( default=128, metadata={"help": "the resolution of the generated image in the image infilling task"} ) pretrain_seed: int = field( default=7, metadata={"help": "pretrain seed"}, ) mask_ratio: float = field( default=0.3, metadata={"help": "fraction of words/subwords that will be masked"}, ) random_ratio: float = field( default=0.0, metadata={"help": "instead of using [MASK], use random token this often"}, ) keep_ratio: float = field( default=0.0, metadata={"help": "instead of using [MASK], keep original token this often"}, ) mask_length: str = field( default="span-poisson", metadata={"help": "mask length to choose ['subword', 'word', 'span-poisson']"}, ) poisson_lambda: float = field( default=3.0, metadata={"help": "randomly shuffle sentences for this proportion of inputs"}, ) replace_length: int = field( default=1, metadata={"help": "when masking N tokens, replace with 0, 1, or N tokens (use -1 for N)"}, ) @register_task("unify_task", dataclass=UnifyConfig) class UnifyTask(OFATask): def __init__(self, cfg: UnifyConfig, src_dict, tgt_dict): super().__init__(cfg, src_dict, tgt_dict) self.type2ans_dict = json.load(open(os.path.join(self.cfg.neg_sample_dir, 'type2ans.json'))) self.ans2type_dict = {} for type, answer_list in self.type2ans_dict.items(): if type == 'other': continue for answer in answer_list: self.ans2type_dict[answer] = type self.all_object_list = [ row.strip() for row in open(os.path.join(self.cfg.neg_sample_dir, 'object.txt')) if row.strip() != '' ] self.all_caption_list = [ row.strip() for row in open(os.path.join(self.cfg.neg_sample_dir, 'all_captions.txt')) if row.strip() != '' ] self.pure_text_dataset = None self.pure_image_dataset = None self.detection_dataset = None if self.cfg.text_data is not None: self.pure_text_dataset = FileDataset(self.cfg.text_data, self.cfg.text_selected_cols) if self.cfg.image_data is not None: self.pure_image_dataset = FileDataset(self.cfg.image_data, self.cfg.image_selected_cols) if self.cfg.detection_data is not None: self.detection_dataset = FileDataset(self.cfg.detection_data, self.cfg.detection_selected_cols) def load_dataset(self, split, epoch=1, combine=False, **kwargs): paths = self.cfg.data.split(',') assert len(paths) > 0 file_path = paths[(epoch - 1) % (len(paths))] dataset = FileDataset(file_path, self.cfg.selected_cols)
self.datasets[split] = UnifyDataset(
2
2023-10-20 20:01:42+00:00
16k