疎行列による大規模グラフの表現と計算量

実行環境

Python 3.14.6、NumPy 2.4.6、SciPy 1.18.1、NetworkX 3.7、Matplotlib 3.11.2(Jupyter Notebook)。

本記事は2021年頃の記事をリライトし、上記の環境で計算したものである。

書籍:『グラフの理論と実践』
章:グラフの基礎と行列表現

概要

グラフの隣接行列には、辺が存在しない位置にも要素がある。頂点数が多く、各頂点につながる辺が少ない場合、すべての要素を保存すると大部分がゼロになる。本記事では、このゼロを省いて保存する疎行列を扱う。

小さな無向グラフからCOO・CSR・CSCの構造を確認し、必要なメモリ量と行列・ベクトル積の計算量を求める。その後、SciPyで10万頂点のグラフを作成し、実行時間と、行列積によって非ゼロ要素が増える例を確認する。

計算の準備

コードは上から順に実行する。数値は表示時だけ有効数字3桁に整える。

実行環境の確認・ライブラリの読み込み・描画設定
import platform
import sys
from pathlib import Path
from pprint import pprint
from timeit import repeat

import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.colors import ListedColormap
from matplotlib.patches import Rectangle
from matplotlib.ticker import FuncFormatter, MaxNLocator
from matplotlib_inline.backend_inline import set_matplotlib_formats
import networkx as nx
import numpy as np
import scipy
from scipy.sparse import coo_array, csr_array
from IPython.display import Math, SVG, display

%matplotlib inline
set_matplotlib_formats('svg')

# 表示だけを有効数字3桁にそろえ、計算中の値は丸めない。
def sig3(value):
    return format(float(value), '#.3g').removesuffix('.')


np.set_printoptions(formatter={'float_kind': sig3}, linewidth=100)

# 利用可能な日本語フォントを選ぶ。SVGには文字の輪郭を埋め込む。
font_names = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ['Hiragino Sans', 'Noto Sans CJK JP', 'IPAexGothic', 'YuGothic']:
    if candidate in font_names:
        plt.rcParams['font.family'] = candidate
        break

plt.rcParams.update({
    'font.size': 11,
    'axes.spines.top': False,
    'axes.spines.right': False,
    'axes.unicode_minus': False,
    'svg.fonttype': 'path',
    'svg.hashsalt': 'graph-theory-103',
})

# 通常のNotebook起動と、リポジトリ直下からの実行に対応する。
notebook_dir = Path.cwd()
if (notebook_dir / 'pyproject.toml').is_file():
    notebook_dir = notebook_dir / 'series/graph-theory/103'
figure_dir = notebook_dir / '103_nb_files'
figure_dir.mkdir(parents=True, exist_ok=True)


def save_figure(fig, filename):
    path = figure_dir / filename
    fig.savefig(path, format='svg', bbox_inches='tight', metadata={'Date': None})
    plt.close(fig)
    display(SVG(filename=str(path)))


def matrix_tex(values):
    # 本記事の整数行列・整数ベクトルをLaTeXの行列に変換する。
    rows = np.atleast_2d(values)
    body = r' \\\\ '.join(' & '.join(str(int(v)) for v in row) for row in rows)
    return r'\begin{bmatrix}' + body + r'\end{bmatrix}'


print('環境名: wa-src(3.14.6)')
print(f'Python: {platform.python_version()}')
print(f'OS: {platform.system()} / {platform.machine()}')
print(f'NumPy: {np.__version__}, SciPy: {scipy.__version__}')
print(f'Matplotlib: {matplotlib.__version__}, NetworkX: {nx.__version__}')
print(f'画像ディレクトリ: {figure_dir.name}')
assert sys.version_info[:3] == (3, 14, 6), '指定のPython環境で実行すること'
環境名: wa-src(3.14.6)
Python: 3.14.6
OS: Darwin / arm64
NumPy: 2.4.6, SciPy: 1.18.1
Matplotlib: 3.11.2, NetworkX: 3.7
画像ディレクトリ: 103_nb_files

1. 頂点数・辺数・非ゼロ要素数

頂点集合を $V$、辺集合を $E$ とし、頂点数を $n=|V|$、辺数を $m=|E|$ とする。頂点番号はPythonに合わせて $0$ から $n-1$ までとする。まず自己ループと多重辺がない、重みなし無向グラフを考える。

隣接行列 $\mathbf{A}\in\mathbb{R}^{n\times n}$ の要素は次のとおりである。

$$ A_{ij}=\begin{cases} 1 & \{i,j\}\in E,\\ 0 & \{i,j\}\notin E. \end{cases} $$

1本の辺 $\{i,j\}$ は $A_{ij}$ と $A_{ji}$ の2か所に現れる。したがって、非ゼロ要素数を $q$、頂点 $i$ の次数を $d_i$、平均次数を $\bar d$ とすると、

$$ q=\sum_{i=0}^{n-1}d_i=2m,\qquad \bar d=\frac{2m}{n},\qquad q=n\bar d. $$

