Download nerf_earth.py from calebrob6/nerf-earth: direct link, hf CLI and curl.
- Browser
- Download file 7.02 kB
-
https://huggingface.co/calebrob6/nerf-earth/resolve/main/nerf_earth.py
- Command line
-
hf download hf://calebrob6/nerf-earth/nerf_earth.py
-
curl -L -o nerf_earth.py https://huggingface.co/calebrob6/nerf-earth/resolve/main/nerf_earth.py
7.02 kB
| # Copyright (c) 2026 Caleb Robinson | |
| # SPDX-License-Identifier: MIT | |
| """NeRF-Earth location encoders: (latitude, longitude) -> unit-length embedding. | |
| Each model is a learned multiresolution hash grid over unit-sphere coordinates | |
| followed by a SIREN MLP. Requires ``torch``, ``numpy``, ``safetensors`` and, | |
| for downloading, ``huggingface_hub``. | |
| from nerf_earth import load | |
| encoder = load("n10") # or a local model folder | |
| features = encoder.encode(lat=[40.71], lon=[-74.01]) # (1, 1023) float32 | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| REPO_ID = "calebrob6/nerf-earth" | |
| MODELS = ("n10", "smooth_global_seed65", "hashgrid_depth4_seed54") | |
| _PRIMES = (1, 2_654_435_761, 805_459_861) | |
| _CORNERS = [[(corner >> axis) & 1 for axis in range(3)] for corner in range(8)] | |
| class SphericalHashGrid(nn.Module): | |
| """Multiresolution hash grid evaluated at unit-sphere Cartesian points.""" | |
| def __init__( | |
| self, | |
| num_levels: int, | |
| features_per_level: int, | |
| log2_hashmap_size: int, | |
| base_resolution: int, | |
| finest_resolution: int, | |
| include_input: bool = True, | |
| ): | |
| super().__init__() | |
| growth = math.exp( | |
| math.log(finest_resolution / base_resolution) / max(1, num_levels - 1) | |
| ) | |
| self.resolutions = [ | |
| max(2, int(round(base_resolution * growth**level))) | |
| for level in range(num_levels) | |
| ] | |
| self.table_size = 1 << log2_hashmap_size | |
| self.include_input = include_input | |
| self.tables = nn.ParameterList( | |
| nn.Parameter(torch.empty(self.table_size, features_per_level)) | |
| for _ in range(num_levels) | |
| ) | |
| self.output_dim = num_levels * features_per_level + 3 * include_input | |
| def forward(self, lat_lon: torch.Tensor) -> torch.Tensor: | |
| lat, lon = torch.deg2rad(lat_lon[..., 0]), torch.deg2rad(lat_lon[..., 1]) | |
| cos_lat = torch.cos(lat) | |
| xyz = torch.stack( | |
| [cos_lat * torch.cos(lon), cos_lat * torch.sin(lon), torch.sin(lat)], -1 | |
| ) | |
| unit = (xyz + 1.0) * 0.5 | |
| corners = torch.tensor(_CORNERS, dtype=torch.int64, device=xyz.device) | |
| outputs = [xyz] if self.include_input else [] | |
| for resolution, table in zip(self.resolutions, self.tables): | |
| position = unit * (resolution - 1) | |
| base = torch.floor(position).to(torch.int64) | |
| fraction = position - base | |
| level = torch.zeros( | |
| *position.shape[:-1], table.shape[1], device=xyz.device | |
| ) | |
| for bits in corners: | |
| weight = torch.where(bits.bool(), fraction, 1.0 - fraction).prod( | |
| -1, keepdim=True | |
| ) | |
| x, y, z = (base + bits).unbind(-1) | |
| index = torch.remainder( | |
| x * _PRIMES[0] ^ y * _PRIMES[1] ^ z * _PRIMES[2], self.table_size | |
| ) | |
| level = level + weight * table[index].float() | |
| outputs.append(level) | |
| return torch.cat(outputs, -1) | |
| class SirenTower(nn.Module): | |
| """Sine-activated MLP with a linear output layer.""" | |
| def __init__( | |
| self, | |
| in_features: int, | |
| hidden_features: int, | |
| out_features: int, | |
| depth: int, | |
| w0_first: float = 30.0, | |
| w0: float = 1.0, | |
| ): | |
| super().__init__() | |
| self.w0 = [w0_first] + [w0] * (depth - 1) | |
| self.hidden_layers = nn.ModuleList( | |
| nn.Linear(in_features if i == 0 else hidden_features, hidden_features) | |
| for i in range(depth) | |
| ) | |
| self.output_layer = nn.Linear(hidden_features, out_features) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| for w0, layer in zip(self.w0, self.hidden_layers): | |
| x = torch.sin(w0 * layer(x)) | |
| return self.output_layer(x) | |
| class LocationEncoder(nn.Module): | |
| """Frozen location encoder. ``forward`` takes ``[N, 2]`` (lat, lon) degrees.""" | |
| def __init__(self, config: dict): | |
| super().__init__() | |
| self.config = config | |
| self.dim = int(config["embedding_dim"]) | |
| self.encoding = SphericalHashGrid(**config["hash_grid"]) | |
| self.location_tower = SirenTower( | |
| self.encoding.output_dim, out_features=self.dim, **config["siren"] | |
| ) | |
| def forward(self, lat_lon: torch.Tensor) -> torch.Tensor: | |
| features = self.location_tower(self.encoding(lat_lon.float())) | |
| return F.normalize(features, dim=-1) | |
| def encode(self, lat, lon, batch_size: int = 4096) -> np.ndarray: | |
| """Embed array-like latitudes and longitudes (degrees, WGS84). | |
| Returns a float32 array of shape ``(N, dim)`` with unit-length rows. | |
| """ | |
| lat = np.asarray(lat, dtype=np.float64).reshape(-1) | |
| lon = np.asarray(lon, dtype=np.float64).reshape(-1) | |
| if lat.shape != lon.shape: | |
| raise ValueError("lat and lon must have the same number of elements") | |
| if not (np.isfinite(lat).all() and np.isfinite(lon).all()): | |
| raise ValueError("coordinates must be finite") | |
| if np.any(np.abs(lat) > 90) or np.any(np.abs(lon) > 180): | |
| raise ValueError("latitude must be in [-90, 90], longitude in [-180, 180]") | |
| coords = torch.from_numpy(np.stack([lat, lon], 1).astype(np.float32)) | |
| device = self.encoding.tables[0].device | |
| outputs = [ | |
| self(coords[start : start + batch_size].to(device)).cpu().numpy() | |
| for start in range(0, len(coords), batch_size) | |
| ] | |
| if not outputs: | |
| return np.empty((0, self.dim), dtype=np.float32) | |
| return np.concatenate(outputs) | |
| def load( | |
| name_or_path: str = "n10", | |
| device: str | torch.device = "cpu", | |
| repo_id: str = REPO_ID, | |
| revision: str | None = None, | |
| ) -> LocationEncoder: | |
| """Load a model by name from the Hub, or from a local folder. | |
| A folder must contain ``config.json`` and ``model.safetensors``. | |
| """ | |
| from safetensors.torch import load_file | |
| folder = Path(name_or_path) | |
| if folder.is_dir(): | |
| config_path = folder / "config.json" | |
| weights_path = folder / "model.safetensors" | |
| else: | |
| if name_or_path not in MODELS: | |
| raise ValueError(f"unknown model {name_or_path!r}; choose from {MODELS}") | |
| from huggingface_hub import hf_hub_download | |
| config_path, weights_path = ( | |
| hf_hub_download(repo_id, f"{name_or_path}/{file}", revision=revision) | |
| for file in ("config.json", "model.safetensors") | |
| ) | |
| config = json.loads(Path(config_path).read_text()) | |
| with torch.device("meta"): | |
| model = LocationEncoder(config) | |
| state = load_file(weights_path, device=str(torch.device(device))) | |
| model.load_state_dict(state, strict=True, assign=True) | |
| return model.eval().requires_grad_(False) | |