Algorithm Search⌘K

Algorithmcore

Unit selection synthesis

Also called concatenative synthesis.

Speech synthesis that picks recorded units from a large database to minimize the sum of target costs and join costs, found by a Viterbi search over the candidates, and joins them.

Time
Θ(n K^2) worst
Space
Θ(n K) extra
Where
K = the number of candidates per target; n = the number of target units
Properties
deterministicexactnot in placeoffline
Origin
Andrew J. Hunt, Alan W. Black, 1996

Unit selection synthesis makes speech for a text-to-speech system by cutting pieces out of a large recorded database and joining them. For each unit of the planned utterance, usually a phone or a diphone with a target pitch and duration, many recorded candidates exist. A target cost measures how well a candidate fits its target, and a join cost measures how well two candidates fit together, and it is zero for two units that were recorded next to each other. The best sequence minimizes the sum of all these costs. It is a shortest path through a layered graph of candidates, so the Viterbi algorithm finds it in Θ(nK2)\Theta(n K^2) time for nn targets and KK candidates each. Hunt and Black gave this formulation in 1996, and it was the most natural-sounding commercial method until neural synthesis.

In plain words

Record one speaker reading many hours of text, and cut the recordings into small sound pieces. To say a new sentence, you need one piece for each sound. There are many recorded copies of each sound, each said with a different pitch, length and neighbors.

A good choice fits two kinds of need. Each piece should sound like what the sentence needs at that place. And each pair of pieces should join without a click or a jump in pitch. Two pieces that were next to each other in the recording join perfectly, so long stretches of the original recording are good.

Trying all choices is too slow. But the best choice up to a given sound only depends on which piece ends there. So the method goes through the sentence once, keeps the best cost for each piece at each place, and follows the links back at the end.

The problem

The front end of the synthesizer gives a sequence of targets t1,…,tnt_1, \ldots, t_n. A target names a unit type (here a phone) and the wanted prosody and context: an F0 in Hz, a duration in ms, and the left and right neighbor phones. The database holds units uu with the same fields, measured on the recordings, plus their recording, their position in it, and spectral vectors at their two ends, for example MFCCs.

The candidates UiU_i for target tit_i are the database units of the same phone. With weights ww, the code uses