行列の密度を、全 $n^2$ 要素に占める非ゼロ要素の割合 $\rho=q/n^2$ と定義する。これは自己ループを除いて数えるグラフ密度 $2m/[n(n-1)]$ とは異なる。平均次数が一定なら $q=O(n)$ であり、$\rho=\bar d/n$ は頂点数とともに小さくなる。有向グラフでは、各辺を1要素で表す場合に $q=m$ となる。

6頂点の例

辺を $\{0,1\},\{0,3\},\{1,2\},\{1,3\},\{3,4\}$ とする。頂点5は孤立点であり、$n=6$、$m=5$、$q=10$ である。図1の左がグラフ、右が隣接行列である。

n = 6
edges = np.array([(0, 1), (0, 3), (1, 2), (1, 3), (3, 4)], dtype=np.int32)

# 無向辺は両方向に登録する。密な行列を経由せずCOOを作成する。
rows = np.concatenate([edges[:, 0], edges[:, 1]])
cols = np.concatenate([edges[:, 1], edges[:, 0]])
values = np.ones(len(rows), dtype=np.float64)
A_coo = coo_array((values, (rows, cols)), shape=(n, n))
A = A_coo.tocsr()
A.sum_duplicates()
A.eliminate_zeros()
A.sort_indices()

# 全要素の表示のため、この6×6行列だけを密行列にする。
A_dense = A.toarray()
pprint(A_dense)
display(Math(r'\mathbf{A}=' + matrix_tex(A_dense)))

G = nx.Graph()
G.add_nodes_from(range(n))
G.add_edges_from(edges.tolist())
positions = {0: (0, 1), 1: (1, 1), 2: (2, 1), 3: (0, 0), 4: (1, 0), 5: (2, 0)}
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout='constrained')
nx.draw_networkx(
    G, pos=positions, ax=axes[0], node_size=850,
    node_color=['#c8def0'] * 5 + ['#f5d7a5'], edgecolors='#466278',
    width=2, font_size=12,
)
axes[0].set_title('図1a  無向グラフ(頂点5は孤立点)')
axes[0].set_axis_off()
axes[0].margins(x=0.200, y=0.250)
axes[1].imshow(A_dense, cmap=ListedColormap(['#f3f5f7', '#3979a5']), vmin=0, vmax=1)
for i in range(n):
    for j in range(n):
        axes[1].text(j, i, str(int(A_dense[i, j])), ha='center', va='center',
                     color='white' if A_dense[i, j] else '#697581')
axes[1].set(xticks=range(n), yticks=range(n), xlabel='列 j', ylabel='行 i',
            title=r'図1b  隣接行列 $\mathbf{A}$')
save_figure(fig, '01_graph_and_adjacency.svg')
array([[0.00, 1.00, 0.00, 1.00, 0.00, 0.00],
       [1.00, 0.00, 1.00, 1.00, 0.00, 0.00],
       [0.00, 1.00, 0.00, 0.00, 0.00, 0.00],
       [1.00, 1.00, 0.00, 0.00, 1.00, 0.00],
       [0.00, 0.00, 0.00, 1.00, 0.00, 0.00],
       [0.00, 0.00, 0.00, 0.00, 0.00, 0.00]])

$$ \displaystyle \mathbf{A}=\begin{bmatrix}0 & 1 & 0 & 1 & 0 & 0 \\ 1 & 0 & 1 & 1 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 \\ 1 & 1 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0\end{bmatrix} $$

2. COO・CSR・CSCは何を保存するか

COOは座標形式であり、行番号 row、列番号 col、値 data を同じ長さの配列で持つ。先ほどのコードは辺の一覧から直接COOを作っている。shape=(n, n) を明示するのは、末尾の孤立点も行列に含めるためである。

CSRは行単位で値を並べ、各行の範囲を indptr に保存する。indices は列番号、data は値である。第 $i$ 行の要素は、配列の位置 $p$ が次を満たす部分にある。

$$ \operatorname{indptr}[i]\le p<\operatorname{indptr}[i+1],\qquad A_{i,\operatorname{indices}[p]}=\operatorname{data}[p]. $$

図2では同じ行に属する要素を同じ色にした。第1行の範囲は indptr[1]:indptr[2]、つまり 2:5 であり、列番号は $0,2,3$ である。第5行は 10:10 なので空になる。このように開始位置と終了位置が同じなら、その行に保存された要素はない。

print('COOの3配列')
pprint({'row': A_coo.row, 'col': A_coo.col, 'data': A_coo.data}, sort_dicts=False)
print('CSRの3配列')
pprint({'indptr': A.indptr, 'indices': A.indices, 'data': A.data}, sort_dicts=False)

row_index = 1
start, stop = A.indptr[row_index:row_index + 2]
print(f'第{row_index}行の列番号と値')
pprint({'columns': A.indices[start:stop], 'values': A.data[start:stop]})
assert np.array_equal(A.indptr, [0, 2, 5, 6, 9, 10, 10])
assert np.array_equal(np.diff(A.indptr), [2, 3, 1, 3, 1, 0])

