Algorithm Search⌘K

Algorithmadvanced

Hard debiasing of word embeddings

Also called Bolukbasi debiasing, neutralize and equalize.

Find a bias direction by PCA of differences such as he - she, remove it from neutral words, and equalize pairs of gendered words about it.

Time
O(s d^2 + q k d^2 + n k d) worst
Space
O(d^2) extra
Where
d = the dimension of the vectors; k = the dimension of the bias subspace; n = the number of words that are neutralized or equalized; q = the number of power iteration steps; s = the number of words in the defining sets
Properties
deterministicnot exactofflineiterativenot supervised
Origin
Tolga Bolukbasi, Kai Wei Chang, James Zou, Venkatesh Saligrama, Adam Kalai, 2016

Hard debiasing removes one kind of bias, such as gender, from a set of word vectors by geometry. It finds a bias subspace, usually one direction, from defining sets of words such as {she, he} and {woman, man}, as the top principal component of their differences. Then it removes the component in that subspace from words that should be neutral, such as "nurse" or "doctor" (neutralize), and it moves the words of each equality set, such as {grandmother, grandfather}, so that they differ only in that subspace and are equally far from every neutral word (equalize). The geometric effect is exact; whether bias is gone is a measurement, and Gonen and Goldberg 2019 measured that it stays largely recoverable.

In plain words

In vectors trained on news text, "nurse" lies closer to "she" than to "he", and "engineer" the other way around. The method first finds the direction in which "she" and "he", "woman" and "man", "mother" and "father" differ. That direction stands for gender. For every word that should have no gender, it cuts away the part of the vector that points along that direction, so "nurse" now sits exactly between "she" and "he". For pairs that really are about gender, like "grandmother" and "grandfather", it keeps the gender part but makes the rest the same, so that a neutral word such as "babysitter" is equally close to both. The method fixes what one direction shows. Bias that hides in other directions stays.

The problem

The input is a set of word vectors, the defining sets D1,…,DnD_1, \ldots, D_n (small sets of words whose difference is the bias, usually pairs), the dimension kk of the bias subspace, a list NN of neutral words, and the equality sets E1,…,EmE_1, \ldots, E_m (words that should differ only in the bias subspace). The output is a new set of vectors in which every neutral word has no component in the bias subspace, and every neutral word is equidistant from the words of each equality set.

With μi\mu_i the mean of DiD_i, the within-set covariance is

C=∑i=1n∑w∈Di(w−μi)(w−μi)T∣Di∣,C = \sum_{i=1}^{n} \sum_{w \in D_i} \frac{(w - \mu_i)(w - \mu_i)^T}{|D_i|},

and the bias subspace BB is spanned by its top kk eigenvectors, the first kk right singular vectors of the stacked centered vectors. For a pair {a,b}\{a, b\} the term is 14(a−b)(a−b)T\frac{1}{4}(a - b)(a - b)^T, so with pairs and k=1k = 1 the bias direction is the top principal component, without centering, of the pair differences such as she−heshe - he. The paper measures the direct bias of a list NN of neutral words along a direction gg as DirectBiasc=1∣N∣∑w∈N∣cos⁡(w,g)∣c\mathrm{DirectBias}_c = \frac{1}{|N|}\sum_{w \in N} |\cos(w, g)|^c.

The algorithm

  1. HARD-DEBIAS(W, D_1 .. D_n, N, E_1 .. E_m, k)
  2. 1w ← w / ‖w‖ for every word vector w
  3. 2μ_i ← the mean of the vectors of D_i
  4. 3C ← Σ_i Σ_{w ∈ D_i} (w - μ_i)(w - μ_i)^T / |D_i|
  5. 4B ← the top k eigenvectors of C ▷ power iteration with deflation
  6. 5for each w in N do w ← (w - w_B) / ‖w - w_B‖ ▷ neutralize
  7. 6for each equality set E do μ ← the mean of E; ν ← μ - μ_B
  8. 7for each w in E do w ← ν + sqrt(1 - ‖ν‖²) (w_B - μ_B) / ‖w_B - μ_B‖ ▷ equalize
  9. 8return W, B

