id
int64 0
190k
| prompt
stringlengths 21
13.4M
| docstring
stringlengths 1
12k
⌀ |
---|---|---|
702 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def merge_quotes(t):
return re.sub('(\s*"+\s*)+', ' " ', t) | null |
703 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def remove_comma_numbers(t):
def _f(t):
return re.sub("(\d),(\d{3})", r"\1\2", t)
return _f(_f(t)) | null |
704 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
temp_token = "xtokx"
def pre_process_dot_numbers(t):
return re.sub("(\w)\.(\w)", rf"\1{temp_token}dot{temp_token}\2", t) | null |
705 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
temp_token = "xtokx"
def post_process_dot_numbers(t):
return re.sub(f"{temp_token}dot{temp_token}", ".", t) | null |
706 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
temp_token = "xtokx"
def pre_process_quotes(t):
# allows quotes only for 's, 't, 'd, 'm, 'll, 're, 've
return re.sub(
r"'(?=([stdm]|(ll)|(re)|(ve)|(ll))\b)", rf"{temp_token}quote{temp_token}", t
) | null |
707 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
temp_token = "xtokx"
def post_process_quotes(t):
return re.sub(f"{temp_token}quote{temp_token}", "'", t) | null |
708 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
temp_token = "xtokx"
def pre_process_dates(t):
return re.sub("(\d)/(\d)", rf"\1{temp_token}slash{temp_token}\2", t) | null |
709 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
temp_token = "xtokx"
def post_process_dates(t):
return re.sub(f"{temp_token}slash{temp_token}", "/", t) | null |
710 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def merge_commas(t):
return re.sub("(\s*,+\s*)+", ", ", t) | null |
711 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def add_space_after_commas(t):
return re.sub(",", ", ", t) | null |
712 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
The provided code snippet includes necessary dependencies for implementing the `handle_special_chars` function. Write a Python function `def handle_special_chars(t)` to solve the following problem:
Handle special characters
Here is the function:
def handle_special_chars(t):
"Handle special characters"
# replace "-" with a space when between words without space
t = re.sub("(\w)-(\w)", r"\1 \2", t)
# always add space around some characters
return re.sub("([%&\/$*])", r" \1 ", t) | Handle special characters |
713 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
The provided code snippet includes necessary dependencies for implementing the `expand_hashtags` function. Write a Python function `def expand_hashtags(t, hashtag_processor)` to solve the following problem:
Remove # and try to split words
Here is the function:
def expand_hashtags(t, hashtag_processor):
"Remove # and try to split words"
return re.sub("#(\w+)", lambda m: hashtag_processor(m.group(1)), t) | Remove # and try to split words |
714 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
_re_ignore_chars = r"[_#\\]"
The provided code snippet includes necessary dependencies for implementing the `ignore_chars` function. Write a Python function `def ignore_chars(t)` to solve the following problem:
Ignore useless characters
Here is the function:
def ignore_chars(t):
"Ignore useless characters"
return re.sub(_re_ignore_chars, " ", t) | Ignore useless characters |
715 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
The provided code snippet includes necessary dependencies for implementing the `remove_extra_spaces` function. Write a Python function `def remove_extra_spaces(t)` to solve the following problem:
Remove extra spaces (including \t and \n)
Here is the function:
def remove_extra_spaces(t):
"Remove extra spaces (including \t and \n)"
return re.sub("\s+", " ", t) | Remove extra spaces (including \t and \n) |
716 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
The provided code snippet includes necessary dependencies for implementing the `remove_repeating_chars` function. Write a Python function `def remove_repeating_chars(t)` to solve the following problem:
If the same character is present 4+ times (not 3 because of roman 'VIII'), replace with single instance
Here is the function:
def remove_repeating_chars(t):
"If the same character is present 4+ times (not 3 because of roman 'VIII'), replace with single instance"
return re.sub(r"(\D)(\1{3,})", r"\1", t) | If the same character is present 4+ times (not 3 because of roman 'VIII'), replace with single instance |
717 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def remove_urls(t):
return re.sub(r"http\S+", "", t) | null |
718 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def remove_html_tags(t):
return re.sub("<[^<]+?>", " ", t) | null |
719 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def remove_first_last_commas(t):
t = t.strip()
t = t[:-1] if t and t[-1] == "," else t
t = t[1:] if t and t[0] == "," else t
return t.strip() | null |
720 | import html
import math
import random
import re
from pathlib import Path
import emoji
import ftfy
from huggingface_hub import hf_hub_download
from unidecode import unidecode
def remove_wiki_ref(t):
t = re.sub(r"\A\s*\[\d+\]", "", t)
return re.sub(r"\[\d+\]\s*\Z", "", t) | null |
721 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from einops import rearrange
from flax.core.frozen_dict import unfreeze
from flax.linen import combine_masks, make_causal_mask
from flax.linen import partitioning as nn_partitioning
from flax.linen.linear import PrecisionLike
from flax.traverse_util import flatten_dict, unflatten_dict
from jax import custom_jvp, lax
from jax.random import PRNGKey
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
The provided code snippet includes necessary dependencies for implementing the `smelu` function. Write a Python function `def smelu(beta: Any = 1.0)` to solve the following problem:
Implementation of "Real World Large Scale Recommendation Systems Reproducibility and Smooth Activations" https://arxiv.org/abs/2202.06499
Here is the function:
def smelu(beta: Any = 1.0):
"""
Implementation of "Real World Large Scale Recommendation Systems Reproducibility and Smooth Activations"
https://arxiv.org/abs/2202.06499
"""
@custom_jvp
@jax.jit
def _smelu(x: Any) -> Any:
x = jnp.where(x <= -beta, 0.0, x)
return jnp.where(x >= beta, x, jnp.square(x + beta) / (4 * beta))
_smelu.defjvps(
lambda g, ans, x: lax.select(
x == -beta,
lax.full_like(g, 0),
lax.select(x == beta, lax.full_like(g, 1), g),
)
)
return _smelu | Implementation of "Real World Large Scale Recommendation Systems Reproducibility and Smooth Activations" https://arxiv.org/abs/2202.06499 |
722 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from einops import rearrange
from flax.core.frozen_dict import unfreeze
from flax.linen import combine_masks, make_causal_mask
from flax.linen import partitioning as nn_partitioning
from flax.linen.linear import PrecisionLike
from flax.traverse_util import flatten_dict, unflatten_dict
from jax import custom_jvp, lax
from jax.random import PRNGKey
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
def deepnet_init(init_std, gain=1):
init = jax.nn.initializers.normal(init_std)
def _init(*args, **kwargs):
return gain * init(*args, **kwargs)
return _init | null |
723 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from einops import rearrange
from flax.core.frozen_dict import unfreeze
from flax.linen import combine_masks, make_causal_mask
from flax.linen import partitioning as nn_partitioning
from flax.linen.linear import PrecisionLike
from flax.traverse_util import flatten_dict, unflatten_dict
from jax import custom_jvp, lax
from jax.random import PRNGKey
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
class RMSNorm(nn.Module):
"""
From "Root Mean Square Layer Normalization" by https://arxiv.org/abs/1910.07467
Adapted from flax.linen.LayerNorm
"""
epsilon: float = 1e-6
dtype: Any = jnp.float32
param_dtype: Any = jnp.float32
use_scale: bool = True
scale_init: Any = jax.nn.initializers.ones
def __call__(self, x):
reduction_axes = (-1,)
feature_axes = (-1,)
rms_sq = self._compute_rms_sq(x, reduction_axes)
return self._normalize(
self,
x,
rms_sq,
reduction_axes,
feature_axes,
self.dtype,
self.param_dtype,
self.epsilon,
self.use_scale,
self.scale_init,
)
def _compute_rms_sq(self, x, axes):
x = jnp.asarray(x, jnp.promote_types(jnp.float32, jnp.result_type(x)))
rms_sq = jnp.mean(jax.lax.square(x), axes)
return rms_sq
def _normalize(
self,
mdl,
x,
rms_sq,
reduction_axes,
feature_axes,
dtype,
param_dtype,
epsilon,
use_scale,
scale_init,
):
reduction_axes = nn.normalization._canonicalize_axes(x.ndim, reduction_axes)
feature_axes = nn.normalization._canonicalize_axes(x.ndim, feature_axes)
stats_shape = list(x.shape)
for axis in reduction_axes:
stats_shape[axis] = 1
rms_sq = rms_sq.reshape(stats_shape)
feature_shape = [1] * x.ndim
reduced_feature_shape = []
for ax in feature_axes:
feature_shape[ax] = x.shape[ax]
reduced_feature_shape.append(x.shape[ax])
mul = lax.rsqrt(rms_sq + epsilon)
if use_scale:
scale = mdl.param(
"scale", scale_init, reduced_feature_shape, param_dtype
).reshape(feature_shape)
mul *= scale
y = mul * x
return jnp.asarray(y, dtype)
def norm(type, *args, **kwargs):
if type == "rmsnorm":
return RMSNorm(*args, **kwargs)
elif type == "layernorm":
return nn.LayerNorm(*args, **kwargs)
else:
raise ValueError(f"Unknown norm type {type}") | null |
724 | import math
from functools import partial
from typing import Any, Dict, Optional, Tuple
import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from einops import rearrange
from flax.core.frozen_dict import unfreeze
from flax.linen import combine_masks, make_causal_mask
from flax.linen import partitioning as nn_partitioning
from flax.linen.linear import PrecisionLike
from flax.traverse_util import flatten_dict, unflatten_dict
from jax import custom_jvp, lax
from jax.random import PRNGKey
from transformers.modeling_flax_outputs import (
FlaxBaseModelOutput,
FlaxBaseModelOutputWithPastAndCrossAttentions,
FlaxCausalLMOutputWithCrossAttentions,
FlaxSeq2SeqLMOutput,
)
from transformers.modeling_flax_utils import ACT2FN
from transformers.models.bart.modeling_flax_bart import (
FlaxBartAttention,
FlaxBartForConditionalGeneration,
FlaxBartForConditionalGenerationModule,
FlaxBartModule,
)
from transformers.utils import ModelOutput, logging
from .configuration import DalleBartConfig
from .utils import PretrainedFromWandbMixin
The provided code snippet includes necessary dependencies for implementing the `dot_product_attention_weights` function. Write a Python function `def dot_product_attention_weights( query: Any, key: Any, bias: Optional[Any] = None, mask: Optional[Any] = None, embed_pos: Optional[Any] = None, broadcast_dropout: bool = True, dropout_rng: Optional[PRNGKey] = None, dropout_rate: float = 0.0, deterministic: bool = False, dtype: Any = jnp.float32, precision: PrecisionLike = None, sinkhorn_iters: int = 1, is_encoder: bool = False, tau=None, )` to solve the following problem:
Computes dot-product attention weights given query and key. mask is included into the bias. Adapted from flax.linen.attention.dot_product_attention_weights"
Here is the function:
def dot_product_attention_weights(
query: Any,
key: Any,
bias: Optional[Any] = None,
mask: Optional[Any] = None,
embed_pos: Optional[Any] = None,
broadcast_dropout: bool = True,
dropout_rng: Optional[PRNGKey] = None,
dropout_rate: float = 0.0,
deterministic: bool = False,
dtype: Any = jnp.float32,
precision: PrecisionLike = None,
sinkhorn_iters: int = 1,
is_encoder: bool = False,
tau=None,
):
"""
Computes dot-product attention weights given query and key.
mask is included into the bias.
Adapted from flax.linen.attention.dot_product_attention_weights"
"""
assert query.ndim == key.ndim, "q, k must have same rank."
assert query.shape[:-3] == key.shape[:-3], "q, k batch dims must match."
assert query.shape[-2] == key.shape[-2], "q, k num_heads must match."
assert query.shape[-1] == key.shape[-1], "q, k depths must match."
# attn weight shape is (batch..., num_heads, q_length, kv_length)
attn_weights = jnp.einsum("...qhd,...khd->...hqk", query, key, precision=precision)
# divide by tau (used in Swin v2)
if tau is not None:
attn_weights = attn_weights / tau
else:
depth = query.shape[-1]
attn_weights = attn_weights / jnp.sqrt(depth).astype(dtype)
# apply attention bias: masking, dropout, proximity bias, etc.
if bias is not None:
attn_weights = attn_weights + bias
# add relative position
if embed_pos is not None:
attn_weights = attn_weights + embed_pos
# normalize the attention weights
if not is_encoder or sinkhorn_iters == 1:
# sinkhorn does not work for causal (leaks info of future tokens into past)
attn_weights = jax.nn.softmax(attn_weights).astype(dtype)
else:
# adapted from https://github.com/lucidrains/sinkhorn-transformer
for i in range(sinkhorn_iters):
# when causal, some attn_weights have been set to -inf through bias
if i % 2 == 0:
attn_weights -= jax.nn.logsumexp(attn_weights, axis=-1, keepdims=True)
else:
attn_weights -= jax.nn.logsumexp(attn_weights, axis=-2, keepdims=True)
if mask is not None:
attn_weights = jnp.where(mask, attn_weights, -jnp.inf)
attn_weights = jnp.exp(attn_weights).astype(dtype)
# apply attention dropout
if not deterministic and dropout_rate > 0.0:
keep_prob = 1.0 - dropout_rate
if broadcast_dropout:
# dropout is broadcast across the batch + head dimensions
dropout_shape = tuple([1] * (key.ndim - 2)) + attn_weights.shape[-2:]
keep = jax.random.bernoulli(dropout_rng, keep_prob, dropout_shape)
else:
keep = jax.random.bernoulli(dropout_rng, keep_prob, attn_weights.shape)
multiplier = keep.astype(attn_weights.dtype) / jnp.asarray(
keep_prob, dtype=dtype
)
attn_weights = attn_weights * multiplier
return attn_weights | Computes dot-product attention weights given query and key. mask is included into the bias. Adapted from flax.linen.attention.dot_product_attention_weights" |
725 | import re
from flax.core.frozen_dict import freeze
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.experimental import PartitionSpec as P
_unmatched = object()
def _replacement_rules(rules):
def replace(key, val):
for rule, replacement in rules:
if _match(rule, key):
return replacement
return val
return replace
def _get_partition_rules():
return [
# embeddings
(("embed_positions", "embedding"), P("mp", None)),
(("embed_tokens", "embedding"), P("mp", None)),
(("rel_bias", "embedding"), P(None, "mp")),
# attention
(("(q_proj|k_proj|v_proj)", "kernel"), P(None, "mp")),
(("out_proj", "kernel"), P("mp", None)),
# FFN
(("Dense_0", "kernel"), P(None, "mp")),
(("GLU.*", "Dense_1", "kernel"), P(None, "mp")),
(("GLU.*", "Dense_2", "kernel"), P("mp", None)),
(("FFN.*", "Dense_1", "kernel"), P("mp", None)),
# layer norms
(("(bias|scale)",), None),
(("lm_head", "kernel"), P(None, "mp")),
# head scale and tau
(("(head_scale|tau)",), None),
]
def set_partitions(in_dict, use_scan):
rules = _get_partition_rules()
replace = _replacement_rules(rules)
initd = {k: _unmatched for k in flatten_dict(in_dict)}
result = {k: replace(k, v) for k, v in initd.items()}
for k, v in result.items():
if v == _unmatched:
print(f"Unmatched -> {k}")
l = list(result.keys())
if use_scan:
# add None dimension to layers
result = {
k: (P(*(None,) + v) if v is not None else None)
if any(x in k for x in ["FlaxBartEncoderLayers", "FlaxBartDecoderLayers"])
else v
for k, v in result.items()
}
assert _unmatched not in result.values(), "Incomplete partition spec."
return freeze(unflatten_dict(result)) | null |
726 | import base64
from io import BytesIO
import requests
from PIL import Image
class ServiceError(Exception):
def __init__(self, status_code):
def get_model_version(url):
r = requests.get(url)
if r.status_code == 200:
version = r.json()["version"]
return version
else:
raise ServiceError(r.status_code) | null |
727 | import os
import gradio as gr
from backend import get_images_from_backend
backend_url = os.environ["BACKEND_SERVER"] + "/generate"
def get_images_from_backend(prompt, backend_url):
def infer(prompt):
response = get_images_from_backend(prompt, backend_url)
return response["images"] | null |
728 | import base64
from io import BytesIO
import requests
from PIL import Image
class ServiceError(Exception):
def __init__(self, status_code):
self.status_code = status_code
def get_images_from_backend(prompt, backend_url):
r = requests.post(backend_url, json={"prompt": prompt})
if r.status_code == 200:
json = r.json()
images = json["images"]
images = [Image.open(BytesIO(base64.b64decode(img))) for img in images]
version = json.get("version", "unknown")
return {"images": images, "version": version}
else:
raise ServiceError(r.status_code) | null |
729 | import base64
from io import BytesIO
import requests
from PIL import Image
class ServiceError(Exception):
def __init__(self, status_code):
self.status_code = status_code
def get_model_version(url):
r = requests.get(url)
if r.status_code == 200:
version = r.json()["version"]
return version
else:
raise ServiceError(r.status_code) | null |
730 | import io
import logging
import os
import sys
import tempfile
import time
from dataclasses import asdict, dataclass, field
from functools import partial
from pathlib import Path
from typing import Any, Callable, NamedTuple, Optional
import datasets
import flax
import jax
import jax.numpy as jnp
import jaxlib
import numpy as np
import optax
import transformers
import wandb
from datasets import Dataset
from flax import core, struct, traverse_util
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
from flax.serialization import from_bytes, to_bytes
from flax.training.common_utils import onehot
from jax.experimental import PartitionSpec, maps
from jax.experimental.compilation_cache import compilation_cache as cc
from jax.experimental.pjit import pjit, with_sharding_constraint
from scalable_shampoo.distributed_shampoo import GraftingType, distributed_shampoo
from tqdm import tqdm
from transformers import HfArgumentParser
import dalle_mini
from dalle_mini.data import Dataset
from dalle_mini.model import (
DalleBart,
DalleBartConfig,
DalleBartTokenizer,
set_partitions,
)
The provided code snippet includes necessary dependencies for implementing the `split_params` function. Write a Python function `def split_params(data)` to solve the following problem:
Split params between scanned and non-scanned
Here is the function:
def split_params(data):
"""Split params between scanned and non-scanned"""
flat = traverse_util.flatten_dict(unfreeze(data))
split = {"standard": {}, "scanned_encoder": {}, "scanned_decoder": {}}
for k, v in flat.items():
if "FlaxBartEncoderLayers" in k:
split["scanned_encoder"][k] = v
elif "FlaxBartDecoderLayers" in k:
split["scanned_decoder"][k] = v
else:
split["standard"][k] = v
# remove empty keys
split = {k: v for k, v in split.items() if v}
for k, v in split.items():
split[k] = freeze(traverse_util.unflatten_dict(v))
return split | Split params between scanned and non-scanned |
731 | import io
import logging
import os
import sys
import tempfile
import time
from dataclasses import asdict, dataclass, field
from functools import partial
from pathlib import Path
from typing import Any, Callable, NamedTuple, Optional
import datasets
import flax
import jax
import jax.numpy as jnp
import jaxlib
import numpy as np
import optax
import transformers
import wandb
from datasets import Dataset
from flax import core, struct, traverse_util
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
from flax.serialization import from_bytes, to_bytes
from flax.training.common_utils import onehot
from jax.experimental import PartitionSpec, maps
from jax.experimental.compilation_cache import compilation_cache as cc
from jax.experimental.pjit import pjit, with_sharding_constraint
from scalable_shampoo.distributed_shampoo import GraftingType, distributed_shampoo
from tqdm import tqdm
from transformers import HfArgumentParser
import dalle_mini
from dalle_mini.data import Dataset
from dalle_mini.model import (
DalleBart,
DalleBartConfig,
DalleBartTokenizer,
set_partitions,
)
def unsplit_params(data):
flat = {}
for k in ["standard", "scanned_encoder", "scanned_decoder"]:
if k in data:
flat.update(traverse_util.flatten_dict(unfreeze(data[k])))
return freeze(traverse_util.unflatten_dict(flat)) | null |
732 | import io
import logging
import os
import sys
import tempfile
import time
from dataclasses import asdict, dataclass, field
from functools import partial
from pathlib import Path
from typing import Any, Callable, NamedTuple, Optional
import datasets
import flax
import jax
import jax.numpy as jnp
import jaxlib
import numpy as np
import optax
import transformers
import wandb
from datasets import Dataset
from flax import core, struct, traverse_util
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
from flax.serialization import from_bytes, to_bytes
from flax.training.common_utils import onehot
from jax.experimental import PartitionSpec, maps
from jax.experimental.compilation_cache import compilation_cache as cc
from jax.experimental.pjit import pjit, with_sharding_constraint
from scalable_shampoo.distributed_shampoo import GraftingType, distributed_shampoo
from tqdm import tqdm
from transformers import HfArgumentParser
import dalle_mini
from dalle_mini.data import Dataset
from dalle_mini.model import (
DalleBart,
DalleBartConfig,
DalleBartTokenizer,
set_partitions,
)
The provided code snippet includes necessary dependencies for implementing the `trainable_params` function. Write a Python function `def trainable_params(data, embeddings_only)` to solve the following problem:
Keep only trainable parameters
Here is the function:
def trainable_params(data, embeddings_only):
"""Keep only trainable parameters"""
if not embeddings_only:
return data
data = unfreeze(data)
trainable = {
"lm_head": data["lm_head"],
"model": {
"decoder": {
layer: data["model"]["decoder"][layer]
for layer in [
"embed_positions",
"embed_tokens",
"final_ln",
"layernorm_embedding",
]
}
},
}
return freeze(trainable) | Keep only trainable parameters |
733 | import io
import logging
import os
import sys
import tempfile
import time
from dataclasses import asdict, dataclass, field
from functools import partial
from pathlib import Path
from typing import Any, Callable, NamedTuple, Optional
import datasets
import flax
import jax
import jax.numpy as jnp
import jaxlib
import numpy as np
import optax
import transformers
import wandb
from datasets import Dataset
from flax import core, struct, traverse_util
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
from flax.serialization import from_bytes, to_bytes
from flax.training.common_utils import onehot
from jax.experimental import PartitionSpec, maps
from jax.experimental.compilation_cache import compilation_cache as cc
from jax.experimental.pjit import pjit, with_sharding_constraint
from scalable_shampoo.distributed_shampoo import GraftingType, distributed_shampoo
from tqdm import tqdm
from transformers import HfArgumentParser
import dalle_mini
from dalle_mini.data import Dataset
from dalle_mini.model import (
DalleBart,
DalleBartConfig,
DalleBartTokenizer,
set_partitions,
)
The provided code snippet includes necessary dependencies for implementing the `init_embeddings` function. Write a Python function `def init_embeddings(model, params)` to solve the following problem:
Reinitialize trainable embeddings
Here is the function:
def init_embeddings(model, params):
"""Reinitialize trainable embeddings"""
# Must match params in trainable_params() above
trainable_keypaths = [
"lm_head.kernel",
"model.decoder.embed_positions.embedding",
"model.decoder.embed_tokens.embedding",
"model.decoder.final_ln.bias",
"model.decoder.layernorm_embedding.bias",
"model.decoder.layernorm_embedding.scale",
]
# Note: using private _missing_keys
init_keys = {tuple(k.split(".")) for k in trainable_keypaths}
model._missing_keys = init_keys
return model.init_weights(model.key, model.input_shape, params=params) | Reinitialize trainable embeddings |
734 | import functools
from typing import Any, List, Optional, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import struct
from jax import lax
def sliced_transposed_product(
mat,
block_size,
axes=(-1,),
precision=lax.Precision.DEFAULT,
):
"""Returns the blocked slices representing a symmetric contraction.
Specifically, the output is a contraction of the input mat with itself, in the
specified axes.
Args:
mat: The matrix for which we will compute a contraction with itself.
block_size: The size of row blocks to compute.
axes: Axes to use for the contraction.
precision: The precision to use in each computation.
Raises:
ValueError: Raised when the specified block size does not evenly divide
the number of rows of the input mat.
"""
rank = len(mat.shape)
def _make_axis_positive(ax):
assert -rank <= ax < rank
return ax + rank if ax < 0 else ax
positive_axes = [_make_axis_positive(ax) for ax in axes]
assert len(positive_axes) == len(axes)
remaining_axes = set(range(rank)) - set(positive_axes)
assert len(remaining_axes) == 1
remaining_ax = remaining_axes.pop()
num_rows = mat.shape[remaining_ax]
if num_rows % block_size != 0:
raise ValueError(
"The row dimension must be divisible by block_size. "
f"Instead got row dimension={num_rows} and block_size={block_size}."
)
block_rows = []
for i in range(num_rows // block_size):
start_indices = [0] * rank
start_indices[remaining_ax] = i * block_size
slice_sizes = list(mat.shape)
slice_sizes[remaining_ax] = block_size
slice_sizes_full = list(mat.shape)
slice_sizes_full[remaining_ax] = (i + 1) * block_size
block_rows.append(
product_with_transpose(
lax.dynamic_slice(
mat, start_indices=start_indices, slice_sizes=slice_sizes
),
lax.dynamic_slice(
mat, start_indices=[0] * rank, slice_sizes=slice_sizes_full
),
axes=(axes, axes),
precision=precision,
)
)
return SlicedSymmetricMatrix(block_rows=block_rows)
The provided code snippet includes necessary dependencies for implementing the `sliced_transposed_product_concat` function. Write a Python function `def sliced_transposed_product_concat( mat, block_size, axes=(-1,), precision=lax.Precision.DEFAULT, )` to solve the following problem:
Returns the concatenated slices representing mat*mat^T. Args: mat: The matrix for which we will compute mat*mat^T. It does not need to be square, and may be batched. block_size: The size of row blocks to compute. axes: Axes to use for the contraction. precision: The precision to use in each computation. Raises: ValueError: Raised when the specified block size does not evenly divide the number of rows of the input mat.
Here is the function:
def sliced_transposed_product_concat(
mat,
block_size,
axes=(-1,),
precision=lax.Precision.DEFAULT,
):
"""Returns the concatenated slices representing mat*mat^T.
Args:
mat: The matrix for which we will compute mat*mat^T. It does not need to be
square, and may be batched.
block_size: The size of row blocks to compute.
axes: Axes to use for the contraction.
precision: The precision to use in each computation.
Raises:
ValueError: Raised when the specified block size does not evenly divide
the number of rows of the input mat.
"""
sliced_symmetric_matrix = sliced_transposed_product(
mat=mat, block_size=block_size, axes=axes, precision=precision
)
return jnp.concatenate(sliced_symmetric_matrix.block_rows, axis=-1) | Returns the concatenated slices representing mat*mat^T. Args: mat: The matrix for which we will compute mat*mat^T. It does not need to be square, and may be batched. block_size: The size of row blocks to compute. axes: Axes to use for the contraction. precision: The precision to use in each computation. Raises: ValueError: Raised when the specified block size does not evenly divide the number of rows of the input mat. |
735 | import functools
from typing import Any, List, Optional, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import struct
from jax import lax
class SlicedSymmetricMatrix:
"""A symmetric matrix represented by lower-triangular block row slices.
For example, the symmetric matrix M = [[a, b^T], [b, c]] would be represented
by the block rows a and [b, c].
The matrix may be batched, in which case each entry of block_rows may have
dimension greater than 2. The last two dimensions represent the rows and cols.
"""
block_rows: List[jnp.ndarray]
def sliced_transposed_product(
mat,
block_size,
axes=(-1,),
precision=lax.Precision.DEFAULT,
):
"""Returns the blocked slices representing a symmetric contraction.
Specifically, the output is a contraction of the input mat with itself, in the
specified axes.
Args:
mat: The matrix for which we will compute a contraction with itself.
block_size: The size of row blocks to compute.
axes: Axes to use for the contraction.
precision: The precision to use in each computation.
Raises:
ValueError: Raised when the specified block size does not evenly divide
the number of rows of the input mat.
"""
rank = len(mat.shape)
def _make_axis_positive(ax):
assert -rank <= ax < rank
return ax + rank if ax < 0 else ax
positive_axes = [_make_axis_positive(ax) for ax in axes]
assert len(positive_axes) == len(axes)
remaining_axes = set(range(rank)) - set(positive_axes)
assert len(remaining_axes) == 1
remaining_ax = remaining_axes.pop()
num_rows = mat.shape[remaining_ax]
if num_rows % block_size != 0:
raise ValueError(
"The row dimension must be divisible by block_size. "
f"Instead got row dimension={num_rows} and block_size={block_size}."
)
block_rows = []
for i in range(num_rows // block_size):
start_indices = [0] * rank
start_indices[remaining_ax] = i * block_size
slice_sizes = list(mat.shape)
slice_sizes[remaining_ax] = block_size
slice_sizes_full = list(mat.shape)
slice_sizes_full[remaining_ax] = (i + 1) * block_size
block_rows.append(
product_with_transpose(
lax.dynamic_slice(
mat, start_indices=start_indices, slice_sizes=slice_sizes
),
lax.dynamic_slice(
mat, start_indices=[0] * rank, slice_sizes=slice_sizes_full
),
axes=(axes, axes),
precision=precision,
)
)
return SlicedSymmetricMatrix(block_rows=block_rows)
The provided code snippet includes necessary dependencies for implementing the `update_sliced_rows` function. Write a Python function `def update_sliced_rows( symmetric_matrix, mat, alpha, beta, axes=(-1,), )` to solve the following problem:
Implements the blocked equivalent of SYRK. Specifically, the symmetric matrix (represented using lower-triangular block rows) is updated using the sliced product of mat. Args: symmetric_matrix: The symmetric matrix to update. mat: The matrix to use for the update = mat * mat^T. The number of rows should match that of symmetric_matrix. alpha: The weight for the update. beta: The weight for the original symmetric matrix. axes: Axes to use for the contraction of the update. Returns: The updated rows of alpha * mat * mat^T + beta * symmetric_matrix.
Here is the function:
def update_sliced_rows(
symmetric_matrix,
mat,
alpha,
beta,
axes=(-1,),
):
"""Implements the blocked equivalent of SYRK.
Specifically, the symmetric matrix (represented using lower-triangular block
rows) is updated using the sliced product of mat.
Args:
symmetric_matrix: The symmetric matrix to update.
mat: The matrix to use for the update = mat * mat^T. The number of rows
should match that of symmetric_matrix.
alpha: The weight for the update.
beta: The weight for the original symmetric matrix.
axes: Axes to use for the contraction of the update.
Returns:
The updated rows of alpha * mat * mat^T + beta * symmetric_matrix.
"""
block_size = symmetric_matrix.block_rows[0].shape[-2]
sym_prod = sliced_transposed_product(mat=mat, block_size=block_size, axes=axes)
return SlicedSymmetricMatrix(
block_rows=[
update * alpha + row * beta
for update, row in zip(sym_prod.block_rows, symmetric_matrix.block_rows)
]
) | Implements the blocked equivalent of SYRK. Specifically, the symmetric matrix (represented using lower-triangular block rows) is updated using the sliced product of mat. Args: symmetric_matrix: The symmetric matrix to update. mat: The matrix to use for the update = mat * mat^T. The number of rows should match that of symmetric_matrix. alpha: The weight for the update. beta: The weight for the original symmetric matrix. axes: Axes to use for the contraction of the update. Returns: The updated rows of alpha * mat * mat^T + beta * symmetric_matrix. |
736 | import functools
from typing import Any, List, Optional, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import struct
from jax import lax
def slice_symmetric_matrix(
mat,
block_size,
):
"""Returns sliced row blocks.
Args:
mat: A symmetric matrix.
block_size: The size of the row slices.
"""
num_rows = mat.shape[-2]
num_cols = mat.shape[-1]
if num_rows != num_cols:
raise ValueError("mat is not square.")
if num_rows % block_size != 0:
raise ValueError(
f"block size does not evenly divide rows. num_rows={num_rows}, block_size={block_size}"
)
return SlicedSymmetricMatrix(
block_rows=[
mat[
Ellipsis,
i * block_size : (i + 1) * block_size,
0 : (i + 1) * block_size,
]
for i in range(num_rows // block_size)
]
)
The provided code snippet includes necessary dependencies for implementing the `slice_symmetric_matrix_concat` function. Write a Python function `def slice_symmetric_matrix_concat( mat, block_size, )` to solve the following problem:
Returns the concatenated sliced row blocks. Args: mat: A symmetric matrix. block_size: The size of the row slices.
Here is the function:
def slice_symmetric_matrix_concat(
mat,
block_size,
):
"""Returns the concatenated sliced row blocks.
Args:
mat: A symmetric matrix.
block_size: The size of the row slices.
"""
sliced_symmetric_matrix = slice_symmetric_matrix(mat=mat, block_size=block_size)
return jnp.concatenate(sliced_symmetric_matrix.block_rows, axis=-1) | Returns the concatenated sliced row blocks. Args: mat: A symmetric matrix. block_size: The size of the row slices. |
737 | import functools
from typing import Any, List, Optional, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import struct
from jax import lax
def num_blocks_from_total_blocks(total_blocks):
"""Returns the number of blocks (i.e.
block rows) from the total blocks.
This is the inverse of the function x -> x*(x+1)/2.
For example, the matrix M = [[A, B^T], [B, C]] may be represented using a
total of 3 blocks ([A, B, C]). The number of corresponding block rows is 2.
Args:
total_blocks: The total blocks used to represent the matrix.
"""
num_blocks = np.round((np.sqrt(8 * total_blocks + 1) - 1) / 2).astype(np.int32)
if (num_blocks * (num_blocks + 1)) / 2 != total_blocks:
raise ValueError(
f"total_blocks={total_blocks} does not correspond to "
"a symmetric matrix. It must have the form total_blocks = x*(x+1)/2."
)
return num_blocks
The provided code snippet includes necessary dependencies for implementing the `sliced_matrix_diag` function. Write a Python function `def sliced_matrix_diag(mat)` to solve the following problem:
Returns the diagonal of the symmetric matrix. Args: mat: The symmetric matrix represented in concatenated block form.
Here is the function:
def sliced_matrix_diag(mat):
"""Returns the diagonal of the symmetric matrix.
Args:
mat: The symmetric matrix represented in concatenated block form.
"""
rows, cols = mat.shape
total_blocks = cols // rows
num_blocks = num_blocks_from_total_blocks(total_blocks)
diags = []
for i in range(num_blocks):
last_index = rows * ((i + 2) * (i + 1)) // 2
first_index = last_index - rows
diags.append(jnp.diag(mat[Ellipsis, first_index:last_index]))
return jnp.concatenate(diags, axis=-1) | Returns the diagonal of the symmetric matrix. Args: mat: The symmetric matrix represented in concatenated block form. |
738 | import functools
from typing import Any, List, Optional, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import struct
from jax import lax
The provided code snippet includes necessary dependencies for implementing the `diag_as_concat` function. Write a Python function `def diag_as_concat(diag, block_size)` to solve the following problem:
Returns the representation of a diagonal matrix in symmetric block form. Args: diag: The 1D array for the diagonals. block_size: The size of blocks to use. Must divide the length of diag.
Here is the function:
def diag_as_concat(diag, block_size):
"""Returns the representation of a diagonal matrix in symmetric block form.
Args:
diag: The 1D array for the diagonals.
block_size: The size of blocks to use. Must divide the length of diag.
"""
assert len(diag.shape) == 1 # diag must be 1D.
assert len(diag) % block_size == 0
num_diag_blocks = len(diag) // block_size
blocks = []
for i in range(num_diag_blocks):
blocks.append(jnp.zeros(shape=(block_size, block_size * i), dtype=diag.dtype))
blocks.append(jnp.diag(diag[i * block_size : (i + 1) * block_size]))
return jnp.concatenate(blocks, axis=-1) | Returns the representation of a diagonal matrix in symmetric block form. Args: diag: The 1D array for the diagonals. block_size: The size of blocks to use. Must divide the length of diag. |
739 | import functools
from typing import Any, List, Optional, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import struct
from jax import lax
def num_blocks_from_total_blocks(total_blocks):
"""Returns the number of blocks (i.e.
block rows) from the total blocks.
This is the inverse of the function x -> x*(x+1)/2.
For example, the matrix M = [[A, B^T], [B, C]] may be represented using a
total of 3 blocks ([A, B, C]). The number of corresponding block rows is 2.
Args:
total_blocks: The total blocks used to represent the matrix.
"""
num_blocks = np.round((np.sqrt(8 * total_blocks + 1) - 1) / 2).astype(np.int32)
if (num_blocks * (num_blocks + 1)) / 2 != total_blocks:
raise ValueError(
f"total_blocks={total_blocks} does not correspond to "
"a symmetric matrix. It must have the form total_blocks = x*(x+1)/2."
)
return num_blocks
The provided code snippet includes necessary dependencies for implementing the `row_abs_maxes` function. Write a Python function `def row_abs_maxes(mat)` to solve the following problem:
Returns the max of the absolute values of the rows of the full matrix. For example the symmetric matrix M = [[1, 6], [6, 2]] is represented using mat = [1, 6, 2] with block_size = 1. In this case the function returns the aboslute row maxes of the original symmetric matrix, [6, 6]. Args: mat: The symmetric matrix represented as the concatenated blocks.
Here is the function:
def row_abs_maxes(mat):
"""Returns the max of the absolute values of the rows of the full matrix.
For example the symmetric matrix M = [[1, 6], [6, 2]] is represented using
mat = [1, 6, 2] with block_size = 1. In this case the function returns the
aboslute row maxes of the original symmetric matrix, [6, 6].
Args:
mat: The symmetric matrix represented as the concatenated blocks.
"""
rows, cols = mat.shape
# Find col and row max for each block.
col_maxes = []
row_maxes = []
for i in range(cols // rows):
block = jnp.abs(mat[Ellipsis, i * rows : (i + 1) * rows])
col_maxes.append(jnp.max(block, axis=1))
row_maxes.append(jnp.max(block, axis=0))
# global row max from block maxes.
num_blocks = num_blocks_from_total_blocks(cols // rows)
maxes = []
for i in range(num_blocks):
maxes.append(
jnp.concatenate(
row_maxes[(i * (i + 1) // 2) : ((i + 2) * (i + 1) // 2)]
+ [
col_maxes[((j + 1) * (j + 2)) // 2 - (j - i + 1)]
for j in range(i + 1, num_blocks)
],
axis=-1,
)
)
return jnp.max(jnp.stack(maxes), axis=0) | Returns the max of the absolute values of the rows of the full matrix. For example the symmetric matrix M = [[1, 6], [6, 2]] is represented using mat = [1, 6, 2] with block_size = 1. In this case the function returns the aboslute row maxes of the original symmetric matrix, [6, 6]. Args: mat: The symmetric matrix represented as the concatenated blocks. |
740 | import functools
from typing import Any, List, Optional, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from flax import struct
from jax import lax
def num_blocks_from_total_blocks(total_blocks):
"""Returns the number of blocks (i.e.
block rows) from the total blocks.
This is the inverse of the function x -> x*(x+1)/2.
For example, the matrix M = [[A, B^T], [B, C]] may be represented using a
total of 3 blocks ([A, B, C]). The number of corresponding block rows is 2.
Args:
total_blocks: The total blocks used to represent the matrix.
"""
num_blocks = np.round((np.sqrt(8 * total_blocks + 1) - 1) / 2).astype(np.int32)
if (num_blocks * (num_blocks + 1)) / 2 != total_blocks:
raise ValueError(
f"total_blocks={total_blocks} does not correspond to "
"a symmetric matrix. It must have the form total_blocks = x*(x+1)/2."
)
return num_blocks
The provided code snippet includes necessary dependencies for implementing the `times_vector` function. Write a Python function `def times_vector(mat, vec)` to solve the following problem:
Returns the symmetric block-concatenated matrix multiplied by a vector. Specifically, each value in the vector is multiplied by a row of the full matrix. That is, the vector is broadcast and multiplied element-wise. Note this would be the transpose of full_mat * vec if full_mat represented the full symmetric matrix. Args: mat: The symmetric matrix represented as the concatenated blocks. vec: The vector, having the same dimension as the materialized matrix.
Here is the function:
def times_vector(mat, vec):
"""Returns the symmetric block-concatenated matrix multiplied by a vector.
Specifically, each value in the vector is multiplied by a row of the full
matrix. That is, the vector is broadcast and multiplied element-wise. Note
this would be the transpose of full_mat * vec if full_mat represented the full
symmetric matrix.
Args:
mat: The symmetric matrix represented as the concatenated blocks.
vec: The vector, having the same dimension as the materialized matrix.
"""
rows, cols = mat.shape
num_blocks = num_blocks_from_total_blocks(cols // rows)
multiplied = []
for i in range(num_blocks):
mat_block = mat[
Ellipsis, rows * ((i + 1) * i) // 2 : rows * ((i + 1) * (i + 2)) // 2
]
vec_block = vec[Ellipsis, rows * i : rows * (i + 1)]
multiplied.append(jnp.einsum("...ij,...i->ij", mat_block, vec_block))
return jnp.concatenate(multiplied, axis=-1) | Returns the symmetric block-concatenated matrix multiplied by a vector. Specifically, each value in the vector is multiplied by a row of the full matrix. That is, the vector is broadcast and multiplied element-wise. Note this would be the transpose of full_mat * vec if full_mat represented the full symmetric matrix. Args: mat: The symmetric matrix represented as the concatenated blocks. vec: The vector, having the same dimension as the materialized matrix. |
741 | import functools
from typing import Any, NamedTuple
import chex
import jax
import jax.numpy as jnp
import optax
from .quantization_utils import QuantizedValue
class SM3State(NamedTuple):
count: chex.Array
stats: Any
class ParameterStats(NamedTuple):
"""State associated to each parameter of the model being trained."""
diagonal_statistics: chex.Array # Accumulator for diagonal preconditioner
diagonal_momentum: QuantizedValue # Momentum for the diagonal preconditioner
class QuantizedValue:
"""State associated with quantized value."""
quantized: chex.Array
diagonal: chex.Array # Diagonal (if extract_diagonal is set)
bucket_size: chex.Array
quantized_dtype: jnp.dtype = struct.field(
pytree_node=False
) # Dtype for the quantized value.
extract_diagonal: bool = struct.field(pytree_node=False) # In case its centered.
shape: Any = struct.field(pytree_node=False) # Shape of the tensor.
def from_float_value(cls, fvalue, quantized_dtype, extract_diagonal=False):
if isinstance(fvalue, list) and not fvalue:
return QuantizedValue([], [], [], quantized_dtype, extract_diagonal, [])
quantized, diagonal_fvalue, bucket_size = QuantizedValue.quantize(
fvalue, quantized_dtype, extract_diagonal
)
return QuantizedValue(
quantized,
diagonal_fvalue,
bucket_size,
quantized_dtype,
extract_diagonal,
list(quantized.shape),
)
# Quantization is from Lingvo JAX optimizers.
# We extend it for int16 quantization of PSD matrices.
def quantize(cls, fvalue, quantized_dtype, extract_diagonal=False):
"""Returns quantized value and the bucket."""
if quantized_dtype == jnp.float32:
return fvalue, [], []
elif quantized_dtype == jnp.bfloat16:
return fvalue.astype(jnp.bfloat16), [], []
float_dtype = fvalue.dtype
if quantized_dtype == jnp.int8:
# value -128 is not used.
num_buckets = jnp.array(127.0, dtype=float_dtype)
elif quantized_dtype == jnp.int16:
# value -32768 is not used.
num_buckets = jnp.array(32767.0, dtype=float_dtype)
else:
raise ValueError(f"Quantized dtype {quantized_dtype} not supported.")
# max value is mapped to num_buckets
if extract_diagonal and fvalue.ndim != 2:
raise ValueError(
f"Input array {fvalue} must be 2D to work with extract_diagonal."
)
diagonal_fvalue = []
if extract_diagonal:
diagonal_fvalue = jnp.diag(fvalue)
# Remove the diagonal entries.
fvalue = fvalue - jnp.diag(diagonal_fvalue)
# TODO(rohananil): Extend this by making use of information about the blocks
# SM3 style which will be useful for diagonal statistics
# We first decide the scale.
if fvalue.ndim < 1:
raise ValueError(
f"Input array {fvalue} must have a strictly positive number of dimensions."
)
max_abs = jnp.max(jnp.abs(fvalue), axis=0)
bucket_size = max_abs / num_buckets
bs_expanded = bucket_size[jnp.newaxis, Ellipsis]
# To avoid divide by 0.0
bs_nonzero = jnp.where(
bs_expanded > 0.0, bs_expanded, jnp.ones_like(bs_expanded)
)
ratio = fvalue / bs_nonzero
# We use rounding to remove bias.
quantized = jnp.round(ratio)
return quantized.astype(quantized_dtype), diagonal_fvalue, bucket_size
def to_float(self):
"""Returns the float value."""
if isinstance(self.quantized, list) and not self.quantized:
return self.quantized
if self.quantized_dtype == jnp.float32:
return self.quantized
if self.quantized_dtype == jnp.bfloat16:
return self.quantized.astype(jnp.float32)
float_dtype = self.bucket_size.dtype
bucket_size = self.bucket_size[jnp.newaxis, Ellipsis]
val = self.quantized.astype(float_dtype) * bucket_size
if self.extract_diagonal:
val += jnp.diag(self.diagonal)
return val
The provided code snippet includes necessary dependencies for implementing the `sm3` function. Write a Python function `def sm3( learning_rate, beta1=0.9, beta2=0.999, diagonal_epsilon=1e-10, normalize_grads=False )` to solve the following problem:
SM3 optimizer. Memory-Efficient Adaptive Optimization, Rohan Anil, Vineet Gupta, Tomer Koren, Yoram Singer https://arxiv.org/abs/1901.11150 Args: learning_rate: the step size used to update the parameters. beta1: momentum parameter. beta2: second moment averaging parameter. diagonal_epsilon: epsilon for sm3 normalize_grads: Whether to normalize grads. Author finds it useful when grads are high variance. Returns: a GradientTransformation.
Here is the function:
def sm3(
learning_rate, beta1=0.9, beta2=0.999, diagonal_epsilon=1e-10, normalize_grads=False
):
"""SM3 optimizer.
Memory-Efficient Adaptive Optimization, Rohan Anil, Vineet Gupta, Tomer Koren,
Yoram Singer
https://arxiv.org/abs/1901.11150
Args:
learning_rate: the step size used to update the parameters.
beta1: momentum parameter.
beta2: second moment averaging parameter.
diagonal_epsilon: epsilon for sm3
normalize_grads: Whether to normalize grads. Author finds it useful when
grads are high variance.
Returns:
a GradientTransformation.
"""
def _quantize_momentum(momentum_statistics):
return QuantizedValue.from_float_value(momentum_statistics, jnp.int8)
def init_fn(params):
"""Initialise the optimiser's state."""
def _init(param):
accumulators = [jnp.zeros([s]) for s in param.shape]
momentum = _quantize_momentum(jnp.zeros_like(param))
return ParameterStats(accumulators, momentum)
return SM3State(
count=jnp.zeros([], jnp.int32), stats=jax.tree_map(_init, params)
)
def _get_expanded_shape(shape, i):
rank = len(shape)
# Replaces a `shape` of [M, N, K] with 1 in all dimensions except for i.
# For eg: i = 1 returns [1, N, 1].
return [1] * i + [shape[i]] + [1] * (rank - i - 1)
def _moving_averages(grad, accumulators):
w = (1.0 - beta2) if beta2 != 1.0 else 1.0
if grad.ndim < 2:
return beta2 * accumulators[0] + w * grad**2
else:
min_accumulator = functools.reduce(jnp.minimum, accumulators)
return beta2 * min_accumulator + w * grad**2
def _moving_averages_momentum(grad, momentum):
w = (1.0 - beta1) if beta1 != 1.0 else 1.0
return beta1 * momentum.to_float() + w * grad
def _sketch_diagonal_statistics(grad, updated_diagonal_statistics):
all_diagonal_statistics = []
for i in range(grad.ndim):
axes = list(range(i)) + list(range(i + 1, grad.ndim))
dim_diagonal_statistics = jnp.max(updated_diagonal_statistics, axis=axes)
all_diagonal_statistics.append(dim_diagonal_statistics)
if grad.ndim == 1:
all_diagonal_statistics[0] = updated_diagonal_statistics
return all_diagonal_statistics
def update_fn(updates, state, params=None):
del params
stats = state.stats
if normalize_grads:
updates = jax.tree_map(lambda g: g / (jnp.linalg.norm(g) + 1e-16), updates)
# Reshape all vectors into N-d tensors to compute min over them.
# [n], [m] -> [n, 1], [1, m]
expanded_diagonal_statistics = jax.tree_map(
lambda grad, state: [ # pylint:disable=g-long-lambda
jnp.reshape(
state.diagonal_statistics[i], _get_expanded_shape(grad.shape, i)
)
for i in range(grad.ndim)
],
updates,
stats,
)
# Compute new diagonal statistics
new_diagonal_statistics = jax.tree_map(
_moving_averages, updates, expanded_diagonal_statistics
)
# Compute preconditioners (1/sqrt(s)) where s is the statistics.
new_preconditioners = jax.tree_map(
lambda t: 1.0 / jnp.sqrt(t + diagonal_epsilon), new_diagonal_statistics
)
preconditioned_grads = jax.tree_map(
lambda g, p: g * p, updates, new_preconditioners
)
# Compute updated momentum (also handle quantization)
updated_momentum = jax.tree_map(
lambda preconditioned_grad, state: _moving_averages_momentum( # pylint:disable=g-long-lambda
preconditioned_grad, state.diagonal_momentum
),
preconditioned_grads,
stats,
)
# Update diagonal statistics.
updated_diagonal_statistics = jax.tree_map(
_sketch_diagonal_statistics, updates, new_diagonal_statistics
)
# Update momentum.
new_sm3_stats = jax.tree_map(
lambda momentum, diagonal_stats: ParameterStats( # pylint:disable=g-long-lambda
diagonal_stats, _quantize_momentum(momentum)
),
updated_momentum,
updated_diagonal_statistics,
)
lr = learning_rate
if callable(learning_rate):
lr = learning_rate(state.count)
new_updates = jax.tree_map(lambda pg: -lr * pg, updated_momentum)
return new_updates, SM3State(count=state.count + 1, stats=new_sm3_stats)
return optax.GradientTransformation(init_fn, update_fn) | SM3 optimizer. Memory-Efficient Adaptive Optimization, Rohan Anil, Vineet Gupta, Tomer Koren, Yoram Singer https://arxiv.org/abs/1901.11150 Args: learning_rate: the step size used to update the parameters. beta1: momentum parameter. beta2: second moment averaging parameter. diagonal_epsilon: epsilon for sm3 normalize_grads: Whether to normalize grads. Author finds it useful when grads are high variance. Returns: a GradientTransformation. |
742 | import enum
import functools
import itertools
from typing import Any, Callable, List, NamedTuple, Optional, Tuple, Union
import chex
import jax
import jax.numpy as jnp
import numpy as np
import optax
from absl import logging
from flax import struct
from jax import lax
from jax.experimental import pjit
from jax.experimental.sparse import linalg
from .quantization_utils import QuantizedValue
from .symmetric_matrices import symmetric_matrices
The provided code snippet includes necessary dependencies for implementing the `merge_small_dims` function. Write a Python function `def merge_small_dims(shape_to_merge, max_dim)` to solve the following problem:
Merge small dimensions. If there are some small dimensions, we collapse them: e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024 [1, 2, 768, 1, 2048] --> [2, 768, 2048] Args: shape_to_merge: Shape to merge small dimensions. max_dim: Maximal dimension of output shape used in merging. Returns: Merged shape.
Here is the function:
def merge_small_dims(shape_to_merge, max_dim):
"""Merge small dimensions.
If there are some small dimensions, we collapse them:
e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024
[1, 2, 768, 1, 2048] --> [2, 768, 2048]
Args:
shape_to_merge: Shape to merge small dimensions.
max_dim: Maximal dimension of output shape used in merging.
Returns:
Merged shape.
"""
if shape_to_merge and np.all(np.array(shape_to_merge) == 1):
return [1]
resulting_shape = []
product = 1
for d in shape_to_merge:
if product * d <= max_dim:
product *= d
else:
if product > 1:
resulting_shape.append(product)
product = d
if product > 1:
resulting_shape.append(product)
return resulting_shape | Merge small dimensions. If there are some small dimensions, we collapse them: e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if max_dim = 1024 [1, 2, 768, 1, 2048] --> [2, 768, 2048] Args: shape_to_merge: Shape to merge small dimensions. max_dim: Maximal dimension of output shape used in merging. Returns: Merged shape. |
743 | import enum
import functools
import itertools
from typing import Any, Callable, List, NamedTuple, Optional, Tuple, Union
import chex
import jax
import jax.numpy as jnp
import numpy as np
import optax
from absl import logging
from flax import struct
from jax import lax
from jax.experimental import pjit
from jax.experimental.sparse import linalg
from .quantization_utils import QuantizedValue
from .symmetric_matrices import symmetric_matrices
def pad_square_matrix(mat, max_size):
"""Pad a square matrix up to max_size.
Args:
mat: a matrix to pad.
max_size: matrix size requested.
Returns:
Given M returns [[M, 0], [0, I]]
"""
rows, cols = mat.shape
if rows != cols:
raise ValueError(
f"Must have rows == cols, instead got rows={rows}, cols={cols}"
)
if cols > max_size:
raise ValueError(
f"Must have cols <= max_size. Instead got cols={cols}, max_size={max_size}."
)
if rows == max_size:
return mat
pad_size = max_size - rows
zs1 = jnp.zeros([rows, pad_size], dtype=mat.dtype)
zs2 = jnp.zeros([pad_size, rows], dtype=mat.dtype)
eye = jnp.eye(pad_size, dtype=mat.dtype)
mat = jnp.concatenate([mat, zs1], 1)
mat = jnp.concatenate([mat, jnp.concatenate([zs2, eye], 1)], 0)
return mat
def make_sliced_padding(
symmetric_block_size,
num_blocks,
starting_block,
dtype,
):
"""Returns padding for symmetric block matrix.
Specifically, the padding is given concatenated rectangular matrices
representing the lower-triangular rows below the starting block. For example,
if we want to pad the symmetric matrix
M = [[A, B^T]
[B, C]],
the desired output (in terms of the full matrix) with num_blocks = 4 is
M_padded = [[A, B^T, 0, 0]
[B, C, 0, 0]
[0, 0, I, 0]
0, 0, 0, I].
We would represent M as the block matrix mat = [A, B, C]. In this form, the
additional padding to provide has form [0, 0, I, 0, 0, 0, I] (only the lower
triangular parts in the third and fourth rows).
Args:
symmetric_block_size: The size of each block.
num_blocks: The total number of blocks.
starting_block: The block where to start the padding.
dtype: The type to use for the blocks.
"""
if starting_block == num_blocks:
return jnp.zeros(shape=(symmetric_block_size, 0), dtype=dtype)
blocks = []
for i in range(starting_block, num_blocks):
blocks.append(
jnp.zeros(
shape=(symmetric_block_size, symmetric_block_size * i), dtype=dtype
)
)
blocks.append(jnp.eye(symmetric_block_size, dtype=dtype))
return jnp.concatenate(blocks, axis=-1)
The provided code snippet includes necessary dependencies for implementing the `pad_block_symmetric_matrix` function. Write a Python function `def pad_block_symmetric_matrix( mat, symmetric_block_size, max_num_blocks, )` to solve the following problem:
Returns the padded blocked symmetric matrix. The size of the padded matrix will be: [symmetric_block_size, symmetric_block_size * max_num_blocks] The input matrix can either: - Be square with size less or equal to symmetric_block_size. In this case, mat will first be padded to a square matrix of size symmetric_block_size, and then be padded again up to the full size of the blocked matrix. - Be a rectangle with number of rows equal to block size. In this case, number of columns must be a multiple of number of rows, and the ratio must correspond to a block representation of a symmetric matrix. That is, the ratio must have form x * (x + 1) / 2. Here, x represents the number of block rows represented by the matrix. Args: mat: The input block matrix. symmetric_block_size: The size of blocks. max_num_blocks: The largest number of blocks to pad to.
Here is the function:
def pad_block_symmetric_matrix(
mat,
symmetric_block_size,
max_num_blocks,
):
"""Returns the padded blocked symmetric matrix.
The size of the padded matrix will be:
[symmetric_block_size, symmetric_block_size * max_num_blocks]
The input matrix can either:
- Be square with size less or equal to symmetric_block_size. In this case,
mat will first be padded to a square matrix of size symmetric_block_size,
and then be padded again up to the full size of the blocked matrix.
- Be a rectangle with number of rows equal to block size.
In this case, number of columns must be a multiple of number of rows, and
the ratio must correspond to a block representation of a symmetric matrix.
That is, the ratio must have form x * (x + 1) / 2. Here, x represents the
number of block rows represented by the matrix.
Args:
mat: The input block matrix.
symmetric_block_size: The size of blocks.
max_num_blocks: The largest number of blocks to pad to.
"""
rows, cols = mat.shape
if rows > symmetric_block_size:
raise ValueError(
"Must have rows <= symmetric_block_size. Instead got "
f"rows={rows}, symmetric_block_size={symmetric_block_size}."
)
if rows > cols:
raise ValueError(
f"Must have rows <= cols, instead got rows={rows}, cols={cols}."
)
if cols > symmetric_block_size * max_num_blocks:
raise ValueError(
"Must have cols <= symmetric_block_size * max_num_blocks "
f"Instead got cols={cols}, "
f"symmetric_block_size={symmetric_block_size}, "
f"max_num_blocks={max_num_blocks}."
)
if rows < symmetric_block_size:
mat = pad_square_matrix(mat, max_size=symmetric_block_size)
# Update rows and cols after possibly padding in pad_square_matrix.
rows, cols = mat.shape
assert rows == symmetric_block_size
assert cols % rows == 0
filled_blocks = cols // rows
padding_blocks = make_sliced_padding(
symmetric_block_size=symmetric_block_size,
num_blocks=symmetric_matrices.num_blocks_from_total_blocks(max_num_blocks),
starting_block=symmetric_matrices.num_blocks_from_total_blocks(filled_blocks),
dtype=mat.dtype,
)
return jnp.concatenate([mat, padding_blocks], axis=-1) | Returns the padded blocked symmetric matrix. The size of the padded matrix will be: [symmetric_block_size, symmetric_block_size * max_num_blocks] The input matrix can either: - Be square with size less or equal to symmetric_block_size. In this case, mat will first be padded to a square matrix of size symmetric_block_size, and then be padded again up to the full size of the blocked matrix. - Be a rectangle with number of rows equal to block size. In this case, number of columns must be a multiple of number of rows, and the ratio must correspond to a block representation of a symmetric matrix. That is, the ratio must have form x * (x + 1) / 2. Here, x represents the number of block rows represented by the matrix. Args: mat: The input block matrix. symmetric_block_size: The size of blocks. max_num_blocks: The largest number of blocks to pad to. |
744 | import enum
import functools
import itertools
from typing import Any, Callable, List, NamedTuple, Optional, Tuple, Union
import chex
import jax
import jax.numpy as jnp
import numpy as np
import optax
from absl import logging
from flax import struct
from jax import lax
from jax.experimental import pjit
from jax.experimental.sparse import linalg
from .quantization_utils import QuantizedValue
from .symmetric_matrices import symmetric_matrices
The provided code snippet includes necessary dependencies for implementing the `gram_weighted_update` function. Write a Python function `def gram_weighted_update(old_stats, g, axis, w1, w2, precision=None)` to solve the following problem:
Updated statistics via weighted average with new Gram matrix. Returns w₁ R + w₂ Gᵀ G where R is `old_stats` and G is the matrix whose columns are the flattened slices of the tensor `g` along the given `axis`. (So, `old_stats` and the returned matrix have dimensions n x n where n = `g.shape[axis]`). Args: old_stats: Old statistics. g: Gradient tensor. axis: Axis along which to slice `g`. w1: Scalar weight for old statistics. w2: Scalar weight for new Gram matrix. precision: Optional precision XLA related flag, the available options are: a) lax.Precision.DEFAULT (better step time, but not precise) b) lax.Precision.HIGH (increased precision, slower) c) lax.Precision.HIGHEST (best possible precision, slowest) Returns: Weighted average of old and new statistics.
Here is the function:
def gram_weighted_update(old_stats, g, axis, w1, w2, precision=None):
"""Updated statistics via weighted average with new Gram matrix.
Returns w₁ R + w₂ Gᵀ G where R is `old_stats` and G is the matrix whose
columns are the flattened slices of the tensor `g` along the given `axis`.
(So, `old_stats` and the returned matrix have dimensions n x n where
n = `g.shape[axis]`).
Args:
old_stats: Old statistics.
g: Gradient tensor.
axis: Axis along which to slice `g`.
w1: Scalar weight for old statistics.
w2: Scalar weight for new Gram matrix.
precision: Optional precision XLA related flag, the available options are:
a) lax.Precision.DEFAULT (better step time, but not precise)
b) lax.Precision.HIGH (increased precision, slower)
c) lax.Precision.HIGHEST (best possible precision, slowest)
Returns:
Weighted average of old and new statistics.
"""
axes = [i for i in range(g.ndim) if i != axis]
gram_matrix = jnp.tensordot(g, g, axes=(axes, axes), precision=precision)
return w1 * old_stats + w2 * gram_matrix | Updated statistics via weighted average with new Gram matrix. Returns w₁ R + w₂ Gᵀ G where R is `old_stats` and G is the matrix whose columns are the flattened slices of the tensor `g` along the given `axis`. (So, `old_stats` and the returned matrix have dimensions n x n where n = `g.shape[axis]`). Args: old_stats: Old statistics. g: Gradient tensor. axis: Axis along which to slice `g`. w1: Scalar weight for old statistics. w2: Scalar weight for new Gram matrix. precision: Optional precision XLA related flag, the available options are: a) lax.Precision.DEFAULT (better step time, but not precise) b) lax.Precision.HIGH (increased precision, slower) c) lax.Precision.HIGHEST (best possible precision, slowest) Returns: Weighted average of old and new statistics. |
745 | import enum
import functools
import itertools
from typing import Any, Callable, List, NamedTuple, Optional, Tuple, Union
import chex
import jax
import jax.numpy as jnp
import numpy as np
import optax
from absl import logging
from flax import struct
from jax import lax
from jax.experimental import pjit
from jax.experimental.sparse import linalg
from .quantization_utils import QuantizedValue
from .symmetric_matrices import symmetric_matrices
class TrainingMetrics:
inverse_pth_root_errors: chex.Array # Error for inverse-pth roots.
# TODO(rohananil): Add more important metrics to track during training.
class ParameterStats(NamedTuple):
"""State associated to each parameter of the model being trained."""
diagonal_statistics: QuantizedValue # Accumulator for diagonal preconditioner
statistics: List[Any] # Statistics (QuantizedValue, chex.Array)
preconditioners: List[Any] # Preconditioners (QuantizedValue, chex.Array)
diagonal_momentum: QuantizedValue # Momentum for the diagonal preconditioner
momentum: QuantizedValue # Momentum for the shampoo preconditioner
training_metrics: TrainingMetrics # Metrics (optional for training).
class GlobalShardedParameterStats:
statistics: chex.Array # Statistics
preconditioners: chex.Array # Preconditioners
exponents: chex.Array # exponents
class LocalShardedParameterStats:
"""State associated to each parameter of the model being trained."""
diagonal_statistics: QuantizedValue # Accumulator for diagonal preconditioner
diagonal_momentum: QuantizedValue # Momentum for the diagonal preconditioner
momentum: QuantizedValue # Momentum for the shampoo preconditioner
training_metrics: TrainingMetrics # Metrics (optional for training).
index_start: np.int32 = struct.field(
pytree_node=False
) # Index into global statistics array
sizes: Any = struct.field(pytree_node=False) # Sizes of the statistics.
def init_training_metrics(num_statistics):
# Since the downstream apis expect a jnp.array - we create a dummy one if
# num_statistics=0.
if not num_statistics:
return TrainingMetrics(jnp.array(0, jnp.float32))
else:
return TrainingMetrics(jnp.zeros([num_statistics], jnp.float32))
def init_training_metrics_shapes(num_statistics):
# Since the downstream apis expect a jnp.array - we create a dummy one if
# num_statistics=0.
if not num_statistics:
return TrainingMetrics([[], jnp.float32])
else:
return TrainingMetrics([[num_statistics], jnp.float32])
def init_training_metrics_pspec():
return TrainingMetrics(pjit.PartitionSpec())
class ShardedShampooStats(NamedTuple):
"""Shampoo state in sharded mode."""
global_stats: Any
local_stats: Any
class ShampooState(NamedTuple):
count: chex.Array
stats: Any
class InitFnState(NamedTuple):
init_fn: Any
pspec_fn: Any
shape_and_dtype_fn: Any
class GraftingType(enum.IntEnum):
SGD = 1
ADAGRAD = 2
RMSPROP = 3
RMSPROP_NORMALIZED = 4
SQRT_N = 5
ADAGRAD_NORMALIZED = 6
class PreconditionerType(enum.IntEnum):
# Default, computes preconditioner for each dim
ALL = 1
# One sided Shampoo, in this cases only on input dim.
# Assumes last dim is always the output dim and everything else input dim.
INPUT = 2
def matrix_inverse_pth_root(
matrix,
p,
num_iters=100,
ridge_epsilon=1e-6,
error_tolerance=1e-6,
precision=lax.Precision.HIGHEST,
relative_matrix_epsilon=True,
lobpcg_topk_precondition=0,
lobpcg_max_iter=0,
):
"""Computes `matrix^(-1/p)`, where `p` is a positive integer.
This function uses the Coupled newton iterations algorithm for
the computation of a matrix's inverse pth root.
References:
[Functions of Matrices, Theory and Computation,
Nicholas J Higham, Pg 184, Eq 7.18](
https://epubs.siam.org/doi/book/10.1137/1.9780898717778)
Args:
matrix: the symmetric PSD matrix whose power it to be computed
p: exponent, for p a positive integer.
num_iters: Maximum number of iterations.
ridge_epsilon: Ridge epsilon added to make the matrix positive definite.
error_tolerance: Error indicator, useful for early termination.
precision: precision XLA related flag, the available options are: a)
lax.Precision.DEFAULT (better step time, but not precise) b)
lax.Precision.HIGH (increased precision, slower) c) lax.Precision.HIGHEST
(best possible precision, slowest)
relative_matrix_epsilon: Whether to use relative epsilon to the max eigen
value when computing inverse-pth root.
lobpcg_topk_precondition: If nonzero, specifies the number of top
eigenvectors to subtract out before performing LOBPCG. Note this makes
relative_matrix_epsilon essentially free.
lobpcg_max_iter: Maximum iteration count for LOBPCG, defaults to
`lobpcg_topk_precondition`.
Returns:
matrix^(-1/p) and the error
"""
# If the input is not square, materialize it from the concatenated form.
if matrix.shape[0] != matrix.shape[1]:
matrix = symmetric_matrices.materialize_matrix_from_concat(matrix)
assert matrix.shape[0] == matrix.shape[1]
# We use _MAT_INV_PTH_ROOT_DTYPE for the matrix inverse pth root.
# Switch to f64 if you have hardware that supports it. Enable the jax flag
# jax_enable_x64 for this to work.
matrix_size = matrix.shape[0]
orig_dtype = matrix.dtype
matrix = matrix.astype(_MAT_INV_PTH_ROOT_DTYPE)
alpha = jnp.asarray(-1.0 / p, _MAT_INV_PTH_ROOT_DTYPE)
identity = jnp.eye(matrix_size, dtype=_MAT_INV_PTH_ROOT_DTYPE)
original_matrix = matrix
if lobpcg_topk_precondition > 0:
# TODO(vladf): reuse previous top-k as the initial search directions
pad_shape = (matrix_size - lobpcg_topk_precondition, lobpcg_topk_precondition)
search_dirs = jnp.concatenate(
(jnp.eye(lobpcg_topk_precondition), jnp.zeros(pad_shape)), axis=0
)
eigvals, eigvecs, actual_iters = linalg.lobpcg_standard(
matrix,
search_dirs,
lobpcg_topk_precondition if lobpcg_max_iter == 0 else lobpcg_max_iter,
)
del actual_iters # TODO(vladf): return diagnostics dictionary
# The minimal eigenvalue among top-k becomes the maximal one in the whole
# matrix after deflation.
max_ev = jnp.min(eigvals)
deflation = eigvals - max_ev
scaled_vecs = eigvecs * jnp.sqrt(deflation)
# Deflate out top eigenvectors to reduce matrix condition number.
matrix -= scaled_vecs.dot(scaled_vecs.T, precision=jax.lax.Precision.HIGHEST)
# Only use power iteration if lobpcg wasn't already used to derive the
# top eigenvalue.
elif relative_matrix_epsilon:
_, max_ev = power_iteration(
matrix=matrix, num_iters=100, error_tolerance=1e-6, precision=precision
)
eigvals, eigvecs = None, None # Unused but required by pytype.
# Use absolute matrix epsilon scaling otherwise.
else:
max_ev = 1.0
eigvals, eigvecs = None, None # Unused but required by pytype.
ridge_epsilon = ridge_epsilon * jnp.maximum(max_ev, 1e-6)
def _iter_condition(state):
(i, unused_mat_m, unused_mat_h, unused_old_mat_h, error, run_step) = state
error_above_threshold = jnp.logical_and(error > error_tolerance, run_step)
return jnp.logical_and(i < num_iters, error_above_threshold)
def _iter_body(state):
(i, mat_m, mat_h, unused_old_mat_h, error, unused_run_step) = state
mat_m_i = (1 - alpha) * identity + alpha * mat_m
new_mat_m = jnp.matmul(mat_power(mat_m_i, p), mat_m, precision=precision)
new_mat_h = jnp.matmul(mat_h, mat_m_i, precision=precision)
new_error = jnp.max(jnp.abs(new_mat_m - identity))
# sometimes error increases after an iteration before decreasing and
# converging. 1.2 factor is used to bound the maximal allowed increase.
return (i + 1, new_mat_m, new_mat_h, mat_h, new_error, new_error < error * 1.2)
if matrix_size == 1:
resultant_mat_h = (matrix + ridge_epsilon) ** alpha
error = jnp.array(0, jnp.float32)
else:
damped_matrix = matrix + ridge_epsilon * identity
z = (1 + p) / (2 * jnp.linalg.norm(damped_matrix))
new_mat_m_0 = damped_matrix * z
new_error = jnp.max(jnp.abs(new_mat_m_0 - identity))
new_mat_h_0 = identity * jnp.power(z, 1.0 / p)
init_state = tuple([0, new_mat_m_0, new_mat_h_0, new_mat_h_0, new_error, True])
_, mat_m, mat_h, old_mat_h, error, convergence = lax.while_loop(
_iter_condition, _iter_body, init_state
)
error = jnp.max(jnp.abs(mat_m - identity)).astype(jnp.float32)
is_converged = jnp.asarray(convergence, old_mat_h.dtype)
resultant_mat_h = is_converged * mat_h + (1 - is_converged) * old_mat_h
resultant_mat_h = jnp.asarray(resultant_mat_h, orig_dtype)
if lobpcg_topk_precondition > 0:
# Since we deflated the top eigenvectors prior to p-th root inverse,
# the resultant matrix has larger eigenvalues associated with those
# same eigenvectors, which we need to now re-deflate.
#
# Note that _pth_root_difference returns positive values for this
# particular argument ordering as min(eigvals) <= eigvals for the
# jnp.sqrt below.
pth_diff = _pth_root_difference(ridge_epsilon, jnp.min(eigvals), eigvals, p)
scaled_vecs = eigvecs * jnp.sqrt(pth_diff)
resultant_mat_h = (
resultant_mat_h.astype(scaled_vecs.dtype)
- scaled_vecs.dot(scaled_vecs.T, precision=jax.lax.Precision.HIGHEST)
).astype(orig_dtype)
mat_m = jnp.matmul(
mat_power(resultant_mat_h, p),
original_matrix,
precision=jax.lax.Precision.HIGHEST,
)
error = jnp.max(jnp.abs(mat_m - identity)).astype(jnp.float32)
return resultant_mat_h, error
def pad_square_matrix(mat, max_size):
"""Pad a square matrix up to max_size.
Args:
mat: a matrix to pad.
max_size: matrix size requested.
Returns:
Given M returns [[M, 0], [0, I]]
"""
rows, cols = mat.shape
if rows != cols:
raise ValueError(
f"Must have rows == cols, instead got rows={rows}, cols={cols}"
)
if cols > max_size:
raise ValueError(
f"Must have cols <= max_size. Instead got cols={cols}, max_size={max_size}."
)
if rows == max_size:
return mat
pad_size = max_size - rows
zs1 = jnp.zeros([rows, pad_size], dtype=mat.dtype)
zs2 = jnp.zeros([pad_size, rows], dtype=mat.dtype)
eye = jnp.eye(pad_size, dtype=mat.dtype)
mat = jnp.concatenate([mat, zs1], 1)
mat = jnp.concatenate([mat, jnp.concatenate([zs2, eye], 1)], 0)
return mat
def pad_vector(vec, max_size):
"""Pad a vector to a max_size.
Args:
vec: a vector to pad.
max_size: matrix size requested.
Returns:
Given V returns [V, 0]
"""
size = vec.shape[0]
assert size <= max_size
if size == max_size:
return vec
pad_size = max_size - size
zs1 = jnp.zeros([pad_size], dtype=vec.dtype)
return jnp.concatenate([vec, zs1], 0)
def efficient_cond(predicate, compute_fn, init_state, *args, **kwargs):
"""Avoids wasteful buffer allocation with XLA."""
def _iter_body(unused_state):
results = compute_fn(*args, **kwargs)
return tuple([False] + list(results))
def _iter_condition(state):
return state[0]
results = jax.lax.while_loop(
_iter_condition, _iter_body, tuple([predicate] + init_state)
)
return tuple(results[1:])
class Preconditioner:
"""Compute statistics/shape from gradients for preconditioning."""
def __init__(
self,
param,
block_size,
merge_small_dims_block_size,
best_effort_shape_interpretation,
preconditioner_type=PreconditionerType.ALL,
):
"""Initializes the preconditioner.
Args:
param: parameter to precondition.
block_size: Block size used to split param.
merge_small_dims_block_size: Block size for merging dims.
best_effort_shape_interpretation: Whether to collapse/merge dims together.
preconditioner_type: Type of preconditioner to use.
"""
self._original_shape = param.shape
self._transformed_shape = param.shape
if best_effort_shape_interpretation:
self._transformed_shape = merge_small_dims(
self._original_shape, merge_small_dims_block_size
)
reshaped_param = jnp.reshape(param, self._transformed_shape)
self._partitioner = BlockPartitioner(reshaped_param, block_size)
self._preconditioner_type = preconditioner_type
def updated_statistics_from_grad(
self,
stats,
grad,
w1,
w2,
to_float=None,
from_float=None,
precision=None,
):
"""Update statistics from gradients.
Args:
stats: Old statistics or its Cholesky factor if `cholesky` is True.
grad: Gradient to compute statistics from.
w1: Weight for old statistics.
w2: Weight for new statistics.
to_float: Optional function for converting stats to floating point.
from_float: Optional function for converting from floating point.
precision: Optional precision XLA related flag, the available options are:
a) lax.Precision.DEFAULT (better step time, but not precise)
b) lax.Precision.HIGH (increased precision, slower)
c) lax.Precision.HIGHEST (best possible precision, slowest)
Returns:
A list of updated gradient statistics for each partition.
"""
to_float = to_float if to_float is not None else (lambda x: x)
from_float = from_float if from_float is not None else (lambda x: x)
update = functools.partial(gram_weighted_update, precision=precision)
reshaped_grad = jnp.reshape(grad, self._transformed_shape)
partitioned_grads = self._partitioner.partition(reshaped_grad)
new_stats = []
index = 0
for g in partitioned_grads:
should_preconditioned_dims = self.should_precondition_dims()
num_preconditioners = sum(should_preconditioned_dims)
for axis in range(num_preconditioners):
new_stat = update(to_float(stats[index]), g, axis, w1, w2)
new_stats.append(from_float(new_stat))
index += 1
return new_stats
def should_precondition_dims(self):
"""A vector containing indicator indicating if the dim is preconditioned."""
split_sizes = self._partitioner.split_sizes()
rank = len(split_sizes)
if self._preconditioner_type == PreconditionerType.ALL or rank <= 1:
return [True] * rank
else:
return [True] * (rank - 1) + [False]
def shapes_for_preconditioners(self):
"""Returns shape from statistics."""
split_sizes = self._partitioner.split_sizes()
rank = len(split_sizes)
# We ignore preconditioner types if rank == 1
preconditioner_shapes = []
for t in itertools.product(*split_sizes):
if self._preconditioner_type == PreconditionerType.ALL or rank <= 1:
preconditioner_shapes.extend([[d, d] for d in t])
else:
preconditioner_shapes.extend([[d, d] for d in t[:-1]])
return preconditioner_shapes
def exponent_for_preconditioner(self):
"""Returns exponent to use for inverse-pth root M^{-1/p}."""
should_preconditioned_dims = self.should_precondition_dims()
num_preconditioners = sum(should_preconditioned_dims)
return 2 * num_preconditioners
def preconditioned_grad(self, grad, preconditioners):
"""Precondition the gradient.
Args:
grad: A gradient tensor to precondition.
preconditioners: A list of preconditioners to apply.
Returns:
A preconditioned gradient.
"""
reshaped_grad = jnp.reshape(grad, self._transformed_shape)
partitioned_grads = self._partitioner.partition(reshaped_grad)
preconditioned_partitioned_grads = []
for i, g in enumerate(partitioned_grads):
should_preconditioned_dims = self.should_precondition_dims()
num_preconditioners = sum(should_preconditioned_dims)
preconditioners_for_grad = preconditioners[
i * num_preconditioners : (i + 1) * num_preconditioners
]
precond_g = g
rank = len(g.shape)
for j, precondition in enumerate(should_preconditioned_dims):
if precondition:
precond_g = jnp.tensordot(
precond_g, preconditioners_for_grad[j], axes=[[0], [0]]
)
else:
precond_g = jnp.transpose(precond_g, axes=(*range(1, rank), 0))
preconditioned_partitioned_grads.append(precond_g)
merged_grad = self._partitioner.merge_partitions(
preconditioned_partitioned_grads
)
return jnp.reshape(merged_grad, self._original_shape)
def _convert_to_parameter_stats(global_stats, local_stat, convert_statistics=True):
"""Creates parameter stats from sharded stats."""
index_start = int(local_stat.index_start)
index_end = int(len(local_stat.sizes)) + index_start
statistics = global_stats.statistics[index_start:index_end, :, :]
preconditioners = global_stats.preconditioners[index_start:index_end, :, :]
new_statistics = []
new_preconditioners = []
for i, size in enumerate(local_stat.sizes):
new_statistics.append(statistics[i][:size, :size])
new_preconditioners.append(preconditioners[i][:size, :size])
if not convert_statistics:
new_statistics = None
return ParameterStats(
local_stat.diagonal_statistics,
new_statistics,
new_preconditioners,
local_stat.diagonal_momentum,
local_stat.momentum,
local_stat.training_metrics,
)
def _convert_from_parameter_stats(parameter_stats, local_stats):
"""Creates sharded stats from paramter stats."""
return LocalShardedParameterStats(
parameter_stats.diagonal_statistics,
parameter_stats.diagonal_momentum,
parameter_stats.momentum,
parameter_stats.training_metrics,
local_stats.index_start,
local_stats.sizes,
)
def _add_error_into_local_stats(local_stats, errors, inverse_failure_threshold):
"""Adds errors back into local statistics."""
new_local_stats = []
for local_stat in local_stats:
if local_stat.sizes:
index_start = int(local_stat.index_start)
index_end = int(len(local_stat.sizes)) + index_start
per_stat_error = errors[index_start:index_end]
else:
per_stat_error = jnp.array(0, jnp.float32)
if local_stat.sizes:
per_stat_error = jnp.where(
jnp.logical_and(
per_stat_error > 0.0, per_stat_error != inverse_failure_threshold
),
per_stat_error,
local_stat.training_metrics.inverse_pth_root_errors,
)
new_local_stats.append(
LocalShardedParameterStats(
local_stat.diagonal_statistics,
local_stat.diagonal_momentum,
local_stat.momentum,
TrainingMetrics(per_stat_error),
local_stat.index_start,
local_stat.sizes,
)
)
return new_local_stats
def batch(x, num_devices):
"""Batch `x` so that so that leading axis is num_devices."""
n = len(x)
b = int(n / num_devices)
return jnp.stack([jnp.stack(x[idx : idx + b]) for idx in range(0, n, b)])
def unbatch(batched_values):
"""Unbatch values across leading axis and return a list of elements."""
b1, b2 = batched_values.shape[0], batched_values.shape[1]
results = []
for v_array in jnp.split(batched_values, indices_or_sections=b1, axis=0):
v_array = jnp.squeeze(v_array)
# b2 = batches (number of preconditioner computation) per core.
if b2 > 1:
for v in jnp.split(v_array, indices_or_sections=b2, axis=0):
results.append(jnp.squeeze(v))
else:
results.append(v_array)
return results
class QuantizedValue:
"""State associated with quantized value."""
quantized: chex.Array
diagonal: chex.Array # Diagonal (if extract_diagonal is set)
bucket_size: chex.Array
quantized_dtype: jnp.dtype = struct.field(
pytree_node=False
) # Dtype for the quantized value.
extract_diagonal: bool = struct.field(pytree_node=False) # In case its centered.
shape: Any = struct.field(pytree_node=False) # Shape of the tensor.
def from_float_value(cls, fvalue, quantized_dtype, extract_diagonal=False):
if isinstance(fvalue, list) and not fvalue:
return QuantizedValue([], [], [], quantized_dtype, extract_diagonal, [])
quantized, diagonal_fvalue, bucket_size = QuantizedValue.quantize(
fvalue, quantized_dtype, extract_diagonal
)
return QuantizedValue(
quantized,
diagonal_fvalue,
bucket_size,
quantized_dtype,
extract_diagonal,
list(quantized.shape),
)
# Quantization is from Lingvo JAX optimizers.
# We extend it for int16 quantization of PSD matrices.
def quantize(cls, fvalue, quantized_dtype, extract_diagonal=False):
"""Returns quantized value and the bucket."""
if quantized_dtype == jnp.float32:
return fvalue, [], []
elif quantized_dtype == jnp.bfloat16:
return fvalue.astype(jnp.bfloat16), [], []
float_dtype = fvalue.dtype
if quantized_dtype == jnp.int8:
# value -128 is not used.
num_buckets = jnp.array(127.0, dtype=float_dtype)
elif quantized_dtype == jnp.int16:
# value -32768 is not used.
num_buckets = jnp.array(32767.0, dtype=float_dtype)
else:
raise ValueError(f"Quantized dtype {quantized_dtype} not supported.")
# max value is mapped to num_buckets
if extract_diagonal and fvalue.ndim != 2:
raise ValueError(
f"Input array {fvalue} must be 2D to work with extract_diagonal."
)
diagonal_fvalue = []
if extract_diagonal:
diagonal_fvalue = jnp.diag(fvalue)
# Remove the diagonal entries.
fvalue = fvalue - jnp.diag(diagonal_fvalue)
# TODO(rohananil): Extend this by making use of information about the blocks
# SM3 style which will be useful for diagonal statistics
# We first decide the scale.
if fvalue.ndim < 1:
raise ValueError(
f"Input array {fvalue} must have a strictly positive number of dimensions."
)
max_abs = jnp.max(jnp.abs(fvalue), axis=0)
bucket_size = max_abs / num_buckets
bs_expanded = bucket_size[jnp.newaxis, Ellipsis]
# To avoid divide by 0.0
bs_nonzero = jnp.where(
bs_expanded > 0.0, bs_expanded, jnp.ones_like(bs_expanded)
)
ratio = fvalue / bs_nonzero
# We use rounding to remove bias.
quantized = jnp.round(ratio)
return quantized.astype(quantized_dtype), diagonal_fvalue, bucket_size
def to_float(self):
"""Returns the float value."""
if isinstance(self.quantized, list) and not self.quantized:
return self.quantized
if self.quantized_dtype == jnp.float32:
return self.quantized
if self.quantized_dtype == jnp.bfloat16:
return self.quantized.astype(jnp.float32)
float_dtype = self.bucket_size.dtype
bucket_size = self.bucket_size[jnp.newaxis, Ellipsis]
val = self.quantized.astype(float_dtype) * bucket_size
if self.extract_diagonal:
val += jnp.diag(self.diagonal)
return val
The provided code snippet includes necessary dependencies for implementing the `distributed_shampoo` function. Write a Python function `def distributed_shampoo( learning_rate, block_size, beta1=0.9, beta2=0.999, diagonal_epsilon=1e-10, matrix_epsilon=1e-6, weight_decay=0.0, start_preconditioning_step=5, preconditioning_compute_steps=1, statistics_compute_steps=1, best_effort_shape_interpretation=True, graft_type=GraftingType.SGD, nesterov=True, exponent_override=0, # Pass pmap 'batch axis name' in pmap mode. batch_axis_name=None, ### Only set following 3 params in pjit/spmd mode. ### WARNING: Experimental statistics_partition_spec=None, preconditioner_partition_spec=None, num_devices_for_pjit=None, shard_optimizer_states=False, ### ### Experimental memory reduction mode best_effort_memory_usage_reduction=False, ### inverse_failure_threshold=0.1, moving_average_for_momentum=False, skip_preconditioning_dim_size_gt=4096, clip_by_scaled_gradient_norm=None, precision=lax.Precision.HIGHEST, tensordot_precision=None, relative_matrix_epsilon=True, merge_small_dims_block_size=4096, lobpcg_topk_precondition=0, lobpcg_max_iter=0, precondtioner_type=PreconditionerType.ALL, skip_preconditioning_rank_lt=1, decoupled_learning_rate=True, decoupled_weight_decay=False, )` to solve the following problem:
Distributed Shampoo optimizer. Distributed Shampoo is a second-order preconditioned method (concretely, a variant of full-matrix Adagrad), that provides significant convergence and wall-clock time improvements compared to conventional first-order methods, and that has been shown to scale to large state-of-the-art deep learning models. References: Scalable Second Order Optimization for Deep Learning, Rohan Anil, Vineet Gupta, Tomer Koren, Kevin Regan, Yoram Singer Preprint: https://arxiv.org/abs/2002.09018 Args: learning_rate: the step size used to update the parameters. block_size: Block size for large layers (if > 0). Preconditioning compute operation is cubic in the dimension of the tensor. Block size allows us to chunk the layers into sub-layers of maximal dimension dictated by this value. Use 128 as default (increase if you have compute budget). beta1: momentum parameter. beta2: second moment averaging parameter. diagonal_epsilon: epsilon for diagonal adagrad (only if layerwise grafting to AdaGrad is enabled). matrix_epsilon: epsilon to add to statistics before computing inverse pth root. If you are running in f32 precision for inverse pth root (recommended today) this can go upto 1e-6. If you have latest hardware with native f64 precision, set this upto 1e-12. weight_decay: Weight decay for regularization. start_preconditioning_step: When to start Shampoo update before which diagonal update is used. This is because we dont have enough information to do stable inverse. preconditioning_compute_steps: How often to compute preconditioner. Performance tuning params for controlling memory and compute requirements. Ideally set this and statistics_compute_steps params to 1. statistics_compute_steps: How often to compute statistics. best_effort_shape_interpretation: If there are some small dimensions, collapse them e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if block = 1024, [1, 2, 768, 1, 2048] --> [2, 768, 2048] graft_type: Grafting is a technique to fix the layerwise scale of Shampoo optimizer. This allows us to plugin the Shampoo optimizer into settings where SGD/AdaGrad is already well tuned. nesterov: Nesterov momentum. exponent_override: Override the exponent used in matrix inverse. batch_axis_name: labeled axis over pmap for data-parallel training the optimizer used for. statistics_partition_spec: PartitionSpec to be used in sharded mode. preconditioner_partition_spec: PartitionSpec to be used in sharded mode. num_devices_for_pjit: Number of devices to parallelize over when using pjit. shard_optimizer_states: Shard optimizer states to save memory in model parallel training. best_effort_memory_usage_reduction: Best effort memory usage reduction. - diagonal_statistics -> jnp.bfloat16 - momentum buffers (2x) -> jnp.int8 - statistics, preconditioners -> jnp.int16 + diagonals inverse_failure_threshold: numerics are hard and inverses fail sometimes; we determine that using this threshold. moving_average_for_momentum: Whether to use moving average for momentum instead of exponential moving average. skip_preconditioning_dim_size_gt: Skip if preconditioning dim size is greater than this value. clip_by_scaled_gradient_norm: Clip by scaled gradient norm (only useful when using RMSProp Grafting). precision: precision XLA related flag, the available options are: a) lax.Precision.DEFAULT (better step time, but not precise) b) lax.Precision.HIGH (increased precision, slower) c) lax.Precision.HIGHEST (best possible precision, slowest) tensordot_precision: Optional precision to use for the tensordot operation when computing statistics (e.g., G Gᵀ). Same options as `precision` above. relative_matrix_epsilon: Whether to use relative epsilon to the max eigen value when computing inverse-pth root. merge_small_dims_block_size: Used as the maximum block size to merge the shapes. lobpcg_topk_precondition: If nonzero, specifies the number of top eigenvectors to subtract out before performing LOBPCG. Note this makes relative_matrix_epsilon essentially free. lobpcg_max_iter: Number of LOBPCG iterations, if zero defaults to `lobpcg_topk_precondition`. precondtioner_type: Preconditioner type to select all, left only or right only preconditioners. skip_preconditioning_rank_lt: Skips preconditioning for parameters with rank less than this value. decoupled_learning_rate: If True, use decoupled learning rate, otherwise couple it with preconditioned gradient computation. (Default True) decoupled_weight_decay: If True, use decoupled weight decay, otherwise couple with weight decay. (Default False) Returns: a GradientTransformation.
Here is the function:
def distributed_shampoo(
learning_rate,
block_size,
beta1=0.9,
beta2=0.999,
diagonal_epsilon=1e-10,
matrix_epsilon=1e-6,
weight_decay=0.0,
start_preconditioning_step=5,
preconditioning_compute_steps=1,
statistics_compute_steps=1,
best_effort_shape_interpretation=True,
graft_type=GraftingType.SGD,
nesterov=True,
exponent_override=0,
# Pass pmap 'batch axis name' in pmap mode.
batch_axis_name=None,
### Only set following 3 params in pjit/spmd mode.
### WARNING: Experimental
statistics_partition_spec=None,
preconditioner_partition_spec=None,
num_devices_for_pjit=None,
shard_optimizer_states=False,
###
### Experimental memory reduction mode
best_effort_memory_usage_reduction=False,
###
inverse_failure_threshold=0.1,
moving_average_for_momentum=False,
skip_preconditioning_dim_size_gt=4096,
clip_by_scaled_gradient_norm=None,
precision=lax.Precision.HIGHEST,
tensordot_precision=None,
relative_matrix_epsilon=True,
merge_small_dims_block_size=4096,
lobpcg_topk_precondition=0,
lobpcg_max_iter=0,
precondtioner_type=PreconditionerType.ALL,
skip_preconditioning_rank_lt=1,
decoupled_learning_rate=True,
decoupled_weight_decay=False,
):
"""Distributed Shampoo optimizer.
Distributed Shampoo is a second-order preconditioned method (concretely, a
variant of full-matrix Adagrad), that provides significant convergence and
wall-clock time improvements compared to conventional first-order methods,
and that has been shown to scale to large state-of-the-art deep learning
models.
References:
Scalable Second Order Optimization for Deep Learning,
Rohan Anil, Vineet Gupta, Tomer Koren, Kevin Regan, Yoram Singer
Preprint: https://arxiv.org/abs/2002.09018
Args:
learning_rate: the step size used to update the parameters.
block_size: Block size for large layers (if > 0). Preconditioning compute
operation is cubic in the dimension of the tensor. Block size allows us to
chunk the layers into sub-layers of maximal dimension dictated by this
value. Use 128 as default (increase if you have compute budget).
beta1: momentum parameter.
beta2: second moment averaging parameter.
diagonal_epsilon: epsilon for diagonal adagrad (only if layerwise grafting
to AdaGrad is enabled).
matrix_epsilon: epsilon to add to statistics before computing inverse pth
root. If you are running in f32 precision for inverse pth root
(recommended today) this can go upto 1e-6. If you have latest hardware
with native f64 precision, set this upto 1e-12.
weight_decay: Weight decay for regularization.
start_preconditioning_step: When to start Shampoo update before which
diagonal update is used. This is because we dont have enough information
to do stable inverse.
preconditioning_compute_steps: How often to compute preconditioner.
Performance tuning params for controlling memory and compute requirements.
Ideally set this and statistics_compute_steps params to 1.
statistics_compute_steps: How often to compute statistics.
best_effort_shape_interpretation: If there are some small dimensions,
collapse them e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if
block = 1024, [1, 2, 768, 1, 2048] --> [2, 768, 2048]
graft_type: Grafting is a technique to fix the layerwise scale of Shampoo
optimizer. This allows us to plugin the Shampoo optimizer into settings
where SGD/AdaGrad is already well tuned.
nesterov: Nesterov momentum.
exponent_override: Override the exponent used in matrix inverse.
batch_axis_name: labeled axis over pmap for data-parallel training the
optimizer used for.
statistics_partition_spec: PartitionSpec to be used in sharded mode.
preconditioner_partition_spec: PartitionSpec to be used in sharded mode.
num_devices_for_pjit: Number of devices to parallelize over when using pjit.
shard_optimizer_states: Shard optimizer states to save memory in model
parallel training.
best_effort_memory_usage_reduction: Best effort memory usage reduction. -
diagonal_statistics -> jnp.bfloat16 - momentum buffers (2x) -> jnp.int8 -
statistics, preconditioners -> jnp.int16 + diagonals
inverse_failure_threshold: numerics are hard and inverses fail sometimes; we
determine that using this threshold.
moving_average_for_momentum: Whether to use moving average for momentum
instead of exponential moving average.
skip_preconditioning_dim_size_gt: Skip if preconditioning dim size is
greater than this value.
clip_by_scaled_gradient_norm: Clip by scaled gradient norm (only useful when
using RMSProp Grafting).
precision: precision XLA related flag, the available options are: a)
lax.Precision.DEFAULT (better step time, but not precise) b)
lax.Precision.HIGH (increased precision, slower) c) lax.Precision.HIGHEST
(best possible precision, slowest)
tensordot_precision: Optional precision to use for the tensordot operation
when computing statistics (e.g., G Gᵀ). Same options as `precision` above.
relative_matrix_epsilon: Whether to use relative epsilon to the max eigen
value when computing inverse-pth root.
merge_small_dims_block_size: Used as the maximum block size
to merge the shapes.
lobpcg_topk_precondition: If nonzero, specifies the number of top
eigenvectors to subtract out before performing LOBPCG. Note this makes
relative_matrix_epsilon essentially free.
lobpcg_max_iter: Number of LOBPCG iterations, if zero defaults to
`lobpcg_topk_precondition`.
precondtioner_type: Preconditioner type to select all, left only or right
only preconditioners.
skip_preconditioning_rank_lt: Skips preconditioning for parameters with
rank less than this value.
decoupled_learning_rate: If True, use decoupled learning rate, otherwise
couple it with preconditioned gradient computation. (Default True)
decoupled_weight_decay: If True, use decoupled weight decay, otherwise
couple with weight decay. (Default False)
Returns:
a GradientTransformation.
"""
def _graft_type_has_diagonal_statistics():
"""Returns True if using diagonal firt order method for grafting."""
return graft_type != GraftingType.SGD and graft_type != GraftingType.SQRT_N
def quantized_dtype_for_momentum_buffers(var):
return (
jnp.int8
if best_effort_memory_usage_reduction and len(var.shape) > 1
else jnp.float32
)
# Preconditioner and statistics are both stores as int16 in this mode.
# We take out the diagonal to make quantization easier.
def quantized_dtype_for_second_moment_statistics_buffers():
return (
jnp.int16
if best_effort_memory_usage_reduction and batch_axis_name
else jnp.float32
)
# Preconditioner and statistics are both stores as int16 in this mode.
# We take out the diagonal to make quantization easier.
def quantized_dtype_for_second_moment_preconditioner_buffers():
return (
jnp.int16
if best_effort_memory_usage_reduction and batch_axis_name
else jnp.float32
)
def _to_float(maybe_quantized):
if isinstance(maybe_quantized, QuantizedValue):
return maybe_quantized.to_float()
else:
return maybe_quantized
def _maybe_quantize_statistics(statistics_list):
return _maybe_quantize_matrices_with_dtype(
statistics_list, quantized_dtype_for_second_moment_statistics_buffers()
)
def _maybe_quantize_preconditioners(statistics_list):
return _maybe_quantize_matrices_with_dtype(
statistics_list, quantized_dtype_for_second_moment_preconditioner_buffers()
)
def _maybe_quantize_matrices_with_dtype(statistics_list, quantized_dtype):
if quantized_dtype != jnp.float32:
return [
QuantizedValue.from_float_value(
s, quantized_dtype, extract_diagonal=True
)
for s in statistics_list
]
else:
return statistics_list
def _maybe_dequantize_preconditioners(preconditioner_list):
return _maybe_dequantize_matrices_with_dtype(
preconditioner_list,
quantized_dtype_for_second_moment_preconditioner_buffers(),
)
def _maybe_dequantize_matrices_with_dtype(statistics_list, quantized_dtype):
if quantized_dtype != jnp.float32:
return [s.to_float() for s in statistics_list]
else:
return statistics_list
def _quantize_diagonal_statistics(diagonal_statistics):
return QuantizedValue.from_float_value(diagonal_statistics, jnp.float32)
def _quantize_momentum(momentum_statistics):
return QuantizedValue.from_float_value(
momentum_statistics,
quantized_dtype_for_momentum_buffers(momentum_statistics),
)
def preconditioner_from_params(param):
"""Returns a Preconditioner object for given param."""
return Preconditioner(
param,
block_size,
merge_small_dims_block_size,
best_effort_shape_interpretation,
precondtioner_type,
)
def sharded_init_fn(params):
"""Returns optimizer state (for PJIT mode).
Args:
params: the parameters that should be updated.
"""
params_flat, treedef = jax.tree_flatten(params)
# Find max size to pad to.
max_size = 0
for param in params_flat:
preconditioner = preconditioner_from_params(param)
if not _skip_preconditioning(param):
shapes = preconditioner.shapes_for_preconditioners()
sizes = [s[0] for s in shapes]
max_size = max(max(sizes), max_size)
padded_statistics = []
padded_preconditioners = []
local_stats_flat = []
exponents = []
for param in params_flat:
preconditioner = preconditioner_from_params(param)
shapes = preconditioner.shapes_for_preconditioners()
sizes = []
statistics = []
preconditioners = []
index_start = len(padded_statistics)
if not _skip_preconditioning(param):
sizes = [s[0] for s in shapes]
shapes = preconditioner.shapes_for_preconditioners()
statistics = [
matrix_epsilon * jnp.eye(max_size, dtype=jnp.float32)
for s in shapes
]
preconditioners = [jnp.eye(max_size, dtype=jnp.float32) for s in shapes]
padded_statistics.extend(statistics)
padded_preconditioners.extend(preconditioners)
exponent = (
preconditioner.exponent_for_preconditioner()
if exponent_override == 0
else exponent_override
)
exponents.extend([exponent] * len(shapes))
diagonal_statistics = _quantize_diagonal_statistics(jnp.zeros_like(param))
diagonal_momentum = _quantize_momentum(jnp.zeros_like(param))
momentum = _quantize_momentum(jnp.zeros_like(param))
local_stats_flat.append(
LocalShardedParameterStats(
diagonal_statistics,
diagonal_momentum,
momentum,
init_training_metrics(len(sizes)),
index_start,
sizes,
)
)
local_stats = jax.tree_unflatten(treedef, local_stats_flat)
to_pad = -len(padded_statistics) % num_devices_for_pjit
if max_size == 0:
to_pad = num_devices_for_pjit
max_size = block_size
stat_dtype = jnp.float32
else:
stat_dtype = padded_statistics[0].dtype
# Pad the statistics and preconditioner matrices to be a multiple of
# num devices.
# TODO(rohananil): Relax to only the size of the mesh axis where the dim
# is split on.
padded_statistics.extend(
[jnp.eye(max_size, dtype=stat_dtype) for _ in range(to_pad)]
)
padded_preconditioners.extend(
[jnp.eye(max_size, dtype=stat_dtype) for _ in range(to_pad)]
)
exponents.extend([1 for _ in range(to_pad)])
global_stats = GlobalShardedParameterStats(
jnp.stack(padded_statistics),
jnp.stack(padded_preconditioners),
jnp.stack(exponents),
)
return ShampooState(
count=jnp.zeros([], jnp.int32),
stats=ShardedShampooStats(global_stats, local_stats),
)
def _max_statistics_size_from_params(params):
max_size = 0
for param in params:
param_clone = jnp.zeros(param.shape, dtype=param.dtype)
preconditioner = preconditioner_from_params(param_clone)
if not _skip_preconditioning(param):
shapes = preconditioner.shapes_for_preconditioners()
sizes = [s[0] for s in shapes]
max_size = max(max(sizes), max_size)
return max_size
def _remove_leading_sharding_annotation(pspec):
"""Mapping from N-d to (N-1)-d, used for quantization, factoring etc."""
# None and PSpec(None) are valid PSpecs.
if pspec and len(pspec) > 1:
return pjit.PartitionSpec(*pspec[1:])
else:
return []
def sharded_init_partition_spec_fn(
params, params_partition_spec, partition_spec_for_statistics
):
"""Returns a parallel state tree with PartitionSpec associated with state.
Args:
params: A pytree with params.
params_partition_spec: A pytree with PartitionSpec for params.
partition_spec_for_statistics: PartitionSpec for the statistics.
"""
# Parallel lists of spec, and params.
param_pspec_flat, _ = jax.tree_flatten(
params_partition_spec, is_leaf=lambda x: x is None
)
params_flat, treedef = jax.tree_flatten(params)
assert param_pspec_flat
assert params_flat
# Step is replicated across cores.
# None means cores.
local_stats_flat = []
num_statistics = 0
for param, param_pspec in zip(params_flat, param_pspec_flat):
param_clone = jnp.zeros(param.shape, dtype=param.dtype)
preconditioner = preconditioner_from_params(param_clone)
shapes = preconditioner.shapes_for_preconditioners()
sizes = []
index_start = num_statistics
if not _skip_preconditioning(param):
sizes = [s[0] for s in shapes]
shapes = preconditioner.shapes_for_preconditioners()
num_statistics += len(shapes)
qdtype = quantized_dtype_for_momentum_buffers(param)
m1_pspec = param_pspec
m2_pspec = param_pspec
m1_scale_pspec = []
m2_scale_pspec = []
if qdtype != jnp.float32:
m1_scale_pspec = _remove_leading_sharding_annotation(m1_pspec)
m2_scale_pspec = _remove_leading_sharding_annotation(m2_pspec)
local_stats_flat.append(
LocalShardedParameterStats(
QuantizedValue(
param_pspec, [], [], jnp.float32, False, list(param.shape)
),
QuantizedValue(
m1_pspec, [], m1_scale_pspec, qdtype, False, list(param.shape)
),
QuantizedValue(
m2_pspec, [], m2_scale_pspec, qdtype, False, list(param.shape)
),
init_training_metrics_pspec(),
index_start,
sizes,
)
)
local_stats = jax.tree_unflatten(treedef, local_stats_flat)
global_stats = GlobalShardedParameterStats(
partition_spec_for_statistics,
partition_spec_for_statistics,
pjit.PartitionSpec(),
)
count_pspec = pjit.PartitionSpec()
return ShampooState(
count=count_pspec, stats=ShardedShampooStats(global_stats, local_stats)
)
def sharded_init_shape_and_dtype_fn(params):
"""Returns a parallel state tree with shape, dtype associated with state.
Args:
params: A pytree with params.
"""
# Parallel lists of spec, and params.
params_flat, treedef = jax.tree_flatten(params)
assert params_flat
# Step is replicated across cores.
# None means cores.
local_stats_flat = []
num_statistics = 0
for param in params_flat:
param_clone = jnp.zeros(param.shape, dtype=param.dtype)
preconditioner = preconditioner_from_params(param_clone)
shapes = preconditioner.shapes_for_preconditioners()
sizes = []
index_start = num_statistics
if not _skip_preconditioning(param):
sizes = [s[0] for s in shapes]
shapes = preconditioner.shapes_for_preconditioners()
num_statistics += len(shapes)
qdtype = quantized_dtype_for_momentum_buffers(param)
m1_shape_and_dtype = [list(param.shape), param.dtype]
m2_shape_and_dtype = [list(param.shape), param.dtype]
m1_scale_shape_and_dtype = []
m2_scale_shape_and_dtype = []
if qdtype != jnp.float32:
m1_scale_shape_and_dtype = [list(param.shape)[1:], qdtype]
m2_scale_shape_and_dtype = [list(param.shape)[1:], qdtype]
diagonal_statistics_shape_and_dtype = [list(param.shape), param.dtype]
local_stats_flat.append(
LocalShardedParameterStats(
QuantizedValue(
diagonal_statistics_shape_and_dtype,
[],
[],
jnp.float32,
False,
list(param.shape),
),
QuantizedValue(
m1_shape_and_dtype,
[],
m1_scale_shape_and_dtype,
qdtype,
False,
list(param.shape),
),
QuantizedValue(
m2_shape_and_dtype,
[],
m2_scale_shape_and_dtype,
qdtype,
False,
list(param.shape),
),
init_training_metrics_shapes(len(sizes)),
index_start,
sizes,
)
)
local_stats = jax.tree_unflatten(treedef, local_stats_flat)
max_statistics_size = _max_statistics_size_from_params(params_flat)
to_pad = -num_statistics % num_devices_for_pjit
num_statistics += to_pad
if num_statistics == 0:
num_statistics = num_devices_for_pjit
max_statistics_size = block_size
statistics_shape = [num_statistics, max_statistics_size, max_statistics_size]
global_stats = GlobalShardedParameterStats(
[statistics_shape, jnp.float32],
[statistics_shape, jnp.float32],
[[num_statistics], jnp.int32],
)
return ShampooState(
count=[[], jnp.float32],
stats=ShardedShampooStats(global_stats, local_stats),
)
def sharded_update_fn(grads, state, params):
"""Transform the input gradient and update all statistics in sharded mode.
Args:
grads: the gradient tensors for the parameters.
state: a named tuple containing the state of the optimizer
params: the parameters that should be updated.
Returns:
A tuple containing the new parameters and the new optimizer state.
"""
params_flat, treedef = jax.tree_flatten(params)
grads_flat = treedef.flatten_up_to(grads)
global_stats = state.stats.global_stats
local_stats_flat = treedef.flatten_up_to(state.stats.local_stats)
stats_flat = [
_convert_to_parameter_stats(global_stats, local_stat)
for local_stat in local_stats_flat
]
new_stats_flat = jax.tree_map(
lambda g, s, p: _compute_stats(g, s, p, state.count),
grads_flat,
stats_flat,
params_flat,
)
outputs = jax.tree_map(
lambda g, s, p: _transform_grad(g, s, p, state.count),
grads_flat,
new_stats_flat,
params_flat,
)
updates_flat, new_stats_flat = list(zip(*outputs)) if outputs else ((), ())
updates = jax.tree_unflatten(treedef, updates_flat)
# Create new local_stats
new_local_stats_flat = [
_convert_from_parameter_stats(new_stat, local_stat)
for new_stat, local_stat in zip(new_stats_flat, local_stats_flat)
]
max_size = global_stats.statistics.shape[1]
new_padded_statistics = []
for stat in new_stats_flat:
new_padded_statistics.extend(
[pad_square_matrix(stat, max_size) for stat in stat.statistics]
)
# Create global stats
# TODO(rohananil): Preconditioner is not updated every step, so cost of
# stack/pad can be obviated away.
# Pad the statistics and preconditioner matrices to be a multiple of
# num devices.
# TODO(rohananil): Relax to only the size of the mesh axis where the dim
# is split on.
to_pad = -len(new_padded_statistics) % num_devices_for_pjit
if not new_padded_statistics:
to_pad = num_devices_for_pjit
stat_dtype = jnp.float32
else:
stat_dtype = new_padded_statistics[0].dtype
new_padded_statistics.extend(
[jnp.eye(max_size, dtype=stat_dtype) for _ in range(to_pad)]
)
new_stacked_padded_statistics = jnp.stack(new_padded_statistics)
new_stacked_padded_statistics = pjit.with_sharding_constraint(
new_stacked_padded_statistics, statistics_partition_spec
)
def _internal_inverse_pth_root_all():
preconditioners, errors = _matrix_inverse_pth_root_pjit(
new_stacked_padded_statistics,
global_stats.exponents,
statistics_partition_spec,
)
return preconditioners, errors
if preconditioning_compute_steps == 1:
new_preconditioners, errors = _internal_inverse_pth_root_all()
else:
# Passing statistics instead of preconditioners as they are similarly
# shaped tensors. Note statistics will be ignored as we are passing in
# a large init value for error.
preconditioners_init = new_stacked_padded_statistics
n = new_stacked_padded_statistics.shape[0]
errors_init = jnp.ones([n], jnp.float32) * inverse_failure_threshold
init_state = [preconditioners_init, errors_init]
perform_step = state.count % preconditioning_compute_steps == 0
new_preconditioners, errors = efficient_cond(
perform_step, _internal_inverse_pth_root_all, init_state
)
new_local_stats_flat = _add_error_into_local_stats(
new_local_stats_flat, errors, inverse_failure_threshold
)
new_local_stats = jax.tree_unflatten(treedef, new_local_stats_flat)
errors = errors.reshape((-1, 1, 1))
predicate = jnp.logical_or(
jnp.isnan(errors), errors >= inverse_failure_threshold
).astype(new_preconditioners.dtype)
# TODO(rohananil): Check for numerical instabilities.
new_conditional_preconditioners = (
predicate * global_stats.preconditioners
+ (1.0 - predicate) * new_preconditioners
)
new_global_stats = GlobalShardedParameterStats(
new_stacked_padded_statistics,
new_conditional_preconditioners,
global_stats.exponents,
)
new_shampoo_state = ShampooState(
count=state.count + 1,
stats=ShardedShampooStats(new_global_stats, new_local_stats),
)
return updates, new_shampoo_state
def init_fn(params):
"""Initialise the optimiser's state."""
def _init(param):
preconditioner = preconditioner_from_params(param)
statistics = []
preconditioners = []
if not _skip_preconditioning(param):
shapes = preconditioner.shapes_for_preconditioners()
statistics = [
matrix_epsilon * jnp.eye(s[0], dtype=jnp.float32) for s in shapes
]
preconditioners = [jnp.eye(s[0], dtype=jnp.float32) for s in shapes]
diagonal_statistics = []
if _graft_type_has_diagonal_statistics():
diagonal_statistics = jnp.zeros_like(param)
diagonal_momentum = _quantize_momentum(jnp.zeros_like(param))
momentum = _quantize_momentum(jnp.zeros_like(param))
return ParameterStats(
_quantize_diagonal_statistics(diagonal_statistics),
_maybe_quantize_statistics(statistics),
_maybe_quantize_preconditioners(preconditioners),
diagonal_momentum,
momentum,
init_training_metrics(len(statistics)),
)
return ShampooState(
count=jnp.zeros([], jnp.int32), stats=jax.tree_map(_init, params)
)
def _skip_preconditioning(param):
return len(param.shape) < skip_preconditioning_rank_lt or any(
[s > skip_preconditioning_dim_size_gt for s in param.shape]
)
def _compute_stats(grad, state, param, step):
"""Compute per-parameter statistics."""
preconditioner = preconditioner_from_params(param)
new_statistics = [[]] * len(state.statistics)
w1 = beta2
w2 = beta2 if beta2 == 1.0 else (1.0 - beta2)
if not _skip_preconditioning(param):
def compute_updated_statistics():
return preconditioner.updated_statistics_from_grad(
state.statistics,
grad,
w1=w1,
w2=w2,
to_float=_to_float,
from_float=lambda x: _maybe_quantize_statistics([x])[0],
precision=tensordot_precision,
)
if statistics_compute_steps > 1:
perform_step = step % statistics_compute_steps == 0
init_state = state.statistics
new_statistics = list(
efficient_cond(perform_step, compute_updated_statistics, init_state)
)
else:
new_statistics = compute_updated_statistics()
return ParameterStats(
state.diagonal_statistics,
new_statistics,
state.preconditioners,
state.diagonal_momentum,
state.momentum,
state.training_metrics,
)
mi_pth_root = functools.partial(
matrix_inverse_pth_root,
ridge_epsilon=matrix_epsilon,
precision=precision,
relative_matrix_epsilon=relative_matrix_epsilon,
lobpcg_topk_precondition=lobpcg_topk_precondition,
lobpcg_max_iter=lobpcg_max_iter,
)
def _matrix_inverse_pth_root_vmap(xs, ps):
return jax.vmap(mi_pth_root)(xs, ps)
def _quantized_matrix_inverse_pth_root_vmap(qxs, qds, qbs, ps):
def _quantized_to_float(qx, qd, qb):
qv = QuantizedValue(qx, qd, qb, qx.dtype, True, list(qx.shape))
return qv.to_float()
def matrix_inverse_pth_root_wrapper(qx, qd, qb, p):
v = _quantized_to_float(qx, qd, qb)
preconditioner, error = mi_pth_root(v, p)
qp = QuantizedValue.from_float_value(preconditioner, qx.dtype, True)
return qp.quantized, qp.diagonal, qp.bucket_size, error
return jax.vmap(matrix_inverse_pth_root_wrapper)(qxs, qds, qbs, ps)
def _matrix_inverse_pth_root_pjit(xs, ps, statistics_partition_spec=None):
# Partition the concatenated statistics matrix across all cores.
pspec_for_partition = preconditioner_partition_spec
partitioned_xs = pjit.with_sharding_constraint(xs, pspec_for_partition)
if preconditioner_partition_spec:
partitioned_ps_spec = pjit.PartitionSpec(preconditioner_partition_spec[0])
else:
partitioned_ps_spec = None
partitioned_ps = pjit.with_sharding_constraint(ps, partitioned_ps_spec)
# Run matrix inverse pth root on each shard.
partitioned_preconditioners, partitioned_errors = _matrix_inverse_pth_root_vmap(
partitioned_xs, partitioned_ps
)
# Reshard output to have the same PSpec as input. This is required to avoid
# vmap seeing the full set of statistics.
partitioned_preconditioners = pjit.with_sharding_constraint(
partitioned_preconditioners, pspec_for_partition
)
# Recombine the outputs at each core.
preconditioners = pjit.with_sharding_constraint(
partitioned_preconditioners, statistics_partition_spec
)
errors = pjit.with_sharding_constraint(partitioned_errors, pjit.PartitionSpec())
return preconditioners, errors
def _pmap_compute_preconditioners(
states,
step,
statistics,
num_statistics_per_state,
original_shapes,
exponents,
max_size,
prev_preconditioners,
):
"""Computes preconditioners for given statistics in states in PMAP mode.
Args:
states: A list of optimizer states.
step: Current step number
statistics: A list of statistics for all variables (for every dim)
num_statistics_per_state: Number of statistis per state to reconstruct
output states.
original_shapes: A list of shapes of the statistics.
exponents: Exponent power to use for inverse-pth roots.
max_size: Maximum dim of the statistics to pad.
prev_preconditioners: Previously available preconditioner.
Returns:
New optimizer states after computing the preconditioner.
"""
if batch_axis_name:
num_devices = lax.psum(1, batch_axis_name)
else:
num_devices = 1
num_statistics = len(statistics)
# Pad statistics and exponents to next multiple of num_devices.
packed_statistics = [pad_square_matrix(stat, max_size) for stat in statistics]
to_pad = -num_statistics % num_devices
packed_statistics.extend(
[jnp.eye(max_size, dtype=packed_statistics[0].dtype) for _ in range(to_pad)]
)
exponents.extend([1 for _ in range(to_pad)])
if not packed_statistics:
return states
all_statistics = batch(packed_statistics, num_devices)
all_exponents = batch(exponents, num_devices)
def _internal_inverse_pth_root_all():
if batch_axis_name:
current_replica = lax.axis_index(batch_axis_name)
preconditioners, errors = _matrix_inverse_pth_root_vmap(
all_statistics[current_replica], all_exponents[current_replica]
)
preconditioners = jax.lax.all_gather(preconditioners, batch_axis_name)
errors = jax.lax.all_gather(errors, batch_axis_name)
preconditioners_flat = unbatch(preconditioners)
errors_flat = unbatch(errors)
else:
preconditioners, errors = _matrix_inverse_pth_root_vmap(
all_statistics[0], all_exponents[0]
)
preconditioners_flat = unbatch(jnp.stack([preconditioners]))
errors_flat = unbatch(jnp.stack([errors]))
return preconditioners_flat, errors_flat
if preconditioning_compute_steps == 1:
preconditioners_flat, errors_flat = _internal_inverse_pth_root_all()
else:
# Passing statistics instead of preconditioners as they are similarly
# shaped tensors. Note statistics will be ignored as we are passing in
# a large init value for error.
preconditioners_init = packed_statistics
errors_init = [inverse_failure_threshold] * len(packed_statistics)
init_state = [preconditioners_init, errors_init]
perform_step = step % preconditioning_compute_steps == 0
preconditioners_flat, errors_flat = efficient_cond(
perform_step, _internal_inverse_pth_root_all, init_state
)
def _skip(error):
condition = jnp.logical_or(
jnp.isnan(error), error >= inverse_failure_threshold
)
return condition.astype(error.dtype)
def _select_preconditioner(error, new_p, old_p):
return lax.cond(
_skip(error), lambda _: old_p, lambda _: new_p, operand=None
)
new_preconditioners_flat = []
new_errors_flat = []
for p, shape, prev_p, error in zip(
preconditioners_flat, original_shapes, prev_preconditioners, errors_flat
):
new_preconditioners_flat.append(
_select_preconditioner(error, p[: shape[0], : shape[1]], prev_p)
)
new_errors_flat.append(error)
assert len(states) == len(num_statistics_per_state)
assert len(new_preconditioners_flat) == num_statistics
assert len(new_errors_flat) == num_statistics
# Add back empty preconditioners so we that we can set the optimizer state.
preconditioners_for_states = []
idx = 0
errors_for_states = []
for num_statistics, state in zip(num_statistics_per_state, states):
if num_statistics == 0:
preconditioners_for_states.append([])
errors_for_states.append(jnp.array(0, jnp.float32))
else:
preconditioners_for_state = new_preconditioners_flat[
idx : idx + num_statistics
]
assert len(state.statistics) == len(preconditioners_for_state)
preconditioners_for_states.append(preconditioners_for_state)
errors_for_state = jnp.stack(
new_errors_flat[idx : idx + num_statistics]
)
assert len(state.statistics) == len(errors_for_state)
errors_for_states.append(errors_for_state)
idx += num_statistics
new_states = []
for state, new_preconditioners, new_errors in zip(
states, preconditioners_for_states, errors_for_states
):
if state.statistics:
new_errors = jnp.where(
jnp.logical_and(
new_errors > 0.0, new_errors != inverse_failure_threshold
),
new_errors,
state.training_metrics.inverse_pth_root_errors,
)
new_training_metrics = TrainingMetrics(new_errors)
new_states.append(
ParameterStats(
state.diagonal_statistics,
state.statistics,
new_preconditioners,
state.diagonal_momentum,
state.momentum,
new_training_metrics,
)
)
return new_states
def _pmap_quantized_compute_preconditioners(
states,
step,
statistics,
num_statistics_per_state,
original_shapes,
exponents,
max_size,
prev_preconditioners,
):
"""Computes preconditioners for given statistics in states in PMAP mode.
For quantization, each statistic is represented by three values:
quantized matrix, diagonal, and bucket sizes, we run inverse pth-roots
without ever recreating the original matrix in f32.
Args:
states: A list of optimizer states.
step: Current step number
statistics: A list of statistics for all variables (for every dim)
num_statistics_per_state: Number of statistis per state to reconstruct
output states.
original_shapes: A list of shapes of the statistics.
exponents: Exponent power to use for inverse-pth roots.
max_size: Maximum dim of the statistics to pad.
prev_preconditioners: Previously available preconditioner.
Returns:
New optimizer states after computing the preconditioner.
"""
num_devices = lax.psum(1, batch_axis_name)
num_statistics = len(statistics)
quantized_dtype = quantized_dtype_for_second_moment_statistics_buffers()
# Complexity here is around: shapes needing be statically shaped,
# our custom quantization type requires a different type of packing.
# Parallel tensors:
# quantized [dxd]
# diagonals [d] f32
# bucket_sizes [d] f32
packed_quantized_statistics = [
pad_square_matrix(stat.quantized, max_size) for stat in statistics
]
packed_quantized_diagonals = [
pad_vector(stat.diagonal, max_size) for stat in statistics
]
packed_quantized_bucket_sizes = [
pad_vector(stat.bucket_size, max_size) for stat in statistics
]
to_pad = -num_statistics % num_devices
padded_eye = jnp.eye(max_size, dtype=jnp.float32)
quantized_eye = QuantizedValue.from_float_value(
padded_eye, quantized_dtype, True
)
packed_quantized_statistics.extend(
[quantized_eye.quantized for _ in range(to_pad)]
)
packed_quantized_diagonals.extend(
[quantized_eye.diagonal for _ in range(to_pad)]
)
packed_quantized_bucket_sizes.extend(
[quantized_eye.bucket_size for _ in range(to_pad)]
)
exponents.extend([1 for _ in range(to_pad)])
if not packed_quantized_statistics:
return states
all_quantized_statistics = batch(packed_quantized_statistics, num_devices)
all_quantized_diagonals = batch(packed_quantized_diagonals, num_devices)
all_quantized_bucket_sizes = batch(packed_quantized_bucket_sizes, num_devices)
all_exponents = batch(exponents, num_devices)
def _internal_inverse_pth_root_all():
current_replica = lax.axis_index(batch_axis_name)
(
quantized_preconditioners,
quantized_diagonals,
quantized_bucket_sizes,
errors,
) = _quantized_matrix_inverse_pth_root_vmap(
all_quantized_statistics[current_replica],
all_quantized_diagonals[current_replica],
all_quantized_bucket_sizes[current_replica],
all_exponents[current_replica],
)
quantized_preconditioners = jax.lax.all_gather(
quantized_preconditioners, batch_axis_name
)
quantized_diagonals = jax.lax.all_gather(
quantized_diagonals, batch_axis_name
)
quantized_bucket_sizes = jax.lax.all_gather(
quantized_bucket_sizes, batch_axis_name
)
errors = jax.lax.all_gather(errors, batch_axis_name)
quantized_preconditioners_flat = unbatch(quantized_preconditioners)
quantized_diagonals_flat = unbatch(quantized_diagonals)
quantized_bucket_sizes_flat = unbatch(quantized_bucket_sizes)
errors_flat = unbatch(errors)
return (
quantized_preconditioners_flat,
quantized_diagonals_flat,
quantized_bucket_sizes_flat,
errors_flat,
)
if preconditioning_compute_steps == 1:
(
quantized_preconditioners_flat,
quantized_diagonals_flat,
quantized_bucket_sizes_flat,
errors_flat,
) = _internal_inverse_pth_root_all()
else:
# Passing statistics instead of preconditioners as they are similarly
# shaped tensors. Note statistics will be ignored as we are passing in
# a large init value for error.
quantized_preconditioners_init = packed_quantized_statistics
quantized_diagonals_init = packed_quantized_diagonals
quantized_bucket_sizes_init = packed_quantized_bucket_sizes
errors_init = [inverse_failure_threshold] * len(
quantized_preconditioners_init
)
init_state = [
quantized_preconditioners_init,
quantized_diagonals_init,
quantized_bucket_sizes_init,
errors_init,
]
perform_step = step % preconditioning_compute_steps == 0
(
quantized_preconditioners_flat,
quantized_diagonals_flat,
quantized_bucket_sizes_flat,
errors_flat,
) = efficient_cond(perform_step, _internal_inverse_pth_root_all, init_state)
def _skip(error):
condition = jnp.logical_or(
jnp.isnan(error), error >= inverse_failure_threshold
)
return condition.astype(error.dtype)
def _select_preconditioner(error, new_p, old_p):
return lax.cond(
_skip(error), lambda _: old_p, lambda _: new_p, operand=None
)
new_quantized_preconditioners_flat = []
new_quantized_diagonals_flat = []
new_quantized_bucket_sizes_flat = []
new_errors_flat = []
for p, d, b, shape, prev_p, error in zip(
quantized_preconditioners_flat,
quantized_diagonals_flat,
quantized_bucket_sizes_flat,
original_shapes,
prev_preconditioners,
errors_flat,
):
new_quantized_preconditioners_flat.append(
_select_preconditioner(
error, p[: shape[0], : shape[1]], prev_p.quantized
)
)
new_quantized_diagonals_flat.append(
_select_preconditioner(error, d[: shape[0]], prev_p.diagonal)
)
new_quantized_bucket_sizes_flat.append(
_select_preconditioner(error, b[: shape[0]], prev_p.bucket_size)
)
new_errors_flat.append(error)
assert len(states) == len(num_statistics_per_state)
assert len(new_quantized_preconditioners_flat) == num_statistics
assert len(new_quantized_diagonals_flat) == num_statistics
assert len(new_quantized_bucket_sizes_flat) == num_statistics
# Add back empty preconditioners so we that we can set the optimizer state.
preconditioners_for_states = []
errors_for_states = []
idx = 0
for num_statistics, state in zip(num_statistics_per_state, states):
if num_statistics == 0:
preconditioners_for_states.append([])
errors_for_states.append(jnp.array(0, jnp.float32))
else:
quantized_preconditioners_for_state = (
new_quantized_preconditioners_flat[idx : idx + num_statistics]
)
quantized_diagonals_for_state = new_quantized_diagonals_flat[
idx : idx + num_statistics
]
quantized_bucket_sizes_for_state = new_quantized_bucket_sizes_flat[
idx : idx + num_statistics
]
errors_for_state = jnp.stack(
new_errors_flat[idx : idx + num_statistics]
)
assert len(state.statistics) == len(quantized_preconditioners_for_state)
assert len(state.statistics) == len(quantized_diagonals_for_state)
assert len(state.statistics) == len(quantized_bucket_sizes_for_state)
assert len(state.statistics) == len(errors_for_state)
quantized_preconditioners = []
for qv, qd, qb in zip(
quantized_preconditioners_for_state,
quantized_diagonals_for_state,
quantized_bucket_sizes_for_state,
):
quantized_preconditioners.append(
QuantizedValue(qv, qd, qb, qv.dtype, True, list(qv.shape))
)
preconditioners_for_states.append(quantized_preconditioners)
errors_for_states.append(errors_for_state)
idx += num_statistics
new_states = []
for state, new_preconditioners, new_errors in zip(
states, preconditioners_for_states, errors_for_states
):
if state.statistics:
new_errors = jnp.where(
jnp.logical_and(
new_errors > 0.0, new_errors != inverse_failure_threshold
),
new_errors,
state.training_metrics.inverse_pth_root_errors,
)
new_training_metrics = TrainingMetrics(new_errors)
new_states.append(
ParameterStats(
state.diagonal_statistics,
state.statistics,
new_preconditioners,
state.diagonal_momentum,
state.momentum,
new_training_metrics,
)
)
return new_states
def _pjit_compute_preconditioners(
states,
step,
statistics,
num_statistics_per_state,
original_shapes,
exponents,
max_size,
prev_preconditioners,
):
"""Computes preconditioners for given statistics in states in PJIT mode.
Args:
states: A list of optimizer states.
step: Current step number
statistics: A list of statistics for all variables (for every dim)
num_statistics_per_state: Number of statistis per state to reconstruct
output states.
original_shapes: A list of shapes of the statistics.
exponents: Exponent power to use for inverse-pth roots.
max_size: Maximum dim of the statistics to pad.
prev_preconditioners: Previously available preconditioner.
Returns:
New optimizer states after computing the preconditioner.
"""
num_statistics = len(statistics)
to_pad = -num_statistics % num_devices_for_pjit
padded_statistics = [pad_square_matrix(stat, max_size) for stat in statistics]
padded_statistics.extend(
[jnp.eye(max_size, dtype=padded_statistics[0].dtype) for _ in range(to_pad)]
)
exponents.extend([1 for _ in range(to_pad)])
all_statistics = jnp.stack(padded_statistics)
all_exponents = jnp.stack(exponents)
def _internal_inverse_pth_root_all():
preconditioners, errors = _matrix_inverse_pth_root_pjit(
all_statistics, all_exponents
)
b1 = preconditioners.shape[0]
def split(batched_values):
return [
jnp.squeeze(v)
for v in jnp.split(batched_values, indices_or_sections=b1, axis=0)
]
return split(preconditioners), split(errors)
if preconditioning_compute_steps == 1:
preconditioners_flat, errors_flat = _internal_inverse_pth_root_all()
else:
# Passing statistics instead of preconditioners as they are similarly
# shaped tensors. Note statistics will be ignored as we are passing in
# a large init value for error.
preconditioners_init = padded_statistics
errors_init = [inverse_failure_threshold] * len(padded_statistics)
init_state = [preconditioners_init, errors_init]
perform_step = step % preconditioning_compute_steps == 0
preconditioners_flat, errors_flat = efficient_cond(
perform_step, _internal_inverse_pth_root_all, init_state
)
def _skip(error):
condition = jnp.logical_or(
jnp.isnan(error), error >= inverse_failure_threshold
)
return condition.astype(error.dtype)
def _select_preconditioner(error, new_p, old_p):
return lax.cond(
_skip(error), lambda _: old_p, lambda _: new_p, operand=None
)
new_preconditioners_flat = []
new_errors_flat = []
for p, shape, prev_p, error in zip(
preconditioners_flat, original_shapes, prev_preconditioners, errors_flat
):
new_preconditioners_flat.append(
_select_preconditioner(error, p[: shape[0], : shape[1]], prev_p)
)
new_errors_flat.append(error)
assert len(states) == len(num_statistics_per_state)
assert len(new_preconditioners_flat) == num_statistics
# Add back empty preconditioners so we that we can set the optimizer state.
preconditioners_for_states = []
errors_for_states = []
idx = 0
for num_statistics, state in zip(num_statistics_per_state, states):
if num_statistics == 0:
preconditioners_for_states.append([])
errors_for_states.append(jnp.array(0, jnp.float32))
else:
preconditioners_for_state = new_preconditioners_flat[
idx : idx + num_statistics
]
assert len(state.statistics) == len(preconditioners_for_state)
preconditioners_for_states.append(preconditioners_for_state)
errors_for_state = jnp.stack(
new_errors_flat[idx : idx + num_statistics]
)
assert len(state.statistics) == len(errors_for_state)
errors_for_states.append(errors_for_state)
idx += num_statistics
new_states = []
for state, new_preconditioners, new_errors in zip(
states, preconditioners_for_states, errors_for_states
):
if state.statistics:
new_errors = jnp.where(
jnp.logical_and(
new_errors > 0.0, new_errors != inverse_failure_threshold
),
new_errors,
state.training_metrics.inverse_pth_root_errors,
)
new_training_metrics = TrainingMetrics(new_errors)
new_states.append(
ParameterStats(
state.diagonal_statistics,
state.statistics,
new_preconditioners,
state.diagonal_momentum,
state.momentum,
new_training_metrics,
)
)
return new_states
def _compute_preconditioners(states, params, step):
"""Computes preconditioners for given statistics in states.
Args:
states: A list of optimizer states.
params: A list of params.
step: Current step number
Returns:
New optimizer states after computing the preconditioner.
"""
statistics = []
num_statistics_per_state = []
original_shapes = []
exponents = []
max_size = 0
prev_preconditioners = []
for state, param in zip(states, params):
num_statistics = len(state.statistics)
num_statistics_per_state.append(num_statistics)
original_shapes_for_state = []
if num_statistics > 0:
preconditioner = preconditioner_from_params(param)
for statistic in state.statistics:
exponents.append(
preconditioner.exponent_for_preconditioner()
if exponent_override == 0
else exponent_override
)
original_shapes_for_state.append(statistic.shape)
max_size = max(max_size, statistic.shape[0])
statistics.extend(state.statistics)
prev_preconditioners.extend(state.preconditioners)
original_shapes.extend(original_shapes_for_state)
if not shard_optimizer_states:
# Quantization is only enabled if batch_axis_name is not set.
quantized_dtype = quantized_dtype_for_second_moment_statistics_buffers()
if quantized_dtype == jnp.float32:
return _pmap_compute_preconditioners(
states,
step,
statistics,
num_statistics_per_state,
original_shapes,
exponents,
max_size,
prev_preconditioners,
)
else:
return _pmap_quantized_compute_preconditioners(
states,
step,
statistics,
num_statistics_per_state,
original_shapes,
exponents,
max_size,
prev_preconditioners,
)
else:
return _pjit_compute_preconditioners(
states,
step,
statistics,
num_statistics_per_state,
original_shapes,
exponents,
max_size,
prev_preconditioners,
)
def _transform_grad(grad, state, param, step):
"""Transform per-parameter gradients."""
preconditioner = preconditioner_from_params(param)
sgd_update = grad
new_diagonal_statistics = state.diagonal_statistics.to_float()
if (
graft_type == GraftingType.ADAGRAD
or graft_type == GraftingType.ADAGRAD_NORMALIZED
):
scaled_grad = grad
if graft_type == GraftingType.ADAGRAD_NORMALIZED:
scaled_grad = grad / (jnp.linalg.norm(grad) + 1e-16)
new_diagonal_statistics = state.diagonal_statistics.to_float() + jnp.square(
scaled_grad
)
adagrad_update = scaled_grad / (
jnp.sqrt(new_diagonal_statistics) + diagonal_epsilon
)
grafting_update = adagrad_update
elif (
graft_type == GraftingType.RMSPROP
or graft_type == GraftingType.RMSPROP_NORMALIZED
):
scaled_grad = grad
if graft_type == GraftingType.RMSPROP_NORMALIZED:
scaled_grad = grad / (jnp.linalg.norm(grad) + 1e-16)
w1 = beta2
w2 = beta2 if beta2 == 1.0 else (1.0 - beta2)
new_diagonal_statistics = (
w1 * state.diagonal_statistics.to_float() + w2 * jnp.square(scaled_grad)
)
rmsprop_update = scaled_grad / (
jnp.sqrt(new_diagonal_statistics) + diagonal_epsilon
)
if clip_by_scaled_gradient_norm:
scaled_grad_norm = jnp.linalg.norm(rmsprop_update) / (
jnp.sqrt(float(rmsprop_update.size))
)
clipping_denom = jnp.maximum(
1.0, scaled_grad_norm / clip_by_scaled_gradient_norm
)
rmsprop_update /= clipping_denom
grafting_update = rmsprop_update
elif graft_type == GraftingType.SGD:
grafting_update = sgd_update
else:
grafting_update = jnp.ones_like(sgd_update) * jnp.sign(sgd_update)
lr = learning_rate
if callable(learning_rate):
lr = learning_rate(step)
preconditioner_multiplier = lr if not decoupled_learning_rate else 1.0
grafting_update = grafting_update * preconditioner_multiplier
precond_grad = grad
if not _skip_preconditioning(param):
precond_grad = preconditioner.preconditioned_grad(
precond_grad, _maybe_dequantize_preconditioners(state.preconditioners)
)
else:
precond_grad = grafting_update
grafting_update_norm = jnp.linalg.norm(grafting_update)
precond_grad_norm = jnp.linalg.norm(precond_grad)
multiplier = grafting_update_norm / (precond_grad_norm + 1e-16)
shampoo_update = precond_grad * multiplier
shampoo_update_with_wd = shampoo_update
grafting_update_with_wd = grafting_update
if weight_decay != 0 and not decoupled_weight_decay:
shampoo_update_with_wd = shampoo_update + weight_decay * param
grafting_update_with_wd = grafting_update + weight_decay * param
w = (1.0 - beta1) if moving_average_for_momentum else 1.0
shampoo_update_with_wd_momentum = (
state.momentum.to_float() * beta1 + w * shampoo_update_with_wd
)
grafting_update_with_wd_momentum = (
state.diagonal_momentum.to_float() * beta1 + w * grafting_update_with_wd
)
run_shampoo = (step >= start_preconditioning_step).astype(
grafting_update_with_wd_momentum.dtype
)
momentum_update = (
run_shampoo * shampoo_update_with_wd_momentum
+ (1.0 - run_shampoo) * grafting_update_with_wd_momentum
)
wd_update = (
run_shampoo * shampoo_update_with_wd
+ (1.0 - run_shampoo) * grafting_update_with_wd
)
nesterov_momentum_update = momentum_update
if nesterov:
nesterov_momentum_update = w * wd_update + beta1 * momentum_update
if weight_decay != 0 and decoupled_weight_decay:
nesterov_momentum_update = (
nesterov_momentum_update + lr * weight_decay * param
)
momentum_multiplier = lr if decoupled_learning_rate else 1.0
transformed_update = -1.0 * momentum_multiplier * nesterov_momentum_update
new_diagonal_momentum = grafting_update_with_wd_momentum
new_momentum = shampoo_update_with_wd_momentum
param_stats = ParameterStats(
_quantize_diagonal_statistics(new_diagonal_statistics),
state.statistics,
state.preconditioners,
_quantize_momentum(new_diagonal_momentum),
_quantize_momentum(new_momentum),
state.training_metrics,
)
return transformed_update, param_stats
def update_fn(grads, state, params):
"""Transform the input gradient and update all statistics.
Args:
grads: the gradient tensors for the parameters
and any custom gradients for preconditioners.
state: a named tuple containing the state of the optimizer
params: the parameters that should be updated.
Returns:
A tuple containing the new parameters and the new optimizer state.
"""
params_flat, treedef = jax.tree_flatten(params)
stats_flat = treedef.flatten_up_to(state.stats)
grads_flat = treedef.flatten_up_to(grads)
stats_grads = grads_flat
new_stats_flat = jax.tree_map(
lambda g, s, p: _compute_stats(g, s, p, state.count),
stats_grads,
stats_flat,
params_flat,
)
new_stats_flat = _compute_preconditioners(
new_stats_flat, params_flat, state.count
)
outputs = jax.tree_map(
lambda g, s, p: _transform_grad(g, s, p, state.count),
grads_flat,
new_stats_flat,
params_flat,
)
updates_flat, new_stats_flat = list(zip(*outputs)) if outputs else ((), ())
updates = jax.tree_unflatten(treedef, updates_flat)
new_stats = jax.tree_unflatten(treedef, new_stats_flat)
new_state = ShampooState(count=state.count + 1, stats=new_stats)
return updates, new_state
if shard_optimizer_states:
# Hijacks the init_fn signature so we can return an OptState with
# appropriate init_fns.
opt_init_fn = sharded_init_fn
def _init_fns(unused_params):
return InitFnState(
init_fn=opt_init_fn,
pspec_fn=sharded_init_partition_spec_fn,
shape_and_dtype_fn=sharded_init_shape_and_dtype_fn,
)
opt_update_fn = sharded_update_fn
return optax.GradientTransformation(_init_fns, opt_update_fn)
else:
return optax.GradientTransformation(init_fn, update_fn) | Distributed Shampoo optimizer. Distributed Shampoo is a second-order preconditioned method (concretely, a variant of full-matrix Adagrad), that provides significant convergence and wall-clock time improvements compared to conventional first-order methods, and that has been shown to scale to large state-of-the-art deep learning models. References: Scalable Second Order Optimization for Deep Learning, Rohan Anil, Vineet Gupta, Tomer Koren, Kevin Regan, Yoram Singer Preprint: https://arxiv.org/abs/2002.09018 Args: learning_rate: the step size used to update the parameters. block_size: Block size for large layers (if > 0). Preconditioning compute operation is cubic in the dimension of the tensor. Block size allows us to chunk the layers into sub-layers of maximal dimension dictated by this value. Use 128 as default (increase if you have compute budget). beta1: momentum parameter. beta2: second moment averaging parameter. diagonal_epsilon: epsilon for diagonal adagrad (only if layerwise grafting to AdaGrad is enabled). matrix_epsilon: epsilon to add to statistics before computing inverse pth root. If you are running in f32 precision for inverse pth root (recommended today) this can go upto 1e-6. If you have latest hardware with native f64 precision, set this upto 1e-12. weight_decay: Weight decay for regularization. start_preconditioning_step: When to start Shampoo update before which diagonal update is used. This is because we dont have enough information to do stable inverse. preconditioning_compute_steps: How often to compute preconditioner. Performance tuning params for controlling memory and compute requirements. Ideally set this and statistics_compute_steps params to 1. statistics_compute_steps: How often to compute statistics. best_effort_shape_interpretation: If there are some small dimensions, collapse them e.g. [1, 2, 512, 1, 2048, 1, 3, 4] --> [1024, 2048, 12] if block = 1024, [1, 2, 768, 1, 2048] --> [2, 768, 2048] graft_type: Grafting is a technique to fix the layerwise scale of Shampoo optimizer. This allows us to plugin the Shampoo optimizer into settings where SGD/AdaGrad is already well tuned. nesterov: Nesterov momentum. exponent_override: Override the exponent used in matrix inverse. batch_axis_name: labeled axis over pmap for data-parallel training the optimizer used for. statistics_partition_spec: PartitionSpec to be used in sharded mode. preconditioner_partition_spec: PartitionSpec to be used in sharded mode. num_devices_for_pjit: Number of devices to parallelize over when using pjit. shard_optimizer_states: Shard optimizer states to save memory in model parallel training. best_effort_memory_usage_reduction: Best effort memory usage reduction. - diagonal_statistics -> jnp.bfloat16 - momentum buffers (2x) -> jnp.int8 - statistics, preconditioners -> jnp.int16 + diagonals inverse_failure_threshold: numerics are hard and inverses fail sometimes; we determine that using this threshold. moving_average_for_momentum: Whether to use moving average for momentum instead of exponential moving average. skip_preconditioning_dim_size_gt: Skip if preconditioning dim size is greater than this value. clip_by_scaled_gradient_norm: Clip by scaled gradient norm (only useful when using RMSProp Grafting). precision: precision XLA related flag, the available options are: a) lax.Precision.DEFAULT (better step time, but not precise) b) lax.Precision.HIGH (increased precision, slower) c) lax.Precision.HIGHEST (best possible precision, slowest) tensordot_precision: Optional precision to use for the tensordot operation when computing statistics (e.g., G Gᵀ). Same options as `precision` above. relative_matrix_epsilon: Whether to use relative epsilon to the max eigen value when computing inverse-pth root. merge_small_dims_block_size: Used as the maximum block size to merge the shapes. lobpcg_topk_precondition: If nonzero, specifies the number of top eigenvectors to subtract out before performing LOBPCG. Note this makes relative_matrix_epsilon essentially free. lobpcg_max_iter: Number of LOBPCG iterations, if zero defaults to `lobpcg_topk_precondition`. precondtioner_type: Preconditioner type to select all, left only or right only preconditioners. skip_preconditioning_rank_lt: Skips preconditioning for parameters with rank less than this value. decoupled_learning_rate: If True, use decoupled learning rate, otherwise couple it with preconditioned gradient computation. (Default True) decoupled_weight_decay: If True, use decoupled weight decay, otherwise couple with weight decay. (Default False) Returns: a GradientTransformation. |
746 | import os
import signal
import sys
import time
import warnings
import shutil
import numpy
import onnxruntime
from time import sleep
from argparse import ArgumentParser, HelpFormatter
import facefusion.choices
import facefusion.globals
from facefusion.face_analyser import get_one_face, get_average_face
from facefusion.face_store import get_reference_faces, append_reference_face
from facefusion import face_analyser, face_masker, content_analyser, config, metadata, logger, wording
from facefusion.content_analyser import analyse_image, analyse_video
from facefusion.processors.frame.core import get_frame_processors_modules, load_frame_processor_module
from facefusion.common_helper import create_metavar, get_first
from facefusion.execution_helper import encode_execution_providers, decode_execution_providers
from facefusion.normalizer import normalize_output_path, normalize_padding, normalize_fps
from facefusion.memory import limit_system_memory
from facefusion.filesystem import list_directory, get_temp_frame_paths, create_temp, move_temp, clear_temp, is_image, is_video, filter_audio_paths
from facefusion.ffmpeg import extract_frames, compress_image, merge_video, restore_audio, replace_audio
from facefusion.vision import get_video_frame, read_image, read_static_images, pack_resolution, detect_video_resolution, detect_video_fps, create_video_resolutions
onnxruntime.set_default_logger_severity(3)
def run(program : ArgumentParser) -> None:
apply_args(program)
logger.init(facefusion.globals.log_level)
if facefusion.globals.system_memory_limit > 0:
limit_system_memory(facefusion.globals.system_memory_limit)
if not pre_check() or not content_analyser.pre_check() or not face_analyser.pre_check() or not face_masker.pre_check():
return
for frame_processor_module in get_frame_processors_modules(facefusion.globals.frame_processors):
if not frame_processor_module.pre_check():
return
if facefusion.globals.headless:
conditional_process()
else:
import facefusion.uis.core as ui
for ui_layout in ui.get_ui_layouts_modules(facefusion.globals.ui_layouts):
if not ui_layout.pre_check():
return
ui.launch()
def destroy() -> None:
if facefusion.globals.target_path:
clear_temp(facefusion.globals.target_path)
sys.exit(0)
def load_frame_processor_module(frame_processor : str) -> Any:
try:
frame_processor_module = importlib.import_module('facefusion.processors.frame.modules.' + frame_processor)
for method_name in FRAME_PROCESSORS_METHODS:
if not hasattr(frame_processor_module, method_name):
raise NotImplementedError
except ModuleNotFoundError as exception:
logger.error(wording.get('frame_processor_not_loaded').format(frame_processor = frame_processor), __name__.upper())
logger.debug(exception.msg, __name__.upper())
sys.exit(1)
except NotImplementedError:
logger.error(wording.get('frame_processor_not_implemented').format(frame_processor = frame_processor), __name__.upper())
sys.exit(1)
return frame_processor_module
def create_metavar(ranges : List[Any]) -> str:
return '[' + str(ranges[0]) + '-' + str(ranges[-1]) + ']'
def encode_execution_providers(execution_providers : List[str]) -> List[str]:
return [ execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers ]
def list_directory(directory_path : str) -> Optional[List[str]]:
if is_directory(directory_path):
files = os.listdir(directory_path)
return sorted([ Path(file).stem for file in files if not Path(file).stem.startswith(('.', '__')) ])
return None
def cli() -> None:
signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
program = ArgumentParser(formatter_class = lambda prog: HelpFormatter(prog, max_help_position = 130), add_help = False)
# general
program.add_argument('-s', '--source', help = wording.get('help.source'), action = 'append', dest = 'source_paths', default = config.get_str_list('general.source_paths'))
program.add_argument('-t', '--target', help = wording.get('help.target'), dest = 'target_path', default = config.get_str_value('general.target_path'))
program.add_argument('-o', '--output', help = wording.get('help.output'), dest = 'output_path', default = config.get_str_value('general.output_path'))
program.add_argument('-v', '--version', version = metadata.get('name') + ' ' + metadata.get('version'), action = 'version')
# misc
group_misc = program.add_argument_group('misc')
group_misc.add_argument('--skip-download', help = wording.get('help.skip_download'), action = 'store_true', default = config.get_bool_value('misc.skip_download'))
group_misc.add_argument('--headless', help = wording.get('help.headless'), action = 'store_true', default = config.get_bool_value('misc.headless'))
group_misc.add_argument('--log-level', help = wording.get('help.log_level'), default = config.get_str_value('misc.log_level', 'info'), choices = logger.get_log_levels())
# execution
execution_providers = encode_execution_providers(onnxruntime.get_available_providers())
group_execution = program.add_argument_group('execution')
group_execution.add_argument('--execution-providers', help = wording.get('help.execution_providers').format(choices = ', '.join(execution_providers)), default = config.get_str_list('execution.execution_providers', 'cpu'), choices = execution_providers, nargs = '+', metavar = 'EXECUTION_PROVIDERS')
group_execution.add_argument('--execution-thread-count', help = wording.get('help.execution_thread_count'), type = int, default = config.get_int_value('execution.execution_thread_count', '4'), choices = facefusion.choices.execution_thread_count_range, metavar = create_metavar(facefusion.choices.execution_thread_count_range))
group_execution.add_argument('--execution-queue-count', help = wording.get('help.execution_queue_count'), type = int, default = config.get_int_value('execution.execution_queue_count', '1'), choices = facefusion.choices.execution_queue_count_range, metavar = create_metavar(facefusion.choices.execution_queue_count_range))
# memory
group_memory = program.add_argument_group('memory')
group_memory.add_argument('--video-memory-strategy', help = wording.get('help.video_memory_strategy'), default = config.get_str_value('memory.video_memory_strategy', 'strict'), choices = facefusion.choices.video_memory_strategies)
group_memory.add_argument('--system-memory-limit', help = wording.get('help.system_memory_limit'), type = int, default = config.get_int_value('memory.system_memory_limit', '0'), choices = facefusion.choices.system_memory_limit_range, metavar = create_metavar(facefusion.choices.system_memory_limit_range))
# face analyser
group_face_analyser = program.add_argument_group('face analyser')
group_face_analyser.add_argument('--face-analyser-order', help = wording.get('help.face_analyser_order'), default = config.get_str_value('face_analyser.face_analyser_order', 'left-right'), choices = facefusion.choices.face_analyser_orders)
group_face_analyser.add_argument('--face-analyser-age', help = wording.get('help.face_analyser_age'), default = config.get_str_value('face_analyser.face_analyser_age'), choices = facefusion.choices.face_analyser_ages)
group_face_analyser.add_argument('--face-analyser-gender', help = wording.get('help.face_analyser_gender'), default = config.get_str_value('face_analyser.face_analyser_gender'), choices = facefusion.choices.face_analyser_genders)
group_face_analyser.add_argument('--face-detector-model', help = wording.get('help.face_detector_model'), default = config.get_str_value('face_analyser.face_detector_model', 'yoloface'), choices = facefusion.choices.face_detector_set.keys())
group_face_analyser.add_argument('--face-detector-size', help = wording.get('help.face_detector_size'), default = config.get_str_value('face_analyser.face_detector_size', '640x640'))
group_face_analyser.add_argument('--face-detector-score', help = wording.get('help.face_detector_score'), type = float, default = config.get_float_value('face_analyser.face_detector_score', '0.5'), choices = facefusion.choices.face_detector_score_range, metavar = create_metavar(facefusion.choices.face_detector_score_range))
# face selector
group_face_selector = program.add_argument_group('face selector')
group_face_selector.add_argument('--face-selector-mode', help = wording.get('help.face_selector_mode'), default = config.get_str_value('face_selector.face_selector_mode', 'reference'), choices = facefusion.choices.face_selector_modes)
group_face_selector.add_argument('--reference-face-position', help = wording.get('help.reference_face_position'), type = int, default = config.get_int_value('face_selector.reference_face_position', '0'))
group_face_selector.add_argument('--reference-face-distance', help = wording.get('help.reference_face_distance'), type = float, default = config.get_float_value('face_selector.reference_face_distance', '0.6'), choices = facefusion.choices.reference_face_distance_range, metavar = create_metavar(facefusion.choices.reference_face_distance_range))
group_face_selector.add_argument('--reference-frame-number', help = wording.get('help.reference_frame_number'), type = int, default = config.get_int_value('face_selector.reference_frame_number', '0'))
# face mask
group_face_mask = program.add_argument_group('face mask')
group_face_mask.add_argument('--face-mask-types', help = wording.get('help.face_mask_types').format(choices = ', '.join(facefusion.choices.face_mask_types)), default = config.get_str_list('face_mask.face_mask_types', 'box'), choices = facefusion.choices.face_mask_types, nargs = '+', metavar = 'FACE_MASK_TYPES')
group_face_mask.add_argument('--face-mask-blur', help = wording.get('help.face_mask_blur'), type = float, default = config.get_float_value('face_mask.face_mask_blur', '0.3'), choices = facefusion.choices.face_mask_blur_range, metavar = create_metavar(facefusion.choices.face_mask_blur_range))
group_face_mask.add_argument('--face-mask-padding', help = wording.get('help.face_mask_padding'), type = int, default = config.get_int_list('face_mask.face_mask_padding', '0 0 0 0'), nargs = '+')
group_face_mask.add_argument('--face-mask-regions', help = wording.get('help.face_mask_regions').format(choices = ', '.join(facefusion.choices.face_mask_regions)), default = config.get_str_list('face_mask.face_mask_regions', ' '.join(facefusion.choices.face_mask_regions)), choices = facefusion.choices.face_mask_regions, nargs = '+', metavar = 'FACE_MASK_REGIONS')
# frame extraction
group_frame_extraction = program.add_argument_group('frame extraction')
group_frame_extraction.add_argument('--trim-frame-start', help = wording.get('help.trim_frame_start'), type = int, default = facefusion.config.get_int_value('frame_extraction.trim_frame_start'))
group_frame_extraction.add_argument('--trim-frame-end', help = wording.get('help.trim_frame_end'), type = int, default = facefusion.config.get_int_value('frame_extraction.trim_frame_end'))
group_frame_extraction.add_argument('--temp-frame-format', help = wording.get('help.temp_frame_format'), default = config.get_str_value('frame_extraction.temp_frame_format', 'jpg'), choices = facefusion.choices.temp_frame_formats)
group_frame_extraction.add_argument('--temp-frame-quality', help = wording.get('help.temp_frame_quality'), type = int, default = config.get_int_value('frame_extraction.temp_frame_quality', '100'), choices = facefusion.choices.temp_frame_quality_range, metavar = create_metavar(facefusion.choices.temp_frame_quality_range))
group_frame_extraction.add_argument('--keep-temp', help = wording.get('help.keep_temp'), action = 'store_true', default = config.get_bool_value('frame_extraction.keep_temp'))
# output creation
group_output_creation = program.add_argument_group('output creation')
group_output_creation.add_argument('--output-image-quality', help = wording.get('help.output_image_quality'), type = int, default = config.get_int_value('output_creation.output_image_quality', '80'), choices = facefusion.choices.output_image_quality_range, metavar = create_metavar(facefusion.choices.output_image_quality_range))
group_output_creation.add_argument('--output-video-encoder', help = wording.get('help.output_video_encoder'), default = config.get_str_value('output_creation.output_video_encoder', 'libx264'), choices = facefusion.choices.output_video_encoders)
group_output_creation.add_argument('--output-video-preset', help = wording.get('help.output_video_preset'), default = config.get_str_value('output_creation.output_video_preset', 'veryfast'), choices = facefusion.choices.output_video_presets)
group_output_creation.add_argument('--output-video-quality', help = wording.get('help.output_video_quality'), type = int, default = config.get_int_value('output_creation.output_video_quality', '80'), choices = facefusion.choices.output_video_quality_range, metavar = create_metavar(facefusion.choices.output_video_quality_range))
group_output_creation.add_argument('--output-video-resolution', help = wording.get('help.output_video_resolution'), default = config.get_str_value('output_creation.output_video_resolution'))
group_output_creation.add_argument('--output-video-fps', help = wording.get('help.output_video_fps'), type = float)
group_output_creation.add_argument('--skip-audio', help = wording.get('help.skip_audio'), action = 'store_true', default = config.get_bool_value('output_creation.skip_audio'))
# frame processors
available_frame_processors = list_directory('facefusion/processors/frame/modules')
program = ArgumentParser(parents = [ program ], formatter_class = program.formatter_class, add_help = True)
group_frame_processors = program.add_argument_group('frame processors')
group_frame_processors.add_argument('--frame-processors', help = wording.get('help.frame_processors').format(choices = ', '.join(available_frame_processors)), default = config.get_str_list('frame_processors.frame_processors', 'face_swapper'), nargs = '+')
for frame_processor in available_frame_processors:
frame_processor_module = load_frame_processor_module(frame_processor)
frame_processor_module.register_args(group_frame_processors)
# uis
available_ui_layouts = list_directory('facefusion/uis/layouts')
group_uis = program.add_argument_group('uis')
group_uis.add_argument('--ui-layouts', help = wording.get('help.ui_layouts').format(choices = ', '.join(available_ui_layouts)), default = config.get_str_list('uis.ui_layouts', 'default'), nargs = '+')
run(program) | null |
747 | from configparser import ConfigParser
from typing import Any, Optional, List
from facefusion.filesystem import resolve_relative_path
CONFIG = None
def clear_config() -> None:
global CONFIG
CONFIG = None | null |
748 | from configparser import ConfigParser
from typing import Any, Optional, List
from facefusion.filesystem import resolve_relative_path
def get_value_by_notation(key : str) -> Optional[Any]:
config = get_config()
if '.' in key:
section, name = key.split('.')
if section in config and name in config[section]:
return config[section][name]
if key in config:
return config[key]
return None
def get_float_list(key : str, fallback : Optional[str] = None) -> Optional[List[float]]:
value = get_value_by_notation(key)
if value or fallback:
return [ float(value) for value in (value or fallback).split(' ') ]
return None | null |
749 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, webcam_options, source, webcam
def pre_check() -> bool:
return True | null |
750 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, webcam_options, source, webcam
def pre_render() -> bool:
return True | null |
751 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, webcam_options, source, webcam
def render() -> gradio.Blocks:
with gradio.Blocks() as layout:
with gradio.Row():
with gradio.Column(scale = 2):
with gradio.Blocks():
about.render()
with gradio.Blocks():
frame_processors.render()
with gradio.Blocks():
frame_processors_options.render()
with gradio.Blocks():
execution.render()
execution_thread_count.render()
with gradio.Blocks():
webcam_options.render()
with gradio.Blocks():
source.render()
with gradio.Column(scale = 5):
with gradio.Blocks():
webcam.render()
return layout | null |
752 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, webcam_options, source, webcam
def listen() -> None:
frame_processors.listen()
frame_processors_options.listen()
execution.listen()
execution_thread_count.listen()
source.listen()
webcam.listen() | null |
753 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, webcam_options, source, webcam
def run(ui : gradio.Blocks) -> None:
ui.queue(concurrency_count = 2).launch(show_api = False, quiet = True) | null |
754 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, temp_frame, output_options, common_options, source, target, output, preview, trim_frame, face_analyser, face_selector, face_masker
def pre_check() -> bool:
return True | null |
755 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, temp_frame, output_options, common_options, source, target, output, preview, trim_frame, face_analyser, face_selector, face_masker
def pre_render() -> bool:
return True | null |
756 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, temp_frame, output_options, common_options, source, target, output, preview, trim_frame, face_analyser, face_selector, face_masker
def render() -> gradio.Blocks:
with gradio.Blocks() as layout:
with gradio.Row():
with gradio.Column(scale = 2):
with gradio.Blocks():
about.render()
with gradio.Blocks():
frame_processors.render()
with gradio.Blocks():
frame_processors_options.render()
with gradio.Blocks():
execution.render()
execution_thread_count.render()
execution_queue_count.render()
with gradio.Blocks():
memory.render()
with gradio.Blocks():
temp_frame.render()
with gradio.Blocks():
output_options.render()
with gradio.Column(scale = 2):
with gradio.Blocks():
source.render()
with gradio.Blocks():
target.render()
with gradio.Blocks():
output.render()
with gradio.Column(scale = 3):
with gradio.Blocks():
preview.render()
with gradio.Blocks():
trim_frame.render()
with gradio.Blocks():
face_selector.render()
with gradio.Blocks():
face_masker.render()
with gradio.Blocks():
face_analyser.render()
with gradio.Blocks():
common_options.render()
return layout | null |
757 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, temp_frame, output_options, common_options, source, target, output, preview, trim_frame, face_analyser, face_selector, face_masker
def listen() -> None:
frame_processors.listen()
frame_processors_options.listen()
execution.listen()
execution_thread_count.listen()
execution_queue_count.listen()
memory.listen()
temp_frame.listen()
output_options.listen()
source.listen()
target.listen()
output.listen()
preview.listen()
trim_frame.listen()
face_selector.listen()
face_masker.listen()
face_analyser.listen()
common_options.listen() | null |
758 | import gradio
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, temp_frame, output_options, common_options, source, target, output, preview, trim_frame, face_analyser, face_selector, face_masker
def run(ui : gradio.Blocks) -> None:
ui.launch(show_api = False, quiet = True) | null |
759 | import gradio
import facefusion.globals
from facefusion.download import conditional_download
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, benchmark_options, benchmark
def conditional_download(download_directory_path : str, urls : List[str]) -> None:
with ThreadPoolExecutor() as executor:
for url in urls:
executor.submit(get_download_size, url)
for url in urls:
download_file_path = os.path.join(download_directory_path, os.path.basename(url))
initial = os.path.getsize(download_file_path) if is_file(download_file_path) else 0
total = get_download_size(url)
if initial < total:
with tqdm(total = total, initial = initial, desc = wording.get('downloading'), unit = 'B', unit_scale = True, unit_divisor = 1024, ascii = ' =', disable = facefusion.globals.log_level in [ 'warn', 'error' ]) as progress:
subprocess.Popen([ 'curl', '--create-dirs', '--silent', '--insecure', '--location', '--continue-at', '-', '--output', download_file_path, url ])
current = initial
while current < total:
if is_file(download_file_path):
current = os.path.getsize(download_file_path)
progress.update(current - progress.n)
def pre_check() -> bool:
if not facefusion.globals.skip_download:
conditional_download('.assets/examples',
[
'https://github.com/facefusion/facefusion-assets/releases/download/examples/source.jpg',
'https://github.com/facefusion/facefusion-assets/releases/download/examples/target-240p.mp4',
'https://github.com/facefusion/facefusion-assets/releases/download/examples/target-360p.mp4',
'https://github.com/facefusion/facefusion-assets/releases/download/examples/target-540p.mp4',
'https://github.com/facefusion/facefusion-assets/releases/download/examples/target-720p.mp4',
'https://github.com/facefusion/facefusion-assets/releases/download/examples/target-1080p.mp4',
'https://github.com/facefusion/facefusion-assets/releases/download/examples/target-1440p.mp4',
'https://github.com/facefusion/facefusion-assets/releases/download/examples/target-2160p.mp4'
])
return True
return False | null |
760 | import gradio
import facefusion.globals
from facefusion.download import conditional_download
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, benchmark_options, benchmark
def pre_render() -> bool:
return True | null |
761 | import gradio
import facefusion.globals
from facefusion.download import conditional_download
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, benchmark_options, benchmark
def benchmark(target_path : str, benchmark_cycles : int) -> List[Any]:
process_times = []
total_fps = 0.0
for index in range(benchmark_cycles):
facefusion.globals.target_path = target_path
facefusion.globals.output_path = normalize_output_path(facefusion.globals.source_paths, facefusion.globals.target_path, tempfile.gettempdir())
target_video_resolution = detect_video_resolution(facefusion.globals.target_path)
facefusion.globals.output_video_resolution = pack_resolution(target_video_resolution)
facefusion.globals.output_video_fps = detect_video_fps(facefusion.globals.target_path)
video_frame_total = count_video_frame_total(facefusion.globals.target_path)
start_time = time.perf_counter()
conditional_process()
end_time = time.perf_counter()
process_time = end_time - start_time
total_fps += video_frame_total / process_time
process_times.append(process_time)
average_run = round(statistics.mean(process_times), 2)
fastest_run = round(min(process_times), 2)
slowest_run = round(max(process_times), 2)
relative_fps = round(total_fps / benchmark_cycles, 2)
return\
[
facefusion.globals.target_path,
benchmark_cycles,
average_run,
fastest_run,
slowest_run,
relative_fps
]
def render() -> gradio.Blocks:
with gradio.Blocks() as layout:
with gradio.Row():
with gradio.Column(scale = 2):
with gradio.Blocks():
about.render()
with gradio.Blocks():
frame_processors.render()
with gradio.Blocks():
frame_processors_options.render()
with gradio.Blocks():
execution.render()
execution_thread_count.render()
execution_queue_count.render()
with gradio.Blocks():
memory.render()
with gradio.Blocks():
benchmark_options.render()
with gradio.Column(scale = 5):
with gradio.Blocks():
benchmark.render()
return layout | null |
762 | import gradio
import facefusion.globals
from facefusion.download import conditional_download
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, benchmark_options, benchmark
def benchmark(target_path : str, benchmark_cycles : int) -> List[Any]:
def listen() -> None:
frame_processors.listen()
frame_processors_options.listen()
execution.listen()
execution_thread_count.listen()
execution_queue_count.listen()
memory.listen()
benchmark.listen() | null |
763 | import gradio
import facefusion.globals
from facefusion.download import conditional_download
from facefusion.uis.components import about, frame_processors, frame_processors_options, execution, execution_thread_count, execution_queue_count, memory, benchmark_options, benchmark
def run(ui : gradio.Blocks) -> None:
ui.queue(concurrency_count = 2).launch(show_api = False, quiet = True) | null |
764 | from typing import List, Optional
import gradio
import onnxruntime
import facefusion.globals
from facefusion import wording
from facefusion.face_analyser import clear_face_analyser
from facefusion.processors.frame.core import clear_frame_processors_modules
from facefusion.execution_helper import encode_execution_providers, decode_execution_providers
EXECUTION_PROVIDERS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
def encode_execution_providers(execution_providers : List[str]) -> List[str]:
return [ execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers ]
def render() -> None:
global EXECUTION_PROVIDERS_CHECKBOX_GROUP
EXECUTION_PROVIDERS_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = wording.get('uis.execution_providers_checkbox_group'),
choices = encode_execution_providers(onnxruntime.get_available_providers()),
value = encode_execution_providers(facefusion.globals.execution_providers)
) | null |
765 | from typing import List, Optional
import gradio
import onnxruntime
import facefusion.globals
from facefusion import wording
from facefusion.face_analyser import clear_face_analyser
from facefusion.processors.frame.core import clear_frame_processors_modules
from facefusion.execution_helper import encode_execution_providers, decode_execution_providers
EXECUTION_PROVIDERS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
def update_execution_providers(execution_providers : List[str]) -> gradio.CheckboxGroup:
def listen() -> None:
EXECUTION_PROVIDERS_CHECKBOX_GROUP.change(update_execution_providers, inputs = EXECUTION_PROVIDERS_CHECKBOX_GROUP, outputs = EXECUTION_PROVIDERS_CHECKBOX_GROUP) | null |
766 | from typing import Optional, Generator, Deque, List
import os
import platform
import subprocess
import cv2
import gradio
from time import sleep
from concurrent.futures import ThreadPoolExecutor
from collections import deque
from tqdm import tqdm
import facefusion.globals
from facefusion import logger, wording
from facefusion.content_analyser import analyse_stream
from facefusion.typing import VisionFrame, Face, Fps
from facefusion.face_analyser import get_average_face
from facefusion.processors.frame.core import get_frame_processors_modules, load_frame_processor_module
from facefusion.ffmpeg import open_ffmpeg
from facefusion.vision import normalize_frame_color, read_static_images, unpack_resolution
from facefusion.uis.typing import StreamMode, WebcamMode, ComponentName
from facefusion.uis.core import get_ui_component
WEBCAM_IMAGE : Optional[gradio.Image] = None
WEBCAM_START_BUTTON : Optional[gradio.Button] = None
WEBCAM_STOP_BUTTON : Optional[gradio.Button] = None
def render() -> None:
global WEBCAM_IMAGE
global WEBCAM_START_BUTTON
global WEBCAM_STOP_BUTTON
WEBCAM_IMAGE = gradio.Image(
label = wording.get('uis.webcam_image')
)
WEBCAM_START_BUTTON = gradio.Button(
value = wording.get('uis.start_button'),
variant = 'primary',
size = 'sm'
)
WEBCAM_STOP_BUTTON = gradio.Button(
value = wording.get('uis.stop_button'),
size = 'sm'
) | null |
767 | from typing import Optional, Generator, Deque, List
import os
import platform
import subprocess
import cv2
import gradio
from time import sleep
from concurrent.futures import ThreadPoolExecutor
from collections import deque
from tqdm import tqdm
import facefusion.globals
from facefusion import logger, wording
from facefusion.content_analyser import analyse_stream
from facefusion.typing import VisionFrame, Face, Fps
from facefusion.face_analyser import get_average_face
from facefusion.processors.frame.core import get_frame_processors_modules, load_frame_processor_module
from facefusion.ffmpeg import open_ffmpeg
from facefusion.vision import normalize_frame_color, read_static_images, unpack_resolution
from facefusion.uis.typing import StreamMode, WebcamMode, ComponentName
from facefusion.uis.core import get_ui_component
WEBCAM_IMAGE : Optional[gradio.Image] = None
WEBCAM_START_BUTTON : Optional[gradio.Button] = None
WEBCAM_STOP_BUTTON : Optional[gradio.Button] = None
def start(webcam_mode : WebcamMode, webcam_resolution : str, webcam_fps : Fps) -> Generator[VisionFrame, None, None]:
facefusion.globals.face_selector_mode = 'one'
facefusion.globals.face_analyser_order = 'large-small'
source_frames = read_static_images(facefusion.globals.source_paths)
source_face = get_average_face(source_frames)
stream = None
if webcam_mode in [ 'udp', 'v4l2' ]:
stream = open_stream(webcam_mode, webcam_resolution, webcam_fps) # type: ignore[arg-type]
webcam_width, webcam_height = unpack_resolution(webcam_resolution)
webcam_capture = get_webcam_capture()
if webcam_capture and webcam_capture.isOpened():
webcam_capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG')) # type: ignore[attr-defined]
webcam_capture.set(cv2.CAP_PROP_FRAME_WIDTH, webcam_width)
webcam_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, webcam_height)
webcam_capture.set(cv2.CAP_PROP_FPS, webcam_fps)
for capture_frame in multi_process_capture(source_face, webcam_capture, webcam_fps):
if webcam_mode == 'inline':
yield normalize_frame_color(capture_frame)
else:
try:
stream.stdin.write(capture_frame.tobytes())
except Exception:
clear_webcam_capture()
yield None
def update() -> None:
for frame_processor in facefusion.globals.frame_processors:
frame_processor_module = load_frame_processor_module(frame_processor)
while not frame_processor_module.post_check():
logger.disable()
sleep(0.5)
logger.enable()
def stop() -> gradio.Image:
clear_webcam_capture()
return gradio.Image(value = None)
ComponentName = Literal\
[
'source_audio',
'source_image',
'target_image',
'target_video',
'preview_frame_slider',
'face_selector_mode_dropdown',
'reference_face_position_gallery',
'reference_face_distance_slider',
'face_analyser_order_dropdown',
'face_analyser_age_dropdown',
'face_analyser_gender_dropdown',
'face_detector_model_dropdown',
'face_detector_size_dropdown',
'face_detector_score_slider',
'face_mask_types_checkbox_group',
'face_mask_blur_slider',
'face_mask_padding_top_slider',
'face_mask_padding_bottom_slider',
'face_mask_padding_left_slider',
'face_mask_padding_right_slider',
'face_mask_region_checkbox_group',
'frame_processors_checkbox_group',
'face_debugger_items_checkbox_group',
'face_enhancer_model_dropdown',
'face_enhancer_blend_slider',
'face_swapper_model_dropdown',
'frame_enhancer_model_dropdown',
'frame_enhancer_blend_slider',
'lip_syncer_model_dropdown',
'output_path_textbox',
'output_video_fps_slider',
'benchmark_runs_checkbox_group',
'benchmark_cycles_slider',
'webcam_mode_radio',
'webcam_resolution_dropdown',
'webcam_fps_slider'
]
def get_ui_component(name : ComponentName) -> Optional[Component]:
if name in UI_COMPONENTS:
return UI_COMPONENTS[name]
return None
def listen() -> None:
start_event = None
webcam_mode_radio = get_ui_component('webcam_mode_radio')
webcam_resolution_dropdown = get_ui_component('webcam_resolution_dropdown')
webcam_fps_slider = get_ui_component('webcam_fps_slider')
if webcam_mode_radio and webcam_resolution_dropdown and webcam_fps_slider:
start_event = WEBCAM_START_BUTTON.click(start, inputs = [ webcam_mode_radio, webcam_resolution_dropdown, webcam_fps_slider ], outputs = WEBCAM_IMAGE)
WEBCAM_STOP_BUTTON.click(stop, cancels = start_event)
change_two_component_names : List[ComponentName] =\
[
'frame_processors_checkbox_group',
'face_swapper_model_dropdown',
'face_enhancer_model_dropdown',
'frame_enhancer_model_dropdown',
'lip_syncer_model_dropdown',
'source_image'
]
for component_name in change_two_component_names:
component = get_ui_component(component_name)
if component:
component.change(update, cancels = start_event) | null |
768 | from typing import Optional, Tuple, List
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import FaceMaskType, FaceMaskRegion
from facefusion.uis.core import register_ui_component
FACE_MASK_TYPES_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
FACE_MASK_BLUR_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_BOX_GROUP : Optional[gradio.Group] = None
FACE_MASK_REGION_GROUP : Optional[gradio.Group] = None
FACE_MASK_PADDING_TOP_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_PADDING_RIGHT_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_PADDING_BOTTOM_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_PADDING_LEFT_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_REGION_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global FACE_MASK_TYPES_CHECKBOX_GROUP
global FACE_MASK_BLUR_SLIDER
global FACE_MASK_BOX_GROUP
global FACE_MASK_REGION_GROUP
global FACE_MASK_PADDING_TOP_SLIDER
global FACE_MASK_PADDING_RIGHT_SLIDER
global FACE_MASK_PADDING_BOTTOM_SLIDER
global FACE_MASK_PADDING_LEFT_SLIDER
global FACE_MASK_REGION_CHECKBOX_GROUP
has_box_mask = 'box' in facefusion.globals.face_mask_types
has_region_mask = 'region' in facefusion.globals.face_mask_types
FACE_MASK_TYPES_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = wording.get('uis.face_mask_types_checkbox_group'),
choices = facefusion.choices.face_mask_types,
value = facefusion.globals.face_mask_types
)
with gradio.Group(visible = has_box_mask) as FACE_MASK_BOX_GROUP:
FACE_MASK_BLUR_SLIDER = gradio.Slider(
label = wording.get('uis.face_mask_blur_slider'),
step = facefusion.choices.face_mask_blur_range[1] - facefusion.choices.face_mask_blur_range[0],
minimum = facefusion.choices.face_mask_blur_range[0],
maximum = facefusion.choices.face_mask_blur_range[-1],
value = facefusion.globals.face_mask_blur
)
with gradio.Row():
FACE_MASK_PADDING_TOP_SLIDER = gradio.Slider(
label = wording.get('uis.face_mask_padding_top_slider'),
step = facefusion.choices.face_mask_padding_range[1] - facefusion.choices.face_mask_padding_range[0],
minimum = facefusion.choices.face_mask_padding_range[0],
maximum = facefusion.choices.face_mask_padding_range[-1],
value = facefusion.globals.face_mask_padding[0]
)
FACE_MASK_PADDING_RIGHT_SLIDER = gradio.Slider(
label = wording.get('uis.face_mask_padding_right_slider'),
step = facefusion.choices.face_mask_padding_range[1] - facefusion.choices.face_mask_padding_range[0],
minimum = facefusion.choices.face_mask_padding_range[0],
maximum = facefusion.choices.face_mask_padding_range[-1],
value = facefusion.globals.face_mask_padding[1]
)
with gradio.Row():
FACE_MASK_PADDING_BOTTOM_SLIDER = gradio.Slider(
label = wording.get('uis.face_mask_padding_bottom_slider'),
step = facefusion.choices.face_mask_padding_range[1] - facefusion.choices.face_mask_padding_range[0],
minimum = facefusion.choices.face_mask_padding_range[0],
maximum = facefusion.choices.face_mask_padding_range[-1],
value = facefusion.globals.face_mask_padding[2]
)
FACE_MASK_PADDING_LEFT_SLIDER = gradio.Slider(
label = wording.get('uis.face_mask_padding_left_slider'),
step = facefusion.choices.face_mask_padding_range[1] - facefusion.choices.face_mask_padding_range[0],
minimum = facefusion.choices.face_mask_padding_range[0],
maximum = facefusion.choices.face_mask_padding_range[-1],
value = facefusion.globals.face_mask_padding[3]
)
with gradio.Row():
FACE_MASK_REGION_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = wording.get('uis.face_mask_region_checkbox_group'),
choices = facefusion.choices.face_mask_regions,
value = facefusion.globals.face_mask_regions,
visible = has_region_mask
)
register_ui_component('face_mask_types_checkbox_group', FACE_MASK_TYPES_CHECKBOX_GROUP)
register_ui_component('face_mask_blur_slider', FACE_MASK_BLUR_SLIDER)
register_ui_component('face_mask_padding_top_slider', FACE_MASK_PADDING_TOP_SLIDER)
register_ui_component('face_mask_padding_right_slider', FACE_MASK_PADDING_RIGHT_SLIDER)
register_ui_component('face_mask_padding_bottom_slider', FACE_MASK_PADDING_BOTTOM_SLIDER)
register_ui_component('face_mask_padding_left_slider', FACE_MASK_PADDING_LEFT_SLIDER)
register_ui_component('face_mask_region_checkbox_group', FACE_MASK_REGION_CHECKBOX_GROUP) | null |
769 | from typing import Optional, Tuple, List
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import FaceMaskType, FaceMaskRegion
from facefusion.uis.core import register_ui_component
FACE_MASK_TYPES_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
FACE_MASK_BLUR_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_BOX_GROUP : Optional[gradio.Group] = None
FACE_MASK_PADDING_TOP_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_PADDING_RIGHT_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_PADDING_BOTTOM_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_PADDING_LEFT_SLIDER : Optional[gradio.Slider] = None
FACE_MASK_REGION_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
def update_face_mask_type(face_mask_types : List[FaceMaskType]) -> Tuple[gradio.CheckboxGroup, gradio.Group, gradio.CheckboxGroup]:
if not face_mask_types:
face_mask_types = facefusion.choices.face_mask_types
facefusion.globals.face_mask_types = face_mask_types
has_box_mask = 'box' in face_mask_types
has_region_mask = 'region' in face_mask_types
return gradio.CheckboxGroup(value = face_mask_types), gradio.Group(visible = has_box_mask), gradio.CheckboxGroup(visible = has_region_mask)
def update_face_mask_blur(face_mask_blur : float) -> None:
facefusion.globals.face_mask_blur = face_mask_blur
def update_face_mask_padding(face_mask_padding_top : int, face_mask_padding_right : int, face_mask_padding_bottom : int, face_mask_padding_left : int) -> None:
facefusion.globals.face_mask_padding = (face_mask_padding_top, face_mask_padding_right, face_mask_padding_bottom, face_mask_padding_left)
def update_face_mask_regions(face_mask_regions : List[FaceMaskRegion]) -> gradio.CheckboxGroup:
if not face_mask_regions:
face_mask_regions = facefusion.choices.face_mask_regions
facefusion.globals.face_mask_regions = face_mask_regions
return gradio.CheckboxGroup(value = face_mask_regions)
def listen() -> None:
FACE_MASK_TYPES_CHECKBOX_GROUP.change(update_face_mask_type, inputs = FACE_MASK_TYPES_CHECKBOX_GROUP, outputs = [ FACE_MASK_TYPES_CHECKBOX_GROUP, FACE_MASK_BOX_GROUP, FACE_MASK_REGION_CHECKBOX_GROUP ])
FACE_MASK_BLUR_SLIDER.change(update_face_mask_blur, inputs = FACE_MASK_BLUR_SLIDER)
FACE_MASK_REGION_CHECKBOX_GROUP.change(update_face_mask_regions, inputs = FACE_MASK_REGION_CHECKBOX_GROUP, outputs = FACE_MASK_REGION_CHECKBOX_GROUP)
face_mask_padding_sliders = [ FACE_MASK_PADDING_TOP_SLIDER, FACE_MASK_PADDING_RIGHT_SLIDER, FACE_MASK_PADDING_BOTTOM_SLIDER, FACE_MASK_PADDING_LEFT_SLIDER ]
for face_mask_padding_slider in face_mask_padding_sliders:
face_mask_padding_slider.change(update_face_mask_padding, inputs = face_mask_padding_sliders) | null |
770 | from typing import Optional
import gradio
from facefusion import wording
from facefusion.uis.core import register_ui_component
from facefusion.uis.components.benchmark import BENCHMARKS
BENCHMARK_RUNS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
BENCHMARK_CYCLES_SLIDER : Optional[gradio.Button] = None
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
BENCHMARKS : Dict[str, str] =\
{
'240p': '.assets/examples/target-240p.mp4',
'360p': '.assets/examples/target-360p.mp4',
'540p': '.assets/examples/target-540p.mp4',
'720p': '.assets/examples/target-720p.mp4',
'1080p': '.assets/examples/target-1080p.mp4',
'1440p': '.assets/examples/target-1440p.mp4',
'2160p': '.assets/examples/target-2160p.mp4'
}
def render() -> None:
global BENCHMARK_RUNS_CHECKBOX_GROUP
global BENCHMARK_CYCLES_SLIDER
BENCHMARK_RUNS_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = wording.get('uis.benchmark_runs_checkbox_group'),
value = list(BENCHMARKS.keys()),
choices = list(BENCHMARKS.keys())
)
BENCHMARK_CYCLES_SLIDER = gradio.Slider(
label = wording.get('uis.benchmark_cycles_slider'),
value = 5,
step = 1,
minimum = 1,
maximum = 10
)
register_ui_component('benchmark_runs_checkbox_group', BENCHMARK_RUNS_CHECKBOX_GROUP)
register_ui_component('benchmark_cycles_slider', BENCHMARK_CYCLES_SLIDER) | null |
771 | from typing import Tuple, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.core import conditional_process
from facefusion.memory import limit_system_memory
from facefusion.uis.core import get_ui_component
from facefusion.normalizer import normalize_output_path
from facefusion.filesystem import clear_temp, is_image, is_video
OUTPUT_IMAGE : Optional[gradio.Image] = None
OUTPUT_VIDEO : Optional[gradio.Video] = None
OUTPUT_START_BUTTON : Optional[gradio.Button] = None
OUTPUT_CLEAR_BUTTON : Optional[gradio.Button] = None
def render() -> None:
global OUTPUT_IMAGE
global OUTPUT_VIDEO
global OUTPUT_START_BUTTON
global OUTPUT_CLEAR_BUTTON
OUTPUT_IMAGE = gradio.Image(
label = wording.get('uis.output_image_or_video'),
visible = False
)
OUTPUT_VIDEO = gradio.Video(
label = wording.get('uis.output_image_or_video')
)
OUTPUT_START_BUTTON = gradio.Button(
value = wording.get('uis.start_button'),
variant = 'primary',
size = 'sm'
)
OUTPUT_CLEAR_BUTTON = gradio.Button(
value = wording.get('uis.clear_button'),
size = 'sm'
) | null |
772 | from typing import Tuple, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.core import conditional_process
from facefusion.memory import limit_system_memory
from facefusion.uis.core import get_ui_component
from facefusion.normalizer import normalize_output_path
from facefusion.filesystem import clear_temp, is_image, is_video
OUTPUT_IMAGE : Optional[gradio.Image] = None
OUTPUT_VIDEO : Optional[gradio.Video] = None
OUTPUT_START_BUTTON : Optional[gradio.Button] = None
OUTPUT_CLEAR_BUTTON : Optional[gradio.Button] = None
def start(output_path : str) -> Tuple[gradio.Image, gradio.Video]:
def clear() -> Tuple[gradio.Image, gradio.Video]:
def get_ui_component(name : ComponentName) -> Optional[Component]:
def listen() -> None:
output_path_textbox = get_ui_component('output_path_textbox')
if output_path_textbox:
OUTPUT_START_BUTTON.click(start, inputs = output_path_textbox, outputs = [ OUTPUT_IMAGE, OUTPUT_VIDEO ])
OUTPUT_CLEAR_BUTTON.click(clear, outputs = [ OUTPUT_IMAGE, OUTPUT_VIDEO ]) | null |
773 | from typing import Optional, List
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.uis import choices as uis_choices
COMMON_OPTIONS_CHECKBOX_GROUP : Optional[gradio.Checkboxgroup] = None
def render() -> None:
global COMMON_OPTIONS_CHECKBOX_GROUP
value = []
if facefusion.globals.keep_temp:
value.append('keep-temp')
if facefusion.globals.skip_audio:
value.append('skip-audio')
if facefusion.globals.skip_download:
value.append('skip-download')
COMMON_OPTIONS_CHECKBOX_GROUP = gradio.Checkboxgroup(
label = wording.get('uis.common_options_checkbox_group'),
choices = uis_choices.common_options,
value = value
) | null |
774 | from typing import Optional, List
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.uis import choices as uis_choices
COMMON_OPTIONS_CHECKBOX_GROUP : Optional[gradio.Checkboxgroup] = None
def update(common_options : List[str]) -> None:
def listen() -> None:
COMMON_OPTIONS_CHECKBOX_GROUP.change(update, inputs = COMMON_OPTIONS_CHECKBOX_GROUP) | null |
775 | from typing import List, Optional, Tuple, Any, Dict
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.face_store import clear_static_faces, clear_reference_faces
from facefusion.vision import get_video_frame, read_static_image, normalize_frame_color
from facefusion.filesystem import is_image, is_video
from facefusion.face_analyser import get_many_faces
from facefusion.typing import VisionFrame, FaceSelectorMode
from facefusion.uis.core import get_ui_component, register_ui_component
from facefusion.uis.typing import ComponentName
FACE_SELECTOR_MODE_DROPDOWN : Optional[gradio.Dropdown] = None
REFERENCE_FACE_POSITION_GALLERY : Optional[gradio.Gallery] = None
REFERENCE_FACE_DISTANCE_SLIDER : Optional[gradio.Slider] = None
def extract_gallery_frames(temp_vision_frame : VisionFrame) -> List[VisionFrame]:
gallery_vision_frames = []
faces = get_many_faces(temp_vision_frame)
for face in faces:
start_x, start_y, end_x, end_y = map(int, face.bounding_box)
padding_x = int((end_x - start_x) * 0.25)
padding_y = int((end_y - start_y) * 0.25)
start_x = max(0, start_x - padding_x)
start_y = max(0, start_y - padding_y)
end_x = max(0, end_x + padding_x)
end_y = max(0, end_y + padding_y)
crop_vision_frame = temp_vision_frame[start_y:end_y, start_x:end_x]
crop_vision_frame = normalize_frame_color(crop_vision_frame)
gallery_vision_frames.append(crop_vision_frame)
return gallery_vision_frames
def get_video_frame(video_path : str, frame_number : int = 0) -> Optional[VisionFrame]:
if is_video(video_path):
video_capture = cv2.VideoCapture(video_path)
if video_capture.isOpened():
frame_total = video_capture.get(cv2.CAP_PROP_FRAME_COUNT)
video_capture.set(cv2.CAP_PROP_POS_FRAMES, min(frame_total, frame_number - 1))
has_vision_frame, vision_frame = video_capture.read()
video_capture.release()
if has_vision_frame:
return vision_frame
return None
def read_static_image(image_path : str) -> Optional[VisionFrame]:
return read_image(image_path)
def is_image(image_path : str) -> bool:
return is_file(image_path) and filetype.helpers.is_image(image_path)
def is_video(video_path : str) -> bool:
return is_file(video_path) and filetype.helpers.is_video(video_path)
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global FACE_SELECTOR_MODE_DROPDOWN
global REFERENCE_FACE_POSITION_GALLERY
global REFERENCE_FACE_DISTANCE_SLIDER
reference_face_gallery_args: Dict[str, Any] =\
{
'label': wording.get('uis.reference_face_gallery'),
'object_fit': 'cover',
'columns': 8,
'allow_preview': False,
'visible': 'reference' in facefusion.globals.face_selector_mode
}
if is_image(facefusion.globals.target_path):
reference_frame = read_static_image(facefusion.globals.target_path)
reference_face_gallery_args['value'] = extract_gallery_frames(reference_frame)
if is_video(facefusion.globals.target_path):
reference_frame = get_video_frame(facefusion.globals.target_path, facefusion.globals.reference_frame_number)
reference_face_gallery_args['value'] = extract_gallery_frames(reference_frame)
FACE_SELECTOR_MODE_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.face_selector_mode_dropdown'),
choices = facefusion.choices.face_selector_modes,
value = facefusion.globals.face_selector_mode
)
REFERENCE_FACE_POSITION_GALLERY = gradio.Gallery(**reference_face_gallery_args)
REFERENCE_FACE_DISTANCE_SLIDER = gradio.Slider(
label = wording.get('uis.reference_face_distance_slider'),
value = facefusion.globals.reference_face_distance,
step = facefusion.choices.reference_face_distance_range[1] - facefusion.choices.reference_face_distance_range[0],
minimum = facefusion.choices.reference_face_distance_range[0],
maximum = facefusion.choices.reference_face_distance_range[-1],
visible = 'reference' in facefusion.globals.face_selector_mode
)
register_ui_component('face_selector_mode_dropdown', FACE_SELECTOR_MODE_DROPDOWN)
register_ui_component('reference_face_position_gallery', REFERENCE_FACE_POSITION_GALLERY)
register_ui_component('reference_face_distance_slider', REFERENCE_FACE_DISTANCE_SLIDER) | null |
776 | from typing import List, Optional, Tuple, Any, Dict
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.face_store import clear_static_faces, clear_reference_faces
from facefusion.vision import get_video_frame, read_static_image, normalize_frame_color
from facefusion.filesystem import is_image, is_video
from facefusion.face_analyser import get_many_faces
from facefusion.typing import VisionFrame, FaceSelectorMode
from facefusion.uis.core import get_ui_component, register_ui_component
from facefusion.uis.typing import ComponentName
FACE_SELECTOR_MODE_DROPDOWN : Optional[gradio.Dropdown] = None
REFERENCE_FACE_POSITION_GALLERY : Optional[gradio.Gallery] = None
REFERENCE_FACE_DISTANCE_SLIDER : Optional[gradio.Slider] = None
def update_face_selector_mode(face_selector_mode : FaceSelectorMode) -> Tuple[gradio.Gallery, gradio.Slider]:
if face_selector_mode == 'reference':
facefusion.globals.face_selector_mode = face_selector_mode
return gradio.Gallery(visible = True), gradio.Slider(visible = True)
if face_selector_mode == 'one':
facefusion.globals.face_selector_mode = face_selector_mode
return gradio.Gallery(visible = False), gradio.Slider(visible = False)
if face_selector_mode == 'many':
facefusion.globals.face_selector_mode = face_selector_mode
return gradio.Gallery(visible = False), gradio.Slider(visible = False)
def clear_and_update_reference_face_position(event : gradio.SelectData) -> gradio.Gallery:
clear_reference_faces()
clear_static_faces()
update_reference_face_position(event.index)
return update_reference_position_gallery()
def update_reference_face_position(reference_face_position : int = 0) -> None:
facefusion.globals.reference_face_position = reference_face_position
def update_reference_face_distance(reference_face_distance : float) -> None:
facefusion.globals.reference_face_distance = reference_face_distance
def update_reference_frame_number(reference_frame_number : int) -> None:
facefusion.globals.reference_frame_number = reference_frame_number
def clear_and_update_reference_position_gallery() -> gradio.Gallery:
clear_reference_faces()
clear_static_faces()
return update_reference_position_gallery()
def update_reference_position_gallery() -> gradio.Gallery:
gallery_vision_frames = []
if is_image(facefusion.globals.target_path):
temp_vision_frame = read_static_image(facefusion.globals.target_path)
gallery_vision_frames = extract_gallery_frames(temp_vision_frame)
if is_video(facefusion.globals.target_path):
temp_vision_frame = get_video_frame(facefusion.globals.target_path, facefusion.globals.reference_frame_number)
gallery_vision_frames = extract_gallery_frames(temp_vision_frame)
if gallery_vision_frames:
return gradio.Gallery(value = gallery_vision_frames)
return gradio.Gallery(value = None)
def get_ui_component(name : ComponentName) -> Optional[Component]:
if name in UI_COMPONENTS:
return UI_COMPONENTS[name]
return None
ComponentName = Literal\
[
'source_audio',
'source_image',
'target_image',
'target_video',
'preview_frame_slider',
'face_selector_mode_dropdown',
'reference_face_position_gallery',
'reference_face_distance_slider',
'face_analyser_order_dropdown',
'face_analyser_age_dropdown',
'face_analyser_gender_dropdown',
'face_detector_model_dropdown',
'face_detector_size_dropdown',
'face_detector_score_slider',
'face_mask_types_checkbox_group',
'face_mask_blur_slider',
'face_mask_padding_top_slider',
'face_mask_padding_bottom_slider',
'face_mask_padding_left_slider',
'face_mask_padding_right_slider',
'face_mask_region_checkbox_group',
'frame_processors_checkbox_group',
'face_debugger_items_checkbox_group',
'face_enhancer_model_dropdown',
'face_enhancer_blend_slider',
'face_swapper_model_dropdown',
'frame_enhancer_model_dropdown',
'frame_enhancer_blend_slider',
'lip_syncer_model_dropdown',
'output_path_textbox',
'output_video_fps_slider',
'benchmark_runs_checkbox_group',
'benchmark_cycles_slider',
'webcam_mode_radio',
'webcam_resolution_dropdown',
'webcam_fps_slider'
]
def listen() -> None:
FACE_SELECTOR_MODE_DROPDOWN.change(update_face_selector_mode, inputs = FACE_SELECTOR_MODE_DROPDOWN, outputs = [ REFERENCE_FACE_POSITION_GALLERY, REFERENCE_FACE_DISTANCE_SLIDER ])
REFERENCE_FACE_POSITION_GALLERY.select(clear_and_update_reference_face_position)
REFERENCE_FACE_DISTANCE_SLIDER.change(update_reference_face_distance, inputs = REFERENCE_FACE_DISTANCE_SLIDER)
multi_component_names : List[ComponentName] =\
[
'target_image',
'target_video'
]
for component_name in multi_component_names:
component = get_ui_component(component_name)
if component:
for method in [ 'upload', 'change', 'clear' ]:
getattr(component, method)(update_reference_face_position)
getattr(component, method)(update_reference_position_gallery, outputs = REFERENCE_FACE_POSITION_GALLERY)
change_one_component_names : List[ComponentName] =\
[
'face_analyser_order_dropdown',
'face_analyser_age_dropdown',
'face_analyser_gender_dropdown'
]
for component_name in change_one_component_names:
component = get_ui_component(component_name)
if component:
component.change(update_reference_position_gallery, outputs = REFERENCE_FACE_POSITION_GALLERY)
change_two_component_names : List[ComponentName] =\
[
'face_detector_model_dropdown',
'face_detector_size_dropdown',
'face_detector_score_slider'
]
for component_name in change_two_component_names:
component = get_ui_component(component_name)
if component:
component.change(clear_and_update_reference_position_gallery, outputs = REFERENCE_FACE_POSITION_GALLERY)
preview_frame_slider = get_ui_component('preview_frame_slider')
if preview_frame_slider:
preview_frame_slider.change(update_reference_frame_number, inputs = preview_frame_slider)
preview_frame_slider.release(update_reference_position_gallery, outputs = REFERENCE_FACE_POSITION_GALLERY) | null |
777 | from typing import Optional
import gradio
from facefusion import wording
from facefusion.uis import choices as uis_choices
from facefusion.uis.core import register_ui_component
WEBCAM_MODE_RADIO : Optional[gradio.Radio] = None
WEBCAM_RESOLUTION_DROPDOWN : Optional[gradio.Dropdown] = None
WEBCAM_FPS_SLIDER : Optional[gradio.Slider] = None
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global WEBCAM_MODE_RADIO
global WEBCAM_RESOLUTION_DROPDOWN
global WEBCAM_FPS_SLIDER
WEBCAM_MODE_RADIO = gradio.Radio(
label = wording.get('uis.webcam_mode_radio'),
choices = uis_choices.webcam_modes,
value = 'inline'
)
WEBCAM_RESOLUTION_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.webcam_resolution_dropdown'),
choices = uis_choices.webcam_resolutions,
value = uis_choices.webcam_resolutions[0]
)
WEBCAM_FPS_SLIDER = gradio.Slider(
label = wording.get('uis.webcam_fps_slider'),
value = 25,
step = 1,
minimum = 1,
maximum = 60
)
register_ui_component('webcam_mode_radio', WEBCAM_MODE_RADIO)
register_ui_component('webcam_resolution_dropdown', WEBCAM_RESOLUTION_DROPDOWN)
register_ui_component('webcam_fps_slider', WEBCAM_FPS_SLIDER) | null |
778 | from typing import Optional, Dict, Any
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import FaceAnalyserOrder, FaceAnalyserAge, FaceAnalyserGender, FaceDetectorModel
from facefusion.uis.core import register_ui_component
FACE_ANALYSER_ORDER_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_ANALYSER_AGE_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_ANALYSER_GENDER_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_DETECTOR_SIZE_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_DETECTOR_SCORE_SLIDER : Optional[gradio.Slider] = None
FACE_DETECTOR_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global FACE_ANALYSER_ORDER_DROPDOWN
global FACE_ANALYSER_AGE_DROPDOWN
global FACE_ANALYSER_GENDER_DROPDOWN
global FACE_DETECTOR_SIZE_DROPDOWN
global FACE_DETECTOR_SCORE_SLIDER
global FACE_DETECTOR_MODEL_DROPDOWN
face_detector_size_dropdown_args : Dict[str, Any] =\
{
'label': wording.get('uis.face_detector_size_dropdown'),
'value': facefusion.globals.face_detector_size
}
if facefusion.globals.face_detector_size in facefusion.choices.face_detector_set[facefusion.globals.face_detector_model]:
face_detector_size_dropdown_args['choices'] = facefusion.choices.face_detector_set[facefusion.globals.face_detector_model]
with gradio.Row():
FACE_ANALYSER_ORDER_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.face_analyser_order_dropdown'),
choices = facefusion.choices.face_analyser_orders,
value = facefusion.globals.face_analyser_order
)
FACE_ANALYSER_AGE_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.face_analyser_age_dropdown'),
choices = [ 'none' ] + facefusion.choices.face_analyser_ages,
value = facefusion.globals.face_analyser_age or 'none'
)
FACE_ANALYSER_GENDER_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.face_analyser_gender_dropdown'),
choices = [ 'none' ] + facefusion.choices.face_analyser_genders,
value = facefusion.globals.face_analyser_gender or 'none'
)
FACE_DETECTOR_MODEL_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.face_detector_model_dropdown'),
choices = facefusion.choices.face_detector_set.keys(),
value = facefusion.globals.face_detector_model
)
FACE_DETECTOR_SIZE_DROPDOWN = gradio.Dropdown(**face_detector_size_dropdown_args)
FACE_DETECTOR_SCORE_SLIDER = gradio.Slider(
label = wording.get('uis.face_detector_score_slider'),
value = facefusion.globals.face_detector_score,
step = facefusion.choices.face_detector_score_range[1] - facefusion.choices.face_detector_score_range[0],
minimum = facefusion.choices.face_detector_score_range[0],
maximum = facefusion.choices.face_detector_score_range[-1]
)
register_ui_component('face_analyser_order_dropdown', FACE_ANALYSER_ORDER_DROPDOWN)
register_ui_component('face_analyser_age_dropdown', FACE_ANALYSER_AGE_DROPDOWN)
register_ui_component('face_analyser_gender_dropdown', FACE_ANALYSER_GENDER_DROPDOWN)
register_ui_component('face_detector_model_dropdown', FACE_DETECTOR_MODEL_DROPDOWN)
register_ui_component('face_detector_size_dropdown', FACE_DETECTOR_SIZE_DROPDOWN)
register_ui_component('face_detector_score_slider', FACE_DETECTOR_SCORE_SLIDER) | null |
779 | from typing import Optional, Dict, Any
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import FaceAnalyserOrder, FaceAnalyserAge, FaceAnalyserGender, FaceDetectorModel
from facefusion.uis.core import register_ui_component
FACE_ANALYSER_ORDER_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_ANALYSER_AGE_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_ANALYSER_GENDER_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_DETECTOR_SIZE_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_DETECTOR_SCORE_SLIDER : Optional[gradio.Slider] = None
FACE_DETECTOR_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
def update_face_analyser_order(face_analyser_order : FaceAnalyserOrder) -> None:
def update_face_analyser_age(face_analyser_age : FaceAnalyserAge) -> None:
def update_face_analyser_gender(face_analyser_gender : FaceAnalyserGender) -> None:
def update_face_detector_model(face_detector_model : FaceDetectorModel) -> gradio.Dropdown:
def update_face_detector_size(face_detector_size : str) -> None:
def update_face_detector_score(face_detector_score : float) -> None:
def listen() -> None:
FACE_ANALYSER_ORDER_DROPDOWN.change(update_face_analyser_order, inputs = FACE_ANALYSER_ORDER_DROPDOWN)
FACE_ANALYSER_AGE_DROPDOWN.change(update_face_analyser_age, inputs = FACE_ANALYSER_AGE_DROPDOWN)
FACE_ANALYSER_GENDER_DROPDOWN.change(update_face_analyser_gender, inputs = FACE_ANALYSER_GENDER_DROPDOWN)
FACE_DETECTOR_MODEL_DROPDOWN.change(update_face_detector_model, inputs = FACE_DETECTOR_MODEL_DROPDOWN, outputs = FACE_DETECTOR_SIZE_DROPDOWN)
FACE_DETECTOR_SIZE_DROPDOWN.change(update_face_detector_size, inputs = FACE_DETECTOR_SIZE_DROPDOWN)
FACE_DETECTOR_SCORE_SLIDER.change(update_face_detector_score, inputs = FACE_DETECTOR_SCORE_SLIDER) | null |
780 | from typing import Optional
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
EXECUTION_QUEUE_COUNT_SLIDER : Optional[gradio.Slider] = None
def render() -> None:
global EXECUTION_QUEUE_COUNT_SLIDER
EXECUTION_QUEUE_COUNT_SLIDER = gradio.Slider(
label = wording.get('uis.execution_queue_count_slider'),
value = facefusion.globals.execution_queue_count,
step = facefusion.choices.execution_queue_count_range[1] - facefusion.choices.execution_queue_count_range[0],
minimum = facefusion.choices.execution_queue_count_range[0],
maximum = facefusion.choices.execution_queue_count_range[-1]
) | null |
781 | from typing import Optional
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
EXECUTION_QUEUE_COUNT_SLIDER : Optional[gradio.Slider] = None
def update_execution_queue_count(execution_queue_count : int = 1) -> None:
facefusion.globals.execution_queue_count = execution_queue_count
def listen() -> None:
EXECUTION_QUEUE_COUNT_SLIDER.change(update_execution_queue_count, inputs = EXECUTION_QUEUE_COUNT_SLIDER) | null |
782 | from typing import List, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.processors.frame.core import load_frame_processor_module, clear_frame_processors_modules
from facefusion.filesystem import list_directory
from facefusion.uis.core import register_ui_component
FRAME_PROCESSORS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
def sort_frame_processors(frame_processors : List[str]) -> list[str]:
available_frame_processors = list_directory('facefusion/processors/frame/modules')
return sorted(available_frame_processors, key = lambda frame_processor : frame_processors.index(frame_processor) if frame_processor in frame_processors else len(frame_processors))
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global FRAME_PROCESSORS_CHECKBOX_GROUP
FRAME_PROCESSORS_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = wording.get('uis.frame_processors_checkbox_group'),
choices = sort_frame_processors(facefusion.globals.frame_processors),
value = facefusion.globals.frame_processors
)
register_ui_component('frame_processors_checkbox_group', FRAME_PROCESSORS_CHECKBOX_GROUP) | null |
783 | from typing import List, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.processors.frame.core import load_frame_processor_module, clear_frame_processors_modules
from facefusion.filesystem import list_directory
from facefusion.uis.core import register_ui_component
FRAME_PROCESSORS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
def update_frame_processors(frame_processors : List[str]) -> gradio.CheckboxGroup:
def listen() -> None:
FRAME_PROCESSORS_CHECKBOX_GROUP.change(update_frame_processors, inputs = FRAME_PROCESSORS_CHECKBOX_GROUP, outputs = FRAME_PROCESSORS_CHECKBOX_GROUP) | null |
784 | from typing import List, Optional, Tuple
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.processors.frame.core import load_frame_processor_module
from facefusion.processors.frame import globals as frame_processors_globals, choices as frame_processors_choices
from facefusion.processors.frame.typings import FaceDebuggerItem, FaceEnhancerModel, FaceSwapperModel, FrameEnhancerModel, LipSyncerModel
from facefusion.uis.core import get_ui_component, register_ui_component
FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
FACE_ENHANCER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_ENHANCER_BLEND_SLIDER : Optional[gradio.Slider] = None
FACE_SWAPPER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
FRAME_ENHANCER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
FRAME_ENHANCER_BLEND_SLIDER : Optional[gradio.Slider] = None
LIP_SYNCER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP
global FACE_ENHANCER_MODEL_DROPDOWN
global FACE_ENHANCER_BLEND_SLIDER
global FACE_SWAPPER_MODEL_DROPDOWN
global FRAME_ENHANCER_MODEL_DROPDOWN
global FRAME_ENHANCER_BLEND_SLIDER
global LIP_SYNCER_MODEL_DROPDOWN
FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = wording.get('uis.face_debugger_items_checkbox_group'),
choices = frame_processors_choices.face_debugger_items,
value = frame_processors_globals.face_debugger_items,
visible = 'face_debugger' in facefusion.globals.frame_processors
)
FACE_ENHANCER_MODEL_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.face_enhancer_model_dropdown'),
choices = frame_processors_choices.face_enhancer_models,
value = frame_processors_globals.face_enhancer_model,
visible = 'face_enhancer' in facefusion.globals.frame_processors
)
FACE_ENHANCER_BLEND_SLIDER = gradio.Slider(
label = wording.get('uis.face_enhancer_blend_slider'),
value = frame_processors_globals.face_enhancer_blend,
step = frame_processors_choices.face_enhancer_blend_range[1] - frame_processors_choices.face_enhancer_blend_range[0],
minimum = frame_processors_choices.face_enhancer_blend_range[0],
maximum = frame_processors_choices.face_enhancer_blend_range[-1],
visible = 'face_enhancer' in facefusion.globals.frame_processors
)
FACE_SWAPPER_MODEL_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.face_swapper_model_dropdown'),
choices = frame_processors_choices.face_swapper_models,
value = frame_processors_globals.face_swapper_model,
visible = 'face_swapper' in facefusion.globals.frame_processors
)
FRAME_ENHANCER_MODEL_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.frame_enhancer_model_dropdown'),
choices = frame_processors_choices.frame_enhancer_models,
value = frame_processors_globals.frame_enhancer_model,
visible = 'frame_enhancer' in facefusion.globals.frame_processors
)
FRAME_ENHANCER_BLEND_SLIDER = gradio.Slider(
label = wording.get('uis.frame_enhancer_blend_slider'),
value = frame_processors_globals.frame_enhancer_blend,
step = frame_processors_choices.frame_enhancer_blend_range[1] - frame_processors_choices.frame_enhancer_blend_range[0],
minimum = frame_processors_choices.frame_enhancer_blend_range[0],
maximum = frame_processors_choices.frame_enhancer_blend_range[-1],
visible = 'frame_enhancer' in facefusion.globals.frame_processors
)
LIP_SYNCER_MODEL_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.lip_syncer_model_dropdown'),
choices = frame_processors_choices.lip_syncer_models,
value = frame_processors_globals.lip_syncer_model,
visible = 'lip_syncer' in facefusion.globals.frame_processors
)
register_ui_component('face_debugger_items_checkbox_group', FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP)
register_ui_component('face_enhancer_model_dropdown', FACE_ENHANCER_MODEL_DROPDOWN)
register_ui_component('face_enhancer_blend_slider', FACE_ENHANCER_BLEND_SLIDER)
register_ui_component('face_swapper_model_dropdown', FACE_SWAPPER_MODEL_DROPDOWN)
register_ui_component('frame_enhancer_model_dropdown', FRAME_ENHANCER_MODEL_DROPDOWN)
register_ui_component('frame_enhancer_blend_slider', FRAME_ENHANCER_BLEND_SLIDER)
register_ui_component('lip_syncer_model_dropdown', LIP_SYNCER_MODEL_DROPDOWN) | null |
785 | from typing import List, Optional, Tuple
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.processors.frame.core import load_frame_processor_module
from facefusion.processors.frame import globals as frame_processors_globals, choices as frame_processors_choices
from facefusion.processors.frame.typings import FaceDebuggerItem, FaceEnhancerModel, FaceSwapperModel, FrameEnhancerModel, LipSyncerModel
from facefusion.uis.core import get_ui_component, register_ui_component
FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP : Optional[gradio.CheckboxGroup] = None
FACE_ENHANCER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
FACE_ENHANCER_BLEND_SLIDER : Optional[gradio.Slider] = None
FACE_SWAPPER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
FRAME_ENHANCER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
FRAME_ENHANCER_BLEND_SLIDER : Optional[gradio.Slider] = None
LIP_SYNCER_MODEL_DROPDOWN : Optional[gradio.Dropdown] = None
def update_frame_processors(frame_processors : List[str]) -> Tuple[gradio.CheckboxGroup, gradio.Dropdown, gradio.Slider, gradio.Dropdown, gradio.Dropdown, gradio.Slider, gradio.Dropdown]:
has_face_debugger = 'face_debugger' in frame_processors
has_face_enhancer = 'face_enhancer' in frame_processors
has_face_swapper = 'face_swapper' in frame_processors
has_frame_enhancer = 'frame_enhancer' in frame_processors
has_lip_syncer = 'lip_syncer' in frame_processors
return gradio.CheckboxGroup(visible = has_face_debugger), gradio.Dropdown(visible = has_face_enhancer), gradio.Slider(visible = has_face_enhancer), gradio.Dropdown(visible = has_face_swapper), gradio.Dropdown(visible = has_frame_enhancer), gradio.Slider(visible = has_frame_enhancer), gradio.Dropdown(visible = has_lip_syncer)
def update_face_debugger_items(face_debugger_items : List[FaceDebuggerItem]) -> None:
frame_processors_globals.face_debugger_items = face_debugger_items
def update_face_enhancer_model(face_enhancer_model : FaceEnhancerModel) -> gradio.Dropdown:
frame_processors_globals.face_enhancer_model = face_enhancer_model
face_enhancer_module = load_frame_processor_module('face_enhancer')
face_enhancer_module.clear_frame_processor()
face_enhancer_module.set_options('model', face_enhancer_module.MODELS[face_enhancer_model])
if face_enhancer_module.pre_check():
return gradio.Dropdown(value = face_enhancer_model)
return gradio.Dropdown()
def update_face_enhancer_blend(face_enhancer_blend : int) -> None:
frame_processors_globals.face_enhancer_blend = face_enhancer_blend
def update_face_swapper_model(face_swapper_model : FaceSwapperModel) -> gradio.Dropdown:
frame_processors_globals.face_swapper_model = face_swapper_model
if face_swapper_model == 'blendswap_256':
facefusion.globals.face_recognizer_model = 'arcface_blendswap'
if face_swapper_model == 'inswapper_128' or face_swapper_model == 'inswapper_128_fp16':
facefusion.globals.face_recognizer_model = 'arcface_inswapper'
if face_swapper_model == 'simswap_256' or face_swapper_model == 'simswap_512_unofficial':
facefusion.globals.face_recognizer_model = 'arcface_simswap'
if face_swapper_model == 'uniface_256':
facefusion.globals.face_recognizer_model = 'arcface_uniface'
face_swapper_module = load_frame_processor_module('face_swapper')
face_swapper_module.clear_frame_processor()
face_swapper_module.set_options('model', face_swapper_module.MODELS[face_swapper_model])
if face_swapper_module.pre_check():
return gradio.Dropdown(value = face_swapper_model)
return gradio.Dropdown()
def update_frame_enhancer_model(frame_enhancer_model : FrameEnhancerModel) -> gradio.Dropdown:
frame_processors_globals.frame_enhancer_model = frame_enhancer_model
frame_enhancer_module = load_frame_processor_module('frame_enhancer')
frame_enhancer_module.clear_frame_processor()
frame_enhancer_module.set_options('model', frame_enhancer_module.MODELS[frame_enhancer_model])
if frame_enhancer_module.pre_check():
return gradio.Dropdown(value = frame_enhancer_model)
return gradio.Dropdown()
def update_frame_enhancer_blend(frame_enhancer_blend : int) -> None:
frame_processors_globals.frame_enhancer_blend = frame_enhancer_blend
def update_lip_syncer_model(lip_syncer_model : LipSyncerModel) -> gradio.Dropdown:
frame_processors_globals.lip_syncer_model = lip_syncer_model
lip_syncer_module = load_frame_processor_module('lip_syncer')
lip_syncer_module.clear_frame_processor()
lip_syncer_module.set_options('model', lip_syncer_module.MODELS[lip_syncer_model])
if lip_syncer_module.pre_check():
return gradio.Dropdown(value = lip_syncer_model)
return gradio.Dropdown()
def get_ui_component(name : ComponentName) -> Optional[Component]:
if name in UI_COMPONENTS:
return UI_COMPONENTS[name]
return None
def listen() -> None:
FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP.change(update_face_debugger_items, inputs = FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP)
FACE_ENHANCER_MODEL_DROPDOWN.change(update_face_enhancer_model, inputs = FACE_ENHANCER_MODEL_DROPDOWN, outputs = FACE_ENHANCER_MODEL_DROPDOWN)
FACE_ENHANCER_BLEND_SLIDER.change(update_face_enhancer_blend, inputs = FACE_ENHANCER_BLEND_SLIDER)
FACE_SWAPPER_MODEL_DROPDOWN.change(update_face_swapper_model, inputs = FACE_SWAPPER_MODEL_DROPDOWN, outputs = FACE_SWAPPER_MODEL_DROPDOWN)
FRAME_ENHANCER_MODEL_DROPDOWN.change(update_frame_enhancer_model, inputs = FRAME_ENHANCER_MODEL_DROPDOWN, outputs = FRAME_ENHANCER_MODEL_DROPDOWN)
FRAME_ENHANCER_BLEND_SLIDER.change(update_frame_enhancer_blend, inputs = FRAME_ENHANCER_BLEND_SLIDER)
LIP_SYNCER_MODEL_DROPDOWN.change(update_lip_syncer_model, inputs = LIP_SYNCER_MODEL_DROPDOWN, outputs = LIP_SYNCER_MODEL_DROPDOWN)
frame_processors_checkbox_group = get_ui_component('frame_processors_checkbox_group')
if frame_processors_checkbox_group:
frame_processors_checkbox_group.change(update_frame_processors, inputs = frame_processors_checkbox_group, outputs = [ FACE_DEBUGGER_ITEMS_CHECKBOX_GROUP, FACE_ENHANCER_MODEL_DROPDOWN, FACE_ENHANCER_BLEND_SLIDER, FACE_SWAPPER_MODEL_DROPDOWN, FRAME_ENHANCER_MODEL_DROPDOWN, FRAME_ENHANCER_BLEND_SLIDER, LIP_SYNCER_MODEL_DROPDOWN ]) | null |
786 | from typing import Optional
import gradio
from facefusion import metadata, wording
ABOUT_BUTTON : Optional[gradio.HTML] = None
DONATE_BUTTON : Optional[gradio.HTML] = None
def render() -> None:
global ABOUT_BUTTON
global DONATE_BUTTON
ABOUT_BUTTON = gradio.Button(
value = metadata.get('name') + ' ' + metadata.get('version'),
variant = 'primary',
link = metadata.get('url')
)
DONATE_BUTTON = gradio.Button(
value = wording.get('uis.donate_button'),
link = 'https://donate.facefusion.io',
size = 'sm'
) | null |
787 | from typing import Optional, List, Tuple
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.uis.typing import File
from facefusion.common_helper import get_first
from facefusion.filesystem import has_audio, has_image, filter_audio_paths, filter_image_paths
from facefusion.uis.core import register_ui_component
SOURCE_FILE : Optional[gradio.File] = None
SOURCE_AUDIO : Optional[gradio.Audio] = None
SOURCE_IMAGE : Optional[gradio.Image] = None
File = IO[Any]
def get_first(__list__ : Any) -> Any:
return next(iter(__list__), None)
def has_audio(audio_paths : List[str]) -> bool:
if audio_paths:
return any(is_audio(audio_path) for audio_path in audio_paths)
return False
def has_image(image_paths: List[str]) -> bool:
if image_paths:
return any(is_image(image_path) for image_path in image_paths)
return False
def filter_audio_paths(paths : List[str]) -> List[str]:
if paths:
return [ path for path in paths if is_audio(path) ]
return []
def filter_image_paths(paths : List[str]) -> List[str]:
if paths:
return [ path for path in paths if is_image(path) ]
return []
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global SOURCE_FILE
global SOURCE_AUDIO
global SOURCE_IMAGE
has_source_audio = has_audio(facefusion.globals.source_paths)
has_source_image = has_image(facefusion.globals.source_paths)
SOURCE_FILE = gradio.File(
file_count = 'multiple',
file_types =
[
'.mp3',
'.wav',
'.png',
'.jpg',
'.webp'
],
label = wording.get('uis.source_file'),
value = facefusion.globals.source_paths if has_source_audio or has_source_image else None
)
source_file_names = [ source_file_value['name'] for source_file_value in SOURCE_FILE.value ] if SOURCE_FILE.value else None
source_audio_path = get_first(filter_audio_paths(source_file_names))
source_image_path = get_first(filter_image_paths(source_file_names))
SOURCE_AUDIO = gradio.Audio(
value = source_audio_path if has_source_audio else None,
visible = has_source_audio,
show_label = False
)
SOURCE_IMAGE = gradio.Image(
value = source_image_path if has_source_image else None,
visible = has_source_image,
show_label = False
)
register_ui_component('source_audio', SOURCE_AUDIO)
register_ui_component('source_image', SOURCE_IMAGE) | null |
788 | from typing import Optional, List, Tuple
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.uis.typing import File
from facefusion.common_helper import get_first
from facefusion.filesystem import has_audio, has_image, filter_audio_paths, filter_image_paths
from facefusion.uis.core import register_ui_component
SOURCE_FILE : Optional[gradio.File] = None
SOURCE_AUDIO : Optional[gradio.Audio] = None
SOURCE_IMAGE : Optional[gradio.Image] = None
def update(files : List[File]) -> Tuple[gradio.Audio, gradio.Image]:
file_names = [ file.name for file in files ] if files else None
has_source_audio = has_audio(file_names)
has_source_image = has_image(file_names)
if has_source_audio or has_source_image:
source_audio_path = get_first(filter_audio_paths(file_names))
source_image_path = get_first(filter_image_paths(file_names))
facefusion.globals.source_paths = file_names
return gradio.Audio(value = source_audio_path, visible = has_source_audio), gradio.Image(value = source_image_path, visible = has_source_image)
facefusion.globals.source_paths = None
return gradio.Audio(value = None, visible = False), gradio.Image(value = None, visible = False)
def listen() -> None:
SOURCE_FILE.change(update, inputs = SOURCE_FILE, outputs = [ SOURCE_AUDIO, SOURCE_IMAGE ]) | null |
789 | from typing import Any, Optional, List, Dict, Generator
import time
import tempfile
import statistics
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.face_store import clear_static_faces
from facefusion.processors.frame.core import get_frame_processors_modules
from facefusion.vision import count_video_frame_total, detect_video_resolution, detect_video_fps, pack_resolution
from facefusion.core import conditional_process
from facefusion.memory import limit_system_memory
from facefusion.normalizer import normalize_output_path
from facefusion.filesystem import clear_temp
from facefusion.uis.core import get_ui_component
BENCHMARK_RESULTS_DATAFRAME : Optional[gradio.Dataframe] = None
BENCHMARK_START_BUTTON : Optional[gradio.Button] = None
BENCHMARK_CLEAR_BUTTON : Optional[gradio.Button] = None
def render() -> None:
global BENCHMARK_RESULTS_DATAFRAME
global BENCHMARK_START_BUTTON
global BENCHMARK_CLEAR_BUTTON
BENCHMARK_RESULTS_DATAFRAME = gradio.Dataframe(
label = wording.get('uis.benchmark_results_dataframe'),
headers =
[
'target_path',
'benchmark_cycles',
'average_run',
'fastest_run',
'slowest_run',
'relative_fps'
],
datatype =
[
'str',
'number',
'number',
'number',
'number',
'number'
]
)
BENCHMARK_START_BUTTON = gradio.Button(
value = wording.get('uis.start_button'),
variant = 'primary',
size = 'sm'
)
BENCHMARK_CLEAR_BUTTON = gradio.Button(
value = wording.get('uis.clear_button'),
size = 'sm'
) | null |
790 | from typing import Any, Optional, List, Dict, Generator
import time
import tempfile
import statistics
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.face_store import clear_static_faces
from facefusion.processors.frame.core import get_frame_processors_modules
from facefusion.vision import count_video_frame_total, detect_video_resolution, detect_video_fps, pack_resolution
from facefusion.core import conditional_process
from facefusion.memory import limit_system_memory
from facefusion.normalizer import normalize_output_path
from facefusion.filesystem import clear_temp
from facefusion.uis.core import get_ui_component
BENCHMARK_RESULTS_DATAFRAME : Optional[gradio.Dataframe] = None
BENCHMARK_START_BUTTON : Optional[gradio.Button] = None
BENCHMARK_CLEAR_BUTTON : Optional[gradio.Button] = None
def start(benchmark_runs : List[str], benchmark_cycles : int) -> Generator[List[Any], None, None]:
def clear() -> gradio.Dataframe:
def get_ui_component(name : ComponentName) -> Optional[Component]:
def listen() -> None:
benchmark_runs_checkbox_group = get_ui_component('benchmark_runs_checkbox_group')
benchmark_cycles_slider = get_ui_component('benchmark_cycles_slider')
if benchmark_runs_checkbox_group and benchmark_cycles_slider:
BENCHMARK_START_BUTTON.click(start, inputs = [ benchmark_runs_checkbox_group, benchmark_cycles_slider ], outputs = BENCHMARK_RESULTS_DATAFRAME)
BENCHMARK_CLEAR_BUTTON.click(clear, outputs = BENCHMARK_RESULTS_DATAFRAME) | null |
791 | from typing import Optional, Tuple, List
import tempfile
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import OutputVideoEncoder, OutputVideoPreset, Fps
from facefusion.filesystem import is_image, is_video
from facefusion.uis.typing import ComponentName
from facefusion.uis.core import get_ui_component, register_ui_component
from facefusion.vision import detect_video_fps, create_video_resolutions, detect_video_resolution, pack_resolution
OUTPUT_PATH_TEXTBOX : Optional[gradio.Textbox] = None
OUTPUT_IMAGE_QUALITY_SLIDER : Optional[gradio.Slider] = None
OUTPUT_VIDEO_ENCODER_DROPDOWN : Optional[gradio.Dropdown] = None
OUTPUT_VIDEO_PRESET_DROPDOWN : Optional[gradio.Dropdown] = None
OUTPUT_VIDEO_RESOLUTION_DROPDOWN : Optional[gradio.Dropdown] = None
OUTPUT_VIDEO_QUALITY_SLIDER : Optional[gradio.Slider] = None
OUTPUT_VIDEO_FPS_SLIDER : Optional[gradio.Slider] = None
def is_image(image_path : str) -> bool:
return is_file(image_path) and filetype.helpers.is_image(image_path)
def is_video(video_path : str) -> bool:
return is_file(video_path) and filetype.helpers.is_video(video_path)
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def create_video_resolutions(video_path : str) -> Optional[List[str]]:
temp_resolutions = []
video_resolutions = []
video_resolution = detect_video_resolution(video_path)
if video_resolution:
width, height = video_resolution
temp_resolutions.append(normalize_resolution(video_resolution))
for template_size in video_template_sizes:
if width > height:
temp_resolutions.append(normalize_resolution((template_size * width / height, template_size)))
else:
temp_resolutions.append(normalize_resolution((template_size, template_size * height / width)))
temp_resolutions = sorted(set(temp_resolutions))
for temp in temp_resolutions:
video_resolutions.append(pack_resolution(temp))
return video_resolutions
return None
def render() -> None:
global OUTPUT_PATH_TEXTBOX
global OUTPUT_IMAGE_QUALITY_SLIDER
global OUTPUT_VIDEO_ENCODER_DROPDOWN
global OUTPUT_VIDEO_PRESET_DROPDOWN
global OUTPUT_VIDEO_RESOLUTION_DROPDOWN
global OUTPUT_VIDEO_QUALITY_SLIDER
global OUTPUT_VIDEO_FPS_SLIDER
OUTPUT_PATH_TEXTBOX = gradio.Textbox(
label = wording.get('uis.output_path_textbox'),
value = facefusion.globals.output_path or tempfile.gettempdir(),
max_lines = 1
)
OUTPUT_IMAGE_QUALITY_SLIDER = gradio.Slider(
label = wording.get('uis.output_image_quality_slider'),
value = facefusion.globals.output_image_quality,
step = facefusion.choices.output_image_quality_range[1] - facefusion.choices.output_image_quality_range[0],
minimum = facefusion.choices.output_image_quality_range[0],
maximum = facefusion.choices.output_image_quality_range[-1],
visible = is_image(facefusion.globals.target_path)
)
OUTPUT_VIDEO_ENCODER_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.output_video_encoder_dropdown'),
choices = facefusion.choices.output_video_encoders,
value = facefusion.globals.output_video_encoder,
visible = is_video(facefusion.globals.target_path)
)
OUTPUT_VIDEO_PRESET_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.output_video_preset_dropdown'),
choices = facefusion.choices.output_video_presets,
value = facefusion.globals.output_video_preset,
visible = is_video(facefusion.globals.target_path)
)
OUTPUT_VIDEO_QUALITY_SLIDER = gradio.Slider(
label = wording.get('uis.output_video_quality_slider'),
value = facefusion.globals.output_video_quality,
step = facefusion.choices.output_video_quality_range[1] - facefusion.choices.output_video_quality_range[0],
minimum = facefusion.choices.output_video_quality_range[0],
maximum = facefusion.choices.output_video_quality_range[-1],
visible = is_video(facefusion.globals.target_path)
)
OUTPUT_VIDEO_RESOLUTION_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.output_video_resolution_dropdown'),
choices = create_video_resolutions(facefusion.globals.target_path),
value = facefusion.globals.output_video_resolution,
visible = is_video(facefusion.globals.target_path)
)
OUTPUT_VIDEO_FPS_SLIDER = gradio.Slider(
label = wording.get('uis.output_video_fps_slider'),
value = facefusion.globals.output_video_fps,
step = 0.01,
minimum = 1,
maximum = 60,
visible = is_video(facefusion.globals.target_path)
)
register_ui_component('output_path_textbox', OUTPUT_PATH_TEXTBOX)
register_ui_component('output_video_fps_slider', OUTPUT_VIDEO_FPS_SLIDER) | null |
792 | from typing import Optional, Tuple, List
import tempfile
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import OutputVideoEncoder, OutputVideoPreset, Fps
from facefusion.filesystem import is_image, is_video
from facefusion.uis.typing import ComponentName
from facefusion.uis.core import get_ui_component, register_ui_component
from facefusion.vision import detect_video_fps, create_video_resolutions, detect_video_resolution, pack_resolution
OUTPUT_PATH_TEXTBOX : Optional[gradio.Textbox] = None
OUTPUT_IMAGE_QUALITY_SLIDER : Optional[gradio.Slider] = None
OUTPUT_VIDEO_ENCODER_DROPDOWN : Optional[gradio.Dropdown] = None
OUTPUT_VIDEO_PRESET_DROPDOWN : Optional[gradio.Dropdown] = None
OUTPUT_VIDEO_RESOLUTION_DROPDOWN : Optional[gradio.Dropdown] = None
OUTPUT_VIDEO_QUALITY_SLIDER : Optional[gradio.Slider] = None
OUTPUT_VIDEO_FPS_SLIDER : Optional[gradio.Slider] = None
def remote_update() -> Tuple[gradio.Slider, gradio.Dropdown, gradio.Dropdown, gradio.Slider, gradio.Dropdown, gradio.Slider]:
def update_output_path(output_path : str) -> None:
def update_output_image_quality(output_image_quality : int) -> None:
def update_output_video_encoder(output_video_encoder: OutputVideoEncoder) -> None:
def update_output_video_preset(output_video_preset : OutputVideoPreset) -> None:
def update_output_video_quality(output_video_quality : int) -> None:
def update_output_video_resolution(output_video_resolution : str) -> None:
def update_output_video_fps(output_video_fps : Fps) -> None:
ComponentName = Literal\
[
'source_audio',
'source_image',
'target_image',
'target_video',
'preview_frame_slider',
'face_selector_mode_dropdown',
'reference_face_position_gallery',
'reference_face_distance_slider',
'face_analyser_order_dropdown',
'face_analyser_age_dropdown',
'face_analyser_gender_dropdown',
'face_detector_model_dropdown',
'face_detector_size_dropdown',
'face_detector_score_slider',
'face_mask_types_checkbox_group',
'face_mask_blur_slider',
'face_mask_padding_top_slider',
'face_mask_padding_bottom_slider',
'face_mask_padding_left_slider',
'face_mask_padding_right_slider',
'face_mask_region_checkbox_group',
'frame_processors_checkbox_group',
'face_debugger_items_checkbox_group',
'face_enhancer_model_dropdown',
'face_enhancer_blend_slider',
'face_swapper_model_dropdown',
'frame_enhancer_model_dropdown',
'frame_enhancer_blend_slider',
'lip_syncer_model_dropdown',
'output_path_textbox',
'output_video_fps_slider',
'benchmark_runs_checkbox_group',
'benchmark_cycles_slider',
'webcam_mode_radio',
'webcam_resolution_dropdown',
'webcam_fps_slider'
]
def get_ui_component(name : ComponentName) -> Optional[Component]:
def listen() -> None:
OUTPUT_PATH_TEXTBOX.change(update_output_path, inputs = OUTPUT_PATH_TEXTBOX)
OUTPUT_IMAGE_QUALITY_SLIDER.change(update_output_image_quality, inputs = OUTPUT_IMAGE_QUALITY_SLIDER)
OUTPUT_VIDEO_ENCODER_DROPDOWN.change(update_output_video_encoder, inputs = OUTPUT_VIDEO_ENCODER_DROPDOWN)
OUTPUT_VIDEO_PRESET_DROPDOWN.change(update_output_video_preset, inputs = OUTPUT_VIDEO_PRESET_DROPDOWN)
OUTPUT_VIDEO_QUALITY_SLIDER.change(update_output_video_quality, inputs = OUTPUT_VIDEO_QUALITY_SLIDER)
OUTPUT_VIDEO_RESOLUTION_DROPDOWN.change(update_output_video_resolution, inputs = OUTPUT_VIDEO_RESOLUTION_DROPDOWN)
OUTPUT_VIDEO_FPS_SLIDER.change(update_output_video_fps, inputs = OUTPUT_VIDEO_FPS_SLIDER)
multi_component_names : List[ComponentName] =\
[
'target_image',
'target_video'
]
for component_name in multi_component_names:
component = get_ui_component(component_name)
if component:
for method in [ 'upload', 'change', 'clear' ]:
getattr(component, method)(remote_update, outputs = [ OUTPUT_IMAGE_QUALITY_SLIDER, OUTPUT_VIDEO_ENCODER_DROPDOWN, OUTPUT_VIDEO_PRESET_DROPDOWN, OUTPUT_VIDEO_QUALITY_SLIDER, OUTPUT_VIDEO_RESOLUTION_DROPDOWN, OUTPUT_VIDEO_FPS_SLIDER ]) | null |
793 | from typing import Optional, Tuple
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import TempFrameFormat
from facefusion.filesystem import is_video
from facefusion.uis.core import get_ui_component
TEMP_FRAME_FORMAT_DROPDOWN : Optional[gradio.Dropdown] = None
TEMP_FRAME_QUALITY_SLIDER : Optional[gradio.Slider] = None
def is_video(video_path : str) -> bool:
def render() -> None:
global TEMP_FRAME_FORMAT_DROPDOWN
global TEMP_FRAME_QUALITY_SLIDER
TEMP_FRAME_FORMAT_DROPDOWN = gradio.Dropdown(
label = wording.get('uis.temp_frame_format_dropdown'),
choices = facefusion.choices.temp_frame_formats,
value = facefusion.globals.temp_frame_format,
visible = is_video(facefusion.globals.target_path)
)
TEMP_FRAME_QUALITY_SLIDER = gradio.Slider(
label = wording.get('uis.temp_frame_quality_slider'),
value = facefusion.globals.temp_frame_quality,
step = facefusion.choices.temp_frame_quality_range[1] - facefusion.choices.temp_frame_quality_range[0],
minimum = facefusion.choices.temp_frame_quality_range[0],
maximum = facefusion.choices.temp_frame_quality_range[-1],
visible = is_video(facefusion.globals.target_path)
) | null |
794 | from typing import Optional, Tuple
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
from facefusion.typing import TempFrameFormat
from facefusion.filesystem import is_video
from facefusion.uis.core import get_ui_component
TEMP_FRAME_FORMAT_DROPDOWN : Optional[gradio.Dropdown] = None
TEMP_FRAME_QUALITY_SLIDER : Optional[gradio.Slider] = None
def remote_update() -> Tuple[gradio.Dropdown, gradio.Slider]:
if is_video(facefusion.globals.target_path):
return gradio.Dropdown(visible = True), gradio.Slider(visible = True)
return gradio.Dropdown(visible = False), gradio.Slider(visible = False)
def update_temp_frame_format(temp_frame_format : TempFrameFormat) -> None:
facefusion.globals.temp_frame_format = temp_frame_format
def update_temp_frame_quality(temp_frame_quality : int) -> None:
facefusion.globals.temp_frame_quality = temp_frame_quality
def get_ui_component(name : ComponentName) -> Optional[Component]:
if name in UI_COMPONENTS:
return UI_COMPONENTS[name]
return None
def listen() -> None:
TEMP_FRAME_FORMAT_DROPDOWN.change(update_temp_frame_format, inputs = TEMP_FRAME_FORMAT_DROPDOWN)
TEMP_FRAME_QUALITY_SLIDER.change(update_temp_frame_quality, inputs = TEMP_FRAME_QUALITY_SLIDER)
target_video = get_ui_component('target_video')
if target_video:
for method in [ 'upload', 'change', 'clear' ]:
getattr(target_video, method)(remote_update, outputs = [ TEMP_FRAME_FORMAT_DROPDOWN, TEMP_FRAME_QUALITY_SLIDER ]) | null |
795 | from typing import Any, Dict, Tuple, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.vision import count_video_frame_total
from facefusion.filesystem import is_video
from facefusion.uis.core import get_ui_component
TRIM_FRAME_START_SLIDER : Optional[gradio.Slider] = None
TRIM_FRAME_END_SLIDER : Optional[gradio.Slider] = None
def count_video_frame_total(video_path : str) -> int:
if is_video(video_path):
video_capture = cv2.VideoCapture(video_path)
if video_capture.isOpened():
video_frame_total = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
video_capture.release()
return video_frame_total
return 0
def is_video(video_path : str) -> bool:
return is_file(video_path) and filetype.helpers.is_video(video_path)
def render() -> None:
global TRIM_FRAME_START_SLIDER
global TRIM_FRAME_END_SLIDER
trim_frame_start_slider_args : Dict[str, Any] =\
{
'label': wording.get('uis.trim_frame_start_slider'),
'step': 1,
'minimum': 0,
'maximum': 100,
'visible': False
}
trim_frame_end_slider_args : Dict[str, Any] =\
{
'label': wording.get('uis.trim_frame_end_slider'),
'step': 1,
'minimum': 0,
'maximum': 100,
'visible': False
}
if is_video(facefusion.globals.target_path):
video_frame_total = count_video_frame_total(facefusion.globals.target_path)
trim_frame_start_slider_args['value'] = facefusion.globals.trim_frame_start or 0
trim_frame_start_slider_args['maximum'] = video_frame_total
trim_frame_start_slider_args['visible'] = True
trim_frame_end_slider_args['value'] = facefusion.globals.trim_frame_end or video_frame_total
trim_frame_end_slider_args['maximum'] = video_frame_total
trim_frame_end_slider_args['visible'] = True
with gradio.Row():
TRIM_FRAME_START_SLIDER = gradio.Slider(**trim_frame_start_slider_args)
TRIM_FRAME_END_SLIDER = gradio.Slider(**trim_frame_end_slider_args) | null |
796 | from typing import Any, Dict, Tuple, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.vision import count_video_frame_total
from facefusion.filesystem import is_video
from facefusion.uis.core import get_ui_component
TRIM_FRAME_START_SLIDER : Optional[gradio.Slider] = None
TRIM_FRAME_END_SLIDER : Optional[gradio.Slider] = None
def remote_update() -> Tuple[gradio.Slider, gradio.Slider]:
if is_video(facefusion.globals.target_path):
video_frame_total = count_video_frame_total(facefusion.globals.target_path)
facefusion.globals.trim_frame_start = None
facefusion.globals.trim_frame_end = None
return gradio.Slider(value = 0, maximum = video_frame_total, visible = True), gradio.Slider(value = video_frame_total, maximum = video_frame_total, visible = True)
return gradio.Slider(value = None, maximum = None, visible = False), gradio.Slider(value = None, maximum = None, visible = False)
def update_trim_frame_start(trim_frame_start : int) -> None:
facefusion.globals.trim_frame_start = trim_frame_start if trim_frame_start > 0 else None
def update_trim_frame_end(trim_frame_end : int) -> None:
video_frame_total = count_video_frame_total(facefusion.globals.target_path)
facefusion.globals.trim_frame_end = trim_frame_end if trim_frame_end < video_frame_total else None
def get_ui_component(name : ComponentName) -> Optional[Component]:
if name in UI_COMPONENTS:
return UI_COMPONENTS[name]
return None
def listen() -> None:
TRIM_FRAME_START_SLIDER.change(update_trim_frame_start, inputs = TRIM_FRAME_START_SLIDER)
TRIM_FRAME_END_SLIDER.change(update_trim_frame_end, inputs = TRIM_FRAME_END_SLIDER)
target_video = get_ui_component('target_video')
if target_video:
for method in [ 'upload', 'change', 'clear' ]:
getattr(target_video, method)(remote_update, outputs = [ TRIM_FRAME_START_SLIDER, TRIM_FRAME_END_SLIDER ]) | null |
797 | from typing import Optional
import gradio
import facefusion.globals
import facefusion.choices
from facefusion.typing import VideoMemoryStrategy
from facefusion import wording
VIDEO_MEMORY_STRATEGY : Optional[gradio.Dropdown] = None
SYSTEM_MEMORY_LIMIT_SLIDER : Optional[gradio.Slider] = None
def render() -> None:
global VIDEO_MEMORY_STRATEGY
global SYSTEM_MEMORY_LIMIT_SLIDER
VIDEO_MEMORY_STRATEGY = gradio.Dropdown(
label = wording.get('uis.video_memory_strategy_dropdown'),
choices = facefusion.choices.video_memory_strategies,
value = facefusion.globals.video_memory_strategy
)
SYSTEM_MEMORY_LIMIT_SLIDER = gradio.Slider(
label = wording.get('uis.system_memory_limit_slider'),
step =facefusion.choices.system_memory_limit_range[1] - facefusion.choices.system_memory_limit_range[0],
minimum = facefusion.choices.system_memory_limit_range[0],
maximum = facefusion.choices.system_memory_limit_range[-1],
value = facefusion.globals.system_memory_limit
) | null |
798 | from typing import Optional
import gradio
import facefusion.globals
import facefusion.choices
from facefusion.typing import VideoMemoryStrategy
from facefusion import wording
VIDEO_MEMORY_STRATEGY : Optional[gradio.Dropdown] = None
SYSTEM_MEMORY_LIMIT_SLIDER : Optional[gradio.Slider] = None
def update_video_memory_strategy(video_memory_strategy : VideoMemoryStrategy) -> None:
facefusion.globals.video_memory_strategy = video_memory_strategy
def update_system_memory_limit(system_memory_limit : int) -> None:
facefusion.globals.system_memory_limit = system_memory_limit
def listen() -> None:
VIDEO_MEMORY_STRATEGY.change(update_video_memory_strategy, inputs = VIDEO_MEMORY_STRATEGY)
SYSTEM_MEMORY_LIMIT_SLIDER.change(update_system_memory_limit, inputs = SYSTEM_MEMORY_LIMIT_SLIDER) | null |
799 | from typing import Tuple, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.face_store import clear_static_faces, clear_reference_faces
from facefusion.uis.typing import File
from facefusion.filesystem import is_image, is_video
from facefusion.uis.core import register_ui_component
TARGET_FILE : Optional[gradio.File] = None
TARGET_IMAGE : Optional[gradio.Image] = None
TARGET_VIDEO : Optional[gradio.Video] = None
File = IO[Any]
def is_image(image_path : str) -> bool:
return is_file(image_path) and filetype.helpers.is_image(image_path)
def is_video(video_path : str) -> bool:
return is_file(video_path) and filetype.helpers.is_video(video_path)
def register_ui_component(name : ComponentName, component: Component) -> None:
UI_COMPONENTS[name] = component
def render() -> None:
global TARGET_FILE
global TARGET_IMAGE
global TARGET_VIDEO
is_target_image = is_image(facefusion.globals.target_path)
is_target_video = is_video(facefusion.globals.target_path)
TARGET_FILE = gradio.File(
label = wording.get('uis.target_file'),
file_count = 'single',
file_types =
[
'.png',
'.jpg',
'.webp',
'.mp4'
],
value = facefusion.globals.target_path if is_target_image or is_target_video else None
)
TARGET_IMAGE = gradio.Image(
value = TARGET_FILE.value['name'] if is_target_image else None,
visible = is_target_image,
show_label = False
)
TARGET_VIDEO = gradio.Video(
value = TARGET_FILE.value['name'] if is_target_video else None,
visible = is_target_video,
show_label = False
)
register_ui_component('target_image', TARGET_IMAGE)
register_ui_component('target_video', TARGET_VIDEO) | null |
800 | from typing import Tuple, Optional
import gradio
import facefusion.globals
from facefusion import wording
from facefusion.face_store import clear_static_faces, clear_reference_faces
from facefusion.uis.typing import File
from facefusion.filesystem import is_image, is_video
from facefusion.uis.core import register_ui_component
TARGET_FILE : Optional[gradio.File] = None
TARGET_IMAGE : Optional[gradio.Image] = None
TARGET_VIDEO : Optional[gradio.Video] = None
def update(file : File) -> Tuple[gradio.Image, gradio.Video]:
clear_reference_faces()
clear_static_faces()
if file and is_image(file.name):
facefusion.globals.target_path = file.name
return gradio.Image(value = file.name, visible = True), gradio.Video(value = None, visible = False)
if file and is_video(file.name):
facefusion.globals.target_path = file.name
return gradio.Image(value = None, visible = False), gradio.Video(value = file.name, visible = True)
facefusion.globals.target_path = None
return gradio.Image(value = None, visible = False), gradio.Video(value = None, visible = False)
def listen() -> None:
TARGET_FILE.change(update, inputs = TARGET_FILE, outputs = [ TARGET_IMAGE, TARGET_VIDEO ]) | null |
801 | from typing import Optional
import gradio
import facefusion.globals
import facefusion.choices
from facefusion import wording
EXECUTION_THREAD_COUNT_SLIDER : Optional[gradio.Slider] = None
def render() -> None:
global EXECUTION_THREAD_COUNT_SLIDER
EXECUTION_THREAD_COUNT_SLIDER = gradio.Slider(
label = wording.get('uis.execution_thread_count_slider'),
value = facefusion.globals.execution_thread_count,
step = facefusion.choices.execution_thread_count_range[1] - facefusion.choices.execution_thread_count_range[0],
minimum = facefusion.choices.execution_thread_count_range[0],
maximum = facefusion.choices.execution_thread_count_range[-1]
) | null |
Subsets and Splits