helloadhavan/github_issues huggingface dataset:
Repository: huggingface/transformers
Pull request: [ModernBert] Prevent the attention mask from being None in ModernBertForSequenceClassification

# What does this PR do?

This PR uses the same code for the attention mask in ModernBertForSequenceClassification as the one that is used inside the ModernBertModel class. This means that it will output a warning when the inputs contains padding but no attention_mask was specified, while also setting the attention mask to 1 to avoid it being None in later parts of the code (see #35917).
I did a quick test and it seems to fix the crash and print the warning when training on a sequence classification task.

Fixes #35917


Changed files:
filename: src/transformers/models/modernbert/modeling_modernbert.py
patch: @@ -1151,6 +1151,19 @@ def forward(
         return_dict = return_dict if return_dict is not None else self.config.use_return_dict
         self._maybe_set_compile()
 
+        if input_ids is not None:
+            self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+
+        if batch_size is None and seq_len is None:
+            if inputs_embeds is not None:
+                batch_size, seq_len = inputs_embeds.shape[:2]
+            else:
+                batch_size, seq_len = input_ids.shape[:2]
+        device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+        if attention_mask is None:
+            attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
+
         outputs = self.model(
             input_ids=input_ids,
             attention_mask=attention_mask,

filename: src/transformers/models/modernbert/modular_modernbert.py
patch: @@ -1277,6 +1277,19 @@ def forward(
         return_dict = return_dict if return_dict is not None else self.config.use_return_dict
         self._maybe_set_compile()
 
+        if input_ids is not None:
+            self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+
+        if batch_size is None and seq_len is None:
+            if inputs_embeds is not None:
+                batch_size, seq_len = inputs_embeds.shape[:2]
+            else:
+                batch_size, seq_len = input_ids.shape[:2]
+        device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+        if attention_mask is None:
+            attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
+
         outputs = self.model(
             input_ids=input_ids,
             attention_mask=attention_mask,
Repository: denoland/deno
Pull request: ci: disable symcache generation on Windows, part 2

Follow up to https://github.com/denoland/deno/pull/30646

Changed files:
filename: .github/workflows/ci.generate.ts
patch: @@ -760,7 +760,7 @@ const ci = {
         {
           name: "Generate symcache",
           if: [
-            "(matrix.job == 'test' || matrix.job == 'bench') &&",
+            "(matrix.job == 'test' || matrix.job == 'bench' && matrix.os != 'windows') &&",
             "matrix.profile == 'release' && (matrix.use_sysroot ||",
             "github.repository == 'denoland/deno')",
           ].join("\n"),

filename: .github/workflows/ci.yml
patch: @@ -443,7 +443,7 @@ jobs:
         run: 'sudo chroot /sysroot "$(pwd)/target/${{ matrix.profile }}/deno" --version'
       - name: Generate symcache
         if: |-
-          !(matrix.skip) && ((matrix.job == 'test' || matrix.job == 'bench') &&
+          !(matrix.skip) && ((matrix.job == 'test' || matrix.job == 'bench' && matrix.os != 'windows') &&
           matrix.profile == 'release' && (matrix.use_sysroot ||
           github.repository == 'denoland/deno'))
         run: |-
Repository: facebook/react
Pull request: Jest: remove haste config

Since we're not using haste at all, we can just remove the config to disable haste instead of enabling, just to inject an implementation that blocks any haste modules from being recognized.

Test Plan:
Creating a module and required it to get the expected error that the module doesn't exist.

Changed files:
filename: scripts/jest/config.base.js
patch: @@ -2,9 +2,6 @@
 
 module.exports = {
   globalSetup: require.resolve('./setupGlobal.js'),
-  haste: {
-    hasteImplModulePath: require.resolve('./noHaste.js'),
-  },
   modulePathIgnorePatterns: [
     '<rootDir>/scripts/rollup/shims/',
     '<rootDir>/scripts/bench/',

filename: scripts/jest/noHaste.js
patch: @@ -1,8 +0,0 @@
-'use strict';
-
-module.exports = {
-  getHasteName() {
-    // We never want Haste.
-    return null;
-  },
-};
Repository: ollama/ollama
Pull request: ordered list of install locations

select install dir based what's in the PATH. if `/usr/local/bin` is in the path, install into there, otherwise `/usr/bin` or `/bin`, in order

Changed files:
filename: scripts/install.sh
patch: @@ -54,9 +54,13 @@ fi
 status "Downloading ollama..."
 curl --fail --show-error --location --progress-bar -o $TEMP_DIR/ollama "https://ollama.ai/download/ollama-linux-$ARCH"
 
-status "Installing ollama to /usr/bin..."
-$SUDO install -o0 -g0 -m755 -d /usr/bin
-$SUDO install -o0 -g0 -m755 $TEMP_DIR/ollama /usr/bin/ollama
+for BINDIR in /usr/local/bin /usr/bin /bin; do
+    echo $PATH | grep -q $BINDIR && break || continue
+done
+
+status "Installing ollama to $BINDIR..."
+$SUDO install -o0 -g0 -m755 -d $BINDIR
+$SUDO install -o0 -g0 -m755 $TEMP_DIR/ollama $BINDIR/ollama
 
 install_success() { status 'Install complete. Run "ollama" from the command line.'; }
 trap install_success EXIT
@@ -76,7 +80,7 @@ Description=Ollama Service
 After=network-online.target
 
 [Service]
-ExecStart=/usr/bin/ollama serve
+ExecStart=$BINDIR/ollama serve
 User=ollama
 Group=ollama
 Restart=always
Repository: ollama/ollama
Pull request: prune empty directories

Resolves #270

Changed files:
filename: cmd/cmd.go
patch: @@ -745,6 +745,15 @@ func RunServer(cmd *cobra.Command, _ []string) error {
 		if err := server.PruneLayers(); err != nil {
 			return err
 		}
+
+		manifestsPath, err := server.GetManifestPath()
+		if err != nil {
+			return err
+		}
+
+		if err := server.PruneDirectory(manifestsPath); err != nil {
+			return err
+		}
 	}
 
 	return server.Serve(ln, origins)

filename: server/images.go
patch: @@ -1005,6 +1005,39 @@ func PruneLayers() error {
 	return nil
 }
 
+func PruneDirectory(path string) error {
+	info, err := os.Lstat(path)
+	if err != nil {
+		return err
+	}
+
+	if info.IsDir() && info.Mode()&os.ModeSymlink == 0 {
+		entries, err := os.ReadDir(path)
+		if err != nil {
+			return err
+		}
+
+		for _, entry := range entries {
+			if err := PruneDirectory(filepath.Join(path, entry.Name())); err != nil {
+				return err
+			}
+		}
+
+		entries, err = os.ReadDir(path)
+		if err != nil {
+			return err
+		}
+
+		if len(entries) > 0 {
+			return nil
+		}
+
+		return os.Remove(path)
+	}
+
+	return nil
+}
+
 func DeleteModel(name string) error {
 	mp := ParseModelPath(name)
 	manifest, _, err := GetManifest(mp)

filename: server/routes.go
patch: @@ -378,6 +378,18 @@ func DeleteModelHandler(c *gin.Context) {
 		}
 		return
 	}
+
+	manifestsPath, err := GetManifestPath()
+	if err != nil {
+		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+		return
+	}
+
+	if err := PruneDirectory(manifestsPath); err != nil {
+		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+		return
+	}
+
 	c.JSON(http.StatusOK, nil)
 }
Repository: ollama/ollama
Pull request: windows runner fixes

- use filepath for runner files
- get embedded files with unix filepath
- runner is only available is embedded directories have files

Changed files:
filename: llm/llama.go
patch: @@ -64,27 +64,29 @@ func chooseRunners(workDir, runnerType string) []ModelRunner {
 	runnerAvailable := false // if no runner files are found in the embed, this flag will cause a fast fail
 	for _, r := range runners {
 		// find all the files in the runner's bin directory
-		files, err := fs.Glob(llamaCppEmbed, filepath.Join(filepath.Dir(r), "*"))
+		files, err := fs.Glob(llamaCppEmbed, path.Join(path.Dir(r), "*"))
 		if err != nil {
 			// this is expected, ollama may be compiled without all runners packed in
 			log.Printf("%s runner not found: %v", r, err)
 			continue
 		}
-		runnerAvailable = true
 
 		for _, f := range files {
+			runnerAvailable = true
+
 			srcFile, err := llamaCppEmbed.Open(f)
 			if err != nil {
 				log.Fatalf("read llama runner %s: %v", f, err)
 			}
 			defer srcFile.Close()
 
-			// create the directory in case it does not exist
+			// create the directory in case it does not exist, filepath.Dir() converts the file path to the OS's format
 			destPath := filepath.Join(workDir, filepath.Dir(f))
 			if err := os.MkdirAll(destPath, 0o755); err != nil {
 				log.Fatalf("create runner temp dir %s: %v", filepath.Dir(f), err)
 			}
 
+			// create the path to the destination file, filepath.Base() converts the file path to the OS's format
 			destFile := filepath.Join(destPath, filepath.Base(f))
 
 			_, err = os.Stat(destFile)
@@ -111,7 +113,8 @@ func chooseRunners(workDir, runnerType string) []ModelRunner {
 	// return the runners to try in priority order
 	localRunnersByPriority := []ModelRunner{}
 	for _, r := range runners {
-		localRunnersByPriority = append(localRunnersByPriority, ModelRunner{Path: path.Join(workDir, r)})
+		// clean the ModelRunner paths so that they match the OS we are running on
+		localRunnersByPriority = append(localRunnersByPriority, ModelRunner{Path: filepath.Clean(path.Join(workDir, r))})
 	}
 
 	return localRunnersByPriority
Repository: denoland/deno
Pull request: feat(ext/node): add sqlite-type symbol for DatabaseSync

Related: https://github.com/nodejs/node/commit/d1eabcb044a448ea2ff106fb1ec3814341867235
Related: https://github.com/nodejs/node/pull/59405
Related: https://github.com/better-auth/better-auth/pull/3869
Related: https://github.com/oven-sh/bun/pull/22109

Nowadays, there are tons of database packages, like sqlite3, sqlite, better-sqlite, bun:sqlite... Checking the difference from them is pretty hard.
instanceof is not good, since the developer will still need to import the module, which is costly.
 I think we should provide a symbol to distinguish different SQLite classes, at least nodejs could make the first step

This symbol could help with lots of duplicate properties checking, like https://github.com/kysely-org/kysely, https://github.com/knex/knex

It helps the library author to write an adapter for a different SQLite library. Right now, the library is checking the prototype method to determine whether it's node:sqlite, bun:sqlite, or better-sqlite... It was a lot of performance, and it's not stable as the API could change

https://github.com/better-auth/better-auth/blob/375e9f3ced6f3842c133f4cae689cb2a604ba94a/packages/better-auth/src/adapters/kysely-adapter/dialect.ts#L53-L109

I hope there's an easy way. like a symbol tag, to determine the user's land SQLite lib

Changed files:
filename: ext/node/polyfills/sqlite.ts
patch: @@ -1,7 +1,13 @@
 // Copyright 2018-2025 the Deno authors. MIT license.
 
+import { primordials } from "ext:core/mod.js";
 import { DatabaseSync, StatementSync } from "ext:core/ops";
 
+const {
+  ObjectDefineProperty,
+  SymbolFor,
+} = primordials;
+
 export const constants = {
   SQLITE_CHANGESET_OMIT: 0,
   SQLITE_CHANGESET_REPLACE: 1,
@@ -14,6 +20,14 @@ export const constants = {
   SQLITE_CHANGESET_FOREIGN_KEY: 5,
 };
 
+const sqliteTypeSymbol = SymbolFor("sqlite-type");
+ObjectDefineProperty(DatabaseSync.prototype, sqliteTypeSymbol, {
+  __proto__: null,
+  value: "node:sqlite",
+  enumerable: false,
+  configurable: true,
+});
+
 export { DatabaseSync, StatementSync };
 
 export default {

filename: tests/unit_node/sqlite_test.ts
patch: @@ -4,6 +4,16 @@ import { assert, assertEquals, assertThrows } from "@std/assert";
 
 const tempDir = Deno.makeTempDirSync();
 
+Deno.test("[node/sqlite] sqlite-type symbol", () => {
+  const db = new DatabaseSync(":memory:");
+  const sqliteTypeSymbol = Symbol.for("sqlite-type");
+
+  // @ts-ignore `sqliteTypeSymbol` is not available in `@types:node` for version 24.3
+  assertEquals(db[sqliteTypeSymbol], "node:sqlite");
+
+  db.close();
+});
+
 Deno.test("[node/sqlite] in-memory databases", () => {
   const db1 = new DatabaseSync(":memory:");
   const db2 = new DatabaseSync(":memory:");
Repository: vercel/next.js
Pull request: [devtools] Shim overlay on server

That huge module isn't needed for SSR.

Mirror what Webpack does:
https://github.com/vercel/next.js/blob/b07a315ca945c12e60dae7caa02dcbc924452945/packages/next/next-runtime.webpack-config.js#L82-L83

Before:
<img width="2055" height="386" alt="Bildschirmfoto 2025-08-19 um 18 13 39" src="https://github.com/user-attachments/assets/f9bbbcc7-4030-4889-ae39-49d25d5a6651" />

After:
<img width="2123" height="332" alt="Bildschirmfoto 2025-08-19 um 18 12 50" src="https://github.com/user-attachments/assets/d7e3b96d-7908-41ad-be60-5bae1354e658" />


Closes PACK-5286

Changed files:
filename: crates/next-core/src/next_import_map.rs
patch: @@ -806,6 +806,14 @@ async fn insert_next_server_special_aliases(
         ),
     );
 
+    import_map.insert_exact_alias(
+        rcstr!("next/dist/compiled/next-devtools"),
+        request_to_import_mapping(
+            project_path.clone(),
+            rcstr!("next/dist/next-devtools/dev-overlay.shim.js"),
+        ),
+    );
+
     Ok(())
 }
 

filename: packages/next/src/build/create-compiler-aliases.ts
patch: @@ -126,6 +126,10 @@ export function createWebpackAliases({
     'styled-jsx/style$': defaultOverrides['styled-jsx/style'],
     'styled-jsx$': defaultOverrides['styled-jsx'],
 
+    'next/dist/compiled/next-devtools': isClient
+      ? 'next/dist/compiled/next-devtools'
+      : 'next/dist/next-devtools/dev-overlay.shim.js',
+
     ...customAppAliases,
     ...customDocumentAliases,
Repository: ollama/ollama
Pull request: allow the user to cancel generating with ctrl-C

The change allows the user to cancel generating using Ctrl-C in the REPL. It handles both the cases where the request is canceled before the stream starts back, as well as when the request is streaming.

It also changes the REPL so that you can't accidentally hit Ctrl-C and exit the REPL. Instead it will prompt the user to use Ctrl-D or `/bye` instead.

Changed files:
filename: cmd/cmd.go
patch: @@ -13,9 +13,11 @@ import (
 	"net"
 	"os"
 	"os/exec"
+	"os/signal"
 	"path/filepath"
 	"runtime"
 	"strings"
+	"syscall"
 	"time"
 
 	"github.com/dustin/go-humanize"
@@ -43,7 +45,7 @@ func (p Painter) Paint(line []rune, _ int) []rune {
 		if p.IsMultiLine {
 			prompt = "Use \"\"\" to end multi-line input"
 		} else {
-			prompt = "Send a message (/? for help, /bye to exit)"
+			prompt = "Send a message (/? for help)"
 		}
 		return []rune(fmt.Sprintf("\033[38;5;245m%s\033[%dD\033[0m", prompt, len(prompt)))
 	}
@@ -426,6 +428,19 @@ func generate(cmd *cobra.Command, model, prompt string) error {
 		wrapTerm = false
 	}
 
+	cancelCtx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+
+	sigChan := make(chan os.Signal, 1)
+	signal.Notify(sigChan, syscall.SIGINT)
+	var abort bool
+
+	go func() {
+		<-sigChan
+		cancel()
+		abort = true
+	}()
+
 	var currentLineLength int
 	var wordBuffer string
 
@@ -465,7 +480,7 @@ func generate(cmd *cobra.Command, model, prompt string) error {
 		return nil
 	}
 
-	if err := client.Generate(context.Background(), &request, fn); err != nil {
+	if err := client.Generate(cancelCtx, &request, fn); err != nil {
 		if strings.Contains(err.Error(), "failed to load model") {
 			// tell the user to check the server log, if it exists locally
 			home, nestedErr := os.UserHomeDir()
@@ -477,6 +492,9 @@ func generate(cmd *cobra.Command, model, prompt string) error {
 			if _, nestedErr := os.Stat(logPath); nestedErr == nil {
 				err = fmt.Errorf("%w\nFor more details, check the error logs at %s", err, logPath)
 			}
+		} else if strings.Contains(err.Error(), "context canceled") && abort {
+			spinner.Finish()
+			return nil
 		}
 		return err
 	}
@@ -486,6 +504,9 @@ func generate(cmd *cobra.Command, model, prompt string) error {
 	}
 
 	if !latest.Done {
+		if abort {
+			return nil
+		}
 		return errors.New("unexpected end of response")
 	}
 
@@ -568,7 +589,7 @@ func generateInteractive(cmd *cobra.Command, model string) error {
 			return nil
 		case errors.Is(err, readline.ErrInterrupt):
 			if line == "" {
-				return nil
+				fmt.Println("Use Ctrl-D or /bye to exit.")
 			}
 
 			continue
Repository: ollama/ollama
Pull request: Added missing return preventing SIGSEGV because of missing resp

Closes #619 

Changed files:
filename: cmd/cmd.go
patch: @@ -647,6 +647,7 @@ func generateInteractive(cmd *cobra.Command, model string) error {
 				resp, err := server.GetModelInfo(model)
 				if err != nil {
 					fmt.Println("error: couldn't get model")
+					return err
 				}
 
 				switch args[1] {
Repository: ollama/ollama
Pull request: fix error messages for unknown commands in the repl


Changed files:
filename: cmd/cmd.go
patch: @@ -635,6 +635,8 @@ func generateInteractive(cmd *cobra.Command, model string) error {
 					} else {
 						usage()
 					}
+				default:
+					fmt.Printf("Unknown command '/set %s'. Type /? for help\n", args[1])
 				}
 			} else {
 				usage()
@@ -659,7 +661,7 @@ func generateInteractive(cmd *cobra.Command, model string) error {
 				case "template":
 					fmt.Println(resp.Template)
 				default:
-					fmt.Println("error: unknown command")
+					fmt.Printf("Unknown command '/show %s'. Type /? for help\n", args[1])
 				}
 			} else {
 				usage()
Repository: ggml-org/llama.cpp
Pull request: ggml-alloc : make gallocr prefer chunks that allow memory reuse

Small improvement to graph allocation with multiple buffers/chunks:

In the case where a tensor is allocated, and no free block fits, the current implementation allocates additional memory in the first chunk that can fit the tensor into the max size. The last block can contain both reusable (previously allocated then freed) memory, as well as memory not allocated yet. This PR prioritizes chunks with reusable memory that fits the tensor to reduce total allocation size.

See #16759 for an example.

Vulkan compute buffer size for `llama-bench --model llama-2-7b.Q4_0.gguf --n-gpu-layers 19 --ubatch-size 512`:

| n-prompt | master | PR |
|--|--|--|
|  `--n-prompt 12200` | 1003.88 MiB | 1003.88 MiB |
|  `--n-prompt 12500` | **1711.19 MiB** | **1026.94 MiB** |
|  `--n-prompt 13500` | **1844.88 MiB** | **1106.38 MiB** |
|  `--n-prompt 14500` | 1188.38 MiB | 1188.38 MiB |
| `--n-prompt 15500`  | 1267.81 MiB | 1267.81 MiB |

I tested some other models and they show similar behavior around the 1024 MiB threshold.

Changed files:
filename: ggml/src/ggml-alloc.c
patch: @@ -226,16 +226,23 @@ static struct buffer_address ggml_dyn_tallocr_alloc(struct ggml_dyn_tallocr * al
     }
 
     if (best_fit_block == -1) {
-        // no suitable block found, try the last block (this will grow a chunks size)
+        // no suitable block found, try the last block (this may grow a chunks size)
+        int64_t best_reuse = INT64_MIN;
         for (int c = 0; c < alloc->n_chunks; ++c) {
             struct tallocr_chunk * chunk = alloc->chunks[c];
             if (chunk->n_free_blocks > 0) {
                 struct free_block * block = &chunk->free_blocks[chunk->n_free_blocks - 1];
                 max_avail = MAX(max_avail, block->size);
-                if (block->size >= size) {
+                int64_t reuse_factor = chunk->max_size - block->offset - size;
+                // reuse_factor < 0 : amount of extra memory that needs to be allocated
+                // reuse_factor = 0 : allocated free space exactly matches tensor size
+                // reuse_factor > 0 : superfluous memory that will remain unused
+                bool better_reuse = best_reuse < 0 && reuse_factor > best_reuse;
+                bool better_fit = reuse_factor >= 0 && reuse_factor < best_reuse;
+                if (block->size >= size && (better_reuse || better_fit)) {
                     best_fit_chunk = c;
                     best_fit_block = chunk->n_free_blocks - 1;
-                    break;
+                    best_reuse = reuse_factor;
                 }
             }
         }
@@ -268,7 +275,7 @@ static struct buffer_address ggml_dyn_tallocr_alloc(struct ggml_dyn_tallocr * al
 #ifdef GGML_ALLOCATOR_DEBUG
     add_allocated_tensor(alloc, addr, tensor);
     size_t cur_max = addr.offset + size;
-    if (cur_max > alloc->max_size[addr.chunk]) {
+    if (cur_max > chunk->max_size) {
         // sort allocated_tensors by chunk/offset
         for (int i = 0; i < 1024; i++) {
             for (int j = i + 1; j < 1024; j++) {
Repository: electron/electron
Pull request: fix: zlib pointer alignment

Backport of #46435

See that PR for details.


Notes: Fixes a possible crash using Node.js on some arm32 devices.

Changed files:
filename: patches/node/.patches
patch: @@ -48,3 +48,4 @@ feat_add_oom_error_callback_in_node_isolatesettings.patch
 fix_-wnonnull_warning.patch
 refactor_attach_cppgc_heap_on_v8_isolate_creation.patch
 fix_ensure_traverseparent_bails_on_resource_path_exit.patch
+zlib_fix_pointer_alignment.patch

filename: patches/node/zlib_fix_pointer_alignment.patch
patch: @@ -0,0 +1,50 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Jeroen Hofstee <jhofstee@victronenergy.com>
+Date: Tue, 1 Apr 2025 20:09:31 +0000
+Subject: zlib: fix pointer alignment
+
+The function AllocForBrotli prefixes the allocated memory with its
+size, and returns a pointer to the region after it. This pointer can
+however no longer be suitably aligned. Correct this by allocating
+the maximum of the the size of the size_t and the max alignment.
+
+On Arm 32bits the size_t is 4 bytes long, but the alignment is 8 for
+some NEON instructions. When Brotli is compiled with optimizations
+enabled newer GCC versions will use the NEON instructions and trigger
+a bus error killing node.
+
+see https://github.com/google/brotli/issues/1159
+
+diff --git a/src/node_zlib.cc b/src/node_zlib.cc
+index 90307cd4984ae5aa55386f2980ad9cd540322dfd..6f12b5034d1a98da50c064cf2cfdf12fc88137eb 100644
+--- a/src/node_zlib.cc
++++ b/src/node_zlib.cc
+@@ -493,7 +493,8 @@ class CompressionStream : public AsyncWrap, public ThreadPoolWork {
+   }
+ 
+   static void* AllocForBrotli(void* data, size_t size) {
+-    size += sizeof(size_t);
++    constexpr size_t offset = std::max(sizeof(size_t), alignof(max_align_t));
++    size += offset;
+     CompressionStream* ctx = static_cast<CompressionStream*>(data);
+     char* memory = UncheckedMalloc(size);
+     if (memory == nullptr) [[unlikely]] {
+@@ -502,7 +503,7 @@ class CompressionStream : public AsyncWrap, public ThreadPoolWork {
+     *reinterpret_cast<size_t*>(memory) = size;
+     ctx->unreported_allocations_.fetch_add(size,
+                                            std::memory_order_relaxed);
+-    return memory + sizeof(size_t);
++    return memory + offset;
+   }
+ 
+   static void FreeForZlib(void* data, void* pointer) {
+@@ -510,7 +511,8 @@ class CompressionStream : public AsyncWrap, public ThreadPoolWork {
+       return;
+     }
+     CompressionStream* ctx = static_cast<CompressionStream*>(data);
+-    char* real_pointer = static_cast<char*>(pointer) - sizeof(size_t);
++    constexpr size_t offset = std::max(sizeof(size_t), alignof(max_align_t));
++    char* real_pointer = static_cast<char*>(pointer) - offset;
+     size_t real_size = *reinterpret_cast<size_t*>(real_pointer);
+     ctx->unreported_allocations_.fetch_sub(real_size,
+                                            std::memory_order_relaxed);