Here vBv_B is the projection of vv on BB: vB=∑r(v⋅br) brv_B = \sum_r (v \cdot b_r)\, b_r for the orthonormal basis b1,…,bkb_1, \ldots, b_k. Line L4 needs only the top eigenvectors of a symmetric d×dd \times d matrix, so power iteration is enough; a full singular value decomposition gives the same subspace. Line L5 gives each neutral word length 1 again, so cosine and dot product agree. In line L7 the part ν\nu outside BB is the same for all words of the set, and the parts inside BB have the same length.

Example

The vectors are written for this page, in three dimensions, with the bias along the first axis. The defining pairs are she (0.6,0.8,0)(0.6, 0.8, 0) with he (−0.6,0.8,0)(-0.6, 0.8, 0), and woman (0.8,0,0.6)(0.8, 0, 0.6) with man (−0.8,0,0.6)(-0.8, 0, 0.6). The differences are (1.2,0,0)(1.2, 0, 0) and (1.6,0,0)(1.6, 0, 0), so C=14(1.44+2.56) e1e1T=e1e1TC = \frac{1}{4}(1.44 + 2.56)\, e_1 e_1^T = e_1 e_1^T, and BB is spanned by g=(1,0,0)g = (1, 0, 0), with eigenvalue 1.

word before after
nurse (neutral) (0.28, 0.96, 0) (0, 1, 0)
doctor (neutral) (-0.36, 0.48, 0.8) (0, 0.5145, 0.8575)
grandmother (equality set) (0.48, 0.6, 0.64) (0.5495, 0.62, 0.56)
grandfather (equality set) (-0.6, 0.64, 0.48) (-0.5495, 0.62, 0.56)

For the equality set, μ=(−0.06,0.62,0.56)\mu = (-0.06, 0.62, 0.56) and ν=(0,0.62,0.56)\nu = (0, 0.62, 0.56), with 1−∥ν∥2=0.302=0.5495\sqrt{1 - \|\nu\|^2} = \sqrt{0.302} = 0.5495. Before debiasing, nurse has the cosine 0.7104 with grandmother and 0.4464 with grandfather. After, both cosines are 0.62=nurse⋅ν0.62 = \text{nurse} \cdot \nu. The direct bias of {nurse, doctor} along gg with c=1c = 1 falls from (0.28+0.36)/2=0.32(0.28 + 0.36)/2 = 0.32 to 0.

Correctness

The proof below shows the geometric guarantees, which are theorems. After line L5 each neutral word has length 1 and a zero projection on BB, because w−wBw - w_B is orthogonal to BB. After line L7 each word of an equality set has length 1, all of them share the component ν\nu outside BB, and every vector orthogonal to BB has the same dot product n⋅νn \cdot \nu with all of them, so it is equally far from each. For a pair, the two components inside BB are opposite. The square root is real because ∥ν∥≤∥μ∥≤1\|\nu\| \le \|\mu\| \le 1 for a mean of unit vectors. Line L4 finds the subspace that captures the largest share of the within-set variance, by the same trace argument as principal component analysis.

These are statements about one subspace. That the method removes bias in a wider sense is not a theorem. Bolukbasi et al. measured that the direct bias falls and that crowd workers judge fewer of the generated analogies as stereotypes. Gonen and Goldberg 2019 measured the opposite side: on the debiased word2vec vectors, k-means with two clusters on the 500 most male-biased and the 500 most female-biased words (by their projection on the original gender direction) still matched the original gender label with 92.5% accuracy, against 99.9% before debiasing. The correlation between the original bias of a word and the share of male-biased words among its neighbors stayed at 0.686, against 0.741 before. The WEAT gender tests still gave p-values below 0.05.

Proof: Neutralize removes the bias component and equalize makes every neutral word equidistantfull

We use the pseudocode of the page. All vectors are in Rd\mathbb{R}^d. After line L1 every word vector has length 1. The rows b1,…,bkb_1, \ldots, b_k of BB are orthonormal, and vB=∑r(v⋅br)brv_B = \sum_r (v \cdot b_r) b_r is the orthogonal projection of vv on the span of BB, which we also call BB.

