> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to implement a softmax function as a SQL user-defined function

> ClickHouse has no built-in softmax function. Learn how to build a numerically stable softmax for arrays from array functions and wrap it in a SQL user-defined function.

Softmax converts a vector of numbers into a probability distribution: every element of the result is between 0 and 1, and the elements add up to 1. ClickHouse has no built-in `softmax` function, but you can build one from array functions and wrap it in a [SQL user-defined function](https://clickhouse.com/docs/reference/statements/create/function.md):

```sql theme={null}
CREATE FUNCTION softmax AS (x) ->
    arrayMap(v -> exp(toFloat64(v) - toFloat64(arrayMax(x))), x)
    / arraySum(arrayMap(v -> exp(toFloat64(v) - toFloat64(arrayMax(x))), x));
```

```sql theme={null}
SELECT
    arrayMap(p -> round(p, 4), softmax([3., 1., 0.2])) AS probabilities,
    round(arraySum(softmax([3., 1., 0.2])), 4) AS total;
```

```text theme={null}
   ┌─probabilities─────────┬─total─┐
1. │ [0.836,0.1131,0.0508] │     1 │
   └───────────────────────┴───────┘
```

The examples round the results to four digits to keep the output short. Without rounding, the last digits of the `Float64` values can differ between ClickHouse versions.

## How it works

The softmax of the element `x[i]` is `exp(x[i])` divided by the sum of `exp(x[j])` over all elements. The function does it in three steps:

1. [`arrayMax(x)`](https://clickhouse.com/docs/reference/functions/regular-functions/array-functions#arrayMax) finds the largest element.
2. [`arrayMap`](https://clickhouse.com/docs/reference/functions/regular-functions/array-functions#arrayMap) calculates `exp(toFloat64(v) - toFloat64(arrayMax(x)))` for every element `v`.
3. The resulting array is divided by its sum, which [`arraySum`](https://clickhouse.com/docs/reference/functions/regular-functions/array-functions#arraySum) returns. Dividing an array by a number divides every element.

Subtracting the maximum does not change the result, because the same factor appears in the numerator and in the denominator. It keeps the function numerically stable: the largest argument of `exp` is 0, so `exp` cannot overflow. Without it, large inputs produce `inf` and then `nan`:

```sql theme={null}
SELECT
    arrayMap(v -> exp(v), [1000., 1001., 1002.]) AS e,
    e / arraySum(e) AS naive,
    arrayMap(p -> round(p, 4), softmax([1000., 1001., 1002.])) AS stable;
```

```text theme={null}
   ┌─e─────────────┬─naive─────────┬─stable───────────────┐
1. │ [inf,inf,inf] │ [nan,nan,nan] │ [0.09,0.2447,0.6652] │
   └───────────────┴───────────────┴──────────────────────┘
```

The function accepts an array of any numeric type and returns `Array(Float64)`. The array must not contain `NULL` elements.

`toFloat64` converts both values before the subtraction, so that the difference is calculated in floating point for integer arrays as well. Without the conversion, the difference of two 64-bit integers is calculated in `Int64` and wraps around when the elements are far apart: `toUInt64(0) - toUInt64('18446744073709551615')` returns `1`, and the smaller element would get the larger probability. The price of the conversion is that integers with an absolute value above 2^53 are rounded to the nearest `Float64`, so two such elements that differ by 1 can get the same probability.

## Two-dimensional arrays

A SQL user-defined function can call another one, so softmax over each row of a two-dimensional array is one more `arrayMap`. To normalize along the columns instead, transpose the array before and after with [`arrayTranspose`](https://clickhouse.com/docs/reference/functions/regular-functions/array-functions#arrayTranspose) (available from ClickHouse 26.4):

```sql theme={null}
CREATE FUNCTION softmaxRows AS (m) -> arrayMap(row -> softmax(row), m);

CREATE FUNCTION softmaxColumns AS (m) -> arrayTranspose(softmaxRows(arrayTranspose(m)));
```

```sql theme={null}
WITH [[1, 2, 3], [1, 1, 1]] AS m
SELECT
    arrayMap(row -> arrayMap(p -> round(p, 4), row), softmaxRows(m)) AS by_rows,
    arrayMap(row -> arrayMap(p -> round(p, 4), row), softmaxColumns(m)) AS by_columns;
```

```text theme={null}
   ┌─by_rows───────────────────────────────────────┬─by_columns────────────────────────────────┐
1. │ [[0.09,0.2447,0.6652],[0.3333,0.3333,0.3333]] │ [[0.5,0.7311,0.8808],[0.5,0.2689,0.1192]] │
   └───────────────────────────────────────────────┴───────────────────────────────────────────┘
```

In `by_rows`, every inner array adds up to 1. In `by_columns`, the elements at the same position of the inner arrays add up to 1.

## Use it on a table

```sql theme={null}
CREATE TABLE predictions
(
    id UInt32,
    logits Array(Float32)
)
ENGINE = MergeTree
ORDER BY id;

INSERT INTO predictions VALUES
    (1, [2.0, 1.0, 0.1]),
    (2, [0.5, 0.5, 0.5]),
    (3, [-1.0, 0.0, 4.0]);

SELECT
    id,
    arrayMap(p -> round(p, 4), softmax(logits)) AS probabilities,
    indexOf(logits, arrayMax(logits)) AS predicted_class
FROM predictions
ORDER BY id;
```

```text theme={null}
   ┌─id─┬─probabilities──────────┬─predicted_class─┐
1. │  1 │ [0.659,0.2424,0.0986]  │               1 │
2. │  2 │ [0.3333,0.3333,0.3333] │               1 │
3. │  3 │ [0.0066,0.0179,0.9756] │               3 │
   └────┴────────────────────────┴─────────────────┘
```

## Manage the functions

SQL user-defined functions are stored on the server and stay available after a restart. List them with their definitions in `system.functions`:

```sql theme={null}
SELECT name, create_query
FROM system.functions
WHERE origin = 'SQLUserDefined'
ORDER BY name;
```

```text theme={null}
   ┌─name───────────┬─create_query────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
1. │ softmax        │ CREATE FUNCTION softmax AS x -> (arrayMap(v -> exp(toFloat64(v) - toFloat64(arrayMax(x))), x) / arraySum(arrayMap(v -> exp(toFloat64(v) - toFloat64(arrayMax(x))), x))) │
2. │ softmaxColumns │ CREATE FUNCTION softmaxColumns AS m -> arrayTranspose(softmaxRows(arrayTranspose(m)))                                                                                   │
3. │ softmaxRows    │ CREATE FUNCTION softmaxRows AS m -> arrayMap(row -> softmax(row), m)                                                                                                    │
   └────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```

Use `CREATE OR REPLACE FUNCTION` to change a definition and [`DROP FUNCTION`](https://clickhouse.com/docs/reference/statements/drop#drop-function) to remove it:

```sql theme={null}
DROP FUNCTION softmaxColumns;
DROP FUNCTION softmaxRows;
DROP FUNCTION softmax;
```