colors = ['#c4dcef', '#f4d1ae', '#cbe5cb', '#ddd1eb', '#f0cbd0', '#e0e0e0']
row_of_entry = np.repeat(np.arange(n), np.diff(A.indptr))
fig, ax = plt.subplots(figsize=(11, 4), layout='constrained')

for label, array, y, color_ids in [
    ('indptr', A.indptr, 3, np.minimum(np.arange(n + 1), n - 1)),
    ('indices', A.indices, 1, row_of_entry),
    ('data', A.data, 0, row_of_entry),
]:
    ax.text(-0.150, y + 0.350, label, ha='right', va='center', fontsize=12)
    for k, value in enumerate(array):
        ax.add_patch(Rectangle((k, y), 1, 0.700,
                               facecolor=colors[int(color_ids[k])], edgecolor='white'))
        ax.text(k + 0.500, y + 0.350, str(int(value)), ha='center', va='center')
        if label != 'data':
            ax.text(k + 0.500, y + 0.850, str(k), ha='center', fontsize=9, color='#546473')

for i in range(n - 1):
    start, stop = map(int, A.indptr[i:i + 2])
    ax.plot([start + 0.0500, stop - 0.0500], [2.25, 2.25], color=colors[i], linewidth=7)
    ax.text((start + stop) / 2, 2.45, f'行{i}: [{start}, {stop})', ha='center', fontsize=10)
ax.text(7.30, 3.35, '行5: [10, 10) → 空の行', fontsize=11)
ax.set(xlim=(-1.20, 10.2), ylim=(-0.200, 4.40), title='図2  CSRの配列と各行の範囲(上側の数字は配列位置)')
ax.set_axis_off()
save_figure(fig, '02_csr_storage.svg')
COOの3配列
{'row': array([0, 0, 1, 1, 3, 1, 3, 2, 3, 4], dtype=int32),
 'col': array([1, 3, 2, 3, 4, 0, 0, 1, 1, 3], dtype=int32),
 'data': array([1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00])}
CSRの3配列
{'indptr': array([ 0,  2,  5,  6,  9, 10, 10], dtype=int32),
 'indices': array([1, 3, 0, 2, 3, 1, 0, 1, 4, 3], dtype=int32),
 'data': array([1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00])}
第1行の列番号と値
{'columns': array([0, 2, 3], dtype=int32), 'values': array([1.00, 1.00, 1.00])}

CSCはCSRの行と列の役割を入れ替えた形式であり、列ごとに行番号と値を保存する。用途に応じた使い分けを表に示す。CSRは行の取り出しと行列・ベクトル積に適している一方、列の取り出しや保存位置の追加には向かない。SciPyのCSR仕様

形式主な配列・構造主な用途
COO行番号・列番号・値辺の一覧から一括して構築
CSR行ポインタ・列番号・値行の参照、行列・ベクトル積
CSC列ポインタ・行番号・値列の参照
LIL / DOK行ごとのリスト / 座標をキーとする辞書構築中の個別の挿入・変更

ここでは計算用に csr_array を使用する。疎配列の行列積には @、要素ごとの積には * を使う。SciPyの疎配列

# CSCでは第3列に保存された行番号を取り出す。
A_csc = A.tocsc()
column_index = 3
start, stop = A_csc.indptr[column_index:column_index + 2]
pprint({'column': column_index, 'rows': A_csc.indices[start:stop],
        'values': A_csc.data[start:stop]}, sort_dicts=False)
{'column': 3,
 'rows': array([0, 1, 4], dtype=int32),
 'values': array([1.00, 1.00, 1.00])}

重複と明示的なゼロ

nnz は保存要素数であり、常に数学上の非ゼロ要素数とは限らない。COOには同じ座標を複数回登録でき、CSRへの変換時にはその値が加算される。また、値がゼロでも保存されている間は nnz に含まれる。SciPyのCOO仕様

次の例では、保存要素数が $3\to2\to1$ と変わる。重みなし単純グラフで同じ辺を重複入力すると、値が2になってしまうため、入力段階で重複を除く必要がある。以後は重複を統合し、明示的なゼロを除いた状態で $q=\mathrm{nnz}$ とする。重み0の辺を特別に扱う問題では、ゼロを削除してよいかを別に決める必要がある。

raw = coo_array(
    (np.array([1, 1, 0], dtype=np.float64),
     (np.array([0, 0, 1], dtype=np.int32), np.array([1, 1, 2], dtype=np.int32))),
    shape=(3, 3),
)
counts = {'COOのnnz': int(raw.nnz)}
clean = raw.tocsr()  # 同じ座標の値を加算する。
counts['CSR変換後のnnz'] = int(clean.nnz)
counts['実際の非ゼロ要素数'] = int(clean.count_nonzero())
clean.eliminate_zeros()
counts['ゼロ削除後のnnz'] = int(clean.nnz)
pprint(counts, sort_dicts=False)
pprint(clean.toarray())
assert list(counts.values()) == [3, 2, 1, 1]
{'COOのnnz': 3, 'CSR変換後のnnz': 2, '実際の非ゼロ要素数': 1, 'ゼロ削除後のnnz': 1}
array([[0.00, 2.00, 0.00],
       [0.00, 0.00, 0.00],
       [0.00, 0.00, 0.00]])

