Skip to content
BIASED
Back to topic

Optional

Density and volume in a flow

Fit the reviewed synthetic affine flow, compare complete and missing-Jacobian objectives, then check reflection and a new two-coordinate coupling.

Version
v2
Seed
9303
Minutes
~20
Evidence
Self-check in the notebook

Data: 4096 synthetic Gaussian observations generated locally; reviewed FP82b6cb0 arithmetic and new coupling checks with Codex assistance. / 4096 синтетических гауссовых наблюдений генерируются локально; проверенные расчёты FP82b6cb0 и новые проверки слоя связи с помощью Codex.

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

Density and volume / Плотность и объём

The reviewed affine-fit fixture uses seed 9303 and 4,096 newly generated Gaussian observations. Numerical integration covers eight fitted standard deviations each side; it is a finite numerical check. / Проверенный аффинный пример использует seed 9303 и 4,096 новых гауссовых наблюдений. Численное интегрирование охватывает восемь оценённых стандартных отклонений с каждой стороны; это конечная численная проверка.

Source / Источник: published revision 82b6cb0.

Prepared for the Fedor Pakhurov project with Codex assistance. No datasets, models or packages are downloaded. Only Python standard-library modules are used. Main calculations follow the reviewed source; added checks are identified below. No benchmark/generalization claim.

Подготовлено для проекта Фёдора Пахурова с помощью Codex. Данные, модели и пакеты не скачиваются. Используется стандартная библиотека Python. Основные расчёты следуют проверенному источнику; дополнительные проверки отмечены ниже. Это не бенчмарк и не проверка обобщения.

Run cells in order. Saved stdout is from a local execution; hosted/Colab execution has not been claimed. / Выполняйте ячейки по порядку. Сохранённый stdout получен локально; запуск в Colab не заявляется.

Fit with the complete objective / Подгонка с полной целью

The pure functions are unchanged from the pinned FP source. The missing-Jacobian variant is deliberately not a normalized density; compare its integral and objective. Values below are rounded to six decimals. / Функции расчёта совпадают с закреплённым источником FP. Вариант без якобиана намеренно не является нормированной плотностью; сравните интеграл и цель. Значения округлены до шести знаков.

import json
import math
import random
import statistics
 
def normal_log_density(x, mean=0.0, variance=1.0):
    return -0.5 * (math.log(2 * math.pi * variance) + (x - mean) ** 2 / variance)
 
def normalizing_flows():
    rng = random.Random(9303)
    data = [0.45 + 1.6 * rng.gauss(0, 1) for _ in range(4096)]
    mean = statistics.mean(data)
    scale = math.sqrt(statistics.mean((x - mean) ** 2 for x in data))
 
    def nll(s, include_jacobian):
        return -statistics.mean(normal_log_density((x - mean) / s)
                                - (math.log(s) if include_jacobian else 0) for x in data)
 
    fitted, doubled = nll(scale, True), nll(2 * scale, True)
    naive, naive_doubled = nll(scale, False), nll(2 * scale, False)
    assert fitted < doubled and naive_doubled < naive
    # Integrate over the same transformed z range; the wrong density has mass s.
    steps, bound = 16000, 8.0
    dx = 2 * bound * scale / steps
    mass = 0.0
    for i in range(steps + 1):
        x = mean - bound * scale + i * dx
        value = math.exp(normal_log_density((x - mean) / scale))
        mass += (0.5 if i in (0, steps) else 1) * value * dx
    assert abs(mass / scale - 1) < 1e-10
    return {'sample_count': len(data), 'fitted_mean': mean, 'fitted_scale': scale,
            'correct_nll': fitted, 'correct_nll_at_double_scale': doubled,
            'omitted_jacobian_nll': naive, 'omitted_jacobian_nll_at_double_scale': naive_doubled,
            'integrated_correct_mass': mass / scale, 'integrated_wrong_mass': mass}
 
fit = normalizing_flows()
print(json.dumps({k: round(v, 6) if isinstance(v, float) else v
                  for k, v in fit.items()}, indent=2))

Reflection and coupling checks / Проверки отражения и слоя связи

The first case replays the reviewed triangular example. The two-coordinate coupling and test points below are newly specified for this BIASED lab. Predict the inverse before executing. / Первый расчёт повторяет проверенный треугольный пример. Двухкоординатный слой связи и проверочные точки ниже заново заданы для этой лабораторной BIASED. Предскажите обратное до запуска.

# Reflected triangular density from the reviewed source; exact polynomial integral.
def triangular_density(x):
    return (3 - x) / 2 if 1 <= x <= 3 else 0.0
 
primitive = lambda x: 1.5*x - x*x/4
assert primitive(3) - primitive(1) == 1
assert triangular_density(2.5) == 0.25
print('reflected density at 2.5:', triangular_density(2.5))
 
# Newly specified affine coupling, in the lesson's data-to-latent direction.
def encode(x):
    return (x[0], 2*x[1] + x[0])
 
def generate(z):
    return (z[0], (z[1] - z[0]) / 2)
 
for point in [(2.0, -1.0), (-2.0, 3.0), (0.5, -4.0)]:
    latent = encode(point)
    assert generate(latent) == point
    print('data:', point, 'latent:', latent, 'recovered:', generate(latent))
# Encoding Jacobian [[1, 0], [1, 2]]; generating determinant is reciprocal.
assert 1*2 - 0*1 == 2
log_base = normal_log_density(1) + normal_log_density(0)
log_data = log_base + math.log(2)
print('log density at data (1, -0.5):', round(log_data, 6))
print('Self-checks passed. This lab does not train a neural coupling network.')