id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
19,876 | import re
from typing import Set
from prompt_toolkit import prompt
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.key_binding import KeyBindings
def create_completer(commands: list, pattern_str: str = "$") -> WordCompleter:
return WordCompleter(words=commands, pattern=re.compile(pattern_str)) | null |
19,877 | import re
from typing import Set
from prompt_toolkit import prompt
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.key_binding import KeyBindings
The provided code snippet includes necessary dependencies for implementing the `get_input` function. Write a Python function `def get_input( session: PromptSession = None, completer: WordCompleter = None, key_bindings: KeyBindings = None, ) -> str` to solve the following problem:
Multiline input function.
Here is the function:
def get_input(
session: PromptSession = None,
completer: WordCompleter = None,
key_bindings: KeyBindings = None,
) -> str:
"""
Multiline input function.
"""
return (
session.prompt(
completer=completer,
multiline=True,
auto_suggest=AutoSuggestFromHistory(),
key_bindings=key_bindings,
)
if session
else prompt(multiline=True)
) | Multiline input function. |
19,878 | import re
from typing import Set
from prompt_toolkit import prompt
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.key_binding import KeyBindings
The provided code snippet includes necessary dependencies for implementing the `get_input_async` function. Write a Python function `async def get_input_async( session: PromptSession = None, completer: WordCompleter = None, ) -> str` to solve the following problem:
Multiline input function.
Here is the function:
async def get_input_async(
session: PromptSession = None,
completer: WordCompleter = None,
) -> str:
"""
Multiline input function.
"""
return (
await session.prompt_async(
completer=completer,
multiline=True,
auto_suggest=AutoSuggestFromHistory(),
)
if session
else prompt(multiline=True)
) | Multiline input function. |
19,879 | import re
from typing import Set
from prompt_toolkit import prompt
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.key_binding import KeyBindings
The provided code snippet includes necessary dependencies for implementing the `get_filtered_keys_from_object` function. Write a Python function `def get_filtered_keys_from_object(obj: object, *keys: str) -> Set[str]` to solve the following problem:
Get filtered list of object variable names. :param keys: List of keys to include. If the first key is "not", the remaining keys will be removed from the class keys. :return: List of class keys.
Here is the function:
def get_filtered_keys_from_object(obj: object, *keys: str) -> Set[str]:
"""
Get filtered list of object variable names.
:param keys: List of keys to include. If the first key is "not", the remaining keys will be removed from the class keys.
:return: List of class keys.
"""
class_keys = obj.__dict__.keys()
if not keys:
return set(class_keys)
# Remove the passed keys from the class keys.
if keys[0] == "not":
return {key for key in class_keys if key not in keys[1:]}
# Check if all passed keys are valid
if invalid_keys := set(keys) - class_keys:
raise ValueError(
f"Invalid keys: {invalid_keys}",
)
# Only return specified keys that are in class_keys
return {key for key in keys if key in class_keys} | Get filtered list of object variable names. :param keys: List of keys to include. If the first key is "not", the remaining keys will be removed from the class keys. :return: List of class keys. |
19,880 | from __future__ import annotations
import base64
import binascii
import contextlib
import json
import logging
import secrets
import subprocess
import sys
import time
import uuid
from functools import wraps
from os import environ
from os import getenv
from pathlib import Path
from typing import AsyncGenerator
from typing import Generator
from typing import NoReturn
import tempfile
import random
from typing import Callable as function
import httpx
import requests
from httpx import AsyncClient
from OpenAIAuth import Auth0 as Authenticator
from rich.live import Live
from rich.markdown import Markdown
from . import __version__
from . import typings as t
from .utils import create_completer
from .utils import create_session
from .utils import get_input
The provided code snippet includes necessary dependencies for implementing the `generate_random_hex` function. Write a Python function `def generate_random_hex(length: int = 17) -> str` to solve the following problem:
Generate a random hex string Args: length (int, optional): Length of the hex string. Defaults to 17. Returns: str: Random hex string
Here is the function:
def generate_random_hex(length: int = 17) -> str:
"""Generate a random hex string
Args:
length (int, optional): Length of the hex string. Defaults to 17.
Returns:
str: Random hex string
"""
return secrets.token_hex(length) | Generate a random hex string Args: length (int, optional): Length of the hex string. Defaults to 17. Returns: str: Random hex string |
19,881 | from __future__ import annotations
import base64
import binascii
import contextlib
import json
import logging
import secrets
import subprocess
import sys
import time
import uuid
from functools import wraps
from os import environ
from os import getenv
from pathlib import Path
from typing import AsyncGenerator
from typing import Generator
from typing import NoReturn
import tempfile
import random
from typing import Callable as function
import httpx
import requests
from httpx import AsyncClient
from OpenAIAuth import Auth0 as Authenticator
from rich.live import Live
from rich.markdown import Markdown
from . import __version__
from . import typings as t
from .utils import create_completer
from .utils import create_session
from .utils import get_input
The provided code snippet includes necessary dependencies for implementing the `random_int` function. Write a Python function `def random_int(min: int, max: int) -> int` to solve the following problem:
Generate a random integer Args: min (int): Minimum value max (int): Maximum value Returns: int: Random integer
Here is the function:
def random_int(min: int, max: int) -> int:
"""Generate a random integer
Args:
min (int): Minimum value
max (int): Maximum value
Returns:
int: Random integer
"""
return secrets.randbelow(max - min) + min | Generate a random integer Args: min (int): Minimum value max (int): Maximum value Returns: int: Random integer |
19,882 | from __future__ import annotations
import base64
import binascii
import contextlib
import json
import logging
import secrets
import subprocess
import sys
import time
import uuid
from functools import wraps
from os import environ
from os import getenv
from pathlib import Path
from typing import AsyncGenerator
from typing import Generator
from typing import NoReturn
import tempfile
import random
from typing import Callable as function
import httpx
import requests
from httpx import AsyncClient
from OpenAIAuth import Auth0 as Authenticator
from rich.live import Live
from rich.markdown import Markdown
from . import __version__
from . import typings as t
from .utils import create_completer
from .utils import create_session
from .utils import get_input
The provided code snippet includes necessary dependencies for implementing the `logger` function. Write a Python function `def logger(is_timed: bool) -> function` to solve the following problem:
Logger decorator Args: is_timed (bool): Whether to include function running time in exit log Returns: _type_: decorated function
Here is the function:
def logger(is_timed: bool) -> function:
"""Logger decorator
Args:
is_timed (bool): Whether to include function running time in exit log
Returns:
_type_: decorated function
"""
def decorator(func: function) -> function:
wraps(func)
def wrapper(*args, **kwargs):
log.debug(
"Entering %s with args %s and kwargs %s",
func.__name__,
args,
kwargs,
)
start = time.time()
out = func(*args, **kwargs)
end = time.time()
if is_timed:
log.debug(
"Exiting %s with return value %s. Took %s seconds.",
func.__name__,
out,
end - start,
)
else:
log.debug("Exiting %s with return value %s", func.__name__, out)
return out
return wrapper
return decorator | Logger decorator Args: is_timed (bool): Whether to include function running time in exit log Returns: _type_: decorated function |
19,883 | from __future__ import annotations
import base64
import binascii
import contextlib
import json
import logging
import secrets
import subprocess
import sys
import time
import uuid
from functools import wraps
from os import environ
from os import getenv
from pathlib import Path
from typing import AsyncGenerator
from typing import Generator
from typing import NoReturn
import tempfile
import random
from typing import Callable as function
import httpx
import requests
from httpx import AsyncClient
from OpenAIAuth import Auth0 as Authenticator
from rich.live import Live
from rich.markdown import Markdown
from . import __version__
from . import typings as t
from .utils import create_completer
from .utils import create_session
from .utils import get_input
The provided code snippet includes necessary dependencies for implementing the `get_arkose_token` function. Write a Python function `def get_arkose_token( download_images: bool = True, solver: function = captcha_solver, captcha_supported: bool = True, ) -> str` to solve the following problem:
The solver function should take in a list of images in base64 and a dict of challenge details and return the index of the image that matches the challenge details Challenge details: game_type: str - Audio or Image instructions: str - Instructions for the captcha URLs: list[str] - URLs of the images or audio files
Here is the function:
def get_arkose_token(
download_images: bool = True,
solver: function = captcha_solver,
captcha_supported: bool = True,
) -> str:
"""
The solver function should take in a list of images in base64 and a dict of challenge details
and return the index of the image that matches the challenge details
Challenge details:
game_type: str - Audio or Image
instructions: str - Instructions for the captcha
URLs: list[str] - URLs of the images or audio files
"""
if captcha_supported:
resp = requests.get(
(CAPTCHA_URL + "start?download_images=true")
if download_images
else CAPTCHA_URL + "start",
)
resp_json: dict = resp.json()
if resp.status_code == 200:
return resp_json.get("token")
if resp.status_code != 511:
raise Exception(resp_json.get("error", "Unknown error"))
if resp_json.get("status") != "captcha":
raise Exception("unknown error")
challenge_details: dict = resp_json.get("session", {}).get("concise_challenge")
if not challenge_details:
raise Exception("missing details")
images: list[str] = resp_json.get("images")
index = solver(images, challenge_details)
resp = requests.post(
CAPTCHA_URL + "verify",
json={"session": resp_json.get("session"), "index": index},
)
if resp.status_code != 200:
raise Exception("Failed to verify captcha")
return resp_json.get("token")
working_endpoints: list[str] = []
# Check uptime for different endpoints via gatus
resp2: list[dict] = requests.get(
"https://stats.churchless.tech/api/v1/endpoints/statuses?page=1",
).json()
for endpoint in resp2:
# print(endpoint.get("name"))
if endpoint.get("group") != "Arkose Labs":
continue
# Check the last 5 results
results: list[dict] = endpoint.get("results", [])[-5:-1]
# print(results)
if not results:
print(f"Endpoint {endpoint.get('name')} has no results")
continue
# Check if all the results are up
if all(result.get("success") is True for result in results):
working_endpoints.append(endpoint.get("name"))
if not working_endpoints:
print("No working endpoints found. Please solve the captcha manually.")
return get_arkose_token(download_images=True, captcha_supported=True)
# Choose a random endpoint
endpoint = random.choice(working_endpoints)
resp: requests.Response = requests.get(endpoint)
if resp.status_code != 200:
if resp.status_code != 511:
raise Exception("Failed to get captcha token")
print("Captcha required. Please solve the captcha manually.")
return get_arkose_token(download_images=True, captcha_supported=True)
try:
return resp.json().get("token")
except Exception:
return resp.text | The solver function should take in a list of images in base64 and a dict of challenge details and return the index of the image that matches the challenge details Challenge details: game_type: str - Audio or Image instructions: str - Instructions for the captcha URLs: list[str] - URLs of the images or audio files |
19,884 | from __future__ import annotations
import base64
import binascii
import contextlib
import json
import logging
import secrets
import subprocess
import sys
import time
import uuid
from functools import wraps
from os import environ
from os import getenv
from pathlib import Path
from typing import AsyncGenerator
from typing import Generator
from typing import NoReturn
import tempfile
import random
from typing import Callable as function
import httpx
import requests
from httpx import AsyncClient
from OpenAIAuth import Auth0 as Authenticator
from rich.live import Live
from rich.markdown import Markdown
from . import __version__
from . import typings as t
from .utils import create_completer
from .utils import create_session
from .utils import get_input
The provided code snippet includes necessary dependencies for implementing the `configure` function. Write a Python function `def configure() -> dict` to solve the following problem:
Looks for a config file in the following locations:
Here is the function:
def configure() -> dict:
"""
Looks for a config file in the following locations:
"""
config_files: list[Path] = [Path("config.json")]
if xdg_config_home := getenv("XDG_CONFIG_HOME"):
config_files.append(Path(xdg_config_home, "revChatGPT/config.json"))
if user_home := getenv("HOME"):
config_files.append(Path(user_home, ".config/revChatGPT/config.json"))
if windows_home := getenv("HOMEPATH"):
config_files.append(Path(f"{windows_home}/.config/revChatGPT/config.json"))
if config_file := next((f for f in config_files if f.exists()), None):
with open(config_file, encoding="utf-8") as f:
config = json.load(f)
else:
print("No config file found.")
raise FileNotFoundError("No config file found.")
return config | Looks for a config file in the following locations: |
19,885 | import datetime
import sphinx_rtd_theme
import doctest
import karateclub
import community
def setup(app):
def skip(app, what, name, obj, skip, options):
members = [
'__init__',
'__repr__',
'__weakref__',
'__dict__',
'__module__',
]
return True if name in members else skip
app.connect('autodoc-skip-member', skip) | null |
19,886 | import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from sklearn.decomposition import PCA
from karateclub.node_embedding.structural import SINr
The provided code snippet includes necessary dependencies for implementing the `embed_and_plot` function. Write a Python function `def embed_and_plot(graph: nx.Graph, gamma: int, ax: Axes)` to solve the following problem:
Embed the graph using SINr and plot the 2D PCA projection. Args: graph (nx.Graph): The graph to embed. gamma (int): The modularity multi-resolution parameter. ax (Axes): The matplotlib axis to plot the graph on.
Here is the function:
def embed_and_plot(graph: nx.Graph, gamma: int, ax: Axes):
"""Embed the graph using SINr and plot the 2D PCA projection.
Args:
graph (nx.Graph): The graph to embed.
gamma (int): The modularity multi-resolution parameter.
ax (Axes): The matplotlib axis to plot the graph on.
"""
model = SINr(gamma=gamma)
model.fit(graph)
embedding = model.get_embedding()
pca_embedding = PCA(n_components=2).fit_transform(embedding)
ax.scatter(pca_embedding[:, 0], pca_embedding[:, 1])
for idx, x in enumerate(pca_embedding):
ax.annotate(idx, (x[0], x[1])) | Embed the graph using SINr and plot the 2D PCA projection. Args: graph (nx.Graph): The graph to embed. gamma (int): The modularity multi-resolution parameter. ax (Axes): The matplotlib axis to plot the graph on. |
19,887 | import math
from functools import partial
from typing import List, Callable
import numpy as np
import networkx as nx
import scipy.sparse as sparse
from karateclub.estimator import Estimator
def _weighted_directed_degree(node: int, graph: nx.classes.graph.Graph) -> float:
out = graph.degree(node, weight="weight")
return out
def _unweighted_undirected_degree(node: int, graph: nx.classes.graph.Graph) -> float:
out = graph.degree[node]
return float(out)
The provided code snippet includes necessary dependencies for implementing the `_get_degree_fn` function. Write a Python function `def _get_degree_fn(graph) -> Callable` to solve the following problem:
Gets the function to calculate the graph node degree
Here is the function:
def _get_degree_fn(graph) -> Callable:
"""Gets the function to calculate the graph node degree"""
fn = (
_weighted_directed_degree
if nx.classes.function.is_weighted(graph)
else _unweighted_undirected_degree
)
fn = partial(fn, graph=graph)
return fn | Gets the function to calculate the graph node degree |
19,888 | import random
from functools import partial
from typing import List, Callable
import numpy as np
import networkx as nx
def _check_value(value, name):
try:
_ = 1 / value
except ZeroDivisionError:
raise ValueError(
f"The value of {name} is too small " f"or zero to be used in 1/{name}."
) | null |
19,889 | import random
from functools import partial
from typing import List, Callable
import numpy as np
import networkx as nx
def _undirected(node, graph) -> List[tuple]:
def _directed(node, graph) -> List[tuple]:
def _get_edge_fn(graph) -> Callable:
fn = _directed if nx.classes.function.is_directed(graph) else _undirected
fn = partial(fn, graph=graph)
return fn | null |
19,890 | import random
from functools import partial
from typing import List, Callable
import numpy as np
import networkx as nx
def _unweighted(edges: List[tuple]) -> np.ndarray:
return np.ones(len(edges))
def _weighted(edges: List[tuple]) -> np.ndarray:
weights = map(lambda edge: edge[-1]["weight"], edges)
return np.array([*weights])
def _get_weight_fn(graph) -> Callable:
fn = _weighted if nx.classes.function.is_weighted(graph) else _unweighted
return fn | null |
19,891 | import argparse
import torch
import re
import time
import gradio as gr
from moondream import detect_device, LATEST_REVISION
from threading import Thread
from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM
def img_change(img):
global latest_img
latest_img = img | null |
19,892 | import argparse
import torch
import re
import time
import gradio as gr
from moondream import detect_device, LATEST_REVISION
from threading import Thread
from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM
def prompt_change(prompt):
global latest_prompt
latest_prompt = prompt | null |
19,893 | import argparse
import torch
import re
import time
import gradio as gr
from moondream import detect_device, LATEST_REVISION
from threading import Thread
from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM
def answer_question(img, prompt):
def live_video():
while True:
if latest_img is None:
time.sleep(0.1)
else:
for text in answer_question(latest_img, latest_prompt):
if len(text) > 0:
yield text | null |
19,894 | import torch
The provided code snippet includes necessary dependencies for implementing the `detect_device` function. Write a Python function `def detect_device()` to solve the following problem:
Detects the appropriate device to run on, and return the device and dtype.
Here is the function:
def detect_device():
"""
Detects the appropriate device to run on, and return the device and dtype.
"""
if torch.cuda.is_available():
return torch.device("cuda"), torch.float16
elif torch.backends.mps.is_available():
return torch.device("mps"), torch.float16
else:
return torch.device("cpu"), torch.float32 | Detects the appropriate device to run on, and return the device and dtype. |
19,895 | import math
from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
SequenceClassifierOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import (
is_flash_attn_2_available,
is_flash_attn_greater_or_equal_2_10,
logging,
)
from .configuration_moondream import PhiConfig
def _get_unpad_data(attention_mask):
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
max_seqlen_in_batch = seqlens_in_batch.max().item()
cu_seqlens = F.pad(
torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
)
return (
indices,
cu_seqlens,
max_seqlen_in_batch,
) | null |
19,896 | import math
from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
SequenceClassifierOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import (
is_flash_attn_2_available,
is_flash_attn_greater_or_equal_2_10,
logging,
)
from .configuration_moondream import PhiConfig
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
The provided code snippet includes necessary dependencies for implementing the `apply_rotary_pos_emb` function. Write a Python function `def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1)` to solve the following problem:
Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
Here is the function:
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`):
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
used to pass offsetted position ids when working with a KV-cache.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed | Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. |
19,897 | import math
from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
SequenceClassifierOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import (
is_flash_attn_2_available,
is_flash_attn_greater_or_equal_2_10,
logging,
)
from .configuration_moondream import PhiConfig
The provided code snippet includes necessary dependencies for implementing the `repeat_kv` function. Write a Python function `def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor` to solve the following problem:
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
Here is the function:
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(
batch, num_key_value_heads, n_rep, slen, head_dim
)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) | This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) |
19,898 | import argparse
import torch
import re
import gradio as gr
from moondream import detect_device, LATEST_REVISION
from threading import Thread
from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=LATEST_REVISION)
moondream = AutoModelForCausalLM.from_pretrained(
model_id, trust_remote_code=True, revision=LATEST_REVISION
).to(device=device, dtype=dtype)
moondream.eval()
def answer_question(img, prompt):
image_embeds = moondream.encode_image(img)
streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
thread = Thread(
target=moondream.answer_question,
kwargs={
"image_embeds": image_embeds,
"question": prompt,
"tokenizer": tokenizer,
"streamer": streamer,
},
)
thread.start()
buffer = ""
for new_text in streamer:
clean_text = re.sub("<$|<END$", "", new_text)
buffer += clean_text
yield buffer | null |
19,899 | from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from . import vgg19_loss as vgg19
import gin.tf
import numpy as np
import tensorflow as tf
def create_losses(
loss_names: List[str], loss_weight_schedules: List[
tf.keras.optimizers.schedules.LearningRateSchedule]
) -> Dict[str, Tuple[Callable[[Any, Any], tf.Tensor], Callable[[Any],
tf.Tensor]]]:
"""Returns a dictionary of functions for creating loss and loss_weight ops.
As an example, create_losses(['l1', 'l2'], [PiecewiseConstantDecay(),
PiecewiseConstantDecay()]) returns a dictionary with two keys, and each value
being a tuple of ops for loss calculation and loss_weight sampling.
Args:
loss_names: Names of the losses.
loss_weight_schedules: Instances of loss weight schedules.
Returns:
A dictionary that contains the loss and weight schedule ops keyed by the
names.
"""
losses = dict()
for name, weight_schedule in zip(loss_names, loss_weight_schedules):
unique_values = np.unique(weight_schedule.values)
if len(unique_values) == 1 and unique_values[0] == 1.0:
# Special case 'no weight' for prettier TensorBoard summaries.
weighted_name = name
else:
# Weights are variable/scheduled, a constant "k" is used to
# indicate weights are iteration dependent.
weighted_name = 'k*' + name
losses[weighted_name] = (get_loss_op(name), get_weight_op(weight_schedule))
return losses
The provided code snippet includes necessary dependencies for implementing the `training_losses` function. Write a Python function `def training_losses( loss_names: List[str], loss_weights: Optional[List[float]] = None, loss_weight_schedules: Optional[List[ tf.keras.optimizers.schedules.LearningRateSchedule]] = None, loss_weight_parameters: Optional[List[Mapping[str, List[Any]]]] = None ) -> Mapping[str, Tuple[Callable[[Any, Any], tf.Tensor], Callable[[Any], tf.Tensor]]]` to solve the following problem:
Creates the training loss functions and loss weight schedules.
Here is the function:
def training_losses(
loss_names: List[str],
loss_weights: Optional[List[float]] = None,
loss_weight_schedules: Optional[List[
tf.keras.optimizers.schedules.LearningRateSchedule]] = None,
loss_weight_parameters: Optional[List[Mapping[str, List[Any]]]] = None
) -> Mapping[str, Tuple[Callable[[Any, Any], tf.Tensor], Callable[[Any],
tf.Tensor]]]:
"""Creates the training loss functions and loss weight schedules."""
weight_schedules = []
if not loss_weights:
for weight_schedule, weight_parameters in zip(loss_weight_schedules,
loss_weight_parameters):
weight_schedules.append(weight_schedule(**weight_parameters))
else:
for loss_weight in loss_weights:
weight_parameters = {
'boundaries': [0],
'values': 2 * [
loss_weight,
]
}
weight_schedules.append(
tf.keras.optimizers.schedules.PiecewiseConstantDecay(
**weight_parameters))
return create_losses(loss_names, weight_schedules) | Creates the training loss functions and loss weight schedules. |
19,900 | from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from . import vgg19_loss as vgg19
import gin.tf
import numpy as np
import tensorflow as tf
The provided code snippet includes necessary dependencies for implementing the `aggregate_batch_losses` function. Write a Python function `def aggregate_batch_losses( batch_losses: List[Mapping[str, float]]) -> Mapping[str, float]` to solve the following problem:
Averages per batch losses into single dictionary for the whole epoch. As an example, if the batch_losses contained per batch losses: batch_losses = { {'l1': 0.2, 'ssim': 0.9}, {'l1': 0.3, 'ssim': 0.8}} The returned dictionary would look like: { 'l1': 0.25, 'ssim': 0.95 } Args: batch_losses: A list of dictionary objects, with one entry for each loss. Returns: Single dictionary with the losses aggregated.
Here is the function:
def aggregate_batch_losses(
batch_losses: List[Mapping[str, float]]) -> Mapping[str, float]:
"""Averages per batch losses into single dictionary for the whole epoch.
As an example, if the batch_losses contained per batch losses:
batch_losses = { {'l1': 0.2, 'ssim': 0.9}, {'l1': 0.3, 'ssim': 0.8}}
The returned dictionary would look like: { 'l1': 0.25, 'ssim': 0.95 }
Args:
batch_losses: A list of dictionary objects, with one entry for each loss.
Returns:
Single dictionary with the losses aggregated.
"""
transp_losses = {}
# Loop through all losses
for batch_loss in batch_losses:
# Loop through per batch losses of a single type:
for loss_name, loss in batch_loss.items():
if loss_name not in transp_losses:
transp_losses[loss_name] = []
transp_losses[loss_name].append(loss)
aggregate_losses = {}
for loss_name in transp_losses:
aggregate_losses[loss_name] = np.mean(transp_losses[loss_name])
return aggregate_losses | Averages per batch losses into single dictionary for the whole epoch. As an example, if the batch_losses contained per batch losses: batch_losses = { {'l1': 0.2, 'ssim': 0.9}, {'l1': 0.3, 'ssim': 0.8}} The returned dictionary would look like: { 'l1': 0.25, 'ssim': 0.95 } Args: batch_losses: A list of dictionary objects, with one entry for each loss. Returns: Single dictionary with the losses aggregated. |
19,901 | from typing import Callable, Dict, Text
from ..losses import losses
import tensorflow as tf
class TrainLossMetric(tf.keras.metrics.Metric):
"""Compute training loss for our example and prediction format.
The purpose of this is to ensure that we always include a loss that is exactly
like the training loss into the evaluation in order to detect possible
overfitting.
"""
def __init__(self, name='eval_loss', **kwargs):
super(TrainLossMetric, self).__init__(name=name, **kwargs)
self.acc = self.add_weight(name='train_metric_acc', initializer='zeros')
self.count = self.add_weight(name='train_metric_count', initializer='zeros')
def update_state(self,
batch,
predictions,
sample_weight=None,
checkpoint_step=0):
loss_functions = losses.training_losses()
loss_list = []
for (loss_value, loss_weight) in loss_functions.values():
loss_list.append(
loss_value(batch, predictions) * loss_weight(checkpoint_step))
loss = tf.add_n(loss_list)
self.acc.assign_add(loss)
self.count.assign_add(1)
def result(self):
return self.acc / self.count
def reset_states(self):
self.acc.assign(0)
self.count.assign(0)
class L1Metric(tf.keras.metrics.Metric):
"""Compute L1 over our training example and prediction format.
The purpose of this is to ensure that we have at least one metric that is
compatible across all eval the session and allows us to quickly compare models
against each other.
"""
def __init__(self, name='eval_loss', **kwargs):
super(L1Metric, self).__init__(name=name, **kwargs)
self.acc = self.add_weight(name='l1_metric_acc', initializer='zeros')
self.count = self.add_weight(name='l1_metric_count', initializer='zeros')
def update_state(self, batch, prediction, sample_weight=None,
checkpoint_step=0):
self.acc.assign_add(losses.l1_loss(batch, prediction))
self.count.assign_add(1)
def result(self):
return self.acc / self.count
def reset_states(self):
self.acc.assign(0)
self.count.assign(0)
class GenericLossMetric(tf.keras.metrics.Metric):
"""Metric based on any loss function."""
def __init__(self, name: str, loss: Callable[..., tf.Tensor],
weight: Callable[..., tf.Tensor], **kwargs):
"""Initializes a metric based on a loss function and a weight schedule.
Args:
name: The name of the metric.
loss: The callable loss that calculates a loss value for a (prediction,
target) pair.
weight: The callable weight scheduling function that samples a weight
based on iteration.
**kwargs: Any additional keyword arguments to be passed.
"""
super(GenericLossMetric, self).__init__(name=name, **kwargs)
self.acc = self.add_weight(name='loss_metric_acc', initializer='zeros')
self.count = self.add_weight(name='loss_metric_count', initializer='zeros')
self.loss = loss
self.weight = weight
def update_state(self,
batch,
predictions,
sample_weight=None,
checkpoint_step=0):
self.acc.assign_add(
self.loss(batch, predictions) * self.weight(checkpoint_step))
self.count.assign_add(1)
def result(self):
return self.acc / self.count
def reset_states(self):
self.acc.assign(0)
self.count.assign(0)
The provided code snippet includes necessary dependencies for implementing the `create_metrics_fn` function. Write a Python function `def create_metrics_fn() -> Dict[Text, tf.keras.metrics.Metric]` to solve the following problem:
Create evaluation metrics. L1 and total training loss are added by default. The rest are the configured by the test_losses item via gin. Returns: A dictionary from metric name to Keras Metric object.
Here is the function:
def create_metrics_fn() -> Dict[Text, tf.keras.metrics.Metric]:
"""Create evaluation metrics.
L1 and total training loss are added by default.
The rest are the configured by the test_losses item via gin.
Returns:
A dictionary from metric name to Keras Metric object.
"""
metrics = {}
# L1 is explicitly added just so we always have some consistent numbers around
# to compare across sessions.
metrics['l1'] = L1Metric()
# We also always include training loss for the eval set to detect overfitting:
metrics['training_loss'] = TrainLossMetric()
test_losses = losses.test_losses()
for loss_name, (loss_value, loss_weight) in test_losses.items():
metrics[loss_name] = GenericLossMetric(
name=loss_name, loss=loss_value, weight=loss_weight)
return metrics | Create evaluation metrics. L1 and total training loss are added by default. The rest are the configured by the test_losses item via gin. Returns: A dictionary from metric name to Keras Metric object. |
19,902 | import os
from typing import Sequence
from . import model_lib
from absl import app
from absl import flags
from absl import logging
import gin.tf
import tensorflow as tf
tf.get_logger().setLevel('ERROR')
The provided code snippet includes necessary dependencies for implementing the `_build_saved_model` function. Write a Python function `def _build_saved_model(checkpoint_path: str, config_files: Sequence[str], output_model_path: str)` to solve the following problem:
Builds a saved model based on the checkpoint directory.
Here is the function:
def _build_saved_model(checkpoint_path: str, config_files: Sequence[str],
output_model_path: str):
"""Builds a saved model based on the checkpoint directory."""
gin.parse_config_files_and_bindings(
config_files=config_files,
bindings=None,
skip_unknown=True)
model = model_lib.create_model()
checkpoint = tf.train.Checkpoint(model=model)
checkpoint_file = tf.train.latest_checkpoint(checkpoint_path)
try:
logging.info('Restoring from %s', checkpoint_file)
status = checkpoint.restore(checkpoint_file)
status.assert_existing_objects_matched()
status.expect_partial()
model.save(output_model_path)
except (tf.errors.NotFoundError, AssertionError) as err:
logging.info('Failed to restore checkpoint from %s. Error:\n%s',
checkpoint_file, err) | Builds a saved model based on the checkpoint directory. |
19,903 | from typing import Dict, Mapping, Text
from absl import logging
import tensorflow as tf
The provided code snippet includes necessary dependencies for implementing the `_collect_tensors` function. Write a Python function `def _collect_tensors(tensors: tf.Tensor) -> tf.Tensor` to solve the following problem:
Collect tensors of the different replicas into a list.
Here is the function:
def _collect_tensors(tensors: tf.Tensor) -> tf.Tensor:
"""Collect tensors of the different replicas into a list."""
return tf.nest.flatten(tensors, expand_composites=True) | Collect tensors of the different replicas into a list. |
19,904 | from typing import Dict, Mapping, Text
from absl import logging
import tensorflow as tf
def _distributed_eval_step(strategy: tf.distribute.Strategy,
batch: Dict[Text, tf.Tensor], model: tf.keras.Model,
metrics: Dict[Text, tf.keras.metrics.Metric],
checkpoint_step: int) -> Dict[Text, tf.Tensor]:
"""Distributed eval step.
Args:
strategy: A Tensorflow distribution strategy.
batch: A batch of training examples.
model: The Keras model to evaluate.
metrics: The Keras metrics used for evaluation (a dictionary).
checkpoint_step: The iteration number at which the checkpoint is restored.
Returns:
list of predictions from each replica.
"""
def _eval_step(
batch: Dict[Text, tf.Tensor]) -> Dict[Text, tf.Tensor]:
"""Eval for one step."""
predictions = model(batch, training=False)
# Note: these metrics expect batch and prediction dictionaries rather than
# tensors like standard TF metrics do. This allows our losses and metrics to
# use a richer set of inputs than just the predicted final image.
for metric in metrics.values():
metric.update_state(batch, predictions, checkpoint_step=checkpoint_step)
return predictions
return strategy.run(_eval_step, args=(batch,))
def _summarize_image_tensors(combined, prefix, step):
for name in combined:
image = combined[name]
if isinstance(image, tf.Tensor):
if len(image.shape) == 4 and (image.shape[-1] == 1 or
image.shape[-1] == 3):
tf.summary.image(prefix + '/' + name, image, step=step)
The provided code snippet includes necessary dependencies for implementing the `eval_loop` function. Write a Python function `def eval_loop(strategy: tf.distribute.Strategy, eval_base_folder: str, model: tf.keras.Model, metrics: Dict[str, tf.keras.metrics.Metric], datasets: Mapping[str, tf.data.Dataset], summary_writer: tf.summary.SummaryWriter, checkpoint_step: int)` to solve the following problem:
Eval function that is strategy agnostic. Args: strategy: A Tensorflow distributed strategy. eval_base_folder: A path to where the summaries event files and checkpoints will be saved. model: A function that returns the model. metrics: A function that returns the metrics dictionary. datasets: A dict of tf.data.Dataset to evaluate on. summary_writer: Eval summary writer. checkpoint_step: The number of iterations completed.
Here is the function:
def eval_loop(strategy: tf.distribute.Strategy,
eval_base_folder: str,
model: tf.keras.Model,
metrics: Dict[str, tf.keras.metrics.Metric],
datasets: Mapping[str, tf.data.Dataset],
summary_writer: tf.summary.SummaryWriter,
checkpoint_step: int):
"""Eval function that is strategy agnostic.
Args:
strategy: A Tensorflow distributed strategy.
eval_base_folder: A path to where the summaries event files and
checkpoints will be saved.
model: A function that returns the model.
metrics: A function that returns the metrics dictionary.
datasets: A dict of tf.data.Dataset to evaluate on.
summary_writer: Eval summary writer.
checkpoint_step: The number of iterations completed.
"""
logging.info('Saving eval summaries to: %s...', eval_base_folder)
summary_writer.set_as_default()
for dataset_name, dataset in datasets.items():
for metric in metrics.values():
metric.reset_states()
logging.info('Loading %s testing data ...', dataset_name)
dataset = strategy.experimental_distribute_dataset(dataset)
logging.info('Evaluating %s ...', dataset_name)
batch_idx = 0
max_batches_to_summarize = 10
for batch in dataset:
predictions = _distributed_eval_step(strategy, batch, model, metrics,
checkpoint_step)
# Clip interpolator output to [0,1]. Clipping is done only
# on the eval loop to get better metrics, but not on the training loop
# so gradients are not killed.
if strategy.num_replicas_in_sync > 1:
predictions = {
'image': tf.concat(predictions['image'].values, axis=0)
}
predictions['image'] = tf.clip_by_value(predictions['image'], 0., 1.)
if batch_idx % 10 == 0:
logging.info('Evaluating batch %s', batch_idx)
batch_idx = batch_idx + 1
if batch_idx < max_batches_to_summarize:
# Loop through the global batch:
prefix = f'{dataset_name}/eval_{batch_idx}'
# Find all tensors that look like images, and summarize:
combined = {**batch, **predictions}
_summarize_image_tensors(combined, prefix, step=checkpoint_step)
elif batch_idx == max_batches_to_summarize:
tf.summary.flush()
for name, metric in metrics.items():
tf.summary.scalar(
f'{dataset_name}/{name}', metric.result(), step=checkpoint_step)
tf.summary.flush()
logging.info('Step {:2}, {} {}'.format(checkpoint_step,
f'{dataset_name}/{name}',
metric.result().numpy()))
metric.reset_states() | Eval function that is strategy agnostic. Args: strategy: A Tensorflow distributed strategy. eval_base_folder: A path to where the summaries event files and checkpoints will be saved. model: A function that returns the model. metrics: A function that returns the metrics dictionary. datasets: A dict of tf.data.Dataset to evaluate on. summary_writer: Eval summary writer. checkpoint_step: The number of iterations completed. |
19,905 | import functools
from typing import Any, Callable, Dict, Text, Tuple
from absl import logging
import tensorflow as tf
The provided code snippet includes necessary dependencies for implementing the `get_strategy` function. Write a Python function `def get_strategy(mode) -> tf.distribute.Strategy` to solve the following problem:
Creates a distributed strategy.
Here is the function:
def get_strategy(mode) -> tf.distribute.Strategy:
"""Creates a distributed strategy."""
strategy = None
if mode == 'cpu':
strategy = tf.distribute.OneDeviceStrategy('/cpu:0')
elif mode == 'gpu':
strategy = tf.distribute.MirroredStrategy()
else:
raise ValueError('Unsupported distributed mode.')
return strategy | Creates a distributed strategy. |
19,906 | from typing import Callable, Dict, List, Optional
from absl import logging
import gin.tf
import tensorflow as tf
def _create_from_sharded_tfrecord(batch_size,
train_mode,
file,
augmentation_fns,
crop_size,
max_examples=-1) -> tf.data.Dataset:
"""Creates a dataset from a sharded tfrecord."""
dataset = tf.data.Dataset.from_tensor_slices(
_generate_sharded_filenames(file))
# pylint: disable=g-long-lambda
dataset = dataset.interleave(
lambda x: _create_from_tfrecord(
batch_size,
file=x,
augmentation_fns=augmentation_fns,
crop_size=crop_size),
num_parallel_calls=tf.data.AUTOTUNE,
deterministic=not train_mode)
# pylint: enable=g-long-lambda
dataset = dataset.prefetch(buffer_size=2)
if max_examples > 0:
return dataset.take(max_examples)
return dataset
The provided code snippet includes necessary dependencies for implementing the `create_training_dataset` function. Write a Python function `def create_training_dataset( batch_size: int, file: Optional[str] = None, files: Optional[List[str]] = None, crop_size: int = -1, crop_sizes: Optional[List[int]] = None, augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None ) -> tf.data.Dataset` to solve the following problem:
Creates the training dataset. The given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch per example. file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A list of paths to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If > 0, images are cropped to crop_size x crop_size using tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List of crop sizes. If > 0, images are cropped to crop_size x crop_size using tensorflow's random cropping. augmentation_fns: A Dict of Callables to data augmentation functions. Returns: A tensorflow dataset for accessing examples that contain the input images 'x0', 'x1', ground truth 'y' and time of the ground truth 'time'=[0,1] in a dictionary of tensors.
Here is the function:
def create_training_dataset(
batch_size: int,
file: Optional[str] = None,
files: Optional[List[str]] = None,
crop_size: int = -1,
crop_sizes: Optional[List[int]] = None,
augmentation_fns: Optional[Dict[str, Callable[..., tf.Tensor]]] = None
) -> tf.data.Dataset:
"""Creates the training dataset.
The given tfrecord should contain data in a format produced by
frame_interpolation/datasets/create_*_tfrecord.py
Args:
batch_size: The number of images to batch per example.
file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N format.
Deprecated. Use 'files' instead.
files: A list of paths to sharded tfrecords in <tfrecord>@N format.
crop_size: (deprecated) If > 0, images are cropped to crop_size x crop_size
using tensorflow's random cropping. Deprecated: use 'files' and
'crop_sizes' instead.
crop_sizes: List of crop sizes. If > 0, images are cropped to
crop_size x crop_size using tensorflow's random cropping.
augmentation_fns: A Dict of Callables to data augmentation functions.
Returns:
A tensorflow dataset for accessing examples that contain the input images
'x0', 'x1', ground truth 'y' and time of the ground truth 'time'=[0,1] in a
dictionary of tensors.
"""
if file:
logging.warning('gin-configurable training_dataset.file is deprecated. '
'Use training_dataset.files instead.')
return _create_from_sharded_tfrecord(batch_size, True, file,
augmentation_fns, crop_size)
else:
if not crop_sizes or len(crop_sizes) != len(files):
raise ValueError('Please pass crop_sizes[] with training_dataset.files.')
if crop_size > 0:
raise ValueError(
'crop_size should not be used with files[], use crop_sizes[] instead.'
)
tables = []
for file, crop_size in zip(files, crop_sizes):
tables.append(
_create_from_sharded_tfrecord(batch_size, True, file,
augmentation_fns, crop_size))
return tf.data.experimental.sample_from_datasets(tables) | Creates the training dataset. The given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch per example. file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A list of paths to sharded tfrecords in <tfrecord>@N format. crop_size: (deprecated) If > 0, images are cropped to crop_size x crop_size using tensorflow's random cropping. Deprecated: use 'files' and 'crop_sizes' instead. crop_sizes: List of crop sizes. If > 0, images are cropped to crop_size x crop_size using tensorflow's random cropping. augmentation_fns: A Dict of Callables to data augmentation functions. Returns: A tensorflow dataset for accessing examples that contain the input images 'x0', 'x1', ground truth 'y' and time of the ground truth 'time'=[0,1] in a dictionary of tensors. |
19,907 | from typing import Callable, Dict, List
import gin.tf
import numpy as np
import tensorflow as tf
import tensorflow.math as tfm
import tensorflow_addons.image as tfa_image
_PI = 3.141592653589793
def _rotate_flow_vectors(flow: tf.Tensor, angle_rad: float) -> tf.Tensor:
r"""Rotate the (u,v) vector of each pixel with angle in radians.
Flow matrix system of coordinates.
. . . . u (x)
.
.
. v (-y)
Rotation system of coordinates.
. y
.
.
. . . . x
Args:
flow: Flow map which has been image-rotated.
angle_rad: The rotation angle in radians.
Returns:
A flow with the same map but each (u,v) vector rotated by angle_rad.
"""
u, v = tf.split(flow, 2, axis=-1)
# rotu = u * cos(angle) - (-v) * sin(angle)
rot_u = tfm.cos(angle_rad) * u + tfm.sin(angle_rad) * v
# rotv = -(u * sin(theta) + (-v) * cos(theta))
rot_v = -tfm.sin(angle_rad) * u + tfm.cos(angle_rad) * v
return tf.concat((rot_u, rot_v), axis=-1)
The provided code snippet includes necessary dependencies for implementing the `flow_rot90` function. Write a Python function `def flow_rot90(flow: tf.Tensor, k: int) -> tf.Tensor` to solve the following problem:
Rotates a flow by a multiple of 90 degrees. Args: flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees. k: The multiplier factor. Returns: A flow image of the same shape as the input rotated by multiples of 90 degrees.
Here is the function:
def flow_rot90(flow: tf.Tensor, k: int) -> tf.Tensor:
"""Rotates a flow by a multiple of 90 degrees.
Args:
flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees.
k: The multiplier factor.
Returns:
A flow image of the same shape as the input rotated by multiples of 90
degrees.
"""
angle_rad = tf.cast(k, dtype=tf.float32) * 90. * (_PI/180.)
flow = tf.image.rot90(flow, k)
return _rotate_flow_vectors(flow, angle_rad) | Rotates a flow by a multiple of 90 degrees. Args: flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees. k: The multiplier factor. Returns: A flow image of the same shape as the input rotated by multiples of 90 degrees. |
19,908 | from typing import Callable, Dict, List
import gin.tf
import numpy as np
import tensorflow as tf
import tensorflow.math as tfm
import tensorflow_addons.image as tfa_image
def _rotate_flow_vectors(flow: tf.Tensor, angle_rad: float) -> tf.Tensor:
r"""Rotate the (u,v) vector of each pixel with angle in radians.
Flow matrix system of coordinates.
. . . . u (x)
.
.
. v (-y)
Rotation system of coordinates.
. y
.
.
. . . . x
Args:
flow: Flow map which has been image-rotated.
angle_rad: The rotation angle in radians.
Returns:
A flow with the same map but each (u,v) vector rotated by angle_rad.
"""
u, v = tf.split(flow, 2, axis=-1)
# rotu = u * cos(angle) - (-v) * sin(angle)
rot_u = tfm.cos(angle_rad) * u + tfm.sin(angle_rad) * v
# rotv = -(u * sin(theta) + (-v) * cos(theta))
rot_v = -tfm.sin(angle_rad) * u + tfm.cos(angle_rad) * v
return tf.concat((rot_u, rot_v), axis=-1)
The provided code snippet includes necessary dependencies for implementing the `rotate_flow` function. Write a Python function `def rotate_flow(flow: tf.Tensor, angle_rad: float) -> tf.Tensor` to solve the following problem:
Rotates a flow by a the provided angle in radians. Args: flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees. angle_rad: The angle to ratate the flow in radians. Returns: A flow image of the same shape as the input rotated by the provided angle in radians.
Here is the function:
def rotate_flow(flow: tf.Tensor, angle_rad: float) -> tf.Tensor:
"""Rotates a flow by a the provided angle in radians.
Args:
flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees.
angle_rad: The angle to ratate the flow in radians.
Returns:
A flow image of the same shape as the input rotated by the provided angle in
radians.
"""
flow = tfa_image.rotate(
flow,
angles=angle_rad,
interpolation='bilinear',
fill_mode='reflect')
return _rotate_flow_vectors(flow, angle_rad) | Rotates a flow by a the provided angle in radians. Args: flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees. angle_rad: The angle to ratate the flow in radians. Returns: A flow image of the same shape as the input rotated by the provided angle in radians. |
19,909 | from typing import Callable, Dict, List
import gin.tf
import numpy as np
import tensorflow as tf
import tensorflow.math as tfm
import tensorflow_addons.image as tfa_image
The provided code snippet includes necessary dependencies for implementing the `flow_flip` function. Write a Python function `def flow_flip(flow: tf.Tensor) -> tf.Tensor` to solve the following problem:
Flips a flow left to right. Args: flow: The flow image shaped (H, W, 2) to flip left to right. Returns: A flow image of the same shape as the input flipped left to right.
Here is the function:
def flow_flip(flow: tf.Tensor) -> tf.Tensor:
"""Flips a flow left to right.
Args:
flow: The flow image shaped (H, W, 2) to flip left to right.
Returns:
A flow image of the same shape as the input flipped left to right.
"""
flow = tf.image.flip_left_right(tf.identity(flow))
flow_u, flow_v = tf.split(flow, 2, axis=-1)
return tf.stack([-1 * flow_u, flow_v], axis=-1) | Flips a flow left to right. Args: flow: The flow image shaped (H, W, 2) to flip left to right. Returns: A flow image of the same shape as the input flipped left to right. |
19,910 | from typing import Callable, Dict, List
import gin.tf
import numpy as np
import tensorflow as tf
import tensorflow.math as tfm
import tensorflow_addons.image as tfa_image
def random_image_rot90(images: Dict[str, tf.Tensor]) -> Dict[str, tf.Tensor]:
"""Rotates a stack of images by a random multiples of 90 degrees.
Args:
images: A tf.Tensor shaped (H, W, num_channels) of images stacked along the
channel's axis.
Returns:
A tf.Tensor of the same rank as the `images` after random rotation by
multiples of 90 degrees applied counter-clock wise.
"""
random_k = tf.random.uniform((), minval=0, maxval=4, dtype=tf.int32)
for key in images:
images[key] = tf.image.rot90(images[key], k=random_k)
return images
def random_flip(images: Dict[str, tf.Tensor]) -> Dict[str, tf.Tensor]:
"""Flips a stack of images randomly.
Args:
images: A tf.Tensor shaped (H, W, num_channels) of images stacked along the
channel's axis.
Returns:
A tf.Tensor of the images after random left to right flip.
"""
prob = tf.random.uniform((), minval=0, maxval=2, dtype=tf.int32)
prob = tf.cast(prob, tf.bool)
def _identity(image):
return image
def _flip_left_right(image):
return tf.image.flip_left_right(image)
# pylint: disable=cell-var-from-loop
for key in images:
images[key] = tf.cond(prob, lambda: _flip_left_right(images[key]),
lambda: _identity(images[key]))
return images
def random_reverse(images: Dict[str, tf.Tensor]) -> Dict[str, tf.Tensor]:
"""Reverses a stack of images randomly.
Args:
images: A dictionary of tf.Tensors, each shaped (H, W, num_channels), with
each tensor being a stack of iamges along the last channel axis.
Returns:
A dictionary of tf.Tensors, each shaped the same as the input images dict.
"""
prob = tf.random.uniform((), minval=0, maxval=2, dtype=tf.int32)
prob = tf.cast(prob, tf.bool)
def _identity(images):
return images
def _reverse(images):
images['x0'], images['x1'] = images['x1'], images['x0']
return images
return tf.cond(prob, lambda: _reverse(images), lambda: _identity(images))
def random_rotate(images: Dict[str, tf.Tensor]) -> Dict[str, tf.Tensor]:
"""Rotates image randomly with [-45 to 45 degrees].
Args:
images: A tf.Tensor shaped (H, W, num_channels) of images stacked along the
channel's axis.
Returns:
A tf.Tensor of the images after random rotation with a bound of -72 to 72
degrees.
"""
prob = tf.random.uniform((), minval=0, maxval=2, dtype=tf.int32)
prob = tf.cast(prob, tf.float32)
random_angle = tf.random.uniform((),
minval=-0.25 * np.pi,
maxval=0.25 * np.pi,
dtype=tf.float32)
for key in images:
images[key] = tfa_image.rotate(
images[key],
angles=random_angle * prob,
interpolation='bilinear',
fill_mode='constant')
return images
The provided code snippet includes necessary dependencies for implementing the `data_augmentations` function. Write a Python function `def data_augmentations( names: List[str]) -> Dict[str, Callable[..., tf.Tensor]]` to solve the following problem:
Creates the data augmentation functions. Args: names: The list of augmentation function names. Returns: A dictionary of Callables to the augmentation functions, keyed by their names.
Here is the function:
def data_augmentations(
names: List[str]) -> Dict[str, Callable[..., tf.Tensor]]:
"""Creates the data augmentation functions.
Args:
names: The list of augmentation function names.
Returns:
A dictionary of Callables to the augmentation functions, keyed by their
names.
"""
augmentations = dict()
for name in names:
if name == 'random_image_rot90':
augmentations[name] = random_image_rot90
elif name == 'random_rotate':
augmentations[name] = random_rotate
elif name == 'random_flip':
augmentations[name] = random_flip
elif name == 'random_reverse':
augmentations[name] = random_reverse
else:
raise AttributeError('Invalid augmentation function %s' % name)
return augmentations | Creates the data augmentation functions. Args: names: The list of augmentation function names. Returns: A dictionary of Callables to the augmentation functions, keyed by their names. |
19,911 | import io
import os
from typing import Any, List, Mapping, Optional
from absl import logging
import apache_beam as beam
import numpy as np
import PIL.Image
import six
from skimage import transform
import tensorflow as tf
def _resample_image(image: np.ndarray, resample_image_width: int,
resample_image_height: int) -> np.ndarray:
"""Re-samples and returns an `image` to be `resample_image_size`."""
# Convert image from uint8 gamma [0..255] to float linear [0..1].
image = image.astype(np.float32) / _UINT8_MAX_F
image = np.power(np.clip(image, 0, 1), _GAMMA)
# Re-size the image
resample_image_size = (resample_image_height, resample_image_width)
image = transform.resize_local_mean(image, resample_image_size)
# Convert back from float linear [0..1] to uint8 gamma [0..255].
image = np.power(np.clip(image, 0, 1), 1.0 / _GAMMA)
image = np.clip(image * _UINT8_MAX_F + 0.5, 0.0,
_UINT8_MAX_F).astype(np.uint8)
return image
The provided code snippet includes necessary dependencies for implementing the `generate_image_triplet_example` function. Write a Python function `def generate_image_triplet_example( triplet_dict: Mapping[str, str], scale_factor: int = 1, center_crop_factor: int = 1) -> Optional[tf.train.Example]` to solve the following problem:
Generates and serializes a tf.train.Example proto from an image triplet. Default setting creates a triplet Example with the input images unchanged. Images are processed in the order of center-crop then downscale. Args: triplet_dict: A dict of image key to filepath of the triplet images. scale_factor: An integer scale factor to isotropically downsample images. center_crop_factor: An integer cropping factor to center crop images with the original resolution but isotropically downsized by the factor. Returns: tf.train.Example proto, or None upon error. Raises: ValueError if triplet_dict length is different from three or the scale input arguments are non-positive.
Here is the function:
def generate_image_triplet_example(
triplet_dict: Mapping[str, str],
scale_factor: int = 1,
center_crop_factor: int = 1) -> Optional[tf.train.Example]:
"""Generates and serializes a tf.train.Example proto from an image triplet.
Default setting creates a triplet Example with the input images unchanged.
Images are processed in the order of center-crop then downscale.
Args:
triplet_dict: A dict of image key to filepath of the triplet images.
scale_factor: An integer scale factor to isotropically downsample images.
center_crop_factor: An integer cropping factor to center crop images with
the original resolution but isotropically downsized by the factor.
Returns:
tf.train.Example proto, or None upon error.
Raises:
ValueError if triplet_dict length is different from three or the scale input
arguments are non-positive.
"""
if len(triplet_dict) != 3:
raise ValueError(
f'Length of triplet_dict must be exactly 3, not {len(triplet_dict)}.')
if scale_factor <= 0 or center_crop_factor <= 0:
raise ValueError(f'(scale_factor, center_crop_factor) must be positive, '
f'Not ({scale_factor}, {center_crop_factor}).')
feature = {}
# Keep track of the path where the images came from for debugging purposes.
mid_frame_path = os.path.dirname(triplet_dict['frame_1'])
feature['path'] = tf.train.Feature(
bytes_list=tf.train.BytesList(value=[six.ensure_binary(mid_frame_path)]))
for image_key, image_path in triplet_dict.items():
if not tf.io.gfile.exists(image_path):
logging.error('File not found: %s', image_path)
return None
# Note: we need both the raw bytes and the image size.
# PIL.Image does not expose a method to grab the original bytes.
# (Also it is not aware of non-local file systems.)
# So we read with tf.io.gfile.GFile to get the bytes, and then wrap the
# bytes in BytesIO to let PIL.Image open the image.
try:
byte_array = tf.io.gfile.GFile(image_path, 'rb').read()
except tf.errors.InvalidArgumentError:
logging.exception('Cannot read image file: %s', image_path)
return None
try:
pil_image = PIL.Image.open(io.BytesIO(byte_array))
except PIL.UnidentifiedImageError:
logging.exception('Cannot decode image file: %s', image_path)
return None
width, height = pil_image.size
pil_image_format = pil_image.format
# Optionally center-crop images and downsize images
# by `center_crop_factor`.
if center_crop_factor > 1:
image = np.array(pil_image)
quarter_height = image.shape[0] // (2 * center_crop_factor)
quarter_width = image.shape[1] // (2 * center_crop_factor)
image = image[quarter_height:-quarter_height,
quarter_width:-quarter_width, :]
pil_image = PIL.Image.fromarray(image)
# Update image properties.
height, width, _ = image.shape
buffer = io.BytesIO()
try:
pil_image.save(buffer, format='PNG')
except OSError:
logging.exception('Cannot encode image file: %s', image_path)
return None
byte_array = buffer.getvalue()
# Optionally downsample images by `scale_factor`.
if scale_factor > 1:
image = np.array(pil_image)
image = _resample_image(image, image.shape[1] // scale_factor,
image.shape[0] // scale_factor)
pil_image = PIL.Image.fromarray(image)
# Update image properties.
height, width, _ = image.shape
buffer = io.BytesIO()
try:
pil_image.save(buffer, format='PNG')
except OSError:
logging.exception('Cannot encode image file: %s', image_path)
return None
byte_array = buffer.getvalue()
# Create tf Features.
image_feature = tf.train.Feature(
bytes_list=tf.train.BytesList(value=[byte_array]))
height_feature = tf.train.Feature(
int64_list=tf.train.Int64List(value=[height]))
width_feature = tf.train.Feature(
int64_list=tf.train.Int64List(value=[width]))
encoding = tf.train.Feature(
bytes_list=tf.train.BytesList(
value=[six.ensure_binary(pil_image_format.lower())]))
# Update feature map.
feature[f'{image_key}/encoded'] = image_feature
feature[f'{image_key}/format'] = encoding
feature[f'{image_key}/height'] = height_feature
feature[f'{image_key}/width'] = width_feature
# Create tf Example.
features = tf.train.Features(feature=feature)
example = tf.train.Example(features=features)
return example | Generates and serializes a tf.train.Example proto from an image triplet. Default setting creates a triplet Example with the input images unchanged. Images are processed in the order of center-crop then downscale. Args: triplet_dict: A dict of image key to filepath of the triplet images. scale_factor: An integer scale factor to isotropically downsample images. center_crop_factor: An integer cropping factor to center crop images with the original resolution but isotropically downsized by the factor. Returns: tf.train.Example proto, or None upon error. Raises: ValueError if triplet_dict length is different from three or the scale input arguments are non-positive. |
19,912 | from typing import List
from . import options
import tensorflow as tf
def _relu(x: tf.Tensor) -> tf.Tensor:
return tf.nn.leaky_relu(x, alpha=0.2) | null |
19,913 | from typing import List
from . import options
import tensorflow as tf
def _relu(x: tf.Tensor) -> tf.Tensor:
return tf.nn.leaky_relu(x, alpha=0.2)
def _conv(filters: int, name: str):
return tf.keras.layers.Conv2D(
name=name,
filters=filters,
kernel_size=3,
padding='same',
activation=_relu) | null |
19,914 | from typing import List
from . import options
from . import util
import tensorflow as tf
def _relu(x: tf.Tensor) -> tf.Tensor:
return tf.nn.leaky_relu(x, alpha=0.2) | null |
19,915 | import os
import shutil
from typing import Generator, Iterable, List, Optional
from . import interpolator as interpolator_lib
import numpy as np
import tensorflow as tf
from tqdm import tqdm
def read_image(filename: str) -> np.ndarray:
"""Reads an sRgb 8-bit image.
Args:
filename: The input filename to read.
Returns:
A float32 3-channel (RGB) ndarray with colors in the [0..1] range.
"""
image_data = tf.io.read_file(filename)
image = tf.io.decode_image(image_data, channels=3)
image_numpy = tf.cast(image, dtype=tf.float32).numpy()
return image_numpy / _UINT8_MAX_F
def _recursive_generator(
frame1: np.ndarray, frame2: np.ndarray, num_recursions: int,
interpolator: interpolator_lib.Interpolator,
bar: Optional[tqdm] = None
) -> Generator[np.ndarray, None, None]:
"""Splits halfway to repeatedly generate more frames.
Args:
frame1: Input image 1.
frame2: Input image 2.
num_recursions: How many times to interpolate the consecutive image pairs.
interpolator: The frame interpolator instance.
Yields:
The interpolated frames, including the first frame (frame1), but excluding
the final frame2.
"""
if num_recursions == 0:
yield frame1
else:
# Adds the batch dimension to all inputs before calling the interpolator,
# and remove it afterwards.
time = np.full(shape=(1,), fill_value=0.5, dtype=np.float32)
mid_frame = interpolator(frame1[np.newaxis, ...], frame2[np.newaxis, ...],
time)[0]
bar.update(1) if bar is not None else bar
yield from _recursive_generator(frame1, mid_frame, num_recursions - 1,
interpolator, bar)
yield from _recursive_generator(mid_frame, frame2, num_recursions - 1,
interpolator, bar)
The provided code snippet includes necessary dependencies for implementing the `interpolate_recursively_from_files` function. Write a Python function `def interpolate_recursively_from_files( frames: List[str], times_to_interpolate: int, interpolator: interpolator_lib.Interpolator) -> Iterable[np.ndarray]` to solve the following problem:
Generates interpolated frames by repeatedly interpolating the midpoint. Loads the files on demand and uses the yield paradigm to return the frames to allow streamed processing of longer videos. Recursive interpolation is useful if the interpolator is trained to predict frames at midpoint only and is thus expected to perform poorly elsewhere. Args: frames: List of input frames. Expected shape (H, W, 3). The colors should be in the range[0, 1] and in gamma space. times_to_interpolate: Number of times to do recursive midpoint interpolation. interpolator: The frame interpolation model to use. Yields: The interpolated frames (including the inputs).
Here is the function:
def interpolate_recursively_from_files(
frames: List[str], times_to_interpolate: int,
interpolator: interpolator_lib.Interpolator) -> Iterable[np.ndarray]:
"""Generates interpolated frames by repeatedly interpolating the midpoint.
Loads the files on demand and uses the yield paradigm to return the frames
to allow streamed processing of longer videos.
Recursive interpolation is useful if the interpolator is trained to predict
frames at midpoint only and is thus expected to perform poorly elsewhere.
Args:
frames: List of input frames. Expected shape (H, W, 3). The colors should be
in the range[0, 1] and in gamma space.
times_to_interpolate: Number of times to do recursive midpoint
interpolation.
interpolator: The frame interpolation model to use.
Yields:
The interpolated frames (including the inputs).
"""
n = len(frames)
num_frames = (n - 1) * (2**(times_to_interpolate) - 1)
bar = tqdm(total=num_frames, ncols=100, colour='green')
for i in range(1, n):
yield from _recursive_generator(
read_image(frames[i - 1]), read_image(frames[i]), times_to_interpolate,
interpolator, bar)
# Separately yield the final frame.
yield read_image(frames[-1]) | Generates interpolated frames by repeatedly interpolating the midpoint. Loads the files on demand and uses the yield paradigm to return the frames to allow streamed processing of longer videos. Recursive interpolation is useful if the interpolator is trained to predict frames at midpoint only and is thus expected to perform poorly elsewhere. Args: frames: List of input frames. Expected shape (H, W, 3). The colors should be in the range[0, 1] and in gamma space. times_to_interpolate: Number of times to do recursive midpoint interpolation. interpolator: The frame interpolation model to use. Yields: The interpolated frames (including the inputs). |
19,916 | import os
import shutil
from typing import Generator, Iterable, List, Optional
from . import interpolator as interpolator_lib
import numpy as np
import tensorflow as tf
from tqdm import tqdm
def _recursive_generator(
frame1: np.ndarray, frame2: np.ndarray, num_recursions: int,
interpolator: interpolator_lib.Interpolator,
bar: Optional[tqdm] = None
) -> Generator[np.ndarray, None, None]:
"""Splits halfway to repeatedly generate more frames.
Args:
frame1: Input image 1.
frame2: Input image 2.
num_recursions: How many times to interpolate the consecutive image pairs.
interpolator: The frame interpolator instance.
Yields:
The interpolated frames, including the first frame (frame1), but excluding
the final frame2.
"""
if num_recursions == 0:
yield frame1
else:
# Adds the batch dimension to all inputs before calling the interpolator,
# and remove it afterwards.
time = np.full(shape=(1,), fill_value=0.5, dtype=np.float32)
mid_frame = interpolator(frame1[np.newaxis, ...], frame2[np.newaxis, ...],
time)[0]
bar.update(1) if bar is not None else bar
yield from _recursive_generator(frame1, mid_frame, num_recursions - 1,
interpolator, bar)
yield from _recursive_generator(mid_frame, frame2, num_recursions - 1,
interpolator, bar)
The provided code snippet includes necessary dependencies for implementing the `interpolate_recursively_from_memory` function. Write a Python function `def interpolate_recursively_from_memory( frames: List[np.ndarray], times_to_interpolate: int, interpolator: interpolator_lib.Interpolator) -> Iterable[np.ndarray]` to solve the following problem:
Generates interpolated frames by repeatedly interpolating the midpoint. This is functionally equivalent to interpolate_recursively_from_files(), but expects the inputs frames in memory, instead of loading them on demand. Recursive interpolation is useful if the interpolator is trained to predict frames at midpoint only and is thus expected to perform poorly elsewhere. Args: frames: List of input frames. Expected shape (H, W, 3). The colors should be in the range[0, 1] and in gamma space. times_to_interpolate: Number of times to do recursive midpoint interpolation. interpolator: The frame interpolation model to use. Yields: The interpolated frames (including the inputs).
Here is the function:
def interpolate_recursively_from_memory(
frames: List[np.ndarray], times_to_interpolate: int,
interpolator: interpolator_lib.Interpolator) -> Iterable[np.ndarray]:
"""Generates interpolated frames by repeatedly interpolating the midpoint.
This is functionally equivalent to interpolate_recursively_from_files(), but
expects the inputs frames in memory, instead of loading them on demand.
Recursive interpolation is useful if the interpolator is trained to predict
frames at midpoint only and is thus expected to perform poorly elsewhere.
Args:
frames: List of input frames. Expected shape (H, W, 3). The colors should be
in the range[0, 1] and in gamma space.
times_to_interpolate: Number of times to do recursive midpoint
interpolation.
interpolator: The frame interpolation model to use.
Yields:
The interpolated frames (including the inputs).
"""
n = len(frames)
num_frames = (n - 1) * (2**(times_to_interpolate) - 1)
bar = tqdm(total=num_frames, ncols=100, colour='green')
for i in range(1, n):
yield from _recursive_generator(frames[i - 1], frames[i],
times_to_interpolate, interpolator, bar)
# Separately yield the final frame.
yield frames[-1] | Generates interpolated frames by repeatedly interpolating the midpoint. This is functionally equivalent to interpolate_recursively_from_files(), but expects the inputs frames in memory, instead of loading them on demand. Recursive interpolation is useful if the interpolator is trained to predict frames at midpoint only and is thus expected to perform poorly elsewhere. Args: frames: List of input frames. Expected shape (H, W, 3). The colors should be in the range[0, 1] and in gamma space. times_to_interpolate: Number of times to do recursive midpoint interpolation. interpolator: The frame interpolation model to use. Yields: The interpolated frames (including the inputs). |
19,917 | import os
import shutil
from typing import Generator, Iterable, List, Optional
from . import interpolator as interpolator_lib
import numpy as np
import tensorflow as tf
from tqdm import tqdm
_CONFIG_FFMPEG_NAME_OR_PATH = 'ffmpeg'
def get_ffmpeg_path() -> str:
path = shutil.which(_CONFIG_FFMPEG_NAME_OR_PATH)
if not path:
raise RuntimeError(
f"Program '{_CONFIG_FFMPEG_NAME_OR_PATH}' is not found;"
" perhaps install ffmpeg using 'apt-get install ffmpeg'.")
return path | null |
19,918 | import functools
import os
from typing import List, Sequence
from . import interpolator as interpolator_lib
from . import util
from absl import app
from absl import flags
from absl import logging
import apache_beam as beam
import mediapy as media
import natsort
import numpy as np
import tensorflow as tf
from tqdm.auto import tqdm
The provided code snippet includes necessary dependencies for implementing the `_output_frames` function. Write a Python function `def _output_frames(frames: List[np.ndarray], frames_dir: str)` to solve the following problem:
Writes PNG-images to a directory. If frames_dir doesn't exist, it is created. If frames_dir contains existing PNG-files, they are removed before saving the new ones. Args: frames: List of images to save. frames_dir: The output directory to save the images.
Here is the function:
def _output_frames(frames: List[np.ndarray], frames_dir: str):
"""Writes PNG-images to a directory.
If frames_dir doesn't exist, it is created. If frames_dir contains existing
PNG-files, they are removed before saving the new ones.
Args:
frames: List of images to save.
frames_dir: The output directory to save the images.
"""
if tf.io.gfile.isdir(frames_dir):
old_frames = tf.io.gfile.glob(f'{frames_dir}/frame_*.png')
if old_frames:
logging.info('Removing existing frames from %s.', frames_dir)
for old_frame in old_frames:
tf.io.gfile.remove(old_frame)
else:
tf.io.gfile.makedirs(frames_dir)
for idx, frame in tqdm(
enumerate(frames), total=len(frames), ncols=100, colour='green'):
util.write_image(f'{frames_dir}/frame_{idx:03d}.png', frame)
logging.info('Output frames saved in %s.', frames_dir) | Writes PNG-images to a directory. If frames_dir doesn't exist, it is created. If frames_dir contains existing PNG-files, they are removed before saving the new ones. Args: frames: List of images to save. frames_dir: The output directory to save the images. |
19,919 | import functools
import os
from typing import List, Sequence
from . import interpolator as interpolator_lib
from . import util
from absl import app
from absl import flags
from absl import logging
import apache_beam as beam
import mediapy as media
import natsort
import numpy as np
import tensorflow as tf
from tqdm.auto import tqdm
_PATTERN = flags.DEFINE_string(
name='pattern',
default=None,
help='The pattern to determine the directories with the input frames.',
required=True)
class ProcessDirectory(beam.DoFn):
def setup(self):
def process(self, directory: str):
def _run_pipeline() -> None:
directories = tf.io.gfile.glob(_PATTERN.value)
pipeline = beam.Pipeline('DirectRunner')
(pipeline | 'Create directory names' >> beam.Create(directories) # pylint: disable=expression-not-assigned
| 'Process directories' >> beam.ParDo(ProcessDirectory()))
result = pipeline.run()
result.wait_until_finish() | null |
19,920 | import collections
import os
from typing import Any, Dict
from . import util
from absl import app
from absl import flags
from absl import logging
import gin.tf
from ..losses import losses
import numpy as np
import tensorflow as tf
from ..training import data_lib
The provided code snippet includes necessary dependencies for implementing the `_get_experiment_config` function. Write a Python function `def _get_experiment_config(name) -> Dict[str, Any]` to solve the following problem:
Fetches the gin config.
Here is the function:
def _get_experiment_config(name) -> Dict[str, Any]:
"""Fetches the gin config."""
return {
'name': name,
} | Fetches the gin config. |
19,921 | import collections
import os
from typing import Any, Dict
from . import util
from absl import app
from absl import flags
from absl import logging
import gin.tf
from ..losses import losses
import numpy as np
import tensorflow as tf
from ..training import data_lib
_MODE = flags.DEFINE_enum('mode', 'gpu', ['cpu', 'gpu'],
'Device to run evaluations.')
The provided code snippet includes necessary dependencies for implementing the `_set_visible_devices` function. Write a Python function `def _set_visible_devices()` to solve the following problem:
Set the visible devices according to running mode.
Here is the function:
def _set_visible_devices():
"""Set the visible devices according to running mode."""
mode_devices = tf.config.list_physical_devices(_MODE.value.upper())
tf.config.set_visible_devices([], 'GPU')
tf.config.set_visible_devices([], 'TPU')
tf.config.set_visible_devices(mode_devices, _MODE.value.upper())
return | Set the visible devices according to running mode. |
19,922 | import collections
import os
from typing import Any, Dict
from . import util
from absl import app
from absl import flags
from absl import logging
import gin.tf
from ..losses import losses
import numpy as np
import tensorflow as tf
from ..training import data_lib
_OUTPUT_FRAMES = flags.DEFINE_boolean(
name='output_frames',
default=False,
help='If true, saves the the inputs, groud-truth and interpolated frames.')
The provided code snippet includes necessary dependencies for implementing the `run_evaluation` function. Write a Python function `def run_evaluation(model_path, tfrecord, output_dir, max_examples, metrics)` to solve the following problem:
Runs the eval loop for examples in the tfrecord. The evaluation is run for the first 'max_examples' number of examples, and resulting images are stored into the given output_dir. Any tensor that appears like an image is stored with its name -- this may include intermediate results, depending on what the model outputs. Additionally, numeric results are stored into results.csv file within the same directory. This includes per-example metrics and the mean across the whole dataset. Args: model_path: Directory TF2 saved model. tfrecord: Directory to the tfrecord eval data. output_dir: Directory to store the results into. max_examples: Maximum examples to evaluate. metrics: The names of loss functions to use.
Here is the function:
def run_evaluation(model_path, tfrecord, output_dir, max_examples, metrics):
"""Runs the eval loop for examples in the tfrecord.
The evaluation is run for the first 'max_examples' number of examples, and
resulting images are stored into the given output_dir. Any tensor that
appears like an image is stored with its name -- this may include intermediate
results, depending on what the model outputs.
Additionally, numeric results are stored into results.csv file within the same
directory. This includes per-example metrics and the mean across the whole
dataset.
Args:
model_path: Directory TF2 saved model.
tfrecord: Directory to the tfrecord eval data.
output_dir: Directory to store the results into.
max_examples: Maximum examples to evaluate.
metrics: The names of loss functions to use.
"""
model = tf.saved_model.load(model_path)
# Store a 'readme.txt' that contains information on where the data came from.
with tf.io.gfile.GFile(os.path.join(output_dir, 'readme.txt'), mode='w') as f:
print('Results for:', file=f)
print(f' model: {model_path}', file=f)
print(f' tfrecord: {tfrecord}', file=f)
with tf.io.gfile.GFile(
os.path.join(output_dir, 'results.csv'), mode='w') as csv_file:
test_losses = losses.test_losses(metrics, [
1.0,
] * len(metrics))
title_row = ['key'] + list(test_losses)
print(', '.join(title_row), file=csv_file)
datasets = data_lib.create_eval_datasets(
batch_size=1,
files=[tfrecord],
names=[os.path.basename(output_dir)],
max_examples=max_examples)
dataset = datasets[os.path.basename(output_dir)]
all_losses = collections.defaultdict(list)
for example in dataset:
inputs = {
'x0': example['x0'],
'x1': example['x1'],
'time': example['time'][..., tf.newaxis],
}
prediction = model(inputs, training=False)
# Get the key from encoded mid-frame path.
path = example['path'][0].numpy().decode('utf-8')
key = path.rsplit('.', 1)[0].rsplit(os.sep)[-1]
# Combines both inputs and outputs into a single dictionary:
combined = {**prediction, **example} if _OUTPUT_FRAMES.value else {}
for name in combined:
image = combined[name]
if isinstance(image, tf.Tensor):
# This saves any tensor that has a shape that can be interpreted
# as an image, e.g. (1, H, W, C), where the batch dimension is always
# 1, H and W are the image height and width, and C is either 1 or 3
# (grayscale or color image).
if len(image.shape) == 4 and (image.shape[-1] == 1 or
image.shape[-1] == 3):
util.write_image(
os.path.join(output_dir, f'{key}_{name}.png'), image[0].numpy())
# Evaluate losses if the dataset has ground truth 'y', otherwise just do
# a visual eval.
if 'y' in example:
loss_values = []
# Clip interpolator output to the range [0,1]. Clipping is done only
# on the eval loop to get better metrics, but not on the training loop
# so gradients are not killed.
prediction['image'] = tf.clip_by_value(prediction['image'], 0., 1.)
for loss_name, (loss_value_fn, loss_weight_fn) in test_losses.items():
loss_value = loss_value_fn(example, prediction) * loss_weight_fn(0)
loss_values.append(loss_value.numpy())
all_losses[loss_name].append(loss_value.numpy())
print(f'{key}, {str(loss_values)[1:-1]}', file=csv_file)
if all_losses:
totals = [np.mean(all_losses[loss_name]) for loss_name in test_losses]
print(f'mean, {str(totals)[1:-1]}', file=csv_file)
totals_dict = {
loss_name: np.mean(all_losses[loss_name]) for loss_name in test_losses
}
logging.info('mean, %s', totals_dict) | Runs the eval loop for examples in the tfrecord. The evaluation is run for the first 'max_examples' number of examples, and resulting images are stored into the given output_dir. Any tensor that appears like an image is stored with its name -- this may include intermediate results, depending on what the model outputs. Additionally, numeric results are stored into results.csv file within the same directory. This includes per-example metrics and the mean across the whole dataset. Args: model_path: Directory TF2 saved model. tfrecord: Directory to the tfrecord eval data. output_dir: Directory to store the results into. max_examples: Maximum examples to evaluate. metrics: The names of loss functions to use. |
19,923 | from typing import List, Optional
import numpy as np
import tensorflow as tf
The provided code snippet includes necessary dependencies for implementing the `_pad_to_align` function. Write a Python function `def _pad_to_align(x, align)` to solve the following problem:
Pad image batch x so width and height divide by align. Args: x: Image batch to align. align: Number to align to. Returns: 1) An image padded so width % align == 0 and height % align == 0. 2) A bounding box that can be fed readily to tf.image.crop_to_bounding_box to undo the padding.
Here is the function:
def _pad_to_align(x, align):
"""Pad image batch x so width and height divide by align.
Args:
x: Image batch to align.
align: Number to align to.
Returns:
1) An image padded so width % align == 0 and height % align == 0.
2) A bounding box that can be fed readily to tf.image.crop_to_bounding_box
to undo the padding.
"""
# Input checking.
assert np.ndim(x) == 4
assert align > 0, 'align must be a positive number.'
height, width = x.shape[-3:-1]
height_to_pad = (align - height % align) if height % align != 0 else 0
width_to_pad = (align - width % align) if width % align != 0 else 0
bbox_to_pad = {
'offset_height': height_to_pad // 2,
'offset_width': width_to_pad // 2,
'target_height': height + height_to_pad,
'target_width': width + width_to_pad
}
padded_x = tf.image.pad_to_bounding_box(x, **bbox_to_pad)
bbox_to_crop = {
'offset_height': height_to_pad // 2,
'offset_width': width_to_pad // 2,
'target_height': height,
'target_width': width
}
return padded_x, bbox_to_crop | Pad image batch x so width and height divide by align. Args: x: Image batch to align. align: Number to align to. Returns: 1) An image padded so width % align == 0 and height % align == 0. 2) A bounding box that can be fed readily to tf.image.crop_to_bounding_box to undo the padding. |
19,924 | from typing import List, Optional
import numpy as np
import tensorflow as tf
The provided code snippet includes necessary dependencies for implementing the `image_to_patches` function. Write a Python function `def image_to_patches(image: np.ndarray, block_shape: List[int]) -> np.ndarray` to solve the following problem:
Folds an image into patches and stacks along the batch dimension. Args: image: The input image of shape [B, H, W, C]. block_shape: The number of patches along the height and width to extract. Each patch is shaped (H/block_shape[0], W/block_shape[1]) Returns: The extracted patches shaped [num_blocks, patch_height, patch_width,...], with num_blocks = block_shape[0] * block_shape[1].
Here is the function:
def image_to_patches(image: np.ndarray, block_shape: List[int]) -> np.ndarray:
"""Folds an image into patches and stacks along the batch dimension.
Args:
image: The input image of shape [B, H, W, C].
block_shape: The number of patches along the height and width to extract.
Each patch is shaped (H/block_shape[0], W/block_shape[1])
Returns:
The extracted patches shaped [num_blocks, patch_height, patch_width,...],
with num_blocks = block_shape[0] * block_shape[1].
"""
block_height, block_width = block_shape
num_blocks = block_height * block_width
height, width, channel = image.shape[-3:]
patch_height, patch_width = height//block_height, width//block_width
assert height == (
patch_height * block_height
), 'block_height=%d should evenly divide height=%d.'%(block_height, height)
assert width == (
patch_width * block_width
), 'block_width=%d should evenly divide width=%d.'%(block_width, width)
patch_size = patch_height * patch_width
paddings = 2*[[0, 0]]
patches = tf.space_to_batch(image, [patch_height, patch_width], paddings)
patches = tf.split(patches, patch_size, 0)
patches = tf.stack(patches, axis=3)
patches = tf.reshape(patches,
[num_blocks, patch_height, patch_width, channel])
return patches.numpy() | Folds an image into patches and stacks along the batch dimension. Args: image: The input image of shape [B, H, W, C]. block_shape: The number of patches along the height and width to extract. Each patch is shaped (H/block_shape[0], W/block_shape[1]) Returns: The extracted patches shaped [num_blocks, patch_height, patch_width,...], with num_blocks = block_shape[0] * block_shape[1]. |
19,925 | from typing import List, Optional
import numpy as np
import tensorflow as tf
The provided code snippet includes necessary dependencies for implementing the `patches_to_image` function. Write a Python function `def patches_to_image(patches: np.ndarray, block_shape: List[int]) -> np.ndarray` to solve the following problem:
Unfolds patches (stacked along batch) into an image. Args: patches: The input patches, shaped [num_patches, patch_H, patch_W, C]. block_shape: The number of patches along the height and width to unfold. Each patch assumed to be shaped (H/block_shape[0], W/block_shape[1]). Returns: The unfolded image shaped [B, H, W, C].
Here is the function:
def patches_to_image(patches: np.ndarray, block_shape: List[int]) -> np.ndarray:
"""Unfolds patches (stacked along batch) into an image.
Args:
patches: The input patches, shaped [num_patches, patch_H, patch_W, C].
block_shape: The number of patches along the height and width to unfold.
Each patch assumed to be shaped (H/block_shape[0], W/block_shape[1]).
Returns:
The unfolded image shaped [B, H, W, C].
"""
block_height, block_width = block_shape
paddings = 2 * [[0, 0]]
patch_height, patch_width, channel = patches.shape[-3:]
patch_size = patch_height * patch_width
patches = tf.reshape(patches,
[1, block_height, block_width, patch_size, channel])
patches = tf.split(patches, patch_size, axis=3)
patches = tf.stack(patches, axis=0)
patches = tf.reshape(patches,
[patch_size, block_height, block_width, channel])
image = tf.batch_to_space(patches, [patch_height, patch_width], paddings)
return image.numpy() | Unfolds patches (stacked along batch) into an image. Args: patches: The input patches, shaped [num_patches, patch_H, patch_W, C]. block_shape: The number of patches along the height and width to unfold. Each patch assumed to be shaped (H/block_shape[0], W/block_shape[1]). Returns: The unfolded image shaped [B, H, W, C]. |
19,926 | import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content | null |
19,927 | import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
version_file = 'mmtrack/version.py'
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] | null |
19,928 | import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
def make_cuda_ext(name, module, sources, sources_cuda=[]):
define_macros = []
extra_compile_args = {'cxx': []}
if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':
define_macros += [('WITH_CUDA', None)]
extension = CUDAExtension
extra_compile_args['nvcc'] = [
'-D__CUDA_NO_HALF_OPERATORS__',
'-D__CUDA_NO_HALF_CONVERSIONS__',
'-D__CUDA_NO_HALF2_OPERATORS__',
]
sources += sources_cuda
else:
print(f'Compiling {name} without CUDA')
extension = CppExtension
return extension(
name=f'{module}.{name}',
sources=[os.path.join(*module.split('.'), p) for p in sources],
define_macros=define_macros,
extra_compile_args=extra_compile_args) | null |
19,929 | import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
The provided code snippet includes necessary dependencies for implementing the `parse_requirements` function. Write a Python function `def parse_requirements(fname='requirements.txt', with_version=True)` to solve the following problem:
Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())"
Here is the function:
def parse_requirements(fname='requirements.txt', with_version=True):
"""Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file
with_version (bool, default=False): if True include version specs
Returns:
List[str]: list of requirements items
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
import re
import sys
from os.path import exists
require_fpath = fname
def parse_line(line):
"""Parse information from a line in a requirements text file."""
if line.startswith('-r '):
# Allow specifying requirements in other files
target = line.split(' ')[1]
for info in parse_require_file(target):
yield info
else:
info = {'line': line}
if line.startswith('-e '):
info['package'] = line.split('#egg=')[1]
elif '@git+' in line:
info['package'] = line
else:
# Remove versioning from the package
pat = '(' + '|'.join(['>=', '==', '>']) + ')'
parts = re.split(pat, line, maxsplit=1)
parts = [p.strip() for p in parts]
info['package'] = parts[0]
if len(parts) > 1:
op, rest = parts[1:]
if ';' in rest:
# Handle platform specific dependencies
# http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
version, platform_deps = map(str.strip,
rest.split(';'))
info['platform_deps'] = platform_deps
else:
version = rest # NOQA
info['version'] = (op, version)
yield info
def parse_require_file(fpath):
with open(fpath, 'r') as f:
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
for info in parse_line(line):
yield info
def gen_packages_items():
if exists(require_fpath):
for info in parse_require_file(require_fpath):
parts = [info['package']]
if with_version and 'version' in info:
parts.extend(info['version'])
if not sys.version.startswith('3.4'):
# apparently package_deps are broken in 3.4
platform_deps = info.get('platform_deps')
if platform_deps is not None:
parts.append(';' + platform_deps)
item = ''.join(parts)
yield item
packages = list(gen_packages_items())
return packages | Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_requirements())" |
19,930 | import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
CUDAExtension)
The provided code snippet includes necessary dependencies for implementing the `add_mim_extension` function. Write a Python function `def add_mim_extension()` to solve the following problem:
Add extra files that are required to support MIM into the package. These files will be added by creating a symlink to the originals if the package is installed in `editable` mode (e.g. pip install -e .), or by copying from the originals otherwise.
Here is the function:
def add_mim_extension():
"""Add extra files that are required to support MIM into the package.
These files will be added by creating a symlink to the originals if the
package is installed in `editable` mode (e.g. pip install -e .), or by
copying from the originals otherwise.
"""
# parse installment mode
if 'develop' in sys.argv:
# installed by `pip install -e .`
mode = 'symlink'
elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
# installed by `pip install .`
# or create source distribution by `python setup.py sdist`
mode = 'copy'
else:
return
filenames = ['tools', 'configs', 'model-index.yml']
repo_path = osp.dirname(__file__)
mim_path = osp.join(repo_path, 'mmtrack', '.mim')
os.makedirs(mim_path, exist_ok=True)
for filename in filenames:
if osp.exists(filename):
src_path = osp.join(repo_path, filename)
tar_path = osp.join(mim_path, filename)
if osp.isfile(tar_path) or osp.islink(tar_path):
os.remove(tar_path)
elif osp.isdir(tar_path):
shutil.rmtree(tar_path)
if mode == 'symlink':
src_relpath = osp.relpath(src_path, osp.dirname(tar_path))
try:
os.symlink(src_relpath, tar_path)
except OSError:
# Creating a symbolic link on windows may raise an
# `OSError: [WinError 1314]` due to privilege. If
# the error happens, the src file will be copied
mode = 'copy'
warnings.warn(
f'Failed to create a symbolic link for {src_relpath}, '
f'and it will be copied to {tar_path}')
else:
continue
if mode == 'copy':
if osp.isfile(src_path):
shutil.copyfile(src_path, tar_path)
elif osp.isdir(src_path):
shutil.copytree(src_path, tar_path)
else:
warnings.warn(f'Cannot copy file {src_path}.')
else:
raise ValueError(f'Invalid mode {mode}') | Add extra files that are required to support MIM into the package. These files will be added by creating a symlink to the originals if the package is installed in `editable` mode (e.g. pip install -e .), or by copying from the originals otherwise. |
19,931 | import os
import subprocess
import sys
import pytorch_sphinx_theme
version_file = '../../mmtrack/version.py'
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] | null |
19,932 | import os
import subprocess
import sys
import pytorch_sphinx_theme
def builder_inited_handler(app):
subprocess.run(['./stat.py'])
def setup(app):
app.connect('builder-inited', builder_inited_handler) | null |
19,935 | version_info = parse_version_info(__version__)
def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc') != -1:
patch_version = x.split('rc')
version_info.append(int(patch_version[0]))
version_info.append(f'rc{patch_version[1]}')
return tuple(version_info) | null |
19,936 | import os
import numpy as np
import torch
import torch.distributed as dist
from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner,
build_optimizer, get_dist_info)
from mmcv.utils import build_from_cfg
from mmdet.datasets import build_dataset
from mmtrack.core import DistEvalHook, EvalHook
from mmtrack.datasets import build_dataloader
from mmtrack.utils import build_ddp, build_dp, get_root_logger
The provided code snippet includes necessary dependencies for implementing the `init_random_seed` function. Write a Python function `def init_random_seed(seed=None, device='cuda')` to solve the following problem:
Initialize random seed. If the seed is not set, the seed will be automatically randomized, and then broadcast to all processes to prevent some potential bugs. Args: seed (int, Optional): The seed. Default to None. device (str): The device where the seed will be put on. Default to 'cuda'. Returns: int: Seed to be used.
Here is the function:
def init_random_seed(seed=None, device='cuda'):
"""Initialize random seed.
If the seed is not set, the seed will be automatically randomized,
and then broadcast to all processes to prevent some potential bugs.
Args:
seed (int, Optional): The seed. Default to None.
device (str): The device where the seed will be put on.
Default to 'cuda'.
Returns:
int: Seed to be used.
"""
if seed is not None:
return seed
# Make sure all ranks share the same random seed to prevent
# some potential bugs. Please refer to
# https://github.com/open-mmlab/mmdetection/issues/6339
rank, world_size = get_dist_info()
seed = np.random.randint(2**31)
if world_size == 1:
return seed
if rank == 0:
random_num = torch.tensor(seed, dtype=torch.int32, device=device)
else:
random_num = torch.tensor(0, dtype=torch.int32, device=device)
dist.broadcast(random_num, src=0)
return random_num.item() | Initialize random seed. If the seed is not set, the seed will be automatically randomized, and then broadcast to all processes to prevent some potential bugs. Args: seed (int, Optional): The seed. Default to None. device (str): The device where the seed will be put on. Default to 'cuda'. Returns: int: Seed to be used. |
19,937 | import os
import numpy as np
import torch
import torch.distributed as dist
from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner,
build_optimizer, get_dist_info)
from mmcv.utils import build_from_cfg
from mmdet.datasets import build_dataset
from mmtrack.core import DistEvalHook, EvalHook
from mmtrack.datasets import build_dataloader
from mmtrack.utils import build_ddp, build_dp, get_root_logger
The provided code snippet includes necessary dependencies for implementing the `train_model` function. Write a Python function `def train_model(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None)` to solve the following problem:
Train model entry function. Args: model (nn.Module): The model to be trained. dataset (:obj:`Dataset`): Train dataset. cfg (dict): The config dict for training. distributed (bool): Whether to use distributed training. Default: False. validate (bool): Whether to do evaluation. Default: False. timestamp (str | None): Local time for runner. Default: None. meta (dict | None): Meta dict to record some important information. Default: None
Here is the function:
def train_model(model,
dataset,
cfg,
distributed=False,
validate=False,
timestamp=None,
meta=None):
"""Train model entry function.
Args:
model (nn.Module): The model to be trained.
dataset (:obj:`Dataset`): Train dataset.
cfg (dict): The config dict for training.
distributed (bool): Whether to use distributed training.
Default: False.
validate (bool): Whether to do evaluation. Default: False.
timestamp (str | None): Local time for runner. Default: None.
meta (dict | None): Meta dict to record some important information.
Default: None
"""
logger = get_root_logger(cfg.log_level)
# prepare data loaders
dataset = dataset if isinstance(dataset, (list, tuple)) else [dataset]
if 'imgs_per_gpu' in cfg.data:
logger.warning('"imgs_per_gpu" is deprecated in MMDet V2.0. '
'Please use "samples_per_gpu" instead')
if 'samples_per_gpu' in cfg.data:
logger.warning(
f'Got "imgs_per_gpu"={cfg.data.imgs_per_gpu} and '
f'"samples_per_gpu"={cfg.data.samples_per_gpu}, "imgs_per_gpu"'
f'={cfg.data.imgs_per_gpu} is used in this experiments')
else:
logger.warning(
'Automatically set "samples_per_gpu"="imgs_per_gpu"='
f'{cfg.data.imgs_per_gpu} in this experiments')
cfg.data.samples_per_gpu = cfg.data.imgs_per_gpu
data_loaders = [
build_dataloader(
ds,
cfg.data.samples_per_gpu,
cfg.data.workers_per_gpu,
# cfg.gpus will be ignored if distributed
len(cfg.gpu_ids),
samples_per_epoch=cfg.data.get('samples_per_epoch', None),
dist=distributed,
seed=cfg.seed,
persistent_workers=cfg.data.get('persistent_workers', False))
for ds in dataset
]
# put model on gpus
if distributed:
find_unused_parameters = cfg.get('find_unused_parameters', False)
if find_unused_parameters:
logger.info('set find_unused_parameters = True in DDP')
# Sets the `find_unused_parameters` parameter in
# torch.nn.parallel.DistributedDataParallel
model = build_ddp(
model,
cfg.device,
device_ids=[int(os.environ['LOCAL_RANK'])],
broadcast_buffers=False,
find_unused_parameters=find_unused_parameters)
else:
model = build_dp(model, cfg.device, device_ids=cfg.gpu_ids)
# build runner
optimizer = build_optimizer(model, cfg.optimizer)
runner = EpochBasedRunner(
model,
optimizer=optimizer,
work_dir=cfg.work_dir,
logger=logger,
meta=meta)
# an ugly workaround to make .log and .log.json filenames the same
runner.timestamp = timestamp
# fp16 setting
fp16_cfg = cfg.get('fp16', None)
if fp16_cfg is None and cfg.get('device', None) == 'npu':
fp16_cfg = dict(loss_scale='dynamic')
optimizer_config = cfg.optimizer_config
if 'type' not in cfg.optimizer_config:
optimizer_config.type = 'Fp16OptimizerHook' \
if fp16_cfg else 'OptimizerHook'
if fp16_cfg:
optimizer_config.update(fp16_cfg)
if 'Fp16' in optimizer_config.type:
optimizer_config.update(distributed=distributed)
# register hooks
runner.register_training_hooks(cfg.lr_config, optimizer_config,
cfg.checkpoint_config, cfg.log_config,
cfg.get('momentum_config', None))
if distributed:
runner.register_hook(DistSamplerSeedHook())
# register eval hooks
if validate:
val_dataset = build_dataset(cfg.data.val, dict(test_mode=True))
val_dataloader = build_dataloader(
val_dataset,
samples_per_gpu=1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=distributed,
shuffle=False,
persistent_workers=cfg.data.get('persistent_workers', False))
eval_cfg = cfg.get('evaluation', {})
eval_hook = DistEvalHook if distributed else EvalHook
runner.register_hook(eval_hook(val_dataloader, **eval_cfg))
# user-defined hooks
if cfg.get('custom_hooks', None):
custom_hooks = cfg.custom_hooks
assert isinstance(custom_hooks, list), \
f'custom_hooks expect list type, but got {type(custom_hooks)}'
for hook_cfg in cfg.custom_hooks:
assert isinstance(hook_cfg, dict), \
'Each item in custom_hooks expects dict type, but got ' \
f'{type(hook_cfg)}'
hook_cfg = hook_cfg.copy()
priority = hook_cfg.pop('priority', 'NORMAL')
hook = build_from_cfg(hook_cfg, HOOKS)
runner.register_hook(hook, priority=priority)
if cfg.resume_from:
runner.resume(cfg.resume_from)
elif cfg.load_from:
runner.load_checkpoint(cfg.load_from)
runner.run(data_loaders, cfg.workflow, cfg.total_epochs) | Train model entry function. Args: model (nn.Module): The model to be trained. dataset (:obj:`Dataset`): Train dataset. cfg (dict): The config dict for training. distributed (bool): Whether to use distributed training. Default: False. validate (bool): Whether to do evaluation. Default: False. timestamp (str | None): Local time for runner. Default: None. meta (dict | None): Meta dict to record some important information. Default: None |
19,938 | import logging
import os
import tempfile
import mmcv
import numpy as np
import torch
from mmcv.ops import RoIPool
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmdet.datasets.pipelines import Compose
from mmtrack.models import build_model
The provided code snippet includes necessary dependencies for implementing the `init_model` function. Write a Python function `def init_model(config, checkpoint=None, device='cuda:0', cfg_options=None, verbose_init_params=False)` to solve the following problem:
Initialize a model from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. Default as None. cfg_options (dict, optional): Options to override some settings in the used config. Default to None. verbose_init_params (bool, optional): Whether to print the information of initialized parameters to the console. Default to False. Returns: nn.Module: The constructed detector.
Here is the function:
def init_model(config,
checkpoint=None,
device='cuda:0',
cfg_options=None,
verbose_init_params=False):
"""Initialize a model from config file.
Args:
config (str or :obj:`mmcv.Config`): Config file path or the config
object.
checkpoint (str, optional): Checkpoint path. Default as None.
cfg_options (dict, optional): Options to override some settings in
the used config. Default to None.
verbose_init_params (bool, optional): Whether to print the information
of initialized parameters to the console. Default to False.
Returns:
nn.Module: The constructed detector.
"""
if isinstance(config, str):
config = mmcv.Config.fromfile(config)
elif not isinstance(config, mmcv.Config):
raise TypeError('config must be a filename or Config object, '
f'but got {type(config)}')
if cfg_options is not None:
config.merge_from_dict(cfg_options)
if 'detector' in config.model:
config.model.detector.pretrained = None
model = build_model(config.model)
if not verbose_init_params:
# Creating a temporary file to record the information of initialized
# parameters. If not, the information of initialized parameters will be
# printed to the console because of the call of
# `mmcv.runner.BaseModule.init_weights`.
tmp_file = tempfile.NamedTemporaryFile(delete=False)
file_handler = logging.FileHandler(tmp_file.name, mode='w')
model.logger.addHandler(file_handler)
# We need call `init_weights()` to load pretained weights in MOT
# task.
model.init_weights()
file_handler.close()
model.logger.removeHandler(file_handler)
tmp_file.close()
os.remove(tmp_file.name)
else:
# We need call `init_weights()` to load pretained weights in MOT task.
model.init_weights()
if checkpoint is not None:
checkpoint = load_checkpoint(model, checkpoint, map_location='cpu')
if 'meta' in checkpoint and 'CLASSES' in checkpoint['meta']:
model.CLASSES = checkpoint['meta']['CLASSES']
if not hasattr(model, 'CLASSES'):
if hasattr(model, 'detector') and hasattr(model.detector, 'CLASSES'):
model.CLASSES = model.detector.CLASSES
else:
print("Warning: The model doesn't have classes")
model.CLASSES = None
model.cfg = config # save the config in the model for convenience
model.to(device)
model.eval()
return model | Initialize a model from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. Default as None. cfg_options (dict, optional): Options to override some settings in the used config. Default to None. verbose_init_params (bool, optional): Whether to print the information of initialized parameters to the console. Default to False. Returns: nn.Module: The constructed detector. |
19,939 | import logging
import os
import tempfile
import mmcv
import numpy as np
import torch
from mmcv.ops import RoIPool
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmdet.datasets.pipelines import Compose
from mmtrack.models import build_model
The provided code snippet includes necessary dependencies for implementing the `inference_mot` function. Write a Python function `def inference_mot(model, img, frame_id)` to solve the following problem:
Inference image(s) with the mot model. Args: model (nn.Module): The loaded mot model. img (str | ndarray): Either image name or loaded image. frame_id (int): frame id. Returns: dict[str : ndarray]: The tracking results.
Here is the function:
def inference_mot(model, img, frame_id):
"""Inference image(s) with the mot model.
Args:
model (nn.Module): The loaded mot model.
img (str | ndarray): Either image name or loaded image.
frame_id (int): frame id.
Returns:
dict[str : ndarray]: The tracking results.
"""
cfg = model.cfg
device = next(model.parameters()).device # model device
# prepare data
if isinstance(img, np.ndarray):
# directly add img
data = dict(img=img, img_info=dict(frame_id=frame_id), img_prefix=None)
cfg = cfg.copy()
# set loading pipeline type
cfg.data.test.pipeline[0].type = 'LoadImageFromWebcam'
else:
# add information into dict
data = dict(
img_info=dict(filename=img, frame_id=frame_id), img_prefix=None)
# build the data pipeline
test_pipeline = Compose(cfg.data.test.pipeline)
data = test_pipeline(data)
data = collate([data], samples_per_gpu=1)
if next(model.parameters()).is_cuda:
# scatter to specified GPU
data = scatter(data, [device])[0]
else:
for m in model.modules():
assert not isinstance(
m, RoIPool
), 'CPU inference with RoIPool is not supported currently.'
# just get the actual data from DataContainer
data['img_metas'] = data['img_metas'][0].data
# forward the model
with torch.no_grad():
result = model(return_loss=False, rescale=True, **data)
return result | Inference image(s) with the mot model. Args: model (nn.Module): The loaded mot model. img (str | ndarray): Either image name or loaded image. frame_id (int): frame id. Returns: dict[str : ndarray]: The tracking results. |
19,940 | import logging
import os
import tempfile
import mmcv
import numpy as np
import torch
from mmcv.ops import RoIPool
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmdet.datasets.pipelines import Compose
from mmtrack.models import build_model
The provided code snippet includes necessary dependencies for implementing the `inference_sot` function. Write a Python function `def inference_sot(model, image, init_bbox, frame_id)` to solve the following problem:
Inference image with the single object tracker. Args: model (nn.Module): The loaded tracker. image (ndarray): Loaded images. init_bbox (ndarray): The target needs to be tracked. frame_id (int): frame id. Returns: dict[str : ndarray]: The tracking results.
Here is the function:
def inference_sot(model, image, init_bbox, frame_id):
"""Inference image with the single object tracker.
Args:
model (nn.Module): The loaded tracker.
image (ndarray): Loaded images.
init_bbox (ndarray): The target needs to be tracked.
frame_id (int): frame id.
Returns:
dict[str : ndarray]: The tracking results.
"""
cfg = model.cfg
device = next(model.parameters()).device # model device
data = dict(
img=image.astype(np.float32),
gt_bboxes=np.array(init_bbox).astype(np.float32),
img_info=dict(frame_id=frame_id))
# remove the "LoadImageFromFile" and "LoadAnnotations" in pipeline
test_pipeline = Compose(cfg.data.test.pipeline[2:])
data = test_pipeline(data)
data = collate([data], samples_per_gpu=1)
if next(model.parameters()).is_cuda:
# scatter to specified GPU
data = scatter(data, [device])[0]
else:
for m in model.modules():
assert not isinstance(
m, RoIPool
), 'CPU inference with RoIPool is not supported currently.'
# just get the actual data from DataContainer
data['img_metas'] = data['img_metas'][0].data
# forward the model
with torch.no_grad():
result = model(return_loss=False, rescale=True, **data)
return result | Inference image with the single object tracker. Args: model (nn.Module): The loaded tracker. image (ndarray): Loaded images. init_bbox (ndarray): The target needs to be tracked. frame_id (int): frame id. Returns: dict[str : ndarray]: The tracking results. |
19,941 | import logging
import os
import tempfile
import mmcv
import numpy as np
import torch
from mmcv.ops import RoIPool
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmdet.datasets.pipelines import Compose
from mmtrack.models import build_model
The provided code snippet includes necessary dependencies for implementing the `inference_vid` function. Write a Python function `def inference_vid(model, image, frame_id, ref_img_sampler=dict(frame_stride=10, num_left_ref_imgs=10))` to solve the following problem:
Inference image with the video object detector. Args: model (nn.Module): The loaded detector. image (ndarray): Loaded images. frame_id (int): Frame id. ref_img_sampler (dict): The configuration for sampling reference images. Only used under video detector of fgfa style. Defaults to dict(frame_stride=2, num_left_ref_imgs=10). Returns: dict[str : ndarray]: The detection results.
Here is the function:
def inference_vid(model,
image,
frame_id,
ref_img_sampler=dict(frame_stride=10, num_left_ref_imgs=10)):
"""Inference image with the video object detector.
Args:
model (nn.Module): The loaded detector.
image (ndarray): Loaded images.
frame_id (int): Frame id.
ref_img_sampler (dict): The configuration for sampling reference
images. Only used under video detector of fgfa style. Defaults to
dict(frame_stride=2, num_left_ref_imgs=10).
Returns:
dict[str : ndarray]: The detection results.
"""
cfg = model.cfg
device = next(model.parameters()).device # model device
if cfg.data.test.pipeline[0].type == 'LoadImageFromFile':
data = dict(
img=image.astype(np.float32).copy(),
img_info=dict(frame_id=frame_id))
# remove the "LoadImageFromFile" in pipeline
test_pipeline = Compose(cfg.data.test.pipeline[1:])
elif cfg.data.test.pipeline[0].type == 'LoadMultiImagesFromFile':
data = [
dict(
img=image.astype(np.float32).copy(),
img_info=dict(frame_id=frame_id))
]
num_left_ref_imgs = ref_img_sampler.get('num_left_ref_imgs')
frame_stride = ref_img_sampler.get('frame_stride')
if frame_id == 0:
for i in range(num_left_ref_imgs):
one_ref_img = dict(
img=image.astype(np.float32).copy(),
img_info=dict(frame_id=frame_id))
data.append(one_ref_img)
elif frame_id % frame_stride == 0:
one_ref_img = dict(
img=image.astype(np.float32).copy(),
img_info=dict(frame_id=frame_id))
data.append(one_ref_img)
# remove the "LoadMultiImagesFromFile" in pipeline
test_pipeline = Compose(cfg.data.test.pipeline[1:])
else:
print('Not supported loading data pipeline type: '
f'{cfg.data.test.pipeline[0].type}')
raise NotImplementedError
data = test_pipeline(data)
data = collate([data], samples_per_gpu=1)
if next(model.parameters()).is_cuda:
# scatter to specified GPU
data = scatter(data, [device])[0]
else:
for m in model.modules():
assert not isinstance(
m, RoIPool
), 'CPU inference with RoIPool is not supported currently.'
# just get the actual data from DataContainer
data['img_metas'] = data['img_metas'][0].data
# forward the model
with torch.no_grad():
result = model(return_loss=False, rescale=True, **data)
return result | Inference image with the video object detector. Args: model (nn.Module): The loaded detector. image (ndarray): Loaded images. frame_id (int): Frame id. ref_img_sampler (dict): The configuration for sampling reference images. Only used under video detector of fgfa style. Defaults to dict(frame_stride=2, num_left_ref_imgs=10). Returns: dict[str : ndarray]: The detection results. |
19,942 | import torch
from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh
The provided code snippet includes necessary dependencies for implementing the `quad2bbox` function. Write a Python function `def quad2bbox(quad)` to solve the following problem:
Convert quadrilateral to axis aligned box in [cx, cy, w, h] format. Args: quad (Tensor): of shape (N, 8), (8, ), (N, 4) or (4, ). The coordinates are in [x1, y1, x2, y2, x3, y3, x4, y4] or [tl_x, tl_y, br_x, br_y] format. Returns: Tensor: in [cx, cy, w, h] format.
Here is the function:
def quad2bbox(quad):
"""Convert quadrilateral to axis aligned box in [cx, cy, w, h] format.
Args:
quad (Tensor): of shape (N, 8), (8, ), (N, 4) or (4, ). The
coordinates are in [x1, y1, x2, y2, x3, y3, x4, y4] or
[tl_x, tl_y, br_x, br_y] format.
Returns:
Tensor: in [cx, cy, w, h] format.
"""
if len(quad.shape) == 1:
quad = quad.unsqueeze(0)
length = quad.shape[1]
if length == 8:
cx = torch.mean(quad[:, 0::2], dim=-1)
cy = torch.mean(quad[:, 1::2], dim=-1)
x1 = torch.min(quad[:, 0::2], dim=-1)[0]
x2 = torch.max(quad[:, 0::2], dim=-1)[0]
y1 = torch.min(quad[:, 1::2], dim=-1)[0]
y2 = torch.max(quad[:, 1::2], dim=-1)[0]
area1 = torch.norm(quad[:, 0:2] - quad[:, 2:4], dim=1) * \
torch.norm(quad[:, 2:4] - quad[:, 4:6], dim=1)
area2 = (x2 - x1) * (y2 - y1)
scale_factor = torch.sqrt(area1 / area2)
w = scale_factor * (x2 - x1)
h = scale_factor * (y2 - y1)
bbox = torch.stack((cx, cy, w, h), dim=-1).squeeze(0)
elif length == 4:
bbox = bbox_xyxy_to_cxcywh(quad).squeeze(0)
else:
NotImplementedError(f'The length of quadrilateral: {length} is \
not supported')
return bbox | Convert quadrilateral to axis aligned box in [cx, cy, w, h] format. Args: quad (Tensor): of shape (N, 8), (8, ), (N, 4) or (4, ). The coordinates are in [x1, y1, x2, y2, x3, y3, x4, y4] or [tl_x, tl_y, br_x, br_y] format. Returns: Tensor: in [cx, cy, w, h] format. |
19,943 | import torch
from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh
The provided code snippet includes necessary dependencies for implementing the `bbox_cxcywh_to_x1y1wh` function. Write a Python function `def bbox_cxcywh_to_x1y1wh(bbox)` to solve the following problem:
Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, w, h). Args: bbox (Tensor): Shape (n, 4) or (4, ) for bboxes. Returns: Tensor: Converted bboxes.
Here is the function:
def bbox_cxcywh_to_x1y1wh(bbox):
"""Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, w, h).
Args:
bbox (Tensor): Shape (n, 4) or (4, ) for bboxes.
Returns:
Tensor: Converted bboxes.
"""
cx, cy, w, h = bbox.split((1, 1, 1, 1), dim=-1)
bbox_new = [(cx - 0.5 * w), (cy - 0.5 * h), w, h]
return torch.cat(bbox_new, dim=-1) | Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, w, h). Args: bbox (Tensor): Shape (n, 4) or (4, ) for bboxes. Returns: Tensor: Converted bboxes. |
19,944 | import torch
from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh
The provided code snippet includes necessary dependencies for implementing the `bbox_xyxy_to_x1y1wh` function. Write a Python function `def bbox_xyxy_to_x1y1wh(bbox)` to solve the following problem:
Convert bbox coordinates from (x1, y1, x2, y2) to (x1, y1, w, h). Args: bbox (Tensor): Shape (n, 4) or (4, ) for bboxes. Returns: Tensor: Converted bboxes.
Here is the function:
def bbox_xyxy_to_x1y1wh(bbox):
"""Convert bbox coordinates from (x1, y1, x2, y2) to (x1, y1, w, h).
Args:
bbox (Tensor): Shape (n, 4) or (4, ) for bboxes.
Returns:
Tensor: Converted bboxes.
"""
x1, y1, x2, y2 = bbox.split((1, 1, 1, 1), dim=-1)
bbox_new = [x1, y1, (x2 - x1), (y2 - y1)]
return torch.cat(bbox_new, dim=-1) | Convert bbox coordinates from (x1, y1, x2, y2) to (x1, y1, w, h). Args: bbox (Tensor): Shape (n, 4) or (4, ) for bboxes. Returns: Tensor: Converted bboxes. |
19,945 | import torch
from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh
The provided code snippet includes necessary dependencies for implementing the `bbox_xyxy_to_cxcyah` function. Write a Python function `def bbox_xyxy_to_cxcyah(bboxes)` to solve the following problem:
Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, ratio, h). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes.
Here is the function:
def bbox_xyxy_to_cxcyah(bboxes):
"""Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, ratio, h).
Args:
bbox (Tensor): Shape (n, 4) for bboxes.
Returns:
Tensor: Converted bboxes.
"""
cx = (bboxes[:, 2] + bboxes[:, 0]) / 2
cy = (bboxes[:, 3] + bboxes[:, 1]) / 2
w = bboxes[:, 2] - bboxes[:, 0]
h = bboxes[:, 3] - bboxes[:, 1]
xyah = torch.stack([cx, cy, w / h, h], -1)
return xyah | Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, ratio, h). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes. |
19,946 | import torch
from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh
The provided code snippet includes necessary dependencies for implementing the `bbox_cxcyah_to_xyxy` function. Write a Python function `def bbox_cxcyah_to_xyxy(bboxes)` to solve the following problem:
Convert bbox coordinates from (cx, cy, ratio, h) to (x1, y1, x2, y2). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes.
Here is the function:
def bbox_cxcyah_to_xyxy(bboxes):
"""Convert bbox coordinates from (cx, cy, ratio, h) to (x1, y1, x2, y2).
Args:
bbox (Tensor): Shape (n, 4) for bboxes.
Returns:
Tensor: Converted bboxes.
"""
cx, cy, ratio, h = bboxes.split((1, 1, 1, 1), dim=-1)
w = ratio * h
x1y1x2y2 = [cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0]
return torch.cat(x1y1x2y2, dim=-1) | Convert bbox coordinates from (cx, cy, ratio, h) to (x1, y1, x2, y2). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes. |
19,947 |
def calculate_region_overlap(*args, **kwargs):
if calculate_overlap is None:
raise ImportError(
'Please run'
'pip install git+https://github.com/votchallenge/toolkit.git'
'to manually install vot-toolkit')
return calculate_overlap(*args, **kwargs) | null |
19,948 | import math
import numpy as np
from mmcv.runner.hooks import HOOKS, LrUpdaterHook
The provided code snippet includes necessary dependencies for implementing the `step_lr_interval` function. Write a Python function `def step_lr_interval(start_lr_factor, end_lr_factor, start_epoch, end_epoch)` to solve the following problem:
Exponentially varying learning rate. Generator learning rate factor exponentially varying from `start_lr_factor` to `end_lr_factor` in total `end_epoch - start_epoch` epochs. Args: start_lr_factor (float): Start learning rate factor. end_lr_factor (float): End learning rate factor. start_epoch (int): Start epoch. end_epoch (int): End epoch. Returns: ndarray: The exponentially varying learning rate.
Here is the function:
def step_lr_interval(start_lr_factor, end_lr_factor, start_epoch, end_epoch):
"""Exponentially varying learning rate.
Generator learning rate factor exponentially varying from `start_lr_factor`
to `end_lr_factor` in total `end_epoch - start_epoch` epochs.
Args:
start_lr_factor (float): Start learning rate factor.
end_lr_factor (float): End learning rate factor.
start_epoch (int): Start epoch.
end_epoch (int): End epoch.
Returns:
ndarray: The exponentially varying learning rate.
"""
epochs = end_epoch - start_epoch
mult = math.pow(end_lr_factor / start_lr_factor, 1. / (epochs))
lr_intervals = start_lr_factor * (mult**np.arange(epochs))
return lr_intervals | Exponentially varying learning rate. Generator learning rate factor exponentially varying from `start_lr_factor` to `end_lr_factor` in total `end_epoch - start_epoch` epochs. Args: start_lr_factor (float): Start learning rate factor. end_lr_factor (float): End learning rate factor. start_epoch (int): Start epoch. end_epoch (int): End epoch. Returns: ndarray: The exponentially varying learning rate. |
19,949 | import math
import numpy as np
from mmcv.runner.hooks import HOOKS, LrUpdaterHook
The provided code snippet includes necessary dependencies for implementing the `log_lr_interval` function. Write a Python function `def log_lr_interval(start_lr_factor, end_lr_factor, start_epoch, end_epoch)` to solve the following problem:
Logarithmically varying learning rate. Generator learning rate factor logarithmically varying from `start_lr_factor` to `end_lr_factor` in total `end_epoch - start_epoch` epochs. Args: start_lr_factor (float): Start learning rate factor. end_lr_factor (float): End learning rate factor. start_epoch (int): Start epoch. end_epoch (int): End epoch. Returns: ndarray: The logarithmically varying learning rate.
Here is the function:
def log_lr_interval(start_lr_factor, end_lr_factor, start_epoch, end_epoch):
"""Logarithmically varying learning rate.
Generator learning rate factor logarithmically varying from
`start_lr_factor` to `end_lr_factor` in total `end_epoch - start_epoch`
epochs.
Args:
start_lr_factor (float): Start learning rate factor.
end_lr_factor (float): End learning rate factor.
start_epoch (int): Start epoch.
end_epoch (int): End epoch.
Returns:
ndarray: The logarithmically varying learning rate.
"""
epochs = end_epoch - start_epoch
lr_intervals = np.logspace(
math.log10(start_lr_factor), math.log10(end_lr_factor), epochs)
return lr_intervals | Logarithmically varying learning rate. Generator learning rate factor logarithmically varying from `start_lr_factor` to `end_lr_factor` in total `end_epoch - start_epoch` epochs. Args: start_lr_factor (float): Start learning rate factor. end_lr_factor (float): End learning rate factor. start_epoch (int): Start epoch. end_epoch (int): End epoch. Returns: ndarray: The logarithmically varying learning rate. |
19,950 | import numpy as np
try:
import vot
from vot.analysis import is_special
from vot.region import Polygon, Rectangle, Special
from vot.region import calculate_overlaps as calculate_region_overlaps
except ImportError:
vot = None
def count_failures(trajectory):
"""count the number of failed frame in a trajectory.
Args:
trajectory (list[ndarray]): list of tracking results.
Returns:
List: the number of failed frame in a trajectory.
"""
num_fails = 0
for bbox in trajectory:
if len(bbox) == 1 and bbox[0] == 2.:
num_fails += 1
return num_fails
def calc_accuracy(gt_trajectory,
pred_trajectory,
burnin=10,
ignore_unknown=True,
video_wh=None):
"""Calculate accuracy over the sequence.
Args:
gt_trajectory (list[list]): list of bboxes
pred_trajectory (list[ndarray]): The outer list contains the
tracking results of each frame in one video. The ndarray has two
cases:
- bbox: denotes the normal tracking box in [x1, y1, w, h]
format.
- special tracking state: [0] denotes the unknown state,
namely the skipping frame after failure, [1] denotes the
initialized state, and [2] denotes the failed state.
burnin: number of frames that have to be ignored after the
re-initialization when calculating accuracy. Default is 10.
ignore_unknown (bool): whether ignore the skipping frames after
failures when calculating accuracy. Default is True.
video_wh: bounding region (width, height)
Return:
Float: accuracy over the sequence.
"""
pred_traj_region = trajectory2region(pred_trajectory)
gt_traj_region = trajectory2region(gt_trajectory)
overlaps = np.array(
calculate_region_overlaps(pred_traj_region, gt_traj_region, video_wh))
mask = np.ones(len(overlaps), dtype=bool)
for i, region in enumerate(pred_traj_region):
if is_special(region, Special.UNKNOWN) and ignore_unknown:
mask[i] = False
elif is_special(region, Special.INITIALIZATION):
for j in range(i, min(len(pred_traj_region), i + burnin)):
mask[j] = False
elif is_special(region, Special.FAILURE):
mask[i] = False
return np.mean(overlaps[mask]) if any(mask) else 0.
The provided code snippet includes necessary dependencies for implementing the `eval_sot_accuracy_robustness` function. Write a Python function `def eval_sot_accuracy_robustness(results, annotations, burnin=10, ignore_unknown=True, videos_wh=None)` to solve the following problem:
Calculate accuracy and robustness over all tracking sequences. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray have two cases: - bbox: denotes the normal tracking box in [x1, y1, w, h] format. - special tracking state: [0] denotes the unknown state, namely the skipping frame after failure, [1] denotes the initialized state, and [2] denotes the failed state. annotations (list[ndarray]): The list contains the gt_bboxes of each video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape. Each bbox is in (x1, y1, w, h) format. burnin: number of frames that have to be ignored after the re-initialization when calculating accuracy. Default is 10. ignore_unknown (bool): whether ignore the skipping frames after failures when calculating accuracy. Default is True. videos_wh (list[tuple(width, height), ...]): The list contains the width and height of each video. Default is None. Return: dict{str: float}: accuracy and robustness in EAO evaluation metric.
Here is the function:
def eval_sot_accuracy_robustness(results,
annotations,
burnin=10,
ignore_unknown=True,
videos_wh=None):
"""Calculate accuracy and robustness over all tracking sequences.
Args:
results (list[list[ndarray]]): The first list contains the
tracking results of each video. The second list contains the
tracking results of each frame in one video. The ndarray have two
cases:
- bbox: denotes the normal tracking box in [x1, y1, w, h]
format.
- special tracking state: [0] denotes the unknown state,
namely the skipping frame after failure, [1] denotes the
initialized state, and [2] denotes the failed state.
annotations (list[ndarray]): The list contains the gt_bboxes of each
video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape.
Each bbox is in (x1, y1, w, h) format.
burnin: number of frames that have to be ignored after the
re-initialization when calculating accuracy. Default is 10.
ignore_unknown (bool): whether ignore the skipping frames after
failures when calculating accuracy. Default is True.
videos_wh (list[tuple(width, height), ...]): The list contains the
width and height of each video. Default is None.
Return:
dict{str: float}: accuracy and robustness in EAO evaluation metric.
"""
if vot is None:
raise ImportError(
'Please run'
'pip install git+https://github.com/votchallenge/toolkit.git'
'to manually install vot-toolkit')
accuracy = 0
num_fails = 0
weight = 0
for i, (gt_traj, pred_traj) in enumerate(zip(annotations, results)):
assert len(gt_traj) == len(pred_traj)
assert len(pred_traj[0]) == 1 and pred_traj[0][0] == 1
num_fails += count_failures(pred_traj)
accuracy += calc_accuracy(
gt_traj,
pred_traj,
burnin=burnin,
ignore_unknown=ignore_unknown,
video_wh=videos_wh[i]) * len(pred_traj)
weight += len(pred_traj)
accuracy /= weight
robustness = num_fails / weight * 100
return dict(accuracy=accuracy, robustness=robustness, num_fails=num_fails) | Calculate accuracy and robustness over all tracking sequences. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray have two cases: - bbox: denotes the normal tracking box in [x1, y1, w, h] format. - special tracking state: [0] denotes the unknown state, namely the skipping frame after failure, [1] denotes the initialized state, and [2] denotes the failed state. annotations (list[ndarray]): The list contains the gt_bboxes of each video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape. Each bbox is in (x1, y1, w, h) format. burnin: number of frames that have to be ignored after the re-initialization when calculating accuracy. Default is 10. ignore_unknown (bool): whether ignore the skipping frames after failures when calculating accuracy. Default is True. videos_wh (list[tuple(width, height), ...]): The list contains the width and height of each video. Default is None. Return: dict{str: float}: accuracy and robustness in EAO evaluation metric. |
19,951 | import numpy as np
try:
import vot
from vot.analysis import is_special
from vot.region import Polygon, Rectangle, Special
from vot.region import calculate_overlaps as calculate_region_overlaps
except ImportError:
vot = None
def trajectory2region(trajectory):
"""Convert bbox trajectory to Rectangle or Polygon Class object trajectory.
Args:
trajectory (list[ndarray]): The outer list contains bbox of
each frame in a video. The bbox is a ndarray.
Returns:
List: contains the Region Class object of each frame in a
trajectory.
"""
traj_region = []
for bbox in trajectory:
traj_region.append(bbox2region(bbox))
return traj_region
def locate_failures_inits(trajectory):
"""locate the failure frame and initialized frame in a trajectory.
Args:
trajectory (list[ndarray]): list of tracking results.
Returns:
fail_inds (list): index of failed frame in a trajectory.
init_inds (list): index of initialized frame in a trajectory.
"""
fail_inds = []
init_inds = []
for i, bbox in enumerate(trajectory):
if len(bbox) == 1:
if bbox[0] == 1.:
init_inds.append(i)
elif bbox[0] == 2.:
fail_inds.append(i)
return fail_inds, init_inds
def calc_eao_curve(overlaps, successes):
"""Calculate EAO curve over all tracking sequences.
Args:
overlaps (list[list]): The outer list contains the overlaps of each
video. The inner list contains the overlap of each frame in one
video.
successes (list): The list contains the tracking states of last frame
in each fragment.
Return:
ndarray: The N-th element in ndarray denotes the average overlaps from
1 to N in all fragments.
"""
max_length = max([len(_) for _ in overlaps])
total_runs = len(overlaps)
overlaps_array = np.zeros((total_runs, max_length), dtype=np.float32)
# mask out frames which are not considered in EAO calculation. initial
# value are zero, meaning ignored.
mask = np.zeros((total_runs, max_length), dtype=np.float32)
for i, (overlap, success) in enumerate(zip(overlaps, successes)):
overlaps_array[i, :len(overlap)] = np.array(overlap)
if not success:
# tracker has failed during this sequence - consider all of
# 'overlaps_array' and use the default padding from the end of
# sequence to max length.
mask[i, :] = 1
else:
# tracker has successfully tracked to the end - consider only this
# part of the true sequence, and ignore the padding from the end of
# sequence to max length.
mask[i, :len(overlap)] = 1
overlaps_array_sum = overlaps_array.copy()
# overlaps_array_sum[i,j] means the mean overlap from 1 to j in i-th
# sequence
for j in range(1, overlaps_array_sum.shape[1]):
overlaps_array_sum[:, j] = np.mean(overlaps_array[:, 1:j + 1], axis=1)
return np.sum(overlaps_array_sum * mask, axis=0) / np.sum(mask, axis=0)
The provided code snippet includes necessary dependencies for implementing the `eval_sot_eao` function. Write a Python function `def eval_sot_eao(results, annotations, interval=[100, 356], videos_wh=None)` to solve the following problem:
Calculate EAO socre over all tracking sequences. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray have two cases: - bbox: denotes the normal tracking box in [x1, y1, w, h] format. - special tracking state: [0] denotes the unknown state, namely the skipping frame after failure, [1] denotes the initialized state, and [2] denotes the failed state. annotations (list[ndarray]): The list contains the gt_bboxes of each video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape. Each bbox is in (x1, y1, w, h) format. interval: an specified interval in EAO curve used to calculate the EAO score. There are different settings in different VOT challenge. Default is VOT2018 setting: [100, 356]. videos_wh (list[tuple(width, height), ...]): The list contains the width and height of each video. Default is None. Return: dict[str, float]: EAO score in EAO evaluation metric.
Here is the function:
def eval_sot_eao(results, annotations, interval=[100, 356], videos_wh=None):
"""Calculate EAO socre over all tracking sequences.
Args:
results (list[list[ndarray]]): The first list contains the
tracking results of each video. The second list contains the
tracking results of each frame in one video. The ndarray have two
cases:
- bbox: denotes the normal tracking box in [x1, y1, w, h]
format.
- special tracking state: [0] denotes the unknown state,
namely the skipping frame after failure, [1] denotes the
initialized state, and [2] denotes the failed state.
annotations (list[ndarray]): The list contains the gt_bboxes of each
video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape.
Each bbox is in (x1, y1, w, h) format.
interval: an specified interval in EAO curve used to calculate the EAO
score. There are different settings in different VOT challenge.
Default is VOT2018 setting: [100, 356].
videos_wh (list[tuple(width, height), ...]): The list contains the
width and height of each video. Default is None.
Return:
dict[str, float]: EAO score in EAO evaluation metric.
"""
if vot is None:
raise ImportError(
'Please run'
'pip install git+https://github.com/votchallenge/toolkit.git'
'to manually install vot-toolkit')
if videos_wh is None:
videos_wh = [None] * len(annotations)
all_overlaps = []
all_successes = []
for i, (gt_traj, pred_traj) in enumerate(zip(annotations, results)):
assert len(gt_traj) == len(
pred_traj), f'{len(gt_traj)} == {len(pred_traj)}'
# initialized bbox annotation is [1]
assert len(pred_traj[0]) == 1 and pred_traj[0][
0] == 1, f'{len(pred_traj[0])} == 1 and {pred_traj[0][0]} == 1'
fail_inds, init_inds = locate_failures_inits(pred_traj)
pred_traj = trajectory2region(pred_traj)
gt_traj = trajectory2region(gt_traj)
overlaps = calculate_region_overlaps(pred_traj, gt_traj, videos_wh[i])
if len(fail_inds) > 0:
for i in range(len(fail_inds)):
all_overlaps.append(overlaps[init_inds[i]:fail_inds[i]])
all_successes.append(False)
# handle last initialization
if len(init_inds) > len(fail_inds):
# tracker was initialized, but it has not failed until the end
# of the sequence
all_overlaps.append(overlaps[init_inds[-1]:])
all_successes.append(True)
else:
all_overlaps.append(overlaps)
all_successes.append(True)
eao_curve = calc_eao_curve(all_overlaps, all_successes)
eao_score = np.mean(eao_curve[interval[0]:interval[1] + 1])
eao = dict(eao=eao_score)
return eao | Calculate EAO socre over all tracking sequences. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray have two cases: - bbox: denotes the normal tracking box in [x1, y1, w, h] format. - special tracking state: [0] denotes the unknown state, namely the skipping frame after failure, [1] denotes the initialized state, and [2] denotes the failed state. annotations (list[ndarray]): The list contains the gt_bboxes of each video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape. Each bbox is in (x1, y1, w, h) format. interval: an specified interval in EAO curve used to calculate the EAO score. There are different settings in different VOT challenge. Default is VOT2018 setting: [100, 356]. videos_wh (list[tuple(width, height), ...]): The list contains the width and height of each video. Default is None. Return: dict[str, float]: EAO score in EAO evaluation metric. |
19,952 | import copy
import itertools
import json
import sys
import time
from collections import defaultdict
import numpy as np
from pycocotools import mask as maskUtils
def _isArrayLike(obj):
return hasattr(obj, '__iter__') and hasattr(obj, '__len__') | null |
19,953 | import time
from multiprocessing import Pool
import motmetrics as mm
import numpy as np
import pandas as pd
from mmcv.utils import print_log
from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps
from motmetrics.lap import linear_sum_assignment
from motmetrics.math_util import quiet_divide
from mmtrack.core.track import outs2results
METRIC_MAPS = {
'idf1': 'IDF1',
'mota': 'MOTA',
'motp': 'MOTP',
'num_false_positives': 'FP',
'num_misses': 'FN',
'num_switches': 'IDSw',
'recall': 'Rcll',
'precision': 'Prcn',
'mostly_tracked': 'MT',
'partially_tracked': 'PT',
'mostly_lost': 'ML',
'num_fragmentations': 'FM'
}
def acc_single_video(results,
gts,
iou_thr=0.5,
ignore_iof_thr=0.5,
ignore_by_classes=False):
"""Accumulate results in a single video."""
num_classes = len(results[0])
accumulators = [
mm.MOTAccumulator(auto_id=True) for i in range(num_classes)
]
for result, gt in zip(results, gts):
if ignore_by_classes:
gt_ignore = outs2results(
bboxes=gt['bboxes_ignore'],
labels=gt['labels_ignore'],
num_classes=num_classes)['bbox_results']
else:
gt_ignore = [gt['bboxes_ignore'] for i in range(num_classes)]
gt = outs2results(
bboxes=gt['bboxes'],
labels=gt['labels'],
ids=gt['instance_ids'],
num_classes=num_classes)['bbox_results']
for i in range(num_classes):
gt_ids, gt_bboxes = gt[i][:, 0].astype(np.int), gt[i][:, 1:]
pred_ids, pred_bboxes = result[i][:, 0].astype(
np.int), result[i][:, 1:-1]
dist = bbox_distances(gt_bboxes, pred_bboxes, iou_thr)
if gt_ignore[i].shape[0] > 0:
# 1. assign gt and preds
fps = np.ones(pred_bboxes.shape[0]).astype(np.bool)
row, col = linear_sum_assignment(dist)
for m, n in zip(row, col):
if not np.isfinite(dist[m, n]):
continue
fps[n] = False
# 2. ignore by iof
iofs = bbox_overlaps(pred_bboxes, gt_ignore[i], mode='iof')
ignores = (iofs > ignore_iof_thr).any(axis=1)
# 3. filter preds
valid_inds = ~(fps & ignores)
pred_ids = pred_ids[valid_inds]
dist = dist[:, valid_inds]
if dist.shape != (0, 0):
accumulators[i].update(gt_ids, pred_ids, dist)
return accumulators
def aggregate_accs(accumulators, classes):
"""Aggregate results from each class."""
# accs for each class
items = list(classes)
names, accs = [[] for c in classes], [[] for c in classes]
for video_ind, _accs in enumerate(accumulators):
for cls_ind, acc in enumerate(_accs):
if len(acc._events['Type']) == 0:
continue
name = f'{classes[cls_ind]}_{video_ind}'
names[cls_ind].append(name)
accs[cls_ind].append(acc)
# overall
items.append('OVERALL')
names.append([n for name in names for n in name])
accs.append([a for acc in accs for a in acc])
return names, accs, items
def eval_single_class(names, accs):
"""Evaluate CLEAR MOT results for each class."""
mh = mm.metrics.create()
summary = mh.compute_many(
accs, names=names, metrics=METRIC_MAPS.keys(), generate_overall=True)
results = [v['OVERALL'] for k, v in summary.to_dict().items()]
motp_ind = list(METRIC_MAPS).index('motp')
if np.isnan(results[motp_ind]):
num_dets = mh.compute_many(
accs,
names=names,
metrics=['num_detections'],
generate_overall=True)
sum_motp = (summary['motp'] * num_dets['num_detections']).sum()
motp = quiet_divide(sum_motp, num_dets['num_detections']['OVERALL'])
results[motp_ind] = float(1 - motp)
else:
results[motp_ind] = 1 - results[motp_ind]
return results
The provided code snippet includes necessary dependencies for implementing the `eval_mot` function. Write a Python function `def eval_mot(results, annotations, logger=None, classes=None, iou_thr=0.5, ignore_iof_thr=0.5, ignore_by_classes=False, nproc=4)` to solve the following problem:
Evaluation CLEAR MOT metrics. Args: results (list[list[list[ndarray]]]): The first list indicates videos, The second list indicates images. The third list indicates categories. The ndarray indicates the tracking results. annotations (list[list[dict]]): The first list indicates videos, The second list indicates images. The third list indicates the annotations of each video. Keys of annotations are - `bboxes`: numpy array of shape (n, 4) - `labels`: numpy array of shape (n, ) - `instance_ids`: numpy array of shape (n, ) - `bboxes_ignore` (optional): numpy array of shape (k, 4) - `labels_ignore` (optional): numpy array of shape (k, ) logger (logging.Logger | str | None, optional): The way to print the evaluation results. Defaults to None. classes (list, optional): Classes in the dataset. Defaults to None. iou_thr (float, optional): IoU threshold for evaluation. Defaults to 0.5. ignore_iof_thr (float, optional): Iof threshold to ignore results. Defaults to 0.5. ignore_by_classes (bool, optional): Whether ignore the results by classes or not. Defaults to False. nproc (int, optional): Number of the processes. Defaults to 4. Returns: dict[str, float]: Evaluation results.
Here is the function:
def eval_mot(results,
annotations,
logger=None,
classes=None,
iou_thr=0.5,
ignore_iof_thr=0.5,
ignore_by_classes=False,
nproc=4):
"""Evaluation CLEAR MOT metrics.
Args:
results (list[list[list[ndarray]]]): The first list indicates videos,
The second list indicates images. The third list indicates
categories. The ndarray indicates the tracking results.
annotations (list[list[dict]]): The first list indicates videos,
The second list indicates images. The third list indicates
the annotations of each video. Keys of annotations are
- `bboxes`: numpy array of shape (n, 4)
- `labels`: numpy array of shape (n, )
- `instance_ids`: numpy array of shape (n, )
- `bboxes_ignore` (optional): numpy array of shape (k, 4)
- `labels_ignore` (optional): numpy array of shape (k, )
logger (logging.Logger | str | None, optional): The way to print the
evaluation results. Defaults to None.
classes (list, optional): Classes in the dataset. Defaults to None.
iou_thr (float, optional): IoU threshold for evaluation.
Defaults to 0.5.
ignore_iof_thr (float, optional): Iof threshold to ignore results.
Defaults to 0.5.
ignore_by_classes (bool, optional): Whether ignore the results by
classes or not. Defaults to False.
nproc (int, optional): Number of the processes. Defaults to 4.
Returns:
dict[str, float]: Evaluation results.
"""
print_log('---CLEAR MOT Evaluation---', logger)
t = time.time()
gts = annotations.copy()
if classes is None:
classes = [i + 1 for i in range(len(results[0]))]
assert len(results) == len(gts)
metrics = METRIC_MAPS.keys()
print_log('Accumulating...', logger)
pool = Pool(nproc)
accs = pool.starmap(
acc_single_video,
zip(results, gts, [iou_thr for _ in range(len(gts))],
[ignore_iof_thr for _ in range(len(gts))],
[ignore_by_classes for _ in range(len(gts))]))
names, accs, items = aggregate_accs(accs, classes)
print_log('Evaluating...', logger)
eval_results = pd.DataFrame(columns=metrics)
summaries = pool.starmap(eval_single_class, zip(names, accs))
pool.close()
# category and overall results
for i, item in enumerate(items):
eval_results.loc[item] = summaries[i]
dtypes = {m: type(d) for m, d in zip(metrics, summaries[0])}
# average results
avg_results = []
for i, m in enumerate(metrics):
v = np.array([s[i] for s in summaries[:len(classes)]])
v = np.nan_to_num(v, nan=0)
if dtypes[m] == int:
avg_results.append(int(v.sum()))
elif dtypes[m] == float:
avg_results.append(float(v.mean()))
else:
raise TypeError()
eval_results.loc['AVERAGE'] = avg_results
eval_results = eval_results.astype(dtypes)
print_log('Rendering...', logger)
strsummary = mm.io.render_summary(
eval_results,
formatters=mm.metrics.create().formatters,
namemap=METRIC_MAPS)
print_log('\n' + strsummary, logger)
print_log(f'Evaluation finishes with {(time.time() - t):.2f} s.', logger)
eval_results = eval_results.to_dict()
out = {METRIC_MAPS[k]: v['OVERALL'] for k, v in eval_results.items()}
for k, v in out.items():
out[k] = float(f'{(v):.3f}') if isinstance(v, float) else int(f'{v}')
for m in ['OVERALL', 'AVERAGE']:
out[f'track_{m}_copypaste'] = ''
for k in METRIC_MAPS.keys():
v = eval_results[k][m]
v = f'{(v):.3f} ' if isinstance(v, float) else f'{v} '
out[f'track_{m}_copypaste'] += v
return out | Evaluation CLEAR MOT metrics. Args: results (list[list[list[ndarray]]]): The first list indicates videos, The second list indicates images. The third list indicates categories. The ndarray indicates the tracking results. annotations (list[list[dict]]): The first list indicates videos, The second list indicates images. The third list indicates the annotations of each video. Keys of annotations are - `bboxes`: numpy array of shape (n, 4) - `labels`: numpy array of shape (n, ) - `instance_ids`: numpy array of shape (n, ) - `bboxes_ignore` (optional): numpy array of shape (k, 4) - `labels_ignore` (optional): numpy array of shape (k, ) logger (logging.Logger | str | None, optional): The way to print the evaluation results. Defaults to None. classes (list, optional): Classes in the dataset. Defaults to None. iou_thr (float, optional): IoU threshold for evaluation. Defaults to 0.5. ignore_iof_thr (float, optional): Iof threshold to ignore results. Defaults to 0.5. ignore_by_classes (bool, optional): Whether ignore the results by classes or not. Defaults to False. nproc (int, optional): Number of the processes. Defaults to 4. Returns: dict[str, float]: Evaluation results. |
19,954 | import contextlib
import io
from collections import OrderedDict
from mmcv.utils import print_log
from .ytvis import YTVIS
from .ytviseval import YTVISeval
class YTVIS:
def __init__(self, annotation_file=None):
"""Constructor of Microsoft COCO helper class for reading and
visualizing annotations.
:param annotation_file (str | dict): location of annotation file or
dict results.
:param image_folder (str): location to the folder that hosts images.
:return:
"""
# load dataset
self.dataset, self.anns, self.cats, self.vids = dict(), dict(), dict(
), dict()
self.vidToAnns, self.catToVids = defaultdict(list), defaultdict(list)
if annotation_file is not None:
print('loading annotations into memory...')
tic = time.time()
if type(annotation_file) == str:
dataset = json.load(open(annotation_file, 'r'))
else:
dataset = annotation_file
assert type(
dataset
) == dict, 'annotation file format {} not supported'.format(
type(dataset))
print('Done (t={:0.2f}s)'.format(time.time() - tic))
self.dataset = dataset
self.createIndex()
def createIndex(self):
# create index
print('creating index...')
anns, cats, vids = {}, {}, {}
vidToAnns, catToVids = defaultdict(list), defaultdict(list)
if 'annotations' in self.dataset:
for ann in self.dataset['annotations']:
vidToAnns[ann['video_id']].append(ann)
anns[ann['id']] = ann
if 'videos' in self.dataset:
for vid in self.dataset['videos']:
vids[vid['id']] = vid
if 'categories' in self.dataset:
for cat in self.dataset['categories']:
cats[cat['id']] = cat
if 'annotations' in self.dataset and 'categories' in self.dataset:
for ann in self.dataset['annotations']:
catToVids[ann['category_id']].append(ann['video_id'])
print('index created!')
# create class members
self.anns = anns
self.vidToAnns = vidToAnns
self.catToVids = catToVids
self.vids = vids
self.cats = cats
def getAnnIds(self, vidIds=[], catIds=[], areaRng=[], iscrowd=None):
"""Get ann ids that satisfy given filter conditions. default skips that
filter.
:param vidIds (int array) : get anns for given vids
catIds (int array) : get anns for given cats
areaRng (float array) : get anns for given area range
iscrowd (boolean) : get anns for given crowd label
:return: ids (int array) : integer array of ann ids
"""
vidIds = vidIds if _isArrayLike(vidIds) else [vidIds]
catIds = catIds if _isArrayLike(catIds) else [catIds]
if len(vidIds) == len(catIds) == len(areaRng) == 0:
anns = self.dataset['annotations']
else:
if not len(vidIds) == 0:
lists = [
self.vidToAnns[vidId] for vidId in vidIds
if vidId in self.vidToAnns
]
anns = list(itertools.chain.from_iterable(lists))
else:
anns = self.dataset['annotations']
anns = anns if len(catIds) == 0 else [
ann for ann in anns if ann['category_id'] in catIds
]
anns = anns if len(areaRng) == 0 else [
ann for ann in anns if ann['avg_area'] > areaRng[0]
and ann['avg_area'] < areaRng[1]
]
if iscrowd is not None:
ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd]
else:
ids = [ann['id'] for ann in anns]
return ids
def getCatIds(self, catNms=[], supNms=[], catIds=[]):
"""filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids
"""
catNms = catNms if _isArrayLike(catNms) else [catNms]
supNms = supNms if _isArrayLike(supNms) else [supNms]
catIds = catIds if _isArrayLike(catIds) else [catIds]
if len(catNms) == len(supNms) == len(catIds) == 0:
cats = self.dataset['categories']
else:
cats = self.dataset['categories']
cats = cats if len(catNms) == 0 else [
cat for cat in cats if cat['name'] in catNms
]
cats = cats if len(supNms) == 0 else [
cat for cat in cats if cat['supercategory'] in supNms
]
cats = cats if len(catIds) == 0 else [
cat for cat in cats if cat['id'] in catIds
]
ids = [cat['id'] for cat in cats]
return ids
def getVidIds(self, vidIds=[], catIds=[]):
"""Get vid ids that satisfy given filter conditions.
:param vidIds (int array) : get vids for given ids
:param catIds (int array) : get vids with all given cats
:return: ids (int array) : integer array of vid ids
"""
vidIds = vidIds if _isArrayLike(vidIds) else [vidIds]
catIds = catIds if _isArrayLike(catIds) else [catIds]
if len(vidIds) == len(catIds) == 0:
ids = self.vids.keys()
else:
ids = set(vidIds)
for i, catId in enumerate(catIds):
if i == 0 and len(ids) == 0:
ids = set(self.catToVids[catId])
else:
ids &= set(self.catToVids[catId])
return list(ids)
def loadAnns(self, ids=[]):
"""Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects
"""
if _isArrayLike(ids):
return [self.anns[id] for id in ids]
elif type(ids) == int:
return [self.anns[ids]]
def loadCats(self, ids=[]):
"""Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects
"""
if _isArrayLike(ids):
return [self.cats[id] for id in ids]
elif type(ids) == int:
return [self.cats[ids]]
def loadVids(self, ids=[]):
"""Load anns with the specified ids.
:param ids (int array) : integer ids specifying vid
:return: vids (object array) : loaded vid objects
"""
if _isArrayLike(ids):
return [self.vids[id] for id in ids]
elif type(ids) == int:
return [self.vids[ids]]
def loadRes(self, resFile):
"""Load result file and return a result api object.
:param resFile (str) : file name of result file
:return: res (obj) : result api object
"""
res = YTVIS()
res.dataset['videos'] = [img for img in self.dataset['videos']]
print('Loading and preparing results...')
tic = time.time()
if type(resFile) == str or (PYTHON_VERSION == 2
and type(resFile) == str):
anns = json.load(open(resFile))
elif type(resFile) == np.ndarray:
anns = self.loadNumpyAnnotations(resFile)
else:
anns = resFile
assert type(anns) == list, 'results in not an array of objects'
annsVidIds = [ann['video_id'] for ann in anns]
assert set(annsVidIds) == (set(annsVidIds) & set(self.getVidIds())), \
'Results do not correspond to current coco set'
if 'segmentations' in anns[0]:
res.dataset['categories'] = copy.deepcopy(
self.dataset['categories'])
for id, ann in enumerate(anns):
ann['areas'] = []
if 'bboxes' not in ann:
ann['bboxes'] = []
for seg in ann['segmentations']:
# now only support compressed RLE format
# as segmentation results
if seg:
ann['areas'].append(maskUtils.area(seg))
if len(ann['bboxes']) < len(ann['areas']):
ann['bboxes'].append(maskUtils.toBbox(seg))
else:
ann['areas'].append(None)
if len(ann['bboxes']) < len(ann['areas']):
ann['bboxes'].append(None)
ann['id'] = id + 1
l_ori = [a for a in ann['areas'] if a]
if len(l_ori) == 0:
ann['avg_area'] = 0
else:
ann['avg_area'] = np.array(l_ori).mean()
ann['iscrowd'] = 0
print('DONE (t={:0.2f}s)'.format(time.time() - tic))
res.dataset['annotations'] = anns
res.createIndex()
return res
def annToRLE(self, ann, frameId):
"""Convert annotation which can be polygons, uncompressed RLE to RLE.
:return: binary mask (numpy 2D array)
"""
t = self.vids[ann['video_id']]
h, w = t['height'], t['width']
segm = ann['segmentations'][frameId]
if type(segm) == list:
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = maskUtils.frPyObjects(segm, h, w)
rle = maskUtils.merge(rles)
elif type(segm['counts']) == list:
# uncompressed RLE
rle = maskUtils.frPyObjects(segm, h, w)
else:
# rle
rle = segm
return rle
def annToMask(self, ann, frameId):
"""Convert annotation which can be polygons, uncompressed RLE, or RLE
to binary mask.
:return: binary mask (numpy 2D array)
"""
rle = self.annToRLE(ann, frameId)
m = maskUtils.decode(rle)
return m
class YTVISeval:
# Interface for evaluating video instance segmentation on
# the YouTubeVIS dataset.
#
# The usage for YTVISeval is as follows:
# cocoGt=..., cocoDt=... # load dataset and results
# E = YTVISeval(cocoGt,cocoDt); # initialize YTVISeval object
# E.params.recThrs = ...; # set parameters as desired
# E.evaluate(); # run per image evaluation
# E.accumulate(); # accumulate per image results
# E.summarize(); # display summary metrics of results
# For example usage see evalDemo.m and http://mscoco.org/.
#
# The evaluation parameters are as follows (defaults in brackets):
# imgIds - [all] N img ids to use for evaluation
# catIds - [all] K cat ids to use for evaluation
# iouThrs - [.5:.05:.95] T=10 IoU thresholds for evaluation
# recThrs - [0:.01:1] R=101 recall thresholds for evaluation
# areaRng - [...] A=4 object area ranges for evaluation
# maxDets - [1 10 100] M=3 thresholds on max detections per image
# iouType - ['segm'] set iouType to 'segm', 'bbox' or 'keypoints'
# iouType replaced the now DEPRECATED useSegm parameter.
# useCats - [1] if true use category labels for evaluation
# Note: if useCats=0 category labels are ignored as in proposal scoring.
# Note: multiple areaRngs [Ax2] and maxDets [Mx1] can be specified.
#
# evaluate(): evaluates detections on every image and every category and
# concats the results into the "evalImgs" with fields:
# dtIds - [1xD] id for each of the D detections (dt)
# gtIds - [1xG] id for each of the G ground truths (gt)
# dtMatches - [TxD] matching gt id at each IoU or 0
# gtMatches - [TxG] matching dt id at each IoU or 0
# dtScores - [1xD] confidence of each dt
# gtIgnore - [1xG] ignore flag for each gt
# dtIgnore - [TxD] ignore flag for each dt at each IoU
#
# accumulate(): accumulates the per-image, per-category evaluation
# results in "evalImgs" into the dictionary "eval" with fields:
# params - parameters used for evaluation
# date - date evaluation was performed
# counts - [T,R,K,A,M] parameter dimensions (see above)
# precision - [TxRxKxAxM] precision for every evaluation setting
# recall - [TxKxAxM] max recall for every evaluation setting
# Note: precision and recall==-1 for settings with no gt objects.
#
# See also coco, mask, pycocoDemo, pycocoEvalDemo
#
# Microsoft COCO Toolbox. version 2.0
# Data, paper, and tutorials available at: http://mscoco.org/
# Code written by Piotr Dollar and Tsung-Yi Lin, 2015.
# Licensed under the Simplified BSD License [see coco/license.txt]
def __init__(self, cocoGt=None, cocoDt=None, iouType='segm'):
"""Initialize CocoEval using coco APIs for gt and dt.
:param cocoGt: coco object with ground truth annotations
:param cocoDt: coco object with detection results
:return: None
"""
if not iouType:
print('iouType not specified. use default iouType segm')
self.cocoGt = cocoGt # ground truth COCO API
self.cocoDt = cocoDt # detections COCO API
self.params = {} # evaluation parameters
self.evalVids = defaultdict(
list) # per-image per-category evaluation results [KxAxI] elements
self.eval = {} # accumulated evaluation results
self._gts = defaultdict(list) # gt for evaluation
self._dts = defaultdict(list) # dt for evaluation
self.params = Params(iouType=iouType) # parameters
self._paramsEval = {} # parameters for evaluation
self.stats = [] # result summarization
self.ious = {} # ious between all gts and dts
if cocoGt is not None:
self.params.vidIds = sorted(cocoGt.getVidIds())
self.params.catIds = sorted(cocoGt.getCatIds())
def _prepare(self):
'''
Prepare ._gts and ._dts for evaluation based on params
:return: None
'''
def _toMask(anns, coco):
# modify ann['segmentation'] by reference
for ann in anns:
for i, a in enumerate(ann['segmentations']):
if a:
rle = coco.annToRLE(ann, i)
ann['segmentations'][i] = rle
l_ori = [a for a in ann['areas'] if a]
if len(l_ori) == 0:
ann['avg_area'] = 0
else:
ann['avg_area'] = np.array(l_ori).mean()
p = self.params
if p.useCats:
gts = self.cocoGt.loadAnns(
self.cocoGt.getAnnIds(vidIds=p.vidIds, catIds=p.catIds))
dts = self.cocoDt.loadAnns(
self.cocoDt.getAnnIds(vidIds=p.vidIds, catIds=p.catIds))
else:
gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(vidIds=p.vidIds))
dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(vidIds=p.vidIds))
# convert ground truth to mask if iouType == 'segm'
if p.iouType == 'segm':
_toMask(gts, self.cocoGt)
_toMask(dts, self.cocoDt)
# set ignore flag
for gt in gts:
gt['ignore'] = gt['ignore'] if 'ignore' in gt else 0
gt['ignore'] = 'iscrowd' in gt and gt['iscrowd']
if p.iouType == 'keypoints':
gt['ignore'] = (gt['num_keypoints'] == 0) or gt['ignore']
self._gts = defaultdict(list) # gt for evaluation
self._dts = defaultdict(list) # dt for evaluation
for gt in gts:
self._gts[gt['video_id'], gt['category_id']].append(gt)
for dt in dts:
self._dts[dt['video_id'], dt['category_id']].append(dt)
self.evalVids = defaultdict(
list) # per-image per-category evaluation results
self.eval = {} # accumulated evaluation results
def evaluate(self):
'''
Run per image evaluation on given images and store
results (a list of dict) in self.evalVids
:return: None
'''
tic = time.time()
print('Running per image evaluation...')
p = self.params
# add backward compatibility if useSegm is specified in params
if p.useSegm is not None:
p.iouType = 'segm' if p.useSegm == 1 else 'bbox'
print('useSegm (deprecated) is not None. Running {} evaluation'.
format(p.iouType))
print('Evaluate annotation type *{}*'.format(p.iouType))
p.vidIds = list(np.unique(p.vidIds))
if p.useCats:
p.catIds = list(np.unique(p.catIds))
p.maxDets = sorted(p.maxDets)
self.params = p
self._prepare()
# loop through images, area range, max detection number
catIds = p.catIds if p.useCats else [-1]
if p.iouType == 'segm' or p.iouType == 'bbox':
computeIoU = self.computeIoU
elif p.iouType == 'keypoints':
computeIoU = self.computeOks
self.ious = {(vidId, catId): computeIoU(vidId, catId)
for vidId in p.vidIds for catId in catIds}
evaluateVid = self.evaluateVid
maxDet = p.maxDets[-1]
self.evalImgs = [
evaluateVid(vidId, catId, areaRng, maxDet) for catId in catIds
for areaRng in p.areaRng for vidId in p.vidIds
]
self._paramsEval = copy.deepcopy(self.params)
toc = time.time()
print('DONE (t={:0.2f}s).'.format(toc - tic))
def computeIoU(self, vidId, catId):
p = self.params
if p.useCats:
gt = self._gts[vidId, catId]
dt = self._dts[vidId, catId]
else:
gt = [_ for cId in p.catIds for _ in self._gts[vidId, cId]]
dt = [_ for cId in p.catIds for _ in self._dts[vidId, cId]]
if len(gt) == 0 and len(dt) == 0:
return []
inds = np.argsort([-d['score'] for d in dt], kind='mergesort')
dt = [dt[i] for i in inds]
if len(dt) > p.maxDets[-1]:
dt = dt[0:p.maxDets[-1]]
if p.iouType == 'segm':
g = [g['segmentations'] for g in gt]
d = [d['segmentations'] for d in dt]
elif p.iouType == 'bbox':
g = [g['bboxes'] for g in gt]
d = [d['bboxes'] for d in dt]
else:
raise Exception('unknown iouType for iou computation')
# compute iou between each dt and gt region
def iou_seq(d_seq, g_seq):
i = .0
u = .0
for d, g in zip(d_seq, g_seq):
if d and g:
i += maskUtils.area(maskUtils.merge([d, g], True))
u += maskUtils.area(maskUtils.merge([d, g], False))
elif not d and g:
u += maskUtils.area(g)
elif d and not g:
u += maskUtils.area(d)
if not u > .0:
print('Mask sizes in video {} and category {} may not match!'.
format(vidId, catId))
iou = i / u if u > .0 else .0
return iou
ious = np.zeros([len(d), len(g)])
for i, j in np.ndindex(ious.shape):
ious[i, j] = iou_seq(d[i], g[j])
return ious
def computeOks(self, imgId, catId):
p = self.params
gts = self._gts[imgId, catId]
dts = self._dts[imgId, catId]
inds = np.argsort([-d['score'] for d in dts], kind='mergesort')
dts = [dts[i] for i in inds]
if len(dts) > p.maxDets[-1]:
dts = dts[0:p.maxDets[-1]]
# if len(gts) == 0 and len(dts) == 0:
if len(gts) == 0 or len(dts) == 0:
return []
ious = np.zeros((len(dts), len(gts)))
sigmas = np.array([
.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07,
.87, .87, .89, .89
]) / 10.0
vars = (sigmas * 2)**2
k = len(sigmas)
# compute oks between each detection and ground truth object
for j, gt in enumerate(gts):
# create bounds for ignore regions(double the gt bbox)
g = np.array(gt['keypoints'])
xg = g[0::3]
yg = g[1::3]
vg = g[2::3]
k1 = np.count_nonzero(vg > 0)
bb = gt['bbox']
x0 = bb[0] - bb[2]
x1 = bb[0] + bb[2] * 2
y0 = bb[1] - bb[3]
y1 = bb[1] + bb[3] * 2
for i, dt in enumerate(dts):
d = np.array(dt['keypoints'])
xd = d[0::3]
yd = d[1::3]
if k1 > 0:
# measure the per-keypoint distance if keypoints visible
dx = xd - xg
dy = yd - yg
else:
# measure minimum distance to keypoints
z = np.zeros((k))
dx = np.max((z, x0 - xd), axis=0) + np.max(
(z, xd - x1), axis=0)
dy = np.max((z, y0 - yd), axis=0) + np.max(
(z, yd - y1), axis=0)
e = (dx**2 + dy**2) / vars / (gt['avg_area'] +
np.spacing(1)) / 2
if k1 > 0:
e = e[vg > 0]
ious[i, j] = np.sum(np.exp(-e)) / e.shape[0]
return ious
def evaluateVid(self, vidId, catId, aRng, maxDet):
'''
perform evaluation for single category and image
:return: dict (single image results)
'''
p = self.params
if p.useCats:
gt = self._gts[vidId, catId]
dt = self._dts[vidId, catId]
else:
gt = [_ for cId in p.catIds for _ in self._gts[vidId, cId]]
dt = [_ for cId in p.catIds for _ in self._dts[vidId, cId]]
if len(gt) == 0 and len(dt) == 0:
return None
for g in gt:
if g['ignore'] or (g['avg_area'] < aRng[0]
or g['avg_area'] > aRng[1]):
g['_ignore'] = 1
else:
g['_ignore'] = 0
# sort dt highest score first, sort gt ignore last
gtind = np.argsort([g['_ignore'] for g in gt], kind='mergesort')
gt = [gt[i] for i in gtind]
dtind = np.argsort([-d['score'] for d in dt], kind='mergesort')
dt = [dt[i] for i in dtind[0:maxDet]]
iscrowd = [int(o['iscrowd']) for o in gt]
# load computed ious
ious = self.ious[vidId, catId][:, gtind] if len(
self.ious[vidId, catId]) > 0 else self.ious[vidId, catId]
T = len(p.iouThrs)
G = len(gt)
D = len(dt)
gtm = np.zeros((T, G))
dtm = np.zeros((T, D))
gtIg = np.array([g['_ignore'] for g in gt])
dtIg = np.zeros((T, D))
if not len(ious) == 0:
for tind, t in enumerate(p.iouThrs):
for dind, d in enumerate(dt):
# information about best match so far (m=-1 -> unmatched)
iou = min([t, 1 - 1e-10])
m = -1
for gind, g in enumerate(gt):
# if this gt already matched, and not a crowd, continue
if gtm[tind, gind] > 0 and not iscrowd[gind]:
continue
# if dt matched to reg gt, and on ignore gt, stop
if m > -1 and gtIg[m] == 0 and gtIg[gind] == 1:
break
# continue to next gt unless better match made
if ious[dind, gind] < iou:
continue
# if match successful and best so far,
# store appropriately
iou = ious[dind, gind]
m = gind
# if match made store id of match for both dt and gt
if m == -1:
continue
dtIg[tind, dind] = gtIg[m]
dtm[tind, dind] = gt[m]['id']
gtm[tind, m] = d['id']
# set unmatched detections outside of area range to ignore
a = np.array([
d['avg_area'] < aRng[0] or d['avg_area'] > aRng[1] for d in dt
]).reshape((1, len(dt)))
dtIg = np.logical_or(dtIg, np.logical_and(dtm == 0, np.repeat(a, T,
0)))
# store results for given image and category
return {
'video_id': vidId,
'category_id': catId,
'aRng': aRng,
'maxDet': maxDet,
'dtIds': [d['id'] for d in dt],
'gtIds': [g['id'] for g in gt],
'dtMatches': dtm,
'gtMatches': gtm,
'dtScores': [d['score'] for d in dt],
'gtIgnore': gtIg,
'dtIgnore': dtIg,
}
def accumulate(self, p=None):
"""Accumulate per image evaluation results and store the result in
self.eval.
:param p: input params for evaluation
:return: None
"""
print('Accumulating evaluation results...')
tic = time.time()
if not self.evalImgs:
print('Please run evaluate() first')
# allows input customized parameters
if p is None:
p = self.params
p.catIds = p.catIds if p.useCats == 1 else [-1]
T = len(p.iouThrs)
R = len(p.recThrs)
K = len(p.catIds) if p.useCats else 1
A = len(p.areaRng)
M = len(p.maxDets)
precision = -np.ones(
(T, R, K, A, M)) # -1 for the precision of absent categories
recall = -np.ones((T, K, A, M))
scores = -np.ones((T, R, K, A, M))
# create dictionary for future indexing
_pe = self._paramsEval
catIds = _pe.catIds if _pe.useCats else [-1]
setK = set(catIds)
setA = set(map(tuple, _pe.areaRng))
setM = set(_pe.maxDets)
setI = set(_pe.vidIds)
# get inds to evaluate
k_list = [n for n, k in enumerate(p.catIds) if k in setK]
m_list = [m for n, m in enumerate(p.maxDets) if m in setM]
a_list = [
n for n, a in enumerate(map(lambda x: tuple(x), p.areaRng))
if a in setA
]
i_list = [n for n, i in enumerate(p.vidIds) if i in setI]
I0 = len(_pe.vidIds)
A0 = len(_pe.areaRng)
# retrieve E at each category, area range, and max number of detections
for k, k0 in enumerate(k_list):
Nk = k0 * A0 * I0
for a, a0 in enumerate(a_list):
Na = a0 * I0
for m, maxDet in enumerate(m_list):
E = [self.evalImgs[Nk + Na + i] for i in i_list]
E = [e for e in E if e is not None]
if len(E) == 0:
continue
dtScores = np.concatenate(
[e['dtScores'][0:maxDet] for e in E])
inds = np.argsort(-dtScores, kind='mergesort')
dtScoresSorted = dtScores[inds]
dtm = np.concatenate(
[e['dtMatches'][:, 0:maxDet] for e in E], axis=1)[:,
inds]
dtIg = np.concatenate(
[e['dtIgnore'][:, 0:maxDet] for e in E], axis=1)[:,
inds]
gtIg = np.concatenate([e['gtIgnore'] for e in E])
npig = np.count_nonzero(gtIg == 0)
if npig == 0:
continue
tps = np.logical_and(dtm, np.logical_not(dtIg))
fps = np.logical_and(
np.logical_not(dtm), np.logical_not(dtIg))
tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)
fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)
for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)):
tp = np.array(tp)
fp = np.array(fp)
nd_ori = len(tp)
rc = tp / npig
pr = tp / (fp + tp + np.spacing(1))
q = np.zeros((R, ))
ss = np.zeros((R, ))
if nd_ori:
recall[t, k, a, m] = rc[-1]
else:
recall[t, k, a, m] = 0
# use python array gets significant speed improvement
pr = pr.tolist()
q = q.tolist()
for i in range(nd_ori - 1, 0, -1):
if pr[i] > pr[i - 1]:
pr[i - 1] = pr[i]
inds = np.searchsorted(rc, p.recThrs, side='left')
try:
for ri, pi in enumerate(inds):
q[ri] = pr[pi]
ss[ri] = dtScoresSorted[pi]
except Exception:
pass
precision[t, :, k, a, m] = np.array(q)
scores[t, :, k, a, m] = np.array(ss)
self.eval = {
'params': p,
'counts': [T, R, K, A, M],
'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'precision': precision,
'recall': recall,
'scores': scores,
}
toc = time.time()
print('DONE (t={:0.2f}s).'.format(toc - tic))
def summarize(self):
"""Compute and display summary metrics for evaluation results.
Note this function can *only* be applied on the default parameter
setting
"""
def _summarize(ap=1, iouThr=None, areaRng='all', maxDets=100):
p = self.params
iStr = ' {:<18} {} @[ IoU={:<9} | area={:>6s} | ' \
'maxDets={:>3d} ] = {:0.3f}'
titleStr = 'Average Precision' if ap == 1 else 'Average Recall'
typeStr = '(AP)' if ap == 1 else '(AR)'
iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \
if iouThr is None else '{:0.2f}'.format(iouThr)
aind = [
i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng
]
mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
if ap == 1:
# dimension of precision: [TxRxKxAxM]
s = self.eval['precision']
# IoU
if iouThr is not None:
t = np.where(iouThr == p.iouThrs)[0]
s = s[t]
s = s[:, :, :, aind, mind]
else:
# dimension of recall: [TxKxAxM]
s = self.eval['recall']
if iouThr is not None:
t = np.where(iouThr == p.iouThrs)[0]
s = s[t]
s = s[:, :, aind, mind]
if len(s[s > -1]) == 0:
mean_s = -1
else:
mean_s = np.mean(s[s > -1])
print(
iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets,
mean_s))
return mean_s
def _summarizeDets():
stats = np.zeros((12, ))
stats[0] = _summarize(1)
stats[1] = _summarize(1, iouThr=.5, maxDets=self.params.maxDets[2])
stats[2] = _summarize(
1, iouThr=.75, maxDets=self.params.maxDets[2])
stats[3] = _summarize(
1, areaRng='small', maxDets=self.params.maxDets[2])
stats[4] = _summarize(
1, areaRng='medium', maxDets=self.params.maxDets[2])
stats[5] = _summarize(
1, areaRng='large', maxDets=self.params.maxDets[2])
stats[6] = _summarize(0, maxDets=self.params.maxDets[0])
stats[7] = _summarize(0, maxDets=self.params.maxDets[1])
stats[8] = _summarize(0, maxDets=self.params.maxDets[2])
stats[9] = _summarize(
0, areaRng='small', maxDets=self.params.maxDets[2])
stats[10] = _summarize(
0, areaRng='medium', maxDets=self.params.maxDets[2])
stats[11] = _summarize(
0, areaRng='large', maxDets=self.params.maxDets[2])
return stats
def _summarizeKps():
stats = np.zeros((10, ))
stats[0] = _summarize(1, maxDets=20)
stats[1] = _summarize(1, maxDets=20, iouThr=.5)
stats[2] = _summarize(1, maxDets=20, iouThr=.75)
stats[3] = _summarize(1, maxDets=20, areaRng='medium')
stats[4] = _summarize(1, maxDets=20, areaRng='large')
stats[5] = _summarize(0, maxDets=20)
stats[6] = _summarize(0, maxDets=20, iouThr=.5)
stats[7] = _summarize(0, maxDets=20, iouThr=.75)
stats[8] = _summarize(0, maxDets=20, areaRng='medium')
stats[9] = _summarize(0, maxDets=20, areaRng='large')
return stats
if not self.eval:
raise Exception('Please run accumulate() first')
iouType = self.params.iouType
if iouType == 'segm' or iouType == 'bbox':
summarize = _summarizeDets
elif iouType == 'keypoints':
summarize = _summarizeKps
self.stats = summarize()
def __str__(self):
self.summarize()
The provided code snippet includes necessary dependencies for implementing the `eval_vis` function. Write a Python function `def eval_vis(test_results, vis_anns, logger=None)` to solve the following problem:
Evaluation on VIS metrics. Args: test_results (dict(list[dict])): Testing results of the VIS dataset. vis_anns (dict(list[dict])): The annotation in the format of YouTube-VIS. logger (logging.Logger | str | None): Logger used for printing related information during evaluation. Default: None. Returns: dict[str, float]: Evaluation results.
Here is the function:
def eval_vis(test_results, vis_anns, logger=None):
"""Evaluation on VIS metrics.
Args:
test_results (dict(list[dict])): Testing results of the VIS dataset.
vis_anns (dict(list[dict])): The annotation in the format
of YouTube-VIS.
logger (logging.Logger | str | None): Logger used for printing
related information during evaluation. Default: None.
Returns:
dict[str, float]: Evaluation results.
"""
ytvis = YTVIS(vis_anns)
if len(ytvis.anns) == 0:
print_log('Annotations does not exist', logger=logger)
return
ytvis_dets = ytvis.loadRes(test_results)
vid_ids = ytvis.getVidIds()
iou_type = metric = 'segm'
eval_results = OrderedDict()
ytvisEval = YTVISeval(ytvis, ytvis_dets, iou_type)
ytvisEval.params.vidIds = vid_ids
ytvisEval.evaluate()
ytvisEval.accumulate()
# Save coco summarize print information to logger
redirect_string = io.StringIO()
with contextlib.redirect_stdout(redirect_string):
ytvisEval.summarize()
print_log('\n' + redirect_string.getvalue(), logger=logger)
metric_items = ['mAP', 'mAP_50', 'mAP_75', 'mAP_s', 'mAP_m', 'mAP_l']
coco_metric_names = {
'mAP': 0,
'mAP_50': 1,
'mAP_75': 2,
'mAP_s': 3,
'mAP_m': 4,
'mAP_l': 5,
'AR@1': 6,
'AR@10': 7,
'AR@100': 8,
'AR_s@100': 9,
'AR_m@100': 10,
'AR_l@100': 11
}
for metric_item in metric_items:
key = f'{metric}_{metric_item}'
val = float(f'{ytvisEval.stats[coco_metric_names[metric_item]]:.3f}')
eval_results[key] = val
ap = ytvisEval.stats[:6]
eval_results[f'{metric}_mAP_copypaste'] = (
f'{ap[0]:.3f} {ap[1]:.3f} {ap[2]:.3f} {ap[3]:.3f} '
f'{ap[4]:.3f} {ap[5]:.3f}')
return eval_results | Evaluation on VIS metrics. Args: test_results (dict(list[dict])): Testing results of the VIS dataset. vis_anns (dict(list[dict])): The annotation in the format of YouTube-VIS. logger (logging.Logger | str | None): Logger used for printing related information during evaluation. Default: None. Returns: dict[str, float]: Evaluation results. |
19,955 | import numpy as np
from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps
def success_overlap(gt_bboxes, pred_bboxes, iou_th, video_length):
"""Evaluation based on iou.
Args:
gt_bboxes (ndarray): of shape (video_length, 4) in
[tl_x, tl_y, br_x, br_y] format.
pred_bboxes (ndarray): of shape (video_length, 4) in
[tl_x, tl_y, br_x, br_y] format.
iou_th (ndarray): Different threshold of iou. Typically is set to
`np.arange(0, 1.05, 0.05)`.
video_length (int): Video length.
Returns:
ndarray: The evaluation results at different threshold of iou.
"""
success = np.zeros(len(iou_th))
iou = np.ones(len(gt_bboxes)) * (-1)
valid = (gt_bboxes[:, 2] > gt_bboxes[:, 0]) & (
gt_bboxes[:, 3] > gt_bboxes[:, 1])
iou_matrix = bbox_overlaps(gt_bboxes[valid], pred_bboxes[valid])
iou[valid] = iou_matrix[np.arange(len(gt_bboxes[valid])),
np.arange(len(gt_bboxes[valid]))]
for i in range(len(iou_th)):
success[i] = np.sum(iou > iou_th[i]) / float(video_length)
return success
def success_error(gt_bboxes_center, pred_bboxes_center, pixel_offset_th,
video_length):
"""Evaluation based on pixel offset.
Args:
gt_bboxes (ndarray): of shape (video_length, 2) in [cx, cy] format.
pred_bboxes (ndarray): of shape (video_length, 2) in [cx, cy] format.
pixel_offset_th (ndarray): Different threshold of pixel offset.
video_length (int): Video length.
Returns:
ndarray: The evaluation results at different threshold of pixel offset.
"""
success = np.zeros(len(pixel_offset_th))
dist = np.ones(len(gt_bboxes_center)) * (-1)
valid = (gt_bboxes_center[:, 0] > 0) & (gt_bboxes_center[:, 1] > 0)
dist[valid] = np.sqrt(
np.sum(
(gt_bboxes_center[valid] - pred_bboxes_center[valid])**2, axis=1))
for i in range(len(pixel_offset_th)):
success[i] = np.sum(dist <= pixel_offset_th[i]) / float(video_length)
return success
The provided code snippet includes necessary dependencies for implementing the `eval_sot_ope` function. Write a Python function `def eval_sot_ope(results, annotations, visible_infos=None)` to solve the following problem:
Evaluation in OPE protocol. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray denotes the tracking box in [tl_x, tl_y, br_x, br_y] format. annotations (list[ndarray]): The list contains the bbox annotations of each video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape. Each bbox is in (x1, y1, x2, y2) format. visible_infos (list[ndarray] | None): If not None, the list contains the visible information of each video. The ndarray is visibility (with bool type) of object in one video. It's in (N,) shape. Default to None. Returns: dict[str, float]: OPE style evaluation metric (i.e. success, norm precision and precision).
Here is the function:
def eval_sot_ope(results, annotations, visible_infos=None):
"""Evaluation in OPE protocol.
Args:
results (list[list[ndarray]]): The first list contains the tracking
results of each video. The second list contains the tracking
results of each frame in one video. The ndarray denotes the
tracking box in [tl_x, tl_y, br_x, br_y] format.
annotations (list[ndarray]): The list contains the bbox
annotations of each video. The ndarray is gt_bboxes of one video.
It's in (N, 4) shape. Each bbox is in (x1, y1, x2, y2) format.
visible_infos (list[ndarray] | None): If not None, the list
contains the visible information of each video. The ndarray is
visibility (with bool type) of object in one video. It's in (N,)
shape. Default to None.
Returns:
dict[str, float]: OPE style evaluation metric (i.e. success,
norm precision and precision).
"""
success_results = []
precision_results = []
norm_precision_results = []
if visible_infos is None:
visible_infos = [np.array([True] * len(_)) for _ in annotations]
for single_video_results, single_video_gt_bboxes, single_video_visible in zip( # noqa
results, annotations, visible_infos):
pred_bboxes = np.stack(single_video_results)
assert len(pred_bboxes) == len(single_video_gt_bboxes)
video_length = len(single_video_results)
gt_bboxes = single_video_gt_bboxes[single_video_visible]
pred_bboxes = pred_bboxes[single_video_visible]
# eval success based on iou
iou_th = np.arange(0, 1.05, 0.05)
success_results.append(
success_overlap(gt_bboxes, pred_bboxes, iou_th, video_length))
# eval precision
gt_bboxes_center = np.array(
(0.5 * (gt_bboxes[:, 2] + gt_bboxes[:, 0]),
0.5 * (gt_bboxes[:, 3] + gt_bboxes[:, 1]))).T
pred_bboxes_center = np.array(
(0.5 * (pred_bboxes[:, 2] + pred_bboxes[:, 0]),
0.5 * (pred_bboxes[:, 3] + pred_bboxes[:, 1]))).T
pixel_offset_th = np.arange(0, 51, 1)
precision_results.append(
success_error(gt_bboxes_center, pred_bboxes_center,
pixel_offset_th, video_length))
# eval normed precision
gt_bboxes_wh = np.array((gt_bboxes[:, 2] - gt_bboxes[:, 0],
gt_bboxes[:, 3] - gt_bboxes[:, 1])).T
norm_gt_bboxes_center = gt_bboxes_center / (gt_bboxes_wh + 1e-16)
norm_pred_bboxes_center = pred_bboxes_center / (gt_bboxes_wh + 1e-16)
norm_pixel_offset_th = pixel_offset_th / 100.
norm_precision_results.append(
success_error(norm_gt_bboxes_center, norm_pred_bboxes_center,
norm_pixel_offset_th, video_length))
success = np.mean(success_results) * 100
precision = np.mean(precision_results, axis=0)[20] * 100
norm_precision = np.mean(norm_precision_results, axis=0)[20] * 100
eval_results = dict(
success=success, norm_precision=norm_precision, precision=precision)
return eval_results | Evaluation in OPE protocol. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray denotes the tracking box in [tl_x, tl_y, br_x, br_y] format. annotations (list[ndarray]): The list contains the bbox annotations of each video. The ndarray is gt_bboxes of one video. It's in (N, 4) shape. Each bbox is in (x1, y1, x2, y2) format. visible_infos (list[ndarray] | None): If not None, the list contains the visible information of each video. The ndarray is visibility (with bool type) of object in one video. It's in (N,) shape. Default to None. Returns: dict[str, float]: OPE style evaluation metric (i.e. success, norm precision and precision). |
19,956 | import torch
The provided code snippet includes necessary dependencies for implementing the `flow_warp_feats` function. Write a Python function `def flow_warp_feats(x, flow)` to solve the following problem:
Use flow to warp feature map. Args: x (Tensor): of shape (N, C, H_x, W_x). flow (Tensor): of shape (N, C, H_f, W_f). Returns: Tensor: The warpped feature map with shape (N, C, H_x, W_x).
Here is the function:
def flow_warp_feats(x, flow):
"""Use flow to warp feature map.
Args:
x (Tensor): of shape (N, C, H_x, W_x).
flow (Tensor): of shape (N, C, H_f, W_f).
Returns:
Tensor: The warpped feature map with shape (N, C, H_x, W_x).
"""
assert len(x.shape) == 4
assert len(flow.shape) == 4 and flow.shape[1] == 2
# 1. resize the resolution of flow to be the same as x.
scale_factor = float(x.shape[-1]) / flow.shape[-1]
flow = torch.nn.functional.interpolate(
flow, scale_factor=scale_factor, mode='bilinear', align_corners=False)
flow = flow * scale_factor
# 2. compute the flow_field (grid in the code) used to warp features.
H, W = x.shape[-2:]
h_grid, w_grid = torch.meshgrid(torch.arange(H), torch.arange(W))
# [1, 1, H, W]
h_grid = h_grid.to(flow)[None, None, ...]
# [1, 1, H, W]
w_grid = w_grid.to(flow)[None, None, ...]
# [1, 2, H, W]
grid = torch.cat((w_grid, h_grid), dim=1)
# [N, 2, H, W]
grid = grid + flow
grid[:, 0] = grid[:, 0] / W * 2 - 1
grid[:, 1] = grid[:, 1] / H * 2 - 1
# [N, H, W, 2]
grid = grid.permute(0, 2, 3, 1)
# 3. warp features.
x_warp = torch.nn.functional.grid_sample(
x, grid, padding_mode='border', align_corners=True)
return x_warp | Use flow to warp feature map. Args: x (Tensor): of shape (N, C, H_x, W_x). flow (Tensor): of shape (N, C, H_f, W_f). Returns: Tensor: The warpped feature map with shape (N, C, H_x, W_x). |
19,957 | import mmcv
import numpy as np
import torch
from mmdet.core import bbox2result
def _imrenormalize(img, img_norm_cfg, new_img_norm_cfg):
"""Re-normalize the image."""
img_norm_cfg = img_norm_cfg.copy()
new_img_norm_cfg = new_img_norm_cfg.copy()
for k, v in img_norm_cfg.items():
if (k == 'mean' or k == 'std') and not isinstance(v, np.ndarray):
img_norm_cfg[k] = np.array(v, dtype=img.dtype)
# reverse cfg
if 'to_rgb' in img_norm_cfg:
img_norm_cfg['to_bgr'] = img_norm_cfg['to_rgb']
img_norm_cfg.pop('to_rgb')
for k, v in new_img_norm_cfg.items():
if (k == 'mean' or k == 'std') and not isinstance(v, np.ndarray):
new_img_norm_cfg[k] = np.array(v, dtype=img.dtype)
img = mmcv.imdenormalize(img, **img_norm_cfg)
img = mmcv.imnormalize(img, **new_img_norm_cfg)
return img
The provided code snippet includes necessary dependencies for implementing the `imrenormalize` function. Write a Python function `def imrenormalize(img, img_norm_cfg, new_img_norm_cfg)` to solve the following problem:
Re-normalize the image. Args: img (Tensor | ndarray): Input image. If the input is a Tensor, the shape is (1, C, H, W). If the input is a ndarray, the shape is (H, W, C). img_norm_cfg (dict): Original configuration for the normalization. new_img_norm_cfg (dict): New configuration for the normalization. Returns: Tensor | ndarray: Output image with the same type and shape of the input.
Here is the function:
def imrenormalize(img, img_norm_cfg, new_img_norm_cfg):
"""Re-normalize the image.
Args:
img (Tensor | ndarray): Input image. If the input is a Tensor, the
shape is (1, C, H, W). If the input is a ndarray, the shape
is (H, W, C).
img_norm_cfg (dict): Original configuration for the normalization.
new_img_norm_cfg (dict): New configuration for the normalization.
Returns:
Tensor | ndarray: Output image with the same type and shape of
the input.
"""
if isinstance(img, torch.Tensor):
assert img.ndim == 4 and img.shape[0] == 1
new_img = img.squeeze(0).cpu().numpy().transpose(1, 2, 0)
new_img = _imrenormalize(new_img, img_norm_cfg, new_img_norm_cfg)
new_img = new_img.transpose(2, 0, 1)[None]
return torch.from_numpy(new_img).to(img)
else:
return _imrenormalize(img, img_norm_cfg, new_img_norm_cfg) | Re-normalize the image. Args: img (Tensor | ndarray): Input image. If the input is a Tensor, the shape is (1, C, H, W). If the input is a ndarray, the shape is (H, W, C). img_norm_cfg (dict): Original configuration for the normalization. new_img_norm_cfg (dict): New configuration for the normalization. Returns: Tensor | ndarray: Output image with the same type and shape of the input. |
19,958 | import mmcv
import numpy as np
import torch
from mmdet.core import bbox2result
The provided code snippet includes necessary dependencies for implementing the `outs2results` function. Write a Python function `def outs2results(bboxes=None, labels=None, masks=None, ids=None, num_classes=None, **kwargs)` to solve the following problem:
Convert tracking/detection results to a list of numpy arrays. Args: bboxes (torch.Tensor | np.ndarray): shape (n, 5) labels (torch.Tensor | np.ndarray): shape (n, ) masks (torch.Tensor | np.ndarray): shape (n, h, w) ids (torch.Tensor | np.ndarray): shape (n, ) num_classes (int): class number, not including background class Returns: dict[str : list(ndarray) | list[list[np.ndarray]]]: tracking/detection results of each class. It may contain keys as belows: - bbox_results (list[np.ndarray]): Each list denotes bboxes of one category. - mask_results (list[list[np.ndarray]]): Each outer list denotes masks of one category. Each inner list denotes one mask belonging to the category. Each mask has shape (h, w).
Here is the function:
def outs2results(bboxes=None,
labels=None,
masks=None,
ids=None,
num_classes=None,
**kwargs):
"""Convert tracking/detection results to a list of numpy arrays.
Args:
bboxes (torch.Tensor | np.ndarray): shape (n, 5)
labels (torch.Tensor | np.ndarray): shape (n, )
masks (torch.Tensor | np.ndarray): shape (n, h, w)
ids (torch.Tensor | np.ndarray): shape (n, )
num_classes (int): class number, not including background class
Returns:
dict[str : list(ndarray) | list[list[np.ndarray]]]: tracking/detection
results of each class. It may contain keys as belows:
- bbox_results (list[np.ndarray]): Each list denotes bboxes of one
category.
- mask_results (list[list[np.ndarray]]): Each outer list denotes masks
of one category. Each inner list denotes one mask belonging to
the category. Each mask has shape (h, w).
"""
assert labels is not None
assert num_classes is not None
results = dict()
if ids is not None:
valid_inds = ids > -1
ids = ids[valid_inds]
labels = labels[valid_inds]
if bboxes is not None:
if ids is not None:
bboxes = bboxes[valid_inds]
if bboxes.shape[0] == 0:
bbox_results = [
np.zeros((0, 6), dtype=np.float32)
for i in range(num_classes)
]
else:
if isinstance(bboxes, torch.Tensor):
bboxes = bboxes.cpu().numpy()
labels = labels.cpu().numpy()
ids = ids.cpu().numpy()
bbox_results = [
np.concatenate(
(ids[labels == i, None], bboxes[labels == i, :]),
axis=1) for i in range(num_classes)
]
else:
bbox_results = bbox2result(bboxes, labels, num_classes)
results['bbox_results'] = bbox_results
if masks is not None:
if ids is not None:
masks = masks[valid_inds]
if isinstance(masks, torch.Tensor):
masks = masks.detach().cpu().numpy()
masks_results = [[] for _ in range(num_classes)]
for i in range(bboxes.shape[0]):
masks_results[labels[i]].append(masks[i])
results['mask_results'] = masks_results
return results | Convert tracking/detection results to a list of numpy arrays. Args: bboxes (torch.Tensor | np.ndarray): shape (n, 5) labels (torch.Tensor | np.ndarray): shape (n, ) masks (torch.Tensor | np.ndarray): shape (n, h, w) ids (torch.Tensor | np.ndarray): shape (n, ) num_classes (int): class number, not including background class Returns: dict[str : list(ndarray) | list[list[np.ndarray]]]: tracking/detection results of each class. It may contain keys as belows: - bbox_results (list[np.ndarray]): Each list denotes bboxes of one category. - mask_results (list[list[np.ndarray]]): Each outer list denotes masks of one category. Each inner list denotes one mask belonging to the category. Each mask has shape (h, w). |
19,959 | import mmcv
import numpy as np
import torch
from mmdet.core import bbox2result
The provided code snippet includes necessary dependencies for implementing the `results2outs` function. Write a Python function `def results2outs(bbox_results=None, mask_results=None, mask_shape=None, **kwargs)` to solve the following problem:
Restore the results (list of results of each category) into the results of the model forward. Args: bbox_results (list[np.ndarray]): Each list denotes bboxes of one category. mask_results (list[list[np.ndarray]]): Each outer list denotes masks of one category. Each inner list denotes one mask belonging to the category. Each mask has shape (h, w). mask_shape (tuple[int]): The shape (h, w) of mask. Returns: tuple: tracking results of each class. It may contain keys as belows: - bboxes (np.ndarray): shape (n, 5) - labels (np.ndarray): shape (n, ) - masks (np.ndarray): shape (n, h, w) - ids (np.ndarray): shape (n, )
Here is the function:
def results2outs(bbox_results=None,
mask_results=None,
mask_shape=None,
**kwargs):
"""Restore the results (list of results of each category) into the results
of the model forward.
Args:
bbox_results (list[np.ndarray]): Each list denotes bboxes of one
category.
mask_results (list[list[np.ndarray]]): Each outer list denotes masks of
one category. Each inner list denotes one mask belonging to
the category. Each mask has shape (h, w).
mask_shape (tuple[int]): The shape (h, w) of mask.
Returns:
tuple: tracking results of each class. It may contain keys as belows:
- bboxes (np.ndarray): shape (n, 5)
- labels (np.ndarray): shape (n, )
- masks (np.ndarray): shape (n, h, w)
- ids (np.ndarray): shape (n, )
"""
outputs = dict()
if bbox_results is not None:
labels = []
for i, bbox in enumerate(bbox_results):
labels.extend([i] * bbox.shape[0])
labels = np.array(labels, dtype=np.int64)
outputs['labels'] = labels
bboxes = np.concatenate(bbox_results, axis=0).astype(np.float32)
if bboxes.shape[1] == 5:
outputs['bboxes'] = bboxes
elif bboxes.shape[1] == 6:
ids = bboxes[:, 0].astype(np.int64)
bboxes = bboxes[:, 1:]
outputs['bboxes'] = bboxes
outputs['ids'] = ids
else:
raise NotImplementedError(
f'Not supported bbox shape: (N, {bboxes.shape[1]})')
if mask_results is not None:
assert mask_shape is not None
mask_height, mask_width = mask_shape
mask_results = mmcv.concat_list(mask_results)
if len(mask_results) == 0:
masks = np.zeros((0, mask_height, mask_width)).astype(bool)
else:
masks = np.stack(mask_results, axis=0)
outputs['masks'] = masks
return outputs | Restore the results (list of results of each category) into the results of the model forward. Args: bbox_results (list[np.ndarray]): Each list denotes bboxes of one category. mask_results (list[list[np.ndarray]]): Each outer list denotes masks of one category. Each inner list denotes one mask belonging to the category. Each mask has shape (h, w). mask_shape (tuple[int]): The shape (h, w) of mask. Returns: tuple: tracking results of each class. It may contain keys as belows: - bboxes (np.ndarray): shape (n, 5) - labels (np.ndarray): shape (n, ) - masks (np.ndarray): shape (n, h, w) - ids (np.ndarray): shape (n, ) |
19,960 | import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `depthwise_correlation` function. Write a Python function `def depthwise_correlation(x, kernel)` to solve the following problem:
Depthwise cross correlation. This function is proposed in `SiamRPN++ <https://arxiv.org/abs/1812.11703>`_. Args: x (Tensor): of shape (N, C, H_x, W_x). kernel (Tensor): of shape (N, C, H_k, W_k). Returns: Tensor: of shape (N, C, H_o, W_o). H_o = H_x - H_k + 1. So does W_o.
Here is the function:
def depthwise_correlation(x, kernel):
"""Depthwise cross correlation.
This function is proposed in
`SiamRPN++ <https://arxiv.org/abs/1812.11703>`_.
Args:
x (Tensor): of shape (N, C, H_x, W_x).
kernel (Tensor): of shape (N, C, H_k, W_k).
Returns:
Tensor: of shape (N, C, H_o, W_o). H_o = H_x - H_k + 1. So does W_o.
"""
batch = kernel.size(0)
channel = kernel.size(1)
x = x.view(1, batch * channel, x.size(2), x.size(3))
kernel = kernel.view(batch * channel, 1, kernel.size(2), kernel.size(3))
out = F.conv2d(x, kernel, groups=batch * channel)
out = out.view(batch, channel, out.size(2), out.size(3))
return out | Depthwise cross correlation. This function is proposed in `SiamRPN++ <https://arxiv.org/abs/1812.11703>`_. Args: x (Tensor): of shape (N, C, H_x, W_x). kernel (Tensor): of shape (N, C, H_k, W_k). Returns: Tensor: of shape (N, C, H_o, W_o). H_o = H_x - H_k + 1. So does W_o. |
19,961 | import torch
import torch.nn.functional as F
The provided code snippet includes necessary dependencies for implementing the `embed_similarity` function. Write a Python function `def embed_similarity(key_embeds, ref_embeds, method='dot_product', temperature=-1)` to solve the following problem:
Calculate feature similarity from embeddings. Args: key_embeds (Tensor): Shape (N1, C). ref_embeds (Tensor): Shape (N2, C). method (str, optional): Method to calculate the similarity, options are 'dot_product' and 'cosine'. Defaults to 'dot_product'. temperature (int, optional): Softmax temperature. Defaults to -1. Returns: Tensor: Similarity matrix of shape (N1, N2).
Here is the function:
def embed_similarity(key_embeds,
ref_embeds,
method='dot_product',
temperature=-1):
"""Calculate feature similarity from embeddings.
Args:
key_embeds (Tensor): Shape (N1, C).
ref_embeds (Tensor): Shape (N2, C).
method (str, optional): Method to calculate the similarity,
options are 'dot_product' and 'cosine'. Defaults to
'dot_product'.
temperature (int, optional): Softmax temperature. Defaults to -1.
Returns:
Tensor: Similarity matrix of shape (N1, N2).
"""
assert method in ['dot_product', 'cosine']
if method == 'cosine':
key_embeds = F.normalize(key_embeds, p=2, dim=1)
ref_embeds = F.normalize(ref_embeds, p=2, dim=1)
similarity = torch.mm(key_embeds, ref_embeds.T)
if temperature > 0:
similarity /= float(temperature)
return similarity | Calculate feature similarity from embeddings. Args: key_embeds (Tensor): Shape (N1, C). ref_embeds (Tensor): Shape (N2, C). method (str, optional): Method to calculate the similarity, options are 'dot_product' and 'cosine'. Defaults to 'dot_product'. temperature (int, optional): Softmax temperature. Defaults to -1. Returns: Tensor: Similarity matrix of shape (N1, N2). |
19,962 | import numpy as np
def _interpolate_track(track, track_id, max_num_frames=20):
"""Interpolate a track linearly to make the track more complete.
Args:
track (ndarray): With shape (N, 7). Each row denotes
(frame_id, track_id, x1, y1, x2, y2, score).
max_num_frames (int, optional): The maximum disconnected length in the
track. Defaults to 20.
Returns:
ndarray: The interpolated track with shape (N, 7). Each row denotes
(frame_id, track_id, x1, y1, x2, y2, score)
"""
assert (track[:, 1] == track_id).all(), \
'The track id should not changed when interpolate a track.'
frame_ids = track[:, 0]
interpolated_track = np.zeros((0, 7))
# perform interpolation for the disconnected frames in the track.
for i in np.where(np.diff(frame_ids) > 1)[0]:
left_frame_id = frame_ids[i]
right_frame_id = frame_ids[i + 1]
num_disconnected_frames = int(right_frame_id - left_frame_id)
if 1 < num_disconnected_frames < max_num_frames:
left_bbox = track[i, 2:6]
right_bbox = track[i + 1, 2:6]
# perform interpolation for two adjacent tracklets.
for j in range(1, num_disconnected_frames):
cur_bbox = j / (num_disconnected_frames) * (
right_bbox - left_bbox) + left_bbox
cur_result = np.ones((7, ))
cur_result[0] = j + left_frame_id
cur_result[1] = track_id
cur_result[2:6] = cur_bbox
interpolated_track = np.concatenate(
(interpolated_track, cur_result[None]), axis=0)
interpolated_track = np.concatenate((track, interpolated_track), axis=0)
return interpolated_track
The provided code snippet includes necessary dependencies for implementing the `interpolate_tracks` function. Write a Python function `def interpolate_tracks(tracks, min_num_frames=5, max_num_frames=20)` to solve the following problem:
Interpolate tracks linearly to make tracks more complete. This function is proposed in "ByteTrack: Multi-Object Tracking by Associating Every Detection Box." `ByteTrack<https://arxiv.org/abs/2110.06864>`_. Args: tracks (ndarray): With shape (N, 7). Each row denotes (frame_id, track_id, x1, y1, x2, y2, score). min_num_frames (int, optional): The minimum length of a track that will be interpolated. Defaults to 5. max_num_frames (int, optional): The maximum disconnected length in a track. Defaults to 20. Returns: ndarray: The interpolated tracks with shape (N, 7). Each row denotes (frame_id, track_id, x1, y1, x2, y2, score)
Here is the function:
def interpolate_tracks(tracks, min_num_frames=5, max_num_frames=20):
"""Interpolate tracks linearly to make tracks more complete.
This function is proposed in
"ByteTrack: Multi-Object Tracking by Associating Every Detection Box."
`ByteTrack<https://arxiv.org/abs/2110.06864>`_.
Args:
tracks (ndarray): With shape (N, 7). Each row denotes
(frame_id, track_id, x1, y1, x2, y2, score).
min_num_frames (int, optional): The minimum length of a track that will
be interpolated. Defaults to 5.
max_num_frames (int, optional): The maximum disconnected length in
a track. Defaults to 20.
Returns:
ndarray: The interpolated tracks with shape (N, 7). Each row denotes
(frame_id, track_id, x1, y1, x2, y2, score)
"""
max_track_id = int(np.max(tracks[:, 1]))
min_track_id = int(np.min(tracks[:, 1]))
# perform interpolation for each track
interpolated_tracks = []
for track_id in range(min_track_id, max_track_id + 1):
inds = tracks[:, 1] == track_id
track = tracks[inds]
num_frames = len(track)
if num_frames <= 2:
continue
if num_frames > min_num_frames:
interpolated_track = _interpolate_track(track, track_id,
max_num_frames)
else:
interpolated_track = track
interpolated_tracks.append(interpolated_track)
interpolated_tracks = np.concatenate(interpolated_tracks)
return interpolated_tracks[interpolated_tracks[:, 0].argsort()] | Interpolate tracks linearly to make tracks more complete. This function is proposed in "ByteTrack: Multi-Object Tracking by Associating Every Detection Box." `ByteTrack<https://arxiv.org/abs/2110.06864>`_. Args: tracks (ndarray): With shape (N, 7). Each row denotes (frame_id, track_id, x1, y1, x2, y2, score). min_num_frames (int, optional): The minimum length of a track that will be interpolated. Defaults to 5. max_num_frames (int, optional): The maximum disconnected length in a track. Defaults to 20. Returns: ndarray: The interpolated tracks with shape (N, 7). Each row denotes (frame_id, track_id, x1, y1, x2, y2, score) |
19,963 | import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `crop_image` function. Write a Python function `def crop_image(image, crop_region, crop_size, padding=(0, 0, 0))` to solve the following problem:
Crop image based on `crop_region` and `crop_size`. Args: image (ndarray): of shape (H, W, 3). crop_region (ndarray): of shape (4, ) in [x1, y1, x2, y2] format. crop_size (int): Crop size. padding (tuple | ndarray): of shape (3, ) denoting the padding values. Returns: ndarray: Cropped image of shape (crop_size, crop_size, 3).
Here is the function:
def crop_image(image, crop_region, crop_size, padding=(0, 0, 0)):
"""Crop image based on `crop_region` and `crop_size`.
Args:
image (ndarray): of shape (H, W, 3).
crop_region (ndarray): of shape (4, ) in [x1, y1, x2, y2] format.
crop_size (int): Crop size.
padding (tuple | ndarray): of shape (3, ) denoting the padding values.
Returns:
ndarray: Cropped image of shape (crop_size, crop_size, 3).
"""
a = crop_size / (crop_region[2] - crop_region[0])
b = crop_size / (crop_region[3] - crop_region[1])
c = -a * crop_region[0]
d = -b * crop_region[1]
mapping = np.array([[a, 0, c], [0, b, d]]).astype(np.float32)
crop_image = cv2.warpAffine(
image,
mapping, (crop_size, crop_size),
borderMode=cv2.BORDER_CONSTANT,
borderValue=padding)
return crop_image | Crop image based on `crop_region` and `crop_size`. Args: image (ndarray): of shape (H, W, 3). crop_region (ndarray): of shape (4, ) in [x1, y1, x2, y2] format. crop_size (int): Crop size. padding (tuple | ndarray): of shape (3, ) denoting the padding values. Returns: ndarray: Cropped image of shape (crop_size, crop_size, 3). |
19,964 | import os.path as osp
import random
import cv2
import matplotlib
import matplotlib.pyplot as plt
import mmcv
import numpy as np
import seaborn as sns
from matplotlib.patches import Rectangle
from mmcv.utils import mkdir_or_exist
def _cv2_show_tracks(img,
bboxes,
labels,
ids,
masks=None,
classes=None,
score_thr=0.0,
thickness=2,
font_scale=0.4,
show=False,
wait_time=0,
out_file=None):
"""Show the tracks with opencv."""
assert bboxes.ndim == 2
assert labels.ndim == 1
assert ids.ndim == 1
assert bboxes.shape[0] == labels.shape[0]
assert bboxes.shape[1] == 5
if isinstance(img, str):
img = mmcv.imread(img)
img_shape = img.shape
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
inds = np.where(bboxes[:, -1] > score_thr)[0]
bboxes = bboxes[inds]
labels = labels[inds]
ids = ids[inds]
if masks is not None:
assert masks.ndim == 3
masks = masks[inds]
assert masks.shape[0] == bboxes.shape[0]
text_width, text_height = 9, 13
for i, (bbox, label, id) in enumerate(zip(bboxes, labels, ids)):
x1, y1, x2, y2 = bbox[:4].astype(np.int32)
score = float(bbox[-1])
# bbox
bbox_color = random_color(id)
bbox_color = [int(255 * _c) for _c in bbox_color][::-1]
cv2.rectangle(img, (x1, y1), (x2, y2), bbox_color, thickness=thickness)
# score
text = '{:.02f}'.format(score)
if classes is not None:
text += f'|{classes[label]}'
width = len(text) * text_width
img[y1:y1 + text_height, x1:x1 + width, :] = bbox_color
cv2.putText(
img,
text, (x1, y1 + text_height - 2),
cv2.FONT_HERSHEY_COMPLEX,
font_scale,
color=(0, 0, 0))
# id
text = str(id)
width = len(text) * text_width
img[y1 + text_height:y1 + 2 * text_height,
x1:x1 + width, :] = bbox_color
cv2.putText(
img,
str(id), (x1, y1 + 2 * text_height - 2),
cv2.FONT_HERSHEY_COMPLEX,
font_scale,
color=(0, 0, 0))
# mask
if masks is not None:
mask = masks[i].astype(bool)
mask_color = np.array(bbox_color, dtype=np.uint8).reshape(1, -1)
img[mask] = img[mask] * 0.5 + mask_color * 0.5
if show:
mmcv.imshow(img, wait_time=wait_time)
if out_file is not None:
mmcv.imwrite(img, out_file)
return img
def _plt_show_tracks(img,
bboxes,
labels,
ids,
masks=None,
classes=None,
score_thr=0.0,
thickness=0.1,
font_scale=5,
show=False,
wait_time=0,
out_file=None):
"""Show the tracks with matplotlib."""
assert bboxes.ndim == 2
assert labels.ndim == 1
assert ids.ndim == 1
assert bboxes.shape[0] == ids.shape[0]
assert bboxes.shape[1] == 5
if isinstance(img, str):
img = plt.imread(img)
else:
img = mmcv.bgr2rgb(img)
img_shape = img.shape
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
inds = np.where(bboxes[:, -1] > score_thr)[0]
bboxes = bboxes[inds]
labels = labels[inds]
ids = ids[inds]
if masks is not None:
assert masks.ndim == 3
masks = masks[inds]
assert masks.shape[0] == bboxes.shape[0]
if not show:
matplotlib.use('Agg')
plt.imshow(img)
plt.gca().set_axis_off()
plt.autoscale(False)
plt.subplots_adjust(
top=1, bottom=0, right=1, left=0, hspace=None, wspace=None)
plt.margins(0, 0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.rcParams['figure.figsize'] = img_shape[1], img_shape[0]
text_width, text_height = 12, 16
for i, (bbox, label, id) in enumerate(zip(bboxes, labels, ids)):
x1, y1, x2, y2 = bbox[:4].astype(np.int32)
score = float(bbox[-1])
w, h = int(x2 - x1), int(y2 - y1)
# bbox
bbox_color = random_color(id)
plt.gca().add_patch(
Rectangle((x1, y1),
w,
h,
thickness,
edgecolor=bbox_color,
facecolor='none'))
# score
text = '{:.02f}'.format(score)
if classes is not None:
text += f'|{classes[label]}'
width = len(text) * text_width
plt.gca().add_patch(
Rectangle((x1, y1),
width,
text_height,
thickness,
edgecolor=bbox_color,
facecolor=bbox_color))
plt.text(x1, y1 + text_height, text, fontsize=5)
# id
text = str(id)
width = len(text) * text_width
plt.gca().add_patch(
Rectangle((x1, y1 + text_height + 1),
width,
text_height,
thickness,
edgecolor=bbox_color,
facecolor=bbox_color))
plt.text(x1, y1 + 2 * text_height + 2, text, fontsize=5)
# mask
if masks is not None:
mask = masks[i].astype(bool)
bbox_color = [int(255 * _c) for _c in bbox_color]
mask_color = np.array(bbox_color, dtype=np.uint8).reshape(1, -1)
img[mask] = img[mask] * 0.5 + mask_color * 0.5
# In order to show the mask.
plt.imshow(img)
if out_file is not None:
plt.savefig(out_file, dpi=300, bbox_inches='tight', pad_inches=0.0)
if show:
plt.draw()
plt.pause(wait_time / 1000.)
else:
plt.show()
plt.clf()
return img
The provided code snippet includes necessary dependencies for implementing the `imshow_tracks` function. Write a Python function `def imshow_tracks(*args, backend='cv2', **kwargs)` to solve the following problem:
Show the tracks on the input image.
Here is the function:
def imshow_tracks(*args, backend='cv2', **kwargs):
"""Show the tracks on the input image."""
if backend == 'cv2':
return _cv2_show_tracks(*args, **kwargs)
elif backend == 'plt':
return _plt_show_tracks(*args, **kwargs)
else:
raise NotImplementedError() | Show the tracks on the input image. |
19,965 | import os.path as osp
import random
import cv2
import matplotlib
import matplotlib.pyplot as plt
import mmcv
import numpy as np
import seaborn as sns
from matplotlib.patches import Rectangle
from mmcv.utils import mkdir_or_exist
def _cv2_show_wrong_tracks(img,
bboxes,
ids,
error_types,
thickness=2,
font_scale=0.4,
text_width=10,
text_height=15,
show=False,
wait_time=100,
out_file=None):
"""Show the wrong tracks with opencv.
Args:
img (str or ndarray): The image to be displayed.
bboxes (ndarray): A ndarray of shape (k, 5).
ids (ndarray): A ndarray of shape (k, ).
error_types (ndarray): A ndarray of shape (k, ), where 0 denotes
false positives, 1 denotes false negative and 2 denotes ID switch.
thickness (int, optional): Thickness of lines.
Defaults to 2.
font_scale (float, optional): Font scale to draw id and score.
Defaults to 0.4.
text_width (int, optional): Width to draw id and score.
Defaults to 10.
text_height (int, optional): Height to draw id and score.
Defaults to 15.
show (bool, optional): Whether to show the image on the fly.
Defaults to False.
wait_time (int, optional): Value of waitKey param.
Defaults to 100.
out_file (str, optional): The filename to write the image.
Defaults to None.
Returns:
ndarray: Visualized image.
"""
assert bboxes.ndim == 2, \
f' bboxes ndim should be 2, but its ndim is {bboxes.ndim}.'
assert ids.ndim == 1, \
f' ids ndim should be 1, but its ndim is {ids.ndim}.'
assert error_types.ndim == 1, \
f' error_types ndim should be 1, but its ndim is {error_types.ndim}.'
assert bboxes.shape[0] == ids.shape[0], \
'bboxes.shape[0] and ids.shape[0] should have the same length.'
assert bboxes.shape[1] == 5, \
f' bboxes.shape[1] should be 5, but its {bboxes.shape[1]}.'
bbox_colors = sns.color_palette()
# red, yellow, blue
bbox_colors = [bbox_colors[3], bbox_colors[1], bbox_colors[0]]
bbox_colors = [[int(255 * _c) for _c in bbox_color][::-1]
for bbox_color in bbox_colors]
if isinstance(img, str):
img = mmcv.imread(img)
else:
assert img.ndim == 3
img_shape = img.shape
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
for bbox, error_type, id in zip(bboxes, error_types, ids):
x1, y1, x2, y2 = bbox[:4].astype(np.int32)
score = float(bbox[-1])
# bbox
bbox_color = bbox_colors[error_type]
cv2.rectangle(img, (x1, y1), (x2, y2), bbox_color, thickness=thickness)
# FN does not have id and score
if error_type == 1:
continue
# score
text = '{:.02f}'.format(score)
width = (len(text) - 1) * text_width
img[y1:y1 + text_height, x1:x1 + width, :] = bbox_color
cv2.putText(
img,
text, (x1, y1 + text_height - 2),
cv2.FONT_HERSHEY_COMPLEX,
font_scale,
color=(0, 0, 0))
# id
text = str(id)
width = len(text) * text_width
img[y1 + text_height:y1 + text_height * 2,
x1:x1 + width, :] = bbox_color
cv2.putText(
img,
str(id), (x1, y1 + text_height * 2 - 2),
cv2.FONT_HERSHEY_COMPLEX,
font_scale,
color=(0, 0, 0))
if show:
mmcv.imshow(img, wait_time=wait_time)
if out_file is not None:
mmcv.imwrite(img, out_file)
return img
def _plt_show_wrong_tracks(img,
bboxes,
ids,
error_types,
thickness=0.1,
font_scale=3,
text_width=8,
text_height=13,
show=False,
wait_time=100,
out_file=None):
"""Show the wrong tracks with matplotlib.
Args:
img (str or ndarray): The image to be displayed.
bboxes (ndarray): A ndarray of shape (k, 5).
ids (ndarray): A ndarray of shape (k, ).
error_types (ndarray): A ndarray of shape (k, ), where 0 denotes
false positives, 1 denotes false negative and 2 denotes ID switch.
thickness (float, optional): Thickness of lines.
Defaults to 0.1.
font_scale (float, optional): Font scale to draw id and score.
Defaults to 3.
text_width (int, optional): Width to draw id and score.
Defaults to 8.
text_height (int, optional): Height to draw id and score.
Defaults to 13.
show (bool, optional): Whether to show the image on the fly.
Defaults to False.
wait_time (int, optional): Value of waitKey param.
Defaults to 100.
out_file (str, optional): The filename to write the image.
Defaults to None.
Returns:
ndarray: Original image.
"""
assert bboxes.ndim == 2, \
f' bboxes ndim should be 2, but its ndim is {bboxes.ndim}.'
assert ids.ndim == 1, \
f' ids ndim should be 1, but its ndim is {ids.ndim}.'
assert error_types.ndim == 1, \
f' error_types ndim should be 1, but its ndim is {error_types.ndim}.'
assert bboxes.shape[0] == ids.shape[0], \
'bboxes.shape[0] and ids.shape[0] should have the same length.'
assert bboxes.shape[1] == 5, \
f' bboxes.shape[1] should be 5, but its {bboxes.shape[1]}.'
bbox_colors = sns.color_palette()
# red, yellow, blue
bbox_colors = [bbox_colors[3], bbox_colors[1], bbox_colors[0]]
if isinstance(img, str):
img = plt.imread(img)
else:
assert img.ndim == 3
img = mmcv.bgr2rgb(img)
img_shape = img.shape
bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
plt.imshow(img)
plt.gca().set_axis_off()
plt.autoscale(False)
plt.subplots_adjust(
top=1, bottom=0, right=1, left=0, hspace=None, wspace=None)
plt.margins(0, 0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.rcParams['figure.figsize'] = img_shape[1], img_shape[0]
for bbox, error_type, id in zip(bboxes, error_types, ids):
x1, y1, x2, y2, score = bbox
w, h = int(x2 - x1), int(y2 - y1)
left_top = (int(x1), int(y1))
# bbox
plt.gca().add_patch(
Rectangle(
left_top,
w,
h,
thickness,
edgecolor=bbox_colors[error_type],
facecolor='none'))
# FN does not have id and score
if error_type == 1:
continue
# score
text = '{:.02f}'.format(score)
width = len(text) * text_width
plt.gca().add_patch(
Rectangle((left_top[0], left_top[1]),
width,
text_height,
thickness,
edgecolor=bbox_colors[error_type],
facecolor=bbox_colors[error_type]))
plt.text(
left_top[0],
left_top[1] + text_height + 2,
text,
fontsize=font_scale)
# id
text = str(id)
width = len(text) * text_width
plt.gca().add_patch(
Rectangle((left_top[0], left_top[1] + text_height + 1),
width,
text_height,
thickness,
edgecolor=bbox_colors[error_type],
facecolor=bbox_colors[error_type]))
plt.text(
left_top[0],
left_top[1] + 2 * (text_height + 1),
text,
fontsize=font_scale)
if out_file is not None:
mkdir_or_exist(osp.abspath(osp.dirname(out_file)))
plt.savefig(out_file, dpi=300, bbox_inches='tight', pad_inches=0.0)
if show:
plt.draw()
plt.pause(wait_time / 1000.)
plt.clf()
return img
The provided code snippet includes necessary dependencies for implementing the `imshow_mot_errors` function. Write a Python function `def imshow_mot_errors(*args, backend='cv2', **kwargs)` to solve the following problem:
Show the wrong tracks on the input image. Args: backend (str, optional): Backend of visualization. Defaults to 'cv2'.
Here is the function:
def imshow_mot_errors(*args, backend='cv2', **kwargs):
"""Show the wrong tracks on the input image.
Args:
backend (str, optional): Backend of visualization.
Defaults to 'cv2'.
"""
if backend == 'cv2':
return _cv2_show_wrong_tracks(*args, **kwargs)
elif backend == 'plt':
return _plt_show_wrong_tracks(*args, **kwargs)
else:
raise NotImplementedError() | Show the wrong tracks on the input image. Args: backend (str, optional): Backend of visualization. Defaults to 'cv2'. |
19,966 | import collections.abc as container_abcs
import multiprocessing as mp
import os
import platform
import warnings
from itertools import repeat
import cv2
def setup_multi_processes(cfg):
# set multi-process start method as `fork` to speed up the training
if platform.system() != 'Windows':
mp_start_method = cfg.get('mp_start_method', 'fork')
mp.set_start_method(mp_start_method)
# disable opencv multithreading to avoid system being overloaded
opencv_num_threads = cfg.get('opencv_num_threads', 0)
cv2.setNumThreads(opencv_num_threads)
# setup OMP threads
# This code is referred from https://github.com/pytorch/pytorch/blob/master/torch/distributed/run.py # noqa
if ('OMP_NUM_THREADS' not in os.environ and cfg.data.workers_per_gpu > 1):
omp_num_threads = 1
warnings.warn(
f'Setting OMP_NUM_THREADS environment variable for each process '
f'to be {omp_num_threads} in default, to avoid your system being '
f'overloaded, please further tune the variable for optimal '
f'performance in your application as needed.')
os.environ['OMP_NUM_THREADS'] = str(omp_num_threads)
# setup MKL threads
if 'MKL_NUM_THREADS' not in os.environ and cfg.data.workers_per_gpu > 1:
mkl_num_threads = 1
warnings.warn(
f'Setting MKL_NUM_THREADS environment variable for each process '
f'to be {mkl_num_threads} in default, to avoid your system being '
f'overloaded, please further tune the variable for optimal '
f'performance in your application as needed.')
os.environ['MKL_NUM_THREADS'] = str(mkl_num_threads) | null |
19,967 | import collections.abc as container_abcs
import multiprocessing as mp
import os
import platform
import warnings
from itertools import repeat
import cv2
def ntuple(n):
def parse(x):
if isinstance(x, container_abcs.Iterable):
return x
return tuple(repeat(x, n))
return parse | null |
19,968 | import random
import warnings
from functools import partial
import numpy as np
import torch
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import TORCH_VERSION, digit_version
from mmdet.datasets.samplers import (DistributedGroupSampler,
DistributedSampler, GroupSampler)
from torch.utils.data import DataLoader
from torch.utils.data.sampler import RandomSampler
from mmtrack.datasets.samplers.quota_sampler import DistributedQuotaSampler
from .base_sot_dataset import BaseSOTDataset
from .samplers import DistributedVideoSampler, SOTVideoSampler
def worker_init_fn(worker_id, num_workers, rank, seed):
# The seed of each worker equals to
# num_worker * rank + worker_id + user_seed
worker_seed = num_workers * rank + worker_id + seed
np.random.seed(worker_seed)
random.seed(worker_seed)
torch.manual_seed(worker_seed)
class DistributedQuotaSampler(Sampler):
"""Sampler that gets fixed number of samples per epoch.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
process can pass a DistributedSampler instance as a DataLoader sampler,
and load a subset of the original dataset that is exclusive to it.
.. note::
Dataset is assumed to be of constant size.
Args:
dataset: Dataset used for sampling.
samples_per_epoch (int): The number of samples per epoch.
num_replicas (optional): Number of processes participating in
distributed training.
rank (optional): Rank of the current process within num_replicas.
replacement (bool): samples are drawn with replacement if ``True``,
Default: False.
seed (int, optional): random seed used to shuffle the sampler if
``shuffle=True``. This number should be identical across all
processes in the distributed group. Default: 0.
"""
def __init__(self,
dataset,
samples_per_epoch,
num_replicas=None,
rank=None,
replacement=False,
seed=0):
_rank, _num_replicas = get_dist_info()
if num_replicas is None:
num_replicas = _num_replicas
if rank is None:
rank = _rank
self.dataset = dataset
self.samples_per_epoch = samples_per_epoch
self.num_replicas = num_replicas
self.rank = rank
self.epoch = 0
self.seed = seed if seed is not None else 0
self.replacement = replacement
self.num_samples = int(
math.ceil(samples_per_epoch * 1.0 / self.num_replicas))
self.total_size = self.num_samples * self.num_replicas
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch + self.seed)
# random sampling `self.samples_per_epoch` samples
if self.replacement:
indices = torch.randint(
len(self.dataset),
size=(self.samples_per_epoch, ),
dtype=torch.int64).tolist()
else:
indices = torch.randperm(len(self.dataset), generator=g)
if self.samples_per_epoch > len(self.dataset):
indices = indices.repeat(
int(math.ceil(self.samples_per_epoch / len(self.dataset))))
indices = indices[:self.samples_per_epoch].tolist()
# add extra samples to make it evenly divisible
indices += indices[:(self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank:self.total_size:self.num_replicas]
assert len(indices) == self.num_samples
return iter(indices)
def __len__(self):
return self.num_samples
def set_epoch(self, epoch):
self.epoch = epoch
class BaseSOTDataset(Dataset, metaclass=ABCMeta):
"""Dataset of single object tracking. The dataset can both support training
and testing mode.
Args:
img_prefix (str): Prefix in the paths of image files.
pipeline (list[dict]): Processing pipeline.
split (str): Dataset split.
ann_file (str, optional): The file contains data information. It will
be loaded and parsed in the `self.load_data_infos` function.
test_mode (bool, optional): Default to False.
bbox_min_size (int, optional): Only bounding boxes whose sizes are
larger than `bbox_min_size` can be regarded as valid. Default to 0.
only_eval_visible (bool, optional): Whether to only evaluate frames
where object are visible. Default to False.
file_client_args (dict, optional): Arguments to instantiate a
FileClient. Default: dict(backend='disk').
"""
# Compatible with MOT and VID Dataset class. The 'CLASSES' attribute will
# be called in tools/train.py.
CLASSES = None
def __init__(self,
img_prefix,
pipeline,
split,
ann_file=None,
test_mode=False,
bbox_min_size=0,
only_eval_visible=False,
file_client_args=dict(backend='disk'),
**kwargs):
self.img_prefix = img_prefix
self.split = split
self.pipeline = Compose(pipeline)
self.ann_file = ann_file
self.test_mode = test_mode
self.bbox_min_size = bbox_min_size
self.only_eval_visible = only_eval_visible
self.file_client_args = file_client_args
self.file_client = mmcv.FileClient(**file_client_args)
# 'self.load_as_video' must be set to True in order to using
# distributed video sampler to load dataset when testing.
self.load_as_video = True
''' The self.data_info is a list, which the length is the
number of videos. The default content is in the following format:
[
{
'video_path': the video path
'ann_path': the annotation path
'start_frame_id': the starting frame ID number contained in
the image name
'end_frame_id': the ending frame ID number contained in the
image name
'framename_template': the template of image name
},
...
]
'''
self.data_infos = self.load_data_infos(split=self.split)
self.num_frames_per_video = [
self.get_len_per_video(video_ind)
for video_ind in range(len(self.data_infos))
]
# used to record the video information at the beginning of the video
# test. Thus, we can avoid reloading the files of video information
# repeatedly in all frames of one video.
self.test_memo = Dict()
def __getitem__(self, ind):
if self.test_mode:
assert isinstance(ind, tuple)
# the first element in the tuple is the video index and the second
# element in the tuple is the frame index
return self.prepare_test_data(ind[0], ind[1])
else:
return self.prepare_train_data(ind)
def load_data_infos(self, split='train'):
pass
def loadtxt(self,
filepath,
dtype=float,
delimiter=None,
skiprows=0,
return_array=True):
file_string = self.file_client.get_text(filepath)
if return_array:
return np.loadtxt(
StringIO(file_string),
dtype=dtype,
delimiter=delimiter,
skiprows=skiprows)
else:
return file_string.strip()
def get_bboxes_from_video(self, video_ind):
"""Get bboxes annotation about the instance in a video.
Args:
video_ind (int): video index
Returns:
ndarray: in [N, 4] shape. The N is the number of bbox and the bbox
is in (x, y, w, h) format.
"""
bbox_path = osp.join(self.img_prefix,
self.data_infos[video_ind]['ann_path'])
bboxes = self.loadtxt(bbox_path, dtype=float, delimiter=',')
if len(bboxes.shape) == 1:
bboxes = np.expand_dims(bboxes, axis=0)
end_frame_id = self.data_infos[video_ind]['end_frame_id']
start_frame_id = self.data_infos[video_ind]['start_frame_id']
if not self.test_mode:
assert len(bboxes) == (
end_frame_id - start_frame_id + 1
), f'{len(bboxes)} is not equal to {end_frame_id}-{start_frame_id}+1' # noqa
return bboxes
def get_len_per_video(self, video_ind):
"""Get the number of frames in a video."""
return self.data_infos[video_ind]['end_frame_id'] - self.data_infos[
video_ind]['start_frame_id'] + 1
def get_visibility_from_video(self, video_ind):
"""Get the visible information of instance in a video."""
visible = np.array([True] * self.get_len_per_video(video_ind))
return dict(visible=visible)
def get_masks_from_video(self, video_ind):
pass
def get_ann_infos_from_video(self, video_ind):
"""Get annotation information in a video.
Args:
video_ind (int): video index
Returns:
dict: {'bboxes': ndarray in (N, 4) shape, 'bboxes_isvalid':
ndarray, 'visible':ndarray}. The annotation information in some
datasets may contain 'visible_ratio'. The bbox is in
(x1, y1, x2, y2) format.
"""
bboxes = self.get_bboxes_from_video(video_ind)
# The visible information in some datasets may contain
# 'visible_ratio'.
visible_info = self.get_visibility_from_video(video_ind)
bboxes_isvalid = (bboxes[:, 2] > self.bbox_min_size) & (
bboxes[:, 3] > self.bbox_min_size)
visible_info['visible'] = visible_info['visible'] & bboxes_isvalid
bboxes[:, 2:] += bboxes[:, :2]
ann_infos = dict(
bboxes=bboxes, bboxes_isvalid=bboxes_isvalid, **visible_info)
return ann_infos
def get_img_infos_from_video(self, video_ind):
"""Get image information in a video.
Args:
video_ind (int): video index
Returns:
dict: {'filename': list[str], 'frame_ids':ndarray, 'video_id':int}
"""
img_names = []
start_frame_id = self.data_infos[video_ind]['start_frame_id']
end_frame_id = self.data_infos[video_ind]['end_frame_id']
framename_template = self.data_infos[video_ind]['framename_template']
for frame_id in range(start_frame_id, end_frame_id + 1):
img_names.append(
osp.join(self.data_infos[video_ind]['video_path'],
framename_template % frame_id))
frame_ids = np.arange(self.get_len_per_video(video_ind))
img_infos = dict(
filename=img_names, frame_ids=frame_ids, video_id=video_ind)
return img_infos
def prepare_test_data(self, video_ind, frame_ind):
"""Get testing data of one frame. We parse one video, get one frame
from it and pass the frame information to the pipeline.
Args:
video_ind (int): video index
frame_ind (int): frame index
Returns:
dict: testing data of one frame.
"""
if self.test_memo.get('video_ind', None) != video_ind:
self.test_memo.video_ind = video_ind
self.test_memo.ann_infos = self.get_ann_infos_from_video(video_ind)
self.test_memo.img_infos = self.get_img_infos_from_video(video_ind)
assert 'video_ind' in self.test_memo and 'ann_infos' in \
self.test_memo and 'img_infos' in self.test_memo
img_info = dict(
filename=self.test_memo.img_infos['filename'][frame_ind],
frame_id=frame_ind)
ann_info = dict(
bboxes=self.test_memo.ann_infos['bboxes'][frame_ind],
visible=self.test_memo.ann_infos['visible'][frame_ind])
results = dict(img_info=img_info, ann_info=ann_info)
self.pre_pipeline(results)
results = self.pipeline(results)
return results
def prepare_train_data(self, video_ind):
"""Get training data sampled from some videos. We firstly sample two
videos from the dataset and then parse the data information. The first
operation in the training pipeline is frames sampling.
Args:
video_ind (int): video index
Returns:
dict: training data pairs, triplets or groups.
"""
while True:
video_inds = random.choices(list(range(len(self))), k=2)
pair_video_infos = []
for video_index in video_inds:
ann_infos = self.get_ann_infos_from_video(video_index)
img_infos = self.get_img_infos_from_video(video_index)
video_infos = dict(**ann_infos, **img_infos)
self.pre_pipeline(video_infos)
pair_video_infos.append(video_infos)
results = self.pipeline(pair_video_infos)
if results is not None:
return results
def pre_pipeline(self, results):
"""Prepare results dict for pipeline.
The following keys in dict will be called in the subsequent pipeline.
"""
results['img_prefix'] = self.img_prefix
results['bbox_fields'] = []
results['mask_fields'] = []
results['seg_fields'] = []
def __len__(self):
if self.test_mode:
return sum(self.num_frames_per_video)
else:
return len(self.data_infos)
def evaluate(self, results, metric=['track'], logger=None):
"""Default evaluation standard is OPE.
Args:
results (dict(list[ndarray])): tracking results. The ndarray is in
(x1, y1, x2, y2, score) format.
metric (list, optional): defaults to ['track'].
logger (logging.Logger | str | None, optional): defaults to None.
"""
if isinstance(metric, list):
metrics = metric
elif isinstance(metric, str):
metrics = [metric]
else:
raise TypeError('metric must be a list or a str.')
allowed_metrics = ['track']
for metric in metrics:
if metric not in allowed_metrics:
raise KeyError(f'metric {metric} is not supported.')
# get all test annotations
gt_bboxes = []
visible_infos = []
for video_ind in range(len(self.data_infos)):
video_anns = self.get_ann_infos_from_video(video_ind)
gt_bboxes.append(video_anns['bboxes'])
visible_infos.append(video_anns['visible'])
# tracking_bboxes converting code
eval_results = dict()
if 'track' in metrics:
assert len(self) == len(
results['track_bboxes']
), f"{len(self)} == {len(results['track_bboxes'])}"
print_log('Evaluate OPE Benchmark...', logger=logger)
track_bboxes = []
start_ind = end_ind = 0
for num in self.num_frames_per_video:
end_ind += num
track_bboxes.append(
list(
map(lambda x: x[:-1],
results['track_bboxes'][start_ind:end_ind])))
start_ind += num
if not self.only_eval_visible:
visible_infos = None
# evaluation
track_eval_results = eval_sot_ope(
results=track_bboxes,
annotations=gt_bboxes,
visible_infos=visible_infos)
eval_results.update(track_eval_results)
for k, v in eval_results.items():
if isinstance(v, float):
eval_results[k] = float(f'{(v):.3f}')
print_log(eval_results, logger=logger)
return eval_results
The provided code snippet includes necessary dependencies for implementing the `build_dataloader` function. Write a Python function `def build_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, samples_per_epoch=None, dist=True, shuffle=True, seed=None, persistent_workers=False, **kwargs)` to solve the following problem:
Build PyTorch DataLoader. In distributed training, each GPU/process has a dataloader. In non-distributed training, there is only one dataloader for all GPUs. Args: dataset (Dataset): A PyTorch dataset. samples_per_gpu (int): Number of training samples on each GPU, i.e., batch size of each GPU. workers_per_gpu (int): How many subprocesses to use for data loading for each GPU. num_gpus (int): Number of GPUs. Only used in non-distributed training. samples_per_epoch (int | None, Optional): The number of samples per epoch. If equal to -1, using all samples in the datasets per epoch. Otherwise, using the `samples_per_epoch` samples. Default: None. dist (bool): Distributed training/test or not. Default: True. shuffle (bool): Whether to shuffle the data at every epoch. Default: True. seed (int, Optional): Seed to be used. Default: None. persistent_workers (bool): If True, the data loader will not shutdown the worker processes after a dataset has been consumed once. This allows to maintain the workers `Dataset` instances alive. This argument is only valid when PyTorch>=1.7.0. Default: False. kwargs: any keyword argument to be used to initialize DataLoader Returns: DataLoader: A PyTorch dataloader.
Here is the function:
def build_dataloader(dataset,
samples_per_gpu,
workers_per_gpu,
num_gpus=1,
samples_per_epoch=None,
dist=True,
shuffle=True,
seed=None,
persistent_workers=False,
**kwargs):
"""Build PyTorch DataLoader.
In distributed training, each GPU/process has a dataloader.
In non-distributed training, there is only one dataloader for all GPUs.
Args:
dataset (Dataset): A PyTorch dataset.
samples_per_gpu (int): Number of training samples on each GPU, i.e.,
batch size of each GPU.
workers_per_gpu (int): How many subprocesses to use for data loading
for each GPU.
num_gpus (int): Number of GPUs. Only used in non-distributed training.
samples_per_epoch (int | None, Optional): The number of samples per
epoch. If equal to -1, using all samples in the datasets per epoch.
Otherwise, using the `samples_per_epoch` samples. Default: None.
dist (bool): Distributed training/test or not. Default: True.
shuffle (bool): Whether to shuffle the data at every epoch.
Default: True.
seed (int, Optional): Seed to be used. Default: None.
persistent_workers (bool): If True, the data loader will not shutdown
the worker processes after a dataset has been consumed once.
This allows to maintain the workers `Dataset` instances alive.
This argument is only valid when PyTorch>=1.7.0. Default: False.
kwargs: any keyword argument to be used to initialize DataLoader
Returns:
DataLoader: A PyTorch dataloader.
"""
rank, world_size = get_dist_info()
def is_base_sot_dataset(_dataset):
# handle the case: `_dataset` is a wrapper of normal dataset, such as
# 'RepeatDataset', 'ClassBalancedDataset' and so on.
if hasattr(_dataset, 'dataset'):
return is_base_sot_dataset(_dataset.dataset)
# handle the case: `_dataset` is a wrapper of concatenated dataset,
# such as `ConcatDataset`, `RandomSampleConcatDataset` and so on.
elif hasattr(_dataset, 'datasets'):
return is_base_sot_dataset(_dataset.datasets[0])
else:
return isinstance(_dataset, BaseSOTDataset)
# We set specific data sampler for SOT datasets.
is_sot_dataset = is_base_sot_dataset(dataset)
if dist:
# ----- distributed train mode ------
if shuffle:
if is_sot_dataset:
if samples_per_epoch is None:
sampler = DistributedSampler(
dataset, world_size, rank, shuffle=True)
else:
# get fixed number of samples per epoch to train
# sampling with no-replacement mode
sampler = DistributedQuotaSampler(
dataset,
samples_per_epoch,
world_size,
rank,
replacement=False)
else:
sampler = DistributedGroupSampler(dataset, samples_per_gpu,
world_size, rank)
# ----- distributed test mode ------
else:
if hasattr(dataset, 'load_as_video') and dataset.load_as_video:
# sample videos
sampler = DistributedVideoSampler(
dataset, world_size, rank, shuffle=False)
else:
sampler = DistributedSampler(
dataset, world_size, rank, shuffle=False)
batch_size = samples_per_gpu
num_workers = workers_per_gpu
else:
# ----- non-distributed train mode ------
if shuffle:
if is_sot_dataset:
if samples_per_epoch is None:
sampler = RandomSampler(dataset)
else:
# get fixed number of samples per epoch to train
# sampling with replacement mode
sampler = RandomSampler(
dataset,
replacement=True,
num_samples=samples_per_epoch)
else:
sampler = GroupSampler(dataset, samples_per_gpu)
# ----- non-distributed test mode ------
else:
sampler = SOTVideoSampler(dataset) if is_sot_dataset else None
batch_size = num_gpus * samples_per_gpu
num_workers = num_gpus * workers_per_gpu
init_fn = partial(
worker_init_fn, num_workers=num_workers, rank=rank,
seed=seed) if seed is not None else None
if (TORCH_VERSION != 'parrots'
and digit_version(TORCH_VERSION) >= digit_version('1.7.0')):
kwargs['persistent_workers'] = persistent_workers
elif persistent_workers is True:
warnings.warn('persistent_workers is invalid because your pytorch '
'version is lower than 1.7.0')
data_loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=sampler,
num_workers=num_workers,
collate_fn=partial(collate, samples_per_gpu=samples_per_gpu),
pin_memory=False,
worker_init_fn=init_fn,
**kwargs)
return data_loader | Build PyTorch DataLoader. In distributed training, each GPU/process has a dataloader. In non-distributed training, there is only one dataloader for all GPUs. Args: dataset (Dataset): A PyTorch dataset. samples_per_gpu (int): Number of training samples on each GPU, i.e., batch size of each GPU. workers_per_gpu (int): How many subprocesses to use for data loading for each GPU. num_gpus (int): Number of GPUs. Only used in non-distributed training. samples_per_epoch (int | None, Optional): The number of samples per epoch. If equal to -1, using all samples in the datasets per epoch. Otherwise, using the `samples_per_epoch` samples. Default: None. dist (bool): Distributed training/test or not. Default: True. shuffle (bool): Whether to shuffle the data at every epoch. Default: True. seed (int, Optional): Seed to be used. Default: None. persistent_workers (bool): If True, the data loader will not shutdown the worker processes after a dataset has been consumed once. This allows to maintain the workers `Dataset` instances alive. This argument is only valid when PyTorch>=1.7.0. Default: False. kwargs: any keyword argument to be used to initialize DataLoader Returns: DataLoader: A PyTorch dataloader. |
19,969 | import numpy as np
import torch
import torch.nn as nn
from mmdet.models import LOSSES, weighted_loss
The provided code snippet includes necessary dependencies for implementing the `l2_loss` function. Write a Python function `def l2_loss(pred, target)` to solve the following problem:
L2 loss. Args: pred (torch.Tensor): The prediction. target (torch.Tensor): The learning target of the prediction. Returns: torch.Tensor: Calculated loss
Here is the function:
def l2_loss(pred, target):
"""L2 loss.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
Returns:
torch.Tensor: Calculated loss
"""
assert pred.size() == target.size()
loss = torch.abs(pred - target)**2
return loss | L2 loss. Args: pred (torch.Tensor): The prediction. target (torch.Tensor): The learning target of the prediction. Returns: torch.Tensor: Calculated loss |
19,970 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.utils import Registry
TRACKERS = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_tracker` function. Write a Python function `def build_tracker(cfg)` to solve the following problem:
Build tracker.
Here is the function:
def build_tracker(cfg):
"""Build tracker."""
return TRACKERS.build(cfg) | Build tracker. |
19,971 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.utils import Registry
MOTION = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_motion` function. Write a Python function `def build_motion(cfg)` to solve the following problem:
Build motion model.
Here is the function:
def build_motion(cfg):
"""Build motion model."""
return MOTION.build(cfg) | Build motion model. |
19,972 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.utils import Registry
REID = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_reid` function. Write a Python function `def build_reid(cfg)` to solve the following problem:
Build reid model.
Here is the function:
def build_reid(cfg):
"""Build reid model."""
return REID.build(cfg) | Build reid model. |
19,973 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.utils import Registry
AGGREGATORS = MODELS
The provided code snippet includes necessary dependencies for implementing the `build_aggregator` function. Write a Python function `def build_aggregator(cfg)` to solve the following problem:
Build aggregator model.
Here is the function:
def build_aggregator(cfg):
"""Build aggregator model."""
return AGGREGATORS.build(cfg) | Build aggregator model. |
19,974 | from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.utils import Registry
MODELS = Registry('models', parent=MMCV_MODELS)
The provided code snippet includes necessary dependencies for implementing the `build_model` function. Write a Python function `def build_model(cfg, train_cfg=None, test_cfg=None)` to solve the following problem:
Build model.
Here is the function:
def build_model(cfg, train_cfg=None, test_cfg=None):
"""Build model."""
if train_cfg is None and test_cfg is None:
return MODELS.build(cfg)
else:
return MODELS.build(cfg, MODELS,
dict(train_cfg=train_cfg, test_cfg=test_cfg)) | Build model. |
19,975 | from mmcv.utils import collect_env as collect_base_env
from mmcv.utils import get_git_hash
import mmtrack
The provided code snippet includes necessary dependencies for implementing the `collect_env` function. Write a Python function `def collect_env()` to solve the following problem:
Collect the information of the running environments.
Here is the function:
def collect_env():
"""Collect the information of the running environments."""
env_info = collect_base_env()
env_info['MMTracking'] = mmtrack.__version__ + '+' + get_git_hash()[:7]
return env_info | Collect the information of the running environments. |
19,976 | import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
dp_factory = {'cuda': MMDataParallel, 'cpu': MMDataParallel}
The provided code snippet includes necessary dependencies for implementing the `build_dp` function. Write a Python function `def build_dp(model, device='cuda', dim=0, *args, **kwargs)` to solve the following problem:
build DataParallel module by device type. if device is cuda, return a MMDataParallel model; if device is npu, return a NPUDataParallel model. Args: model (:class:`nn.Module`): model to be parallelized. device (str): device type, cuda, cpu or npu. Defaults to cuda. dim (int): Dimension used to scatter the data. Defaults to 0. Returns: nn.Module: the model to be parallelized.
Here is the function:
def build_dp(model, device='cuda', dim=0, *args, **kwargs):
"""build DataParallel module by device type.
if device is cuda, return a MMDataParallel model; if device is npu,
return a NPUDataParallel model.
Args:
model (:class:`nn.Module`): model to be parallelized.
device (str): device type, cuda, cpu or npu. Defaults to cuda.
dim (int): Dimension used to scatter the data. Defaults to 0.
Returns:
nn.Module: the model to be parallelized.
"""
if device == 'npu':
from mmcv.device.npu import NPUDataParallel
dp_factory['npu'] = NPUDataParallel
torch.npu.set_device(kwargs['device_ids'][0])
torch.npu.set_compile_mode(jit_compile=False)
model = model.npu()
elif device == 'cuda':
model = model.cuda(kwargs['device_ids'][0])
return dp_factory[device](model, dim=dim, *args, **kwargs) | build DataParallel module by device type. if device is cuda, return a MMDataParallel model; if device is npu, return a NPUDataParallel model. Args: model (:class:`nn.Module`): model to be parallelized. device (str): device type, cuda, cpu or npu. Defaults to cuda. dim (int): Dimension used to scatter the data. Defaults to 0. Returns: nn.Module: the model to be parallelized. |
19,977 | import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
ddp_factory = {'cuda': MMDistributedDataParallel}
The provided code snippet includes necessary dependencies for implementing the `build_ddp` function. Write a Python function `def build_ddp(model, device='cuda', *args, **kwargs)` to solve the following problem:
Build DistributedDataParallel module by device type. If device is cuda, return a MMDistributedDataParallel model; if device is npu, return a NPUDistributedDataParallel model. Args: model (:class:`nn.Module`): module to be parallelized. device (str): device type, npu or cuda. Returns: :class:`nn.Module`: the module to be parallelized References: .. [1] https://pytorch.org/docs/stable/generated/torch.nn.parallel. DistributedDataParallel.html
Here is the function:
def build_ddp(model, device='cuda', *args, **kwargs):
"""Build DistributedDataParallel module by device type.
If device is cuda, return a MMDistributedDataParallel model;
if device is npu, return a NPUDistributedDataParallel model.
Args:
model (:class:`nn.Module`): module to be parallelized.
device (str): device type, npu or cuda.
Returns:
:class:`nn.Module`: the module to be parallelized
References:
.. [1] https://pytorch.org/docs/stable/generated/torch.nn.parallel.
DistributedDataParallel.html
"""
assert device in ['cuda', 'npu'], 'Only available for cuda or npu devices.'
if device == 'npu':
from mmcv.device.npu import NPUDistributedDataParallel
torch.npu.set_compile_mode(jit_compile=False)
ddp_factory['npu'] = NPUDistributedDataParallel
model = model.npu()
elif device == 'cuda':
model = model.cuda()
return ddp_factory[device](model, *args, **kwargs) | Build DistributedDataParallel module by device type. If device is cuda, return a MMDistributedDataParallel model; if device is npu, return a NPUDistributedDataParallel model. Args: model (:class:`nn.Module`): module to be parallelized. device (str): device type, npu or cuda. Returns: :class:`nn.Module`: the module to be parallelized References: .. [1] https://pytorch.org/docs/stable/generated/torch.nn.parallel. DistributedDataParallel.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.