3. 必要なメモリ量を求める

値1個を $b_v$ バイト、添字1個を $b_i$ バイトで保存するとする。密行列には $n^2$ 個の値が必要である。COOには長さ $q$ の値・行番号・列番号があり、CSRには長さ $q$ の値・列番号と長さ $n+1$ の行ポインタがある。したがって、配列本体の容量は次のようになる。

$$ \begin{aligned} M_{\mathrm{dense}}&=b_v n^2,\\ M_{\mathrm{COO}}&=b_v q+b_i q+b_i q=(b_v+2b_i)q,\\ M_{\mathrm{CSR}}&=b_v q+b_i q+b_i(n+1)\\ &=(b_v+b_i)q+b_i(n+1). \end{aligned} $$

float64 の値は8バイト、int32 の添字は4バイトなので、CSRは $12q+4(n+1)$ バイトになる。ここにはPythonオブジェクトの管理領域、構築・変換中の一時配列、入力辺リスト、計算用ベクトルは含めない。小さな例で nbytes の合計と式が一致することを確認する。

def csr_nbytes(matrix):
    # CSRを構成する3配列の容量のみを数える。
    return matrix.data.nbytes + matrix.indices.nbytes + matrix.indptr.nbytes


sizes = {
    'dense': A_dense.nbytes,
    'COO': A_coo.data.nbytes + A_coo.row.nbytes + A_coo.col.nbytes,
    'CSR': csr_nbytes(A),
}
pprint({'data型': str(A.data.dtype), 'indices型': str(A.indices.dtype),
        'indptr型': str(A.indptr.dtype)})
pprint(sizes)
expected = (A.data.itemsize + A.indices.itemsize) * A.nnz + A.indptr.itemsize * (n + 1)
assert sizes['CSR'] == expected == 148
{'data型': 'float64', 'indices型': 'int32', 'indptr型': 'int32'}
{'COO': 160, 'CSR': 148, 'dense': 288}

100万頂点、平均次数10の場合

$n=10^6$、$\bar d=10$ なら、$m=n\bar d/2=5\times10^6$、$q=n\bar d=10^7$ である。上の式に代入する。

$$ \begin{aligned} M_{\mathrm{dense}} &=8(10^6)^2=8\times10^{12}\ \mathrm{B}=8.00\ \mathrm{TB},\\ M_{\mathrm{CSR}} &=12\times10^7+4(10^6+1)\\ &=120000000+4000004\\ &=124000004\ \mathrm{B}\approx124\ \mathrm{MB}. \end{aligned} $$

ここでは $1\ \mathrm{MB}=10^6\ \mathrm{B}$、$1\ \mathrm{TB}=10^{12}\ \mathrm{B}$ とする。同じ条件でも添字が int64 なら $16q+8(n+1)$ バイト、約 $168\ \mathrm{MB}$ となる。添字の型は渡す配列にも依存するため、実際の dtype を確認する。頂点番号や累積保存要素数が32ビット整数の範囲を超える場合は、64ビット添字が必要である。

疎形式が常に小さいわけではない。8バイトの値と4バイトの添字の場合、CSRが密行列より小さい条件は、

$$ \begin{aligned} 12q+4(n+1)&<8n^2,\\ 12q&<8n^2-4(n+1),\\ \rho=\frac{q}{n^2}&<\frac{2}{3}-\frac{n+1}{3n^2}. \end{aligned} $$

十分大きい $n$ では境界は約 $0.667$ となる。これは保存容量の境界であり、速度の境界ではない。図3は式から計算した容量であり、巨大な密行列は確保していない。

vertex_counts = np.unique(np.geomspace(100, 10**6, 100).astype(np.int64))
nonzeros = 10 * vertex_counts  # 平均次数10を固定する。
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')

axes[0].loglog(vertex_counts, 8 * vertex_counts**2 / 10**6,
               label='密行列', color='#b75538', linewidth=2)
axes[0].loglog(vertex_counts, 16 * nonzeros / 10**6,
               label='COO / int32', color='#8a6aaf', linestyle='--')
axes[0].loglog(vertex_counts, (12 * nonzeros + 4 * (vertex_counts + 1)) / 10**6,
               label='CSR / int32', color='#2878a6', linewidth=2)
axes[0].loglog(vertex_counts, (16 * nonzeros + 8 * (vertex_counts + 1)) / 10**6,
               label='CSR / int64', color='#4b8a5b', linestyle=':')
axes[0].set(xlabel='頂点数 n', ylabel='配列本体の容量 [MB]', title='図3a  平均次数10での容量')
axes[0].legend(fontsize=9)
axes[0].grid(True, which='major', alpha=0.250)

fixed_n = 10_000
rho = np.linspace(0.00100, 1, 300)
for index_bytes, color in [(4, '#2878a6'), (8, '#4b8a5b')]:
    ratio = ((8 + index_bytes) * rho * fixed_n**2 + index_bytes * (fixed_n + 1)) / (8 * fixed_n**2)
    axes[1].plot(rho, ratio, label=f'CSR / int{8 * index_bytes}', color=color, linewidth=2)
axes[1].axhline(1, color='#b75538', linestyle='--', label='密行列と同じ容量')
axes[1].set(xlabel=r'行列の密度 $\rho$', ylabel='CSR容量 / 密行列容量',
            xlim=(0, 1), ylim=(0, 2.10), title='図3b  密度による容量比(n=10000)')
axes[1].xaxis.set_major_formatter(FuncFormatter(lambda x, _: sig3(x)))
axes[1].yaxis.set_major_formatter(FuncFormatter(lambda x, _: sig3(x)))
axes[1].legend(fontsize=9)
axes[1].grid(True, alpha=0.250)
save_figure(fig, '03_memory_scaling.svg')

4. 行列・ベクトル積の計算量

頂点ごとの値を並べたベクトルを $\mathbf{x}$ とすると、$\mathbf{y}=\mathbf{A}\mathbf{x}$ は各頂点の隣接点の値を足したものである。$N(i)=\{j:A_{ij}\ne0\}$ とおけば、ゼロとの積を省いて次のように書ける。

$$ y_i=\sum_{j=0}^{n-1}A_{ij}x_j =\sum_{j\in N(i)}A_{ij}x_j. $$

$\mathbf{x}=(1,2,3,4,5,6)^{\mathsf T}$ を先ほどのグラフに与える。各行で残る計算は次のとおりである。

$$ \begin{aligned} y_0&=1\cdot2+1\cdot4=6,\\ y_1&=1\cdot1+1\cdot3+1\cdot4=8,\\ y_2&=1\cdot2=2,\\ y_3&=1\cdot1+1\cdot2+1\cdot5=8,\\ y_4&=1\cdot4=4,\\ y_5&=0. \end{aligned} $$

CSRでは行 $i$ の $d_i$ 要素だけを処理する。行の走査と出力ベクトルの初期化に $O(n)$、保存要素の処理に $O(q)$ かかるので、

$$ T_{\mathrm{CSR}}=O\!\left(n+\sum_{i=0}^{n-1}d_i\right) =O(n+q)=O(n+m). $$

孤立点が多数ある場合も $n$ 個の出力を作るため、単に $O(q)$ とするより $O(n+q)$ と書く方が正確である。密行列による通常の積は全 $n^2$ 要素を扱うため $O(n^2)$ となる。

def csr_matvec_by_row(matrix, vector):
    # CSRの構造を理解するための実装。速度計測にはSciPyの @ を使う。
    result = np.zeros(matrix.shape[0], dtype=np.float64)
    for i in range(matrix.shape[0]):
        for p in range(matrix.indptr[i], matrix.indptr[i + 1]):
            j = matrix.indices[p]
            result[i] += matrix.data[p] * vector[j]
    return result


x = np.arange(1, n + 1, dtype=np.float64)
y = A @ x
pprint({'x': x, 'y': y}, sort_dicts=False)
display(Math(r'\mathbf{x}=' + matrix_tex(x[:, None])
             + r',\qquad\mathbf{A}\mathbf{x}=' + matrix_tex(y[:, None])))
assert np.array_equal(y, [6, 8, 2, 8, 4, 0])
assert np.array_equal(y, csr_matvec_by_row(A, x))
assert np.array_equal(y, A_dense @ x)

# 隣接頂点jからの寄与 A_ij x_j を色分けする。
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
bottom = np.zeros(n)
for j in range(n):
    contribution = A_dense[:, j] * x[j]
    if np.any(contribution):
        ax.bar(np.arange(n), contribution, bottom=bottom,
               color=colors[j], edgecolor='white', label=f'頂点{j}の値')
        bottom += contribution
for i, value in enumerate(y):
    ax.text(i, value + 0.150, str(int(value)), ha='center')
ax.set(xticks=range(n), xlabel='値を受け取る頂点 i', ylabel='隣接点の値の合計',
       ylim=(0, 10), title=r'図4  $\mathbf{A}\mathbf{x}$ の内訳')
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend(ncol=3, fontsize=9)
save_figure(fig, '04_neighbor_aggregation.svg')
{'x': array([1.00, 2.00, 3.00, 4.00, 5.00, 6.00]),
 'y': array([6.00, 8.00, 2.00, 8.00, 4.00, 0.00])}

$$ \displaystyle \mathbf{x}=\begin{bmatrix}1 \\ 2 \\ 3 \\ 4 \\ 5 \\ 6\end{bmatrix},\qquad\mathbf{A}\mathbf{x}=\begin{bmatrix}6 \\ 8 \\ 2 \\ 8 \\ 4 \\ 0\end{bmatrix} $$

計算量を比較すると次のようになる。$d_i$ は第 $i$ 行の非ゼロ要素数であり、CSRは重複と明示的なゼロを除いた状態を前提とする。

操作密行列CSR
配列本体の保存容量$O(n^2)$$O(n+q)$
頂点 $i$ の隣接点を列挙$O(n)$$O(1+d_i)$
全頂点の次数を計算$O(n^2)$$O(n)$:diff(indptr)
行列・ベクトル積$O(n^2)$$O(n+q)$