Lemma 1 (projection). For every vv, v−vBv - v_B is orthogonal to every brb_r, and ∥v∥2=∥vB∥2+∥v−vB∥2\|v\|^2 = \|v_B\|^2 + \|v - v_B\|^2.

Proof. (v−vB)⋅bs=v⋅bs−∑r(v⋅br)(br⋅bs)=v⋅bs−v⋅bs=0(v - v_B) \cdot b_s = v \cdot b_s - \sum_r (v \cdot b_r)(b_r \cdot b_s) = v \cdot b_s - v \cdot b_s = 0, by orthonormality. Since vBv_B is a combination of the brb_r, it is orthogonal to v−vBv - v_B, and the Pythagorean theorem gives the second statement. □\square

Lemma 2 (the covariance of pairs). For a defining set {a,b}\{a, b\} of two words, the contribution of line L3 is 14(a−b)(a−b)T\frac{1}{4}(a - b)(a - b)^T. So with pairs only, CC is 14\frac{1}{4} times the sum of the outer products of the differences, and its top eigenvector is the first principal component, without centering, of the differences a−ba - b.

Proof. μ=(a+b)/2\mu = (a + b)/2, so a−μ=(a−b)/2a - \mu = (a - b)/2 and b−μ=−(a−b)/2b - \mu = -(a - b)/2. Each gives the outer product 14(a−b)(a−b)T\frac{1}{4}(a - b)(a - b)^T, and line L3 adds both and divides by ∣D∣=2|D| = 2. □\square

Lemma 3 (the subspace). The span of the top kk eigenvectors of CC maximizes ∑D∑w∈D∥(w−μD)B∥2/∣D∣=tr⁡(PC)\sum_D \sum_{w \in D} \|(w - \mu_D)_B\|^2 / |D| = \operatorname{tr}(P C) over the kk-dimensional subspaces with orthogonal projection PP. This is the theorem of Ky Fan on the trace of a symmetric matrix, the basis of principal component analysis. When the kk-th and the (k+1)(k+1)-th eigenvalues differ, power iteration with deflation from a start vector that is not orthogonal to the eigenvectors converges to this basis (see power iteration). The tests check Cu=λuC u = \lambda u and that no random unit vector has a larger Rayleigh quotient than the first eigenvalue. □\square