TC(t,u)=wf0∣f0(t)−f0(u)∣+wdur∣d(t)−d(u)∣+wctx([ℓ(t)≠ℓ(u)]+[r(t)≠r(u)]),TC(t, u) = w_{f0} |f_0(t) - f_0(u)| + w_{dur} |d(t) - d(u)| + w_{ctx} \bigl([\ell(t) \ne \ell(u)] + [r(t) \ne r(u)]\bigr),
JC(u,v)={0if v follows u in the same recording,wspec∥e(u)−s(v)∥2+wjf0∣f0(u)−f0(v)∣otherwise,JC(u, v) = \begin{cases} 0 & \text{if } v \text{ follows } u \text{ in the same recording,} \\ w_{spec} \|e(u) - s(v)\|^2 + w_{jf0} |f_0(u) - f_0(v)| & \text{otherwise,} \end{cases}

where e(u)e(u) and s(v)s(v) are the spectral vectors at the end of uu and the start of vv. Hunt and Black write both costs as weighted sums of sub-costs in the same way; real systems use many more sub-costs. The task is to find si∈Uis_i \in U_i that minimize

∑i=1nTC(ti,si)+∑i=2nJC(si−1,si).\sum_{i=1}^{n} TC(t_i, s_i) + \sum_{i=2}^{n} JC(s_{i-1}, s_i).

The algorithm

The search is Viterbi in the tropical semiring (min, +): costs are added along a path, and the minimum is taken over paths.

  1. UNIT-SELECTION(t_1 .. t_n, database, w, beam)
  2. 1for i ← 1 to n do U_i ← the database units with the phone of t_i, in database order
  3. 2for each u in U_1 do C_1(u) ← TC(t_1, u)
  4. 3for i ← 2 to n do
  5. 4for each u in U_i do
  6. 5B_i(u) ← the first kept v in U_(i-1) that minimizes C_(i-1)(v) + JC(v, u)
  7. 6C_i(u) ← C_(i-1)(B_i(u)) + JC(B_i(u), u) + TC(t_i, u)
  8. 7if a beam width is given, keep only the beam units of U_i with the smallest C_i
  9. 8u_n ← the first kept u in U_n that minimizes C_n(u)
  10. 9for i ← n downto 2 do u_(i-1) ← B_i(u_i)
  11. 10return u_1 .. u_n and C_n(u_n)

Ci(u)C_i(u) is the least cost of a choice for t1,…,tit_1, \ldots, t_i that ends with uu, and Bi(u)B_i(u) is the unit before uu on such a choice. Line L9 is the traceback. Line L7 is optional; without it every unit is kept and the result is exact. The chosen units are then joined, usually with a short overlap-add at each join, and some systems adjust pitch and duration with PSOLA when the fit is poor.

Tie rule. Lines L5 and L8 take the first minimizer in database order. Then the result is the optimal sequence whose reversed list of candidate indices is the smallest in lexicographic order.

Example

Take two targets: "a" with F0 100 Hz, duration 60 ms, left neighbor silence and right neighbor "b", then "b" with 120 Hz, 70 ms, left "a" and right silence. All weights are 1, and the spectral vectors have one number. The database has three units:

unit recording, position phone F0 duration context start, end vector
A0 0, 0 a 100 60 silence, b 0, 0
A1 1, 0 a 101 60 silence, b 0, 5
B1 1, 1 b 120 70 a, silence 5, 0

The target costs are TC(t1,A0)=0TC(t_1, A0) = 0, TC(t1,A1)=1TC(t_1, A1) = 1 (1 Hz off) and TC(t2,B1)=0TC(t_2, B1) = 0. The join A0→B1A0 \to B1 costs (0−5)2+∣100−120∣=45(0 - 5)^2 + |100 - 120| = 45. The join A1→B1A1 \to B1 costs 0, because B1 follows A1 in recording 1. So C1(A0)=0C_1(A0) = 0, C1(A1)=1C_1(A1) = 1, and

C2(B1)=min⁡(0+45, 1+0)+0=1,B2(B1)=A1.C_2(B1) = \min(0 + 45,\ 1 + 0) + 0 = 1, \qquad B_2(B1) = A1.

The answer is A1, B1 with cost 1: a stretch of real speech wins over a better single unit with a bad join. A beam of width 1 keeps only A0 after the first target, since it has the smaller cost, and then returns A0, B1 with cost 45. This shows that the beam can lose the optimum.

Correctness

Each choice of units is a path from a source through one candidate per layer, and its length is its total cost. The proofs file shows by induction on ii that Ci(u)C_i(u) is the least cost of a choice that ends with uu: the best choice that ends with v→uv \to u extends a best choice that ends with vv, since the cost of the extension does not depend on the earlier units. The traceback rebuilds a choice of that cost, and the tie rule picks the stated optimum. With a beam of width at least the largest ∣Ui∣|U_i| the result is the same; with a smaller beam, CiC_i is only an upper bound and the result can be worse, as in the example. The tests check the exact search, ties included, against brute force over all ∏i∣Ui∣\prod_i |U_i| choices, and the beam case on the example.

Proof: The unit selection search returns a sequence of least total cost, chosen by the tie rulefull

Fix the targets t1,…,tnt_1, \ldots, t_n with n≥1n \ge 1 and the candidate lists U1,…,UnU_1, \ldots, U_n of line L1, each non-empty and in database order. Write u∈Uiu \in U_i also for its index in UiU_i. For a sequence s=(s1,…,si)s = (s_1, \ldots, s_i) with sk∈Uks_k \in U_k define

Ki(s)=∑k=1iTC(tk,sk)+∑k=2iJC(sk−1,sk).K_i(s) = \sum_{k=1}^{i} TC(t_k, s_k) + \sum_{k=2}^{i} JC(s_{k-1}, s_k).

All costs are finite non-negative reals, since a candidate has the phone of its target. The work is in the tropical semiring (R∪{+∞},min⁡,+,+∞,0)(\mathbb{R} \cup \{+\infty\}, \min, +, +\infty, 0). The costs satisfy

Ki(s1,…,si)=Ki−1(s1,…,si−1)+JC(si−1,si)+TC(ti,si).(1)K_i(s_1, \ldots, s_i) = K_{i-1}(s_1, \ldots, s_{i-1}) + JC(s_{i-1}, s_i) + TC(t_i, s_i). \tag{1}

This is the length of a path in the layered graph with one node per candidate, edges from each node of layer i−1i - 1 to each node of layer ii of length JC+TCJC + TC, and a source joined to layer 1 by edges of length TCTC. The sequences are exactly the source to layer nn paths, so a sequence of least cost is a shortest path in a directed acyclic graph.

Exact search (no beam)

Lemma 1. After line L2 and after the pass of line L3 for each i≥2i \ge 2, Ci(u)=min⁡{Ki(s):si=u}C_i(u) = \min \{ K_i(s) : s_i = u \} for every u∈Uiu \in U_i.

Proof. By induction on ii. For i=1i = 1 the only sequence is (u)(u), and line L2 sets C1(u)=TC(t1,u)=K1(u)C_1(u) = TC(t_1, u) = K_1(u). For i≥2i \ge 2, every sequence with si=us_i = u has some si−1=vs_{i-1} = v, and by (1) and the induction hypothesis

min⁡si=uKi=min⁡v∈Ui−1(Ci−1(v)+JC(v,u))+TC(ti,u),\min_{s_i = u} K_i = \min_{v \in U_{i-1}} \bigl( C_{i-1}(v) + JC(v, u) \bigr) + TC(t_i, u),

because adding a constant keeps the order (the principle of optimality). Line L5 takes a minimizer Bi(u)B_i(u) of the inner term and line L6 adds TC(ti,u)TC(t_i, u). □\square

Lemma 2. For i≥2i \ge 2, the sequence obtained by following the back pointers from u∈Uiu \in U_i to layer 1 has cost Ci(u)C_i(u).

Proof. By induction on ii, from (1): the pointer v=Bi(u)v = B_i(u) has Ci−1(v)+JC(v,u)+TC(ti,u)=Ci(u)C_{i-1}(v) + JC(v, u) + TC(t_i, u) = C_i(u), and the sequence from vv has cost Ci−1(v)C_{i-1}(v). □\square

Theorem 1. Without a beam, lines L8 to L10 return a sequence s∗s^* with Kn(s∗)=min⁡sKn(s)K_n(s^*) = \min_s K_n(s), and its cost.

Proof. Line L8 picks unu_n that minimizes CnC_n, which by Lemma 1 is the minimum of KnK_n over all sequences. By Lemma 2 the traceback of line L9 gives a sequence of that cost. □\square

Theorem 2 (tie rule). Among the sequences of least cost, the returned one is the smallest in the lexicographic order of (sn,sn−1,…,s1)(s_n, s_{n-1}, \ldots, s_1), comparing indices in the candidate lists.

Proof. Line L8 takes the first minimizer, so sns_n is the smallest last index of an optimal sequence. Assume sn,…,sis_n, \ldots, s_{i} are the smallest such indices among the optimal sequences that end with them. The optimal sequences that end with si,…,sns_{i}, \ldots, s_n are those whose prefix through layer i−1i - 1 has si−1=vs_{i-1} = v with Ci−1(v)+JC(v,si)=min⁡v′(Ci−1(v′)+JC(v′,si))C_{i-1}(v) + JC(v, s_i) = \min_{v'} (C_{i-1}(v') + JC(v', s_i)) and is optimal for vv. Line L5 scans vv in increasing order and replaces the stored candidate only on a strictly smaller value, so Bi(si)B_i(s_i) is the smallest such vv. Induction down to i=2i = 2 gives the claim. □\square

The tests compare the output, ties included, with a brute force search over all ∏i∣Ui∣\prod_i |U_i| sequences that uses this rule.

Beam

With a beam of width KK, line L7 keeps only the KK units of layer ii with the smallest CiC_i, and line L5 then minimizes over the kept units only. If K≥∣Ui∣K \ge |U_i| for every layer, nothing is removed and Theorems 1 and 2 hold unchanged. For smaller KK the invariant of Lemma 1 becomes an upper bound: Ci(u)C_i(u) is the least cost over the sequences whose units all survived the pruning, which is at least the true minimum. The pruning can remove the first unit of the only optimal sequence. A two-target example with one unit of target cost 0 and a costly join, and one unit of target cost 1 followed by its free join, makes a beam of 1 return a sequence of cost 45 when the optimum is 1; the tests check this case.

Cost

Line L5 looks at ∣Ui−1∣|U_{i-1}| predecessors for each of the ∣Ui∣|U_i| units, so the time is Θ(∑i=2n∣Ui−1∣∣Ui∣)\Theta(\sum_{i=2}^{n} |U_{i-1}| |U_i|) cost evaluations, which is Θ(nK2)\Theta(n K^2) when each list has KK units. With a beam of width BB, the time is O(nKB)O(n K B) plus the selection of the BB best per layer. The back pointers take Θ(nK)\Theta(n K) space.

Complexity

Line L5 evaluates ∣Ui−1∣|U_{i-1}| join costs for each unit of UiU_i, so the time is Θ(∑i∣Ui−1∣∣Ui∣)\Theta(\sum_i |U_{i-1}| |U_i|) join cost evaluations, or Θ(nK2)\Theta(n K^2) with KK candidates per target. The back pointers take Θ(nK)\Theta(n K) space. The brute force search takes Θ(nKn)\Theta(n K^n). A large database can hold thousands of units of a common phone, so K2K^2 join costs per target are the main cost. Real systems cut KK by pre-selection on the phone context, cache the join costs, and prune with a beam, which gives O(nKB)O(n K B) for a beam of width BB.

Properties

  • Exact for the costs. Without pruning, the search returns a minimum of the total cost. Whether this sounds best depends on how well the costs match what listeners hear.
  • Prefers long stretches. Since consecutive units join for free, the optimum often copies whole syllables or words from the database. This is the source of the high naturalness of the method in its domain.
  • Not online. The best unit for an early target can depend on the last target, so the traceback needs the whole utterance. Systems with low latency run the search over a phrase at a time.
  • Bounded by the data. The output can only use recorded speech. A target far from every recording gives a poor unit or a strong modification.
  • Fixed voice. A new voice or speaking style needs a new database of many hours.

Variants and improvements

  • Unit size. Hunt and Black used phone units. Diphones (from the middle of one phone to the middle of the next) put the joins in the stable parts of phones. Half-phones and non-uniform units are also used.
  • Diphone synthesis. The older method keeps exactly one recorded unit per diphone and changes its pitch and duration by signal processing such as PSOLA. It needs no search, but the output sounds more processed.
  • Pre-selection and clustering. Group the units of each type by a decision tree on context and prosody, and take the candidates only from the leaf that matches the target.
  • Weight tuning. Hunt and Black tuned the weights by comparing the selected units with natural held-out utterances under an objective distance. Later systems tuned them with listening tests.
  • Hybrid synthesis. Use a statistical model, an HMM or a neural network, to predict the targets and score the candidates, and select natural units with this score. This combines the smoothness of HMM-based synthesis with real waveforms.

When to use it

Use unit selection when one voice in a narrow domain must sound very natural and a large recorded and labeled database is affordable, for example announcements, navigation, or a product voice with a fixed set of sentence types. Use HMM-based or neural synthesis when you need a small footprint, many voices, control of style and prosody, or good quality on text far from the recordings. Neural vocoders such as WaveNet and HiFi-GAN behind models such as Tacotron now give higher ratings than unit selection in most published tests. For example, in the US English test of the WaveNet paper, a concatenative system had a mean opinion score of 3.86 ± 0.137 and WaveNet had 4.21 ± 0.081 (measurement, 100 test sentences with 8 ratings each, on a 1 to 5 scale).

Pitfalls

  • Bad labels. Wrong phone boundaries or pitch marks in the database give clicks and wrong sounds that no cost can see. Check the forced alignment of the database.
  • Costs that do not match perception. A low total cost does not guarantee a good result. The weights decide which sub-costs win; tune them with listeners or held-out speech.
  • Too narrow a beam. Pruning by the cost so far drops units that are expensive alone but enable a free join, as in the example. Keep the beam wide enough to hold the long stretches.
  • Join costs for neighbors. If the join cost of two units that are adjacent in a recording is not 0, the search loses its preference for long stretches.
  • Uneven quality. The output is very good where the database has the right units and poor where it does not, and listeners notice the change within one sentence.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

unit_selection_synthesis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unit-selection-synthesis/. The authors are listed in prov/V4WYB0.jsonl.

"""Unit selection by dynamic programming over target and join costs, after
Hunt and Black (1996).

A target is the specification of one unit of the utterance to synthesize:
its phone, a target F0 (Hz), a target duration (ms) and the phones to its left
and right. A database unit is a stretch of recorded speech with the same
fields, plus the utterance it comes from, its position in that utterance,
and the spectral vectors at its start and its end.

    target cost  TC(t, u) = w_f0 |t.f0 - u.f0| + w_dur |t.dur - u.dur|
                            + w_ctx ([t.left != u.left] + [t.right != u.right])
    join cost    JC(u, v) = 0 if v follows u directly in the same recording,
                            else w_spec ||u.end - v.start||^2 + w_jf0 |u.f0 - v.f0|

Only units with the phone of the target are candidates. The best sequence
minimizes the sum of the target costs and the join costs, which is a
shortest path in a layered graph, found by Viterbi in the tropical semiring
(min, +). A beam keeps only the best candidates of each layer, which is
faster but can miss the optimum.
"""

from dataclasses import dataclass, field
from typing import Dict, List, Optional, Sequence, Tuple

INF = float("inf")


@dataclass(frozen=True)
class Target:
    phone: str
    f0: float
    dur: float
    left: str = ""
    right: str = ""


@dataclass(frozen=True)
class Unit:
    utt: int
    idx: int
    phone: str
    f0: float
    dur: float
    left: str = ""
    right: str = ""
    start: Tuple[float, ...] = field(default=())
    end: Tuple[float, ...] = field(default=())


DEFAULT_WEIGHTS = {"f0": 1.0, "dur": 1.0, "ctx": 1.0, "spec": 1.0, "jf0": 1.0}


def target_cost(t: Target, u: Unit, w: Dict[str, float] = DEFAULT_WEIGHTS) -> float:
    if t.phone != u.phone:
        return INF
    ctx = (t.left != u.left) + (t.right != u.right)
    return w["f0"] * abs(t.f0 - u.f0) + w["dur"] * abs(t.dur - u.dur) + w["ctx"] * ctx


def join_cost(u: Unit, v: Unit, w: Dict[str, float] = DEFAULT_WEIGHTS) -> float:
    if u.utt == v.utt and v.idx == u.idx + 1:
        return 0.0
    spec = sum((a - b) * (a - b) for a, b in zip(u.end, v.start))
    return w["spec"] * spec + w["jf0"] * abs(u.f0 - v.f0)


def candidates(targets: Sequence[Target], units: Sequence[Unit]) -> List[List[Unit]]:
    """The candidate lists U_1 .. U_n, each in database order."""
    return [[u for u in units if u.phone == t.phone] for t in targets]  # @line L1


def total_cost(targets, seq, w=DEFAULT_WEIGHTS) -> float:
    """The cost of a given unit sequence: all target costs plus all join costs."""
    c = sum(target_cost(t, u, w) for t, u in zip(targets, seq))
    c += sum(join_cost(a, b, w) for a, b in zip(seq, seq[1:]))
    return c


def select_units(targets: Sequence[Target], units: Sequence[Unit], w: Dict[str, float] = DEFAULT_WEIGHTS,
                 beam: Optional[int] = None):
    """Return (units, cost) of a sequence of least total cost, or raise ValueError
    if some target has no candidate.

    Tie rule: in lines L5 and L8 the first minimizer in database order wins.
    With beam = K, only the K cheapest units of each layer (ties to the earlier
    unit) are extended; the result is then not always optimal.
    """
    n = len(targets)
    if n == 0:
        return [], 0.0
    U = candidates(targets, units)
    if any(not layer for layer in U):
        raise ValueError("a target has no candidate unit")
    if beam is not None and beam < 1:
        raise ValueError("the beam must be at least 1")
    C = [[target_cost(targets[0], u, w) for u in U[0]]]  # @line L2
    B: List[List[int]] = [[-1] * len(U[0])]
    alive = _prune(C[0], beam)
    for i in range(1, n):  # @line L3
        row, back = [], []
        for u in U[i]:  # @line L4
            best_j, best = -1, INF
            for j in alive:  # @line L5
                c = C[i - 1][j] + join_cost(U[i - 1][j], u, w)
                if c < best or best_j == -1:
                    best_j, best = j, c
            row.append(best + target_cost(targets[i], u, w))  # @line L6
            back.append(best_j)
        C.append(row)
        B.append(back)
        alive = _prune(row, beam)  # @line L7
    k = min(alive, key=lambda j: (C[n - 1][j], j))  # @line L8
    cost = C[n - 1][k]
    path = [k]
    for i in range(n - 1, 0, -1):  # @line L9
        k = B[i][k]
        path.append(k)
    path.reverse()
    return [U[i][path[i]] for i in range(n)], cost  # @line L10


def _prune(row: List[float], beam: Optional[int]) -> List[int]:
    """The indices kept for the next layer, in increasing order."""
    order = list(range(len(row)))
    if beam is None or beam >= len(row):
        return order
    return sorted(sorted(order, key=lambda j: (row[j], j))[:beam])
test_unit_selection_synthesis.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unit-selection-synthesis/. The authors are listed in prov/V4WYB0.jsonl.

import itertools
import random

import pytest

from unit_selection_synthesis import (
    Target,
    Unit,
    candidates,
    join_cost,
    select_units,
    target_cost,
    total_cost,
)

PHONES = ["a", "b", "c"]


def random_database(rng, n_utts, length):
    units = []
    for utt in range(n_utts):
        phones = [rng.choice(PHONES) for _ in range(length)]
        for i, p in enumerate(phones):
            units.append(Unit(
                utt=utt, idx=i, phone=p,
                f0=float(rng.randint(90, 130)), dur=float(rng.randint(50, 90)),
                left=phones[i - 1] if i > 0 else "#",
                right=phones[i + 1] if i + 1 < length else "#",
                start=(float(rng.randint(0, 4)), float(rng.randint(0, 4))),
                end=(float(rng.randint(0, 4)), float(rng.randint(0, 4))),
            ))
    return units


def random_targets(rng, n, units):
    present = sorted({u.phone for u in units})
    phones = [rng.choice(present) for _ in range(n)]
    return [Target(p, float(rng.randint(90, 130)), float(rng.randint(50, 90)),
                   phones[i - 1] if i > 0 else "#", phones[i + 1] if i + 1 < n else "#")
            for i, p in enumerate(phones)]


def brute_force(targets, units, w=None):
    """All candidate sequences; the best by (cost, reversed index tuple)."""
    U = candidates(targets, units)
    best = None
    for idx in itertools.product(*[range(len(layer)) for layer in U]):
        seq = [U[i][k] for i, k in enumerate(idx)]
        c = total_cost(targets, seq) if w is None else total_cost(targets, seq, w)
        key = (c, tuple(reversed(idx)))
        if best is None or key < best[0]:
            best = (key, seq)
    return best[1], best[0][0]


def test_matches_brute_force_with_ties():
    rng = random.Random(1)
    for _ in range(40):
        units = random_database(rng, rng.randint(1, 3), rng.randint(2, 5))
        targets = random_targets(rng, rng.randint(1, 5), units)
        seq, cost = select_units(targets, units)
        bseq, bcost = brute_force(targets, units)
        assert cost == bcost
        assert seq == bseq
        assert total_cost(targets, seq) == cost


def test_wide_beam_equals_exact():
    rng = random.Random(2)
    for _ in range(30):
        units = random_database(rng, 3, 5)
        targets = random_targets(rng, rng.randint(1, 5), units)
        exact = select_units(targets, units)
        assert select_units(targets, units, beam=len(units)) == exact


def test_narrow_beam_can_fail():
    # Unit 0 of "a" fits its target exactly (cost 0) and unit 1 of "a" has
    # target cost 1, but unit 1 is followed by a matching "b" in the same
    # recording, so its join is free.
    units = [
        Unit(0, 0, "a", 100.0, 60.0, "#", "b", (0.0,), (0.0,)),
        Unit(1, 0, "a", 101.0, 60.0, "#", "b", (0.0,), (5.0,)),
        Unit(1, 1, "b", 120.0, 70.0, "a", "#", (5.0,), (0.0,)),
    ]
    targets = [Target("a", 100.0, 60.0, "#", "b"), Target("b", 120.0, 70.0, "a", "#")]
    exact_seq, exact = select_units(targets, units)
    assert exact == 1.0
    assert [(u.utt, u.idx) for u in exact_seq] == [(1, 0), (1, 1)]
    narrow_seq, narrow = select_units(targets, units, beam=1)
    assert [(u.utt, u.idx) for u in narrow_seq] == [(0, 0), (1, 1)]
    assert narrow == 0.0 + 25.0 + 20.0
    assert narrow > exact


def test_contiguous_stretch_is_preferred():
    # The database holds the whole target word in one recording and also
    # scattered copies with slightly better target costs but costly joins.
    word = ["c", "a", "b"]
    units = [Unit(0, i, p, 100.0, 60.0, "", "", (9.0,), (0.0,)) for i, p in enumerate(word)]
    units += [Unit(1 + i, 0, p, 100.0, 60.0, "", "", (3.0,), (3.0,)) for i, p in enumerate(word)]
    targets = [Target(p, 100.0, 60.0, "", "") for p in word]
    seq, cost = select_units(targets, units)
    assert [(u.utt, u.idx) for u in seq] == [(0, 0), (0, 1), (0, 2)]
    assert cost == 0.0


def test_weights_change_the_choice():
    units = [
        Unit(0, 0, "a", 100.0, 80.0),
        Unit(1, 0, "a", 130.0, 60.0),
    ]
    t = [Target("a", 100.0, 60.0)]
    w_f0 = {"f0": 1.0, "dur": 0.1, "ctx": 1.0, "spec": 1.0, "jf0": 1.0}
    w_dur = {"f0": 0.1, "dur": 1.0, "ctx": 1.0, "spec": 1.0, "jf0": 1.0}
    assert select_units(t, units, w_f0)[0][0].utt == 0
    assert select_units(t, units, w_dur)[0][0].utt == 1


def test_costs():
    u = Unit(0, 3, "a", 100.0, 60.0, "b", "c", (1.0, 2.0), (3.0, 4.0))
    v = Unit(0, 4, "d", 110.0, 50.0, "a", "e", (0.0, 0.0), (0.0, 0.0))
    x = Unit(2, 0, "d", 110.0, 50.0, "a", "e", (0.0, 0.0), (0.0, 0.0))
    assert target_cost(Target("a", 90.0, 70.0, "b", "x"), u) == 10.0 + 10.0 + 1.0
    assert target_cost(Target("z", 100.0, 60.0), u) == float("inf")
    assert join_cost(u, v) == 0.0
    assert join_cost(u, x) == 9.0 + 16.0 + 10.0


def test_errors_and_empty():
    units = [Unit(0, 0, "a", 100.0, 60.0)]
    assert select_units([], units) == ([], 0.0)
    with pytest.raises(ValueError):
        select_units([Target("b", 100.0, 60.0)], units)
    with pytest.raises(ValueError):
        select_units([Target("a", 100.0, 60.0)], units, beam=0)

History

Concatenative synthesis began with diphone systems in the 1970s and 1980s, which stored one recorded example of each diphone and changed its pitch and duration by signal processing. Andrew Hunt and Alan Black, also at ATR and working on the CHATR system, published the unit selection formulation in 1996: target costs and concatenation costs as weighted sums of sub-costs, and the best units by a Viterbi search, with the weights tuned on held-out speech. The Festival system and many commercial voices adopted it, and through the 2000s it gave the most natural synthetic speech in many evaluations. Statistical parametric synthesis offered more flexibility from the late 1990s, and neural models such as WaveNet in 2016 and Tacotron 2 in 2018 overtook unit selection in listening tests.

References

  1. Andrew J. Hunt and Alan W. Black, Unit selection in a concatenative speech synthesis system using a large speech database, ICASSP 1996, volume 1, pages 373 to 376, the target and concatenation costs, the Viterbi search over the units, and the tuning of the weights
  2. Paul Taylor, Text-to-Speech Synthesis, Cambridge University Press, 2009, the chapter Unit selection synthesis
  3. Heiga Zen, Keiichi Tokuda and Alan W. Black, Statistical parametric speech synthesis, Speech Communication 51(11), 2009, pages 1039 to 1064, the comparison of unit selection with statistical parametric synthesis
  4. van den Oord et al. 2016, the subjective listening tests with the concatenative and parametric baselines

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example