次数を np.diff(A.indptr) で得られるのは、各隣接点を1要素で表しているためである。重み付きグラフの重みの合計は A.sum(axis=1) で求めるので $O(n+q)$ となる。辺の挿入が多い処理では、CSRを繰り返し変更するよりCOOで集めてから変換する方が扱いやすい。

非ゼロ要素数が同じでも行ごとの処理量は違う

図5の道グラフと星グラフは、どちらも80頂点79辺である。保存容量と積全体の計算量は同じだが、星グラフの中心だけは79要素を処理する。平均次数だけでは、この行ごとの偏りは分からない。

n_structure = 80
path_graph = nx.path_graph(n_structure)
star_graph = nx.star_graph(n_structure - 1)
A_path = nx.to_scipy_sparse_array(path_graph, nodelist=range(n_structure),
                                 dtype=np.float64, format='csr')
A_star = nx.to_scipy_sparse_array(star_graph, nodelist=range(n_structure),
                                 dtype=np.float64, format='csr')
assert A_path.nnz == A_star.nnz == 2 * (n_structure - 1)
assert csr_nbytes(A_path) == csr_nbytes(A_star)

fig, axes = plt.subplots(1, 3, figsize=(11, 3.60), layout='constrained')
for ax, matrix, title in zip(axes[:2], [A_path, A_star], ['道グラフ', '星グラフ']):
    ax.spy(matrix, markersize=2, color='#2878a6')
    ax.xaxis.tick_bottom()
    ax.set(xlabel='列 j', ylabel='行 i', title=f'{title}: q={matrix.nnz}')
axes[2].plot(np.diff(A_path.indptr), label='道グラフ', color='#2878a6', linewidth=2)
axes[2].plot(np.diff(A_star.indptr), label='星グラフ', color='#b75538', linewidth=2)
axes[2].set(xlabel='頂点 i', ylabel='次数', title='各行の処理要素数')
axes[2].legend()
fig.suptitle('図5  同じ非ゼロ要素数を持つ2つのグラフ')
save_figure(fig, '05_sparsity_and_degrees.svg')

5. 10万頂点での実装と実行時間

各頂点を環状に並べ、左右5個ずつの頂点と結ぶグラフを作る。すべての次数は10なので $q=10n$ である。これは構造を固定して規模の影響を調べる例であり、実データの次数分布を再現したものではない。

10万頂点なら $q=10^6$ となる。密行列は $8(10^5)^2=80.0\ \mathrm{GB}$、32ビット添字のCSRは $12\times10^6+4(10^5+1)=12400004\ \mathrm{B}\approx12.4\ \mathrm{MB}$ である。ここではCSRだけを実際に作る。全要素が1のベクトル $\mathbf{1}$ を掛けると、各成分が次数10になることも確認する。

def ring_adjacency(vertex_count, radius=5):
    if vertex_count <= 2 * radius:
        raise ValueError('頂点数は左右の接続数の合計より大きくする')
    # ±1から±radiusまでの接続先を作る。自己ループも重複もない。
    offsets = np.concatenate([
        np.arange(-radius, 0, dtype=np.int32),
        np.arange(1, radius + 1, dtype=np.int32),
    ])
    row = np.repeat(np.arange(vertex_count, dtype=np.int32), len(offsets))
    col = (row + np.tile(offsets, vertex_count)) % vertex_count
    data = np.ones(len(row), dtype=np.float64)
    return coo_array((data, (row, col)), shape=(vertex_count, vertex_count)).tocsr()


large_n = 100_000
A_large = ring_adjacency(large_n)
large_result = A_large @ np.ones(large_n)
pprint({
    '頂点数': large_n,
    '非ゼロ要素数': int(A_large.nnz),
    '値の型': str(A_large.data.dtype),
    '添字の型': str(A_large.indices.dtype),
    'CSR配列容量 [MB]': sig3(csr_nbytes(A_large) / 10**6),
    '密行列容量の見積もり [GB]': sig3(8 * large_n**2 / 10**9),
}, sort_dicts=False)
pprint(large_result[:10])
assert A_large.nnz == 10 * large_n
assert A_large.indices.dtype == np.int32
assert csr_nbytes(A_large) == 12_400_004
assert np.all(large_result == 10)
{'頂点数': 100000,
 '非ゼロ要素数': 1000000,
 '値の型': 'float64',
 '添字の型': 'int32',
 'CSR配列容量 [MB]': '12.4',
 '密行列容量の見積もり [GB]': '80.0'}
array([10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0])

計測条件

SciPyの @ とNumPyの @ を比較する。密行列は4000頂点までとし、その先はCSRだけを測る。各条件で20回の積を7組計測し、1回当たりの時間の中央値と最小・最大値を出す。初回呼び出しを済ませ、BLASは環境既定のスレッド設定を使う。使用したBLASの名前も出力する。出力ベクトルの確保は含むが、グラフの構築、形式変換、描画は含めない。

計算量は要素数が増えたときの増加率を表す。実際の秒数にはキャッシュやメモリ転送なども影響するため、速度比は実行環境によって変わる。疎形式の変換にも時間と一時メモリが必要であり、1回だけの計算ではその費用も含めて判断する。