Theorem 1 (neutralize). If ww is not in BB, line L5 returns a unit vector w′w' with w′⋅br=0w' \cdot b_r = 0 for every rr. So the direct bias ∣cos⁡(w′,g)∣|\cos(w', g)| is 0 for every gg in BB.

Proof. By Lemma 1, w−wBw - w_B is orthogonal to BB, and it is not 0 because ww is not in BB. Dividing by its length keeps the orthogonality and gives length 1. □\square

Theorem 2 (equalize). Let EE be a set of unit vectors with mean μ\mu, and let ν=μ−μB\nu = \mu - \mu_B. Suppose wB≠μBw_B \ne \mu_B for every w∈Ew \in E. Line L7 maps each w∈Ew \in E to

ew=ν+1−∥ν∥2 uw,uw=wB−μB∥wB−μB∥.e_w = \nu + \sqrt{1 - \|\nu\|^2}\, u_w, \qquad u_w = \frac{w_B - \mu_B}{\|w_B - \mu_B\|}.

Then (a) the square root is real, (b) every ewe_w has length 1, (c) every ewe_w has the same component ν\nu outside BB, and (d) for every vector nn orthogonal to BB, such as a neutralized word, n⋅ew=n⋅νn \cdot e_w = n \cdot \nu and ∥n−ew∥\|n - e_w\| is the same for all w∈Ew \in E. (e) For a pair E={a,b}E = \{a, b\}, (ea)B=−(eb)B(e_a)_B = -(e_b)_B.

Proof. (a) ∥μ∥≤1\|\mu\| \le 1, because μ\mu is a mean of unit vectors and the norm is convex. By Lemma 1, ∥ν∥≤∥μ∥≤1\|\nu\| \le \|\mu\| \le 1. (b) uwu_w lies in BB and ν\nu is orthogonal to BB by Lemma 1, so ∥ew∥2=∥ν∥2+(1−∥ν∥2)∥uw∥2=1\|e_w\|^2 = \|\nu\|^2 + (1 - \|\nu\|^2)\|u_w\|^2 = 1. (c) The part of ewe_w outside BB is ν\nu, since uwu_w is in BB. (d) n⋅uw=0n \cdot u_w = 0, so n⋅ew=n⋅νn \cdot e_w = n \cdot \nu. Then ∥n−ew∥2=∥n∥2−2n⋅ν+1\|n - e_w\|^2 = \|n\|^2 - 2 n \cdot \nu + 1, which does not depend on ww. (e) aB−μB=(aB−bB)/2=−(bB−μB)a_B - \mu_B = (a_B - b_B)/2 = -(b_B - \mu_B), so ua=−ubu_a = -u_b, and the BB components 1−∥ν∥2 ua\sqrt{1 - \|\nu\|^2}\, u_a and 1−∥ν∥2 ub\sqrt{1 - \|\nu\|^2}\, u_b are opposite. □\square

Corollary. After lines L5 to L7, every neutral word is at the same distance from all the words of each equality set, and its projection on the bias subspace is 0. Line L7 runs after line L5, and it changes only the words of the equality sets, so the neutral words keep the property of Theorem 1. A word that is both neutral and in an equality set is not allowed, since the two steps would contradict each other. ■\blacksquare

The theorems are about the geometry that the method enforces. They say nothing about other directions that still separate the words; that the bias stays recoverable from them is a measurement (Gonen and Goldberg 2019), and the test of the code reproduces it on a toy example.

Complexity

The model is the real-RAM.

  • Covariance. Line L3 adds ss outer products: O(sd2)O(s d^2) time and O(d2)O(d^2) space.
  • Subspace. Each power iteration step multiplies CC by a vector, O(d2)O(d^2), so kk vectors with qq steps each cost O(qkd2)O(q k d^2). A full eigendecomposition costs O(d3)O(d^3).
  • Neutralize and equalize. Each projection costs O(kd)O(k d), so nn words cost O(nkd)O(n k d). On ∣V∣|V| words with d=300d = 300, this pass is linear in the vocabulary.

Properties

  • Linear and local. Only the neutral words and the equality sets change. All other words keep their vectors.
  • Unit length. Every changed vector has length 1, so the method assumes cosine similarity.
  • Depends on lists. The defining sets, the neutral words and the equality sets are inputs. The paper takes the definitional pairs from a list of ten (she and he, her and his, woman and man, Mary and John, herself and himself, daughter and son, mother and father, gal and guy, girl and boy, female and male), and it finds the gender-specific words with a classifier trained on a seed list. Every word not judged gender-specific is treated as neutral.
  • Irreversible. The component along BB of a neutral word is lost. A use that needs it, such as gender agreement, breaks for those words.

Variants and improvements

  • Soft debiasing. The same paper proposes a linear map that reduces the bias component of neutral words while keeping the inner products of the other words close to the originals, with a parameter that trades the two goals.
  • Several directions. With k>1k > 1, or with defining sets of more than two words, BB captures bias that one pair difference misses. The algorithm is the same.
  • Training-time methods. GN-GloVe (Zhao et al. 2018) trains GloVe vectors that keep gender in a few reserved coordinates. Gonen and Goldberg 2019 measured that it too leaves the bias recoverable.
  • Projection with a classifier. Iterative nullspace projection (Ravfogel et al. 2020) trains a linear classifier for the protected attribute, projects on its null space, and repeats until no linear classifier works. It targets the bias that Gonen and Goldberg found.

When to use it

Use hard debiasing when a downstream use depends mainly on the projection of words on a known direction, for example analogies of the form "man is to X as woman is to Y" (see word analogy), and when a measurement on that use shows that the projection matters. Do not use it as evidence that an embedding is fair. Measure bias after debiasing with several tests, such as the WEAT, clustering and neighbor tests, and with tests on the downstream task.

Pitfalls

  • Bias outside the subspace. The neighbors of a neutral word stay mostly the same, and they still carry gender. Gonen and Goldberg 2019 recovered gender from the debiased vectors with clustering and with a classifier. Report these measurements next to the direct bias.
  • Uncentered and centered PCA. For pairs, line L3 gives the uncentered principal component of the differences. Centering the differences before PCA gives a different direction, and for pairs that point the same way it can remove the signal itself.
  • A neutral word in an equality set. Neutralize and equalize contradict each other for such a word. Keep the lists disjoint.
  • Missing normalization. Line L1 makes every vector unit length. Without it the square root in line L7 can be imaginary and the equidistance fails.
  • Wrong word lists. Treating a gender-specific word, such as "beard" or "pregnant", as neutral removes real meaning. The lists need care for each language and for each kind of bias.

Implementations

The code takes the word vectors as given and implements the within-set covariance, the bias subspace by power iteration with deflation, neutralize, equalize and the direct bias.

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.

hard_debiasing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hard-debiasing/. The authors are listed in prov/92204H.jsonl.
"""Hard debiasing of word vectors (Bolukbasi, Chang, Zou, Saligrama and Kalai 2016).

The word vectors are given as a dict from a word to a list of floats; the
code does not train them. The bias subspace B is spanned by the top k
eigenvectors of the within-set covariance of the defining sets (for gender,
pairs such as she and he). Neutralize removes the B component of each neutral
word and normalizes it. Equalize moves each word of an equality set to the
same point outside B, with opposite B components of the same length, so that
every neutral word is equally far from all words of the set.
"""

import math
import random
from typing import Dict, List, Sequence, Tuple

Vector = List[float]
Matrix = List[List[float]]


def dot(a: Sequence[float], b: Sequence[float]) -> float:
    return math.fsum(x * y for x, y in zip(a, b))


def norm(a: Sequence[float]) -> float:
    return math.sqrt(dot(a, a))


def normalize(a: Sequence[float]) -> Vector:
    n = norm(a)
    if n == 0:
        raise ValueError("cannot normalize a zero vector")
    return [x / n for x in a]


def mean(vectors: Sequence[Sequence[float]]) -> Vector:
    return [math.fsum(col) / len(vectors) for col in zip(*vectors)]


def within_set_covariance(defining_sets: Sequence[Sequence[Sequence[float]]]) -> Matrix:
    """C = sum over the sets D of sum over w in D of (w - mu_D)(w - mu_D)^T / |D|."""
    d = len(defining_sets[0][0])
    C = [[0.0] * d for _ in range(d)]
    for D in defining_sets:
        mu = mean(D)
        for w in D:
            r = [x - m for x, m in zip(w, mu)]
            for a in range(d):
                for b in range(d):
                    C[a][b] += r[a] * r[b] / len(D)
    return C


def top_eigenvectors(C: Matrix, k: int, seed: int = 0, tol: float = 1e-13, max_iter: int = 20000) -> Tuple[List[Vector], List[float]]:
    """The top k eigenvectors and eigenvalues of a symmetric positive semidefinite C.

    Power iteration with deflation. Each vector is made unique by giving its
    largest entry a positive sign. Convergence needs a gap between the
    eigenvalues, as for any power iteration.
    """
    d = len(C)
    rng = random.Random(seed)
    M = [row[:] for row in C]
    vecs: List[Vector] = []
    vals: List[float] = []
    for _ in range(k):
        x = normalize([rng.gauss(0.0, 1.0) for _ in range(d)])
        for _ in range(max_iter):
            y = [dot(row, x) for row in M]
            for v in vecs:
                c = dot(v, y)
                y = [a - c * b for a, b in zip(y, v)]
            if norm(y) == 0:
                break
            y = normalize(y)
            done = max(abs(a - b) for a, b in zip(x, y)) < tol
            x = y
            if done:
                break
        big = max(range(d), key=lambda i: abs(x[i]))
        if x[big] < 0:
            x = [-a for a in x]
        lam = dot(x, [dot(row, x) for row in M])
        vecs.append(x)
        vals.append(lam)
        M = [[M[a][b] - lam * x[a] * x[b] for b in range(d)] for a in range(d)]
    return vecs, vals


def bias_subspace(defining_sets: Sequence[Sequence[Sequence[float]]], k: int = 1, seed: int = 0) -> List[Vector]:
    """An orthonormal basis of the bias subspace B: the top k eigenvectors of C."""
    return top_eigenvectors(within_set_covariance(defining_sets), k, seed)[0]


def project(w: Sequence[float], B: Sequence[Sequence[float]]) -> Vector:
    """w_B, the projection of w on the span of the orthonormal rows of B."""
    out = [0.0] * len(w)
    for b in B:
        c = dot(w, b)
        out = [o + c * x for o, x in zip(out, b)]
    return out


def neutralize(w: Sequence[float], B: Sequence[Sequence[float]]) -> Vector:
    """(w - w_B) / |w - w_B|."""
    wb = project(w, B)
    return normalize([x - y for x, y in zip(w, wb)])


def equalize(E: Sequence[Sequence[float]], B: Sequence[Sequence[float]]) -> List[Vector]:
    """Move each word of the equality set E to nu + sqrt(1 - |nu|^2) (w_B - mu_B) / |w_B - mu_B|.

    mu is the mean of E and nu = mu - mu_B. The words of E should be unit vectors.
    """
    mu = mean(E)
    mu_b = project(mu, B)
    nu = [x - y for x, y in zip(mu, mu_b)]
    scale = math.sqrt(max(0.0, 1.0 - dot(nu, nu)))
    out = []
    for w in E:
        diff = [x - y for x, y in zip(project(w, B), mu_b)]
        if norm(diff) == 0:
            raise ValueError("a word of the equality set has the same bias component as the mean")
        out.append([n + scale * x for n, x in zip(nu, normalize(diff))])
    return out


def hard_debias(
    vectors: Dict[str, Sequence[float]],
    defining_sets: Sequence[Sequence[str]],
    neutral_words: Sequence[str],
    equality_sets: Sequence[Sequence[str]],
    k: int = 1,
    seed: int = 0,
) -> Tuple[Dict[str, Vector], List[Vector]]:
    """Return (the debiased vectors, the basis of B). The input dict is not changed."""
    W = {w: normalize(v) for w, v in vectors.items()}  # @line L1
    D = [[W[w] for w in S] for S in defining_sets]  # @line L2
    C = within_set_covariance(D)  # @line L3
    B = top_eigenvectors(C, k, seed)[0]  # @line L4
    for w in neutral_words:
        W[w] = neutralize(W[w], B)  # @line L5
    for S in equality_sets:
        E = [W[w] for w in S]  # @line L6
        for w, v in zip(S, equalize(E, B)):
            W[w] = v  # @line L7
    return W, B  # @line L8


def direct_bias(words: Sequence[Sequence[float]], g: Sequence[float], c: float = 1.0) -> float:
    """DirectBias_c = the mean over the words of |cos(w, g)|^c."""
    ng = norm(g)
    return math.fsum(abs(dot(w, g) / (norm(w) * ng)) ** c for w in words) / len(words)
test_hard_debiasing.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hard-debiasing/. The authors are listed in prov/92204H.jsonl.

import math
import random

import pytest

from hard_debiasing import (
    bias_subspace,
    direct_bias,
    dot,
    equalize,
    hard_debias,
    neutralize,
    norm,
    normalize,
    project,
    top_eigenvectors,
    within_set_covariance,
)

PAGE = {
    "she": [0.6, 0.8, 0.0],
    "he": [-0.6, 0.8, 0.0],
    "woman": [0.8, 0.0, 0.6],
    "man": [-0.8, 0.0, 0.6],
    "nurse": [0.28, 0.96, 0.0],
    "doctor": [-0.36, 0.48, 0.8],
    "grandmother": [0.48, 0.6, 0.64],
    "grandfather": [-0.6, 0.64, 0.48],
}


def rand_vec(rng, d):
    return [rng.gauss(0.0, 1.0) for _ in range(d)]


def close(a, b, tol=1e-9):
    return all(abs(x - y) <= tol for x, y in zip(a, b))


def test_page_example():
    W, B = hard_debias(PAGE, [["she", "he"], ["woman", "man"]], ["nurse", "doctor"], [["grandmother", "grandfather"]])
    assert close(B[0], [1.0, 0.0, 0.0])
    assert close(W["nurse"], [0.0, 1.0, 0.0])
    assert close(W["doctor"], [0.0, 0.48 / math.sqrt(0.8704), 0.8 / math.sqrt(0.8704)])
    s = math.sqrt(1 - 0.62**2 - 0.56**2)
    assert close(W["grandmother"], [s, 0.62, 0.56])
    assert close(W["grandfather"], [-s, 0.62, 0.56])
    assert dot(PAGE["nurse"], PAGE["grandmother"]) == pytest.approx(0.7104)
    assert dot(PAGE["nurse"], PAGE["grandfather"]) == pytest.approx(0.4464)
    assert dot(W["nurse"], W["grandmother"]) == pytest.approx(0.62)
    assert dot(W["nurse"], W["grandfather"]) == pytest.approx(0.62)
    assert direct_bias([PAGE["nurse"], PAGE["doctor"]], B[0]) == pytest.approx(0.32)
    assert direct_bias([W["nurse"], W["doctor"]], B[0]) == pytest.approx(0.0, abs=1e-12)


def test_pair_covariance_is_a_quarter_of_the_difference_outer_products():
    rng = random.Random(1)
    pairs = [[rand_vec(rng, 4), rand_vec(rng, 4)] for _ in range(5)]
    C = within_set_covariance(pairs)
    for a in range(4):
        for b in range(4):
            expected = math.fsum((p[0][a] - p[1][a]) * (p[0][b] - p[1][b]) for p in pairs) / 4
            assert C[a][b] == pytest.approx(expected, abs=1e-12)


def test_eigenvectors_satisfy_the_eigen_equation_and_maximize_the_rayleigh_quotient():
    rng = random.Random(2)
    sets = [[rand_vec(rng, 5) for _ in range(rng.randint(2, 4))] for _ in range(6)]
    C = within_set_covariance(sets)
    vecs, vals = top_eigenvectors(C, 3)
    assert vals[0] >= vals[1] >= vals[2] >= 0
    for v, lam in zip(vecs, vals):
        Cv = [dot(row, v) for row in C]
        assert close(Cv, [lam * x for x in v], 1e-8)
        assert norm(v) == pytest.approx(1.0)
    for i in range(3):
        for j in range(i + 1, 3):
            assert dot(vecs[i], vecs[j]) == pytest.approx(0.0, abs=1e-8)
    for _ in range(100):
        r = normalize(rand_vec(rng, 5))
        assert dot(r, [dot(row, r) for row in C]) <= vals[0] + 1e-9


def test_planted_direction_is_recovered():
    rng = random.Random(3)
    g = normalize([1.0, 2.0, -1.0, 0.5, 0.0, 1.0])
    pairs = []
    for _ in range(10):
        base = rand_vec(rng, 6)
        noise = [0.05 * x for x in rand_vec(rng, 6)]
        pairs.append([[b + x + gi for b, x, gi in zip(base, noise, g)], [b - gi for b, gi in zip(base, g)]])
    B = bias_subspace(pairs, 1)
    assert abs(dot(B[0], g)) > 0.99


def test_neutralize_gives_unit_vectors_with_no_bias_component():
    rng = random.Random(4)
    sets = [[rand_vec(rng, 5), rand_vec(rng, 5)] for _ in range(4)]
    for k in (1, 2):
        B = bias_subspace(sets, k)
        for _ in range(20):
            w = neutralize(rand_vec(rng, 5), B)
            assert norm(w) == pytest.approx(1.0)
            assert all(abs(dot(w, b)) < 1e-12 for b in B)
            assert direct_bias([w], B[0]) == pytest.approx(0.0, abs=1e-12)


def test_equalize_makes_every_neutral_word_equidistant():
    rng = random.Random(5)
    sets = [[normalize(rand_vec(rng, 6)), normalize(rand_vec(rng, 6))] for _ in range(4)]
    for k in (1, 2):
        B = bias_subspace(sets, k)
        for size in (2, 3):
            E = [normalize(rand_vec(rng, 6)) for _ in range(size)]
            out = equalize(E, B)
            for e in out:
                assert norm(e) == pytest.approx(1.0)
            for _ in range(10):
                w = neutralize(rand_vec(rng, 6), B)
                dots = [dot(w, e) for e in out]
                assert max(dots) - min(dots) < 1e-12
                dists = [norm([x - y for x, y in zip(w, e)]) for e in out]
                assert max(dists) - min(dists) < 1e-12
        out = equalize(sets[0], B)
        # For a pair the two bias components are opposite.
        assert close(project(out[0], B), [-x for x in project(out[1], B)], 1e-12)


def test_equalize_rejects_a_degenerate_set():
    B = [[1.0, 0.0, 0.0]]
    with pytest.raises(ValueError):
        equalize([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], B)


def test_bias_stays_recoverable_after_debiasing():
    # The Gonen and Goldberg effect on a toy: the words also differ along h, a
    # direction that the defining pairs do not show, so neutralize leaves it.
    rng = random.Random(6)
    d = 8
    g = [1.0] + [0.0] * (d - 1)
    h = [0.0, 1.0] + [0.0] * (d - 2)
    vectors = {}
    pairs = []
    for i in range(6):
        base = rand_vec(rng, d)
        base[0] = 0.0
        vectors[f"f{i}"] = [b + 2 * gi for b, gi in zip(base, g)]
        vectors[f"m{i}"] = [b - 2 * gi for b, gi in zip(base, g)]
        pairs.append([f"f{i}", f"m{i}"])
    labels = {}
    for i in range(40):
        side = 1 if i % 2 == 0 else -1
        v = [0.4 * x for x in rand_vec(rng, d)]
        v = [x + side * (gi + 1.5 * hi) for x, gi, hi in zip(v, g, h)]
        vectors[f"n{i}"] = v
        labels[f"n{i}"] = side
    neutral = list(labels)
    W, B = hard_debias(vectors, pairs, neutral, [], k=1)
    assert abs(B[0][0]) > 0.99
    assert direct_bias([W[w] for w in neutral], B[0]) < 1e-12
    correct = 0
    for w in neutral:
        others = [u for u in neutral if u != w]
        nearest = max(others, key=lambda u: dot(W[w], W[u]))
        correct += labels[nearest] == labels[w]
    assert correct / len(neutral) >= 0.9


def test_input_is_not_changed():
    copy = {w: list(v) for w, v in PAGE.items()}
    hard_debias(PAGE, [["she", "he"]], ["nurse"], [["grandmother", "grandfather"]])
    assert PAGE == copy

History

Bolukbasi, Chang, Zou, Saligrama and Kalai 2016 showed that word2vec vectors trained on Google News complete analogies such as "man is to computer programmer as woman is to homemaker", found a gender direction from definitional pairs, and proposed hard and soft debiasing. Their experiments used 300-dimensional vectors restricted by a filter on the vocabulary to 26,377 words. Caliskan, Bryson and Narayanan 2017 measured similar biases with the WEAT. Gonen and Goldberg 2019 then measured that the debiased vectors still encode gender in the arrangement of the words, which moved later work toward methods that remove all linearly decodable information and toward bias tests on the downstream tasks.

References

  1. Bolukbasi et al. 2016, the identification of the gender subspace from ten definitional pairs, the direct bias measure, and the hard debiasing algorithm with its neutralize and equalize steps
  2. Hila Gonen and Yoav Goldberg, Lipstick on a pig, debiasing methods cover up systematic gender biases in word embeddings but do not remove them, NAACL-HLT 2019, pages 609 to 614, the clustering, bias-by-neighbors, classification and WEAT experiments on the debiased embeddings
  3. the arXiv version of Bolukbasi et al., the appendix with the full lists of definitional pairs and equality sets

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