def matvec_times(matrix, vector, number=20, repeats=7):
    _ = matrix @ vector  # 初回呼び出しを計測から外す。
    samples = np.asarray(repeat(lambda: matrix @ vector, number=number, repeat=repeats)) / number
    return float(samples.min()), float(np.median(samples)), float(samples.max())


benchmark = []
rng = np.random.default_rng(103)
blas = np.show_config(mode='dicts')['Build Dependencies']['blas']
pprint({'BLAS': blas['name'], 'スレッド設定': '環境既定値'}, sort_dicts=False)
for vertex_count in [250, 500, 1000, 2000, 4000, 10_000, 100_000]:
    matrix = A_large if vertex_count == large_n else ring_adjacency(vertex_count)
    vector = rng.standard_normal(vertex_count)
    sparse_times = matvec_times(matrix, vector)
    dense_times = None
    if vertex_count <= 4000:
        dense_matrix = matrix.toarray()
        np.testing.assert_allclose(matrix @ vector, dense_matrix @ vector,
                                   rtol=1.00e-12, atol=1.00e-12)
        dense_times = matvec_times(dense_matrix, vector)
        del dense_matrix
    benchmark.append({'n': vertex_count, 'q': int(matrix.nnz),
                      'csr': sparse_times, 'dense': dense_times})

# リストの計測結果はpprintで表示する。時間の単位はマイクロ秒。
rows_for_output = []
for item in benchmark:
    row = {'n': item['n'], 'q': item['q'],
           'CSR中央値 [μs]': sig3(item['csr'][1] * 10**6),
           'CSR範囲 [μs]': [sig3(item['csr'][i] * 10**6) for i in [0, 2]]}
    if item['dense'] is not None:
        row['密行列中央値 [μs]'] = sig3(item['dense'][1] * 10**6)
        row['密行列範囲 [μs]'] = [sig3(item['dense'][i] * 10**6) for i in [0, 2]]
    rows_for_output.append(row)
pprint(rows_for_output, sort_dicts=False, width=100)

fig, ax = plt.subplots(figsize=(9, 4.50), layout='constrained')
for key, label, color in [('csr', 'CSR', '#2878a6'), ('dense', '密行列', '#b75538')]:
    selected = [item for item in benchmark if item[key] is not None]
    ns = np.array([item['n'] for item in selected])
    times = np.array([item[key] for item in selected]) * 10**6
    ax.loglog(ns, times[:, 1], 'o-', label=label, color=color, linewidth=2)
    ax.fill_between(ns, times[:, 0], times[:, 2], color=color, alpha=0.180)
ax.set(xlabel='頂点数 n(各頂点の次数は10)', ylabel='積1回の時間 [μs]',
       title='図6  行列・ベクトル積の実測時間(線: 中央値、帯: 最小〜最大)')
ax.legend()
ax.grid(True, which='major', alpha=0.250)
save_figure(fig, '06_matvec_benchmark.svg')
{'BLAS': 'accelerate', 'スレッド設定': '環境既定値'}


[{'n': 250,
  'q': 2500,
  'CSR中央値 [μs]': '2.95',
  'CSR範囲 [μs]': ['2.83', '7.55'],
  '密行列中央値 [μs]': '6.99',
  '密行列範囲 [μs]': ['6.93', '13.3']},
 {'n': 500,
  'q': 5000,
  'CSR中央値 [μs]': '3.98',
  'CSR範囲 [μs]': ['3.96', '4.23'],
  '密行列中央値 [μs]': '11.2',
  '密行列範囲 [μs]': ['10.9', '11.5']},
 {'n': 1000,
  'q': 10000,
  'CSR中央値 [μs]': '6.81',
  'CSR範囲 [μs]': ['6.78', '10.2'],
  '密行列中央値 [μs]': '35.3',
  '密行列範囲 [μs]': ['34.4', '42.1']},
 {'n': 2000,
  'q': 20000,
  'CSR中央値 [μs]': '11.0',
  'CSR範囲 [μs]': ['10.8', '11.5'],
  '密行列中央値 [μs]': '580',
  '密行列範囲 [μs]': ['494', '1.01e+03']},
 {'n': 4000,
  'q': 40000,
  'CSR中央値 [μs]': '24.6',
  'CSR範囲 [μs]': ['23.0', '40.8'],
  '密行列中央値 [μs]': '3.99e+03',
  '密行列範囲 [μs]': ['2.45e+03', '6.64e+03']},
 {'n': 10000, 'q': 100000, 'CSR中央値 [μs]': '45.7', 'CSR範囲 [μs]': ['43.1', '103']},
 {'n': 100000, 'q': 1000000, 'CSR中央値 [μs]': '500', 'CSR範囲 [μs]': ['456', '613']}]

6. 疎行列同士の積は疎とは限らない

$\mathbf{A}\mathbf{x}$ の計算量を、そのまま $\mathbf{A}^2$ の構築に当てはめることはできない。行列積では、元の行列にない位置にも非ゼロ要素が現れる。

頂点0を中心とする $n$ 頂点の星グラフを考える。残りの $n-1$ 頂点を葉と呼ぶ。長さ $n-1$ の全成分が1のベクトルを $\mathbf{1}$ とすれば、隣接行列とその2乗は次のブロック行列になる。

$$ \begin{aligned} \mathbf{A}&= \begin{bmatrix}0&\mathbf{1}^{\mathsf T}\\\mathbf{1}&\mathbf{0}\end{bmatrix},\\ \mathbf{A}^2&= \begin{bmatrix} 0\cdot0+\mathbf{1}^{\mathsf T}\mathbf{1}&0\cdot\mathbf{1}^{\mathsf T}+\mathbf{1}^{\mathsf T}\mathbf{0}\\ \mathbf{1}\cdot0+\mathbf{0}\mathbf{1}&\mathbf{1}\mathbf{1}^{\mathsf T}+\mathbf{0}\mathbf{0} \end{bmatrix}\\ &=\begin{bmatrix}n-1&\mathbf{0}^{\mathsf T}\\\mathbf{0}&\mathbf{1}\mathbf{1}^{\mathsf T}\end{bmatrix}. \end{aligned} $$

任意の葉から別の葉、または同じ葉へ、中心を経由して2歩で移動できる。そのため右下の $(n-1)\times(n-1)$ 部分はすべて1となる。

$$ \operatorname{nnz}(\mathbf{A})=2(n-1),\qquad \operatorname{nnz}(\mathbf{A}^2)=1+(n-1)^2. $$

つまり、元の非ゼロ要素数は $O(n)$ でも、積の保存には $O(n^2)$ が必要になる。80頂点なら $158$ 要素が $6242$ 要素に増える。図7でこの変化を確認する。

# ここでは80×80なので積そのものを作り、非ゼロ位置を表示する。
A_squared = A_star @ A_star
expected_nonzeros = 1 + (n_structure - 1)**2
assert A_squared.nnz == expected_nonzeros

pprint({
    'Aのnnz': int(A_star.nnz),
    'A²のnnz': int(A_squared.nnz),
    'A²の行列密度': sig3(A_squared.nnz / n_structure**2),
    'AのCSR配列容量 [B]': csr_nbytes(A_star),
    'A²のCSR配列容量 [B]': csr_nbytes(A_squared),
}, sort_dicts=False)

fig, axes = plt.subplots(1, 2, figsize=(8, 4), layout='constrained')
for ax, matrix, label in zip(axes, [A_star, A_squared], [r'$\mathbf{A}$', r'$\mathbf{A}^2$']):
    ax.spy(matrix, markersize=2, color='#2878a6')
    ax.xaxis.tick_bottom()
    ax.set(xlabel='列 j', ylabel='行 i', title=f'{label}: q={matrix.nnz}')
fig.suptitle('図7  星グラフの隣接行列を2乗したときの非ゼロ位置')
save_figure(fig, '07_matrix_product_fill_in.svg')

# A²そのものが不要なら、ベクトルにAを2回掛ければよい。
vector = np.arange(n_structure, dtype=np.float64)
via_matrix = A_squared @ vector
via_repetition = A_star @ (A_star @ vector)
np.testing.assert_allclose(via_matrix, via_repetition, rtol=1.00e-12, atol=1.00e-12)
print('A²を作る計算と、Aを2回掛ける計算の結果は一致した。')
{'Aのnnz': 158,
 'A²のnnz': 6242,
 'A²の行列密度': '0.975',
 'AのCSR配列容量 [B]': 3176,
 'A²のCSR配列容量 [B]': 100520}
A²を作る計算と、Aを2回掛ける計算の結果は一致した。

必要なのが $\mathbf{A}^2\mathbf{x}$ だけなら、A @ (A @ x) と計算できる。さらに $\mathbf{z}^{(0)}=\mathbf{x}$、$\mathbf{z}^{(t+1)}=\mathbf{A}\mathbf{z}^{(t)}$ とすれば、帰納的に $\mathbf{z}^{(k)}=\mathbf{A}^k\mathbf{x}$ となる。$\mathbf{A}$ を固定したまま $k$ 回掛ける費用は $O(k(n+q))$、途中で必要なベクトルの領域は $O(n)$ である。$\mathbf{A}^k$ 自体を保存する必要はない。

結論

この記事では、疎行列によるグラフの保存形式を確認し、必要なメモリ量と行列・ベクトル積の計算量を導いた。

重複と明示的なゼロを除いたCSRは、$n$ 頂点・$q$ 非ゼロ要素の行列を $O(n+q)$ の容量で保存する。自己ループのない重みなし無向グラフでは $q=2m$ なので、平均次数が一定なら保存容量も行列・ベクトル積の計算量も頂点数に比例する。

辺の一覧からCOOを作り、計算時にCSRへ変換すると実装しやすい。容量は値だけでなく添字の型も含めて見積もる。また、疎行列同士の積は非ゼロ要素が増えるため、必要な結果がベクトルなら行列・ベクトル積を繰り返す方法を検討する。

参考文献