diff --git a/.gitignore b/.gitignore index 1f32eac746..4d65f7193e 100644 --- a/.gitignore +++ b/.gitignore @@ -95,3 +95,10 @@ iOSInjectionProject/ .idea .vscode +# Claude +.claude/ + +# Benchmark writer state sidecars. The markdown reports in benchmarks/ are +# committed as baselines; the JSON state is local-only so the writer can +# re-render the markdown across processes within a single sweep. +benchmarks/.*.state.json \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e1fbe678ed..69b7dbb497 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,11 +14,44 @@ possible. You can also run the formatters manually as follows: ``` - swift-format format --in-place --recursive Libraries Tools Applications + swift-format format --in-place --recursive Libraries Tools Applications IntegrationTesting ``` or run `pre-commit run --all-files` to check all files in the repo. +## Running Tests + +Unit tests run without any special hardware and do not download models. +Note: `swift test` [does not work yet](https://github.com/ml-explore/mlx-swift?tab=readme-ov-file#xcodebuild) — use `xcodebuild` instead: + +```bash +xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' +``` + +Integration tests verify end-to-end model loading and generation. They require +macOS with Metal and download models from Hugging Face Hub on first run. These +tests do not run in CI. + +Open `IntegrationTesting/IntegrationTesting.xcodeproj` in Xcode and run the +test target (`Cmd+U` or via the Test Navigator), or use `xcodebuild`: + +```bash +# Run all integration tests +xcodebuild test \ + -project IntegrationTesting/IntegrationTesting.xcodeproj \ + -scheme IntegrationTesting \ + -destination 'platform=macOS' + +# Run a single test +xcodebuild test \ + -project IntegrationTesting/IntegrationTesting.xcodeproj \ + -scheme IntegrationTesting \ + -destination 'platform=macOS' \ + -only-testing:IntegrationTestingTests/ToolCallIntegrationTests/qwen35FormatAutoDetection\(\) +``` + +See [Libraries/IntegrationTestHelpers/README.md](Libraries/IntegrationTestHelpers/README.md) for more details. + ## Issues We use GitHub issues to track public bugs. Please ensure your description is diff --git a/IntegrationTesting/IntegrationTesting.xcodeproj/project.pbxproj b/IntegrationTesting/IntegrationTesting.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..fbd35dedf3 --- /dev/null +++ b/IntegrationTesting/IntegrationTesting.xcodeproj/project.pbxproj @@ -0,0 +1,586 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + 57408EB82F82A947001E2121 /* HuggingFace in Frameworks */ = {isa = PBXBuildFile; productRef = 57408EB72F82A947001E2121 /* HuggingFace */; }; + 57408EBC2F82A947001E2121 /* Tokenizers in Frameworks */ = {isa = PBXBuildFile; productRef = 57408EBB2F82A947001E2121 /* Tokenizers */; }; + 57408EE32F82B8FB001E2121 /* MLXLMCommon in Frameworks */ = {isa = PBXBuildFile; productRef = 57408EE22F82B8FB001E2121 /* MLXLMCommon */; }; + 57408EE52F82B8FB001E2121 /* MLXVLM in Frameworks */ = {isa = PBXBuildFile; productRef = 57408EE42F82B8FB001E2121 /* MLXVLM */; }; + 578E559D2F82A3B9001FEF6B /* IntegrationTesting.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 578E55932F82A3B9001FEF6B /* IntegrationTesting.framework */; }; + 57DEAED72F83CB0A0050B4ED /* BenchmarkHelpers in Frameworks */ = {isa = PBXBuildFile; productRef = 57DEAED62F83CB0A0050B4ED /* BenchmarkHelpers */; }; + 57DEAED92F83CB0A0050B4ED /* IntegrationTestHelpers in Frameworks */ = {isa = PBXBuildFile; productRef = 57DEAED82F83CB0A0050B4ED /* IntegrationTestHelpers */; }; + 57DEAEDB2F83CB0A0050B4ED /* MLXEmbedders in Frameworks */ = {isa = PBXBuildFile; productRef = 57DEAEDA2F83CB0A0050B4ED /* MLXEmbedders */; }; + 57DEAEDD2F83CB0A0050B4ED /* MLXHuggingFace in Frameworks */ = {isa = PBXBuildFile; productRef = 57DEAEDC2F83CB0A0050B4ED /* MLXHuggingFace */; }; + 57DEAEDF2F83CB0A0050B4ED /* MLXLLM in Frameworks */ = {isa = PBXBuildFile; productRef = 57DEAEDE2F83CB0A0050B4ED /* MLXLLM */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 578E559E2F82A3B9001FEF6B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 578E558A2F82A3B9001FEF6B /* Project object */; + proxyType = 1; + remoteGlobalIDString = 578E55922F82A3B9001FEF6B; + remoteInfo = IntegrationTesting; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 578E55932F82A3B9001FEF6B /* IntegrationTesting.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = IntegrationTesting.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 578E559C2F82A3B9001FEF6B /* IntegrationTestingTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = IntegrationTestingTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 578E55952F82A3B9001FEF6B /* IntegrationTesting */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = IntegrationTesting; + sourceTree = ""; + }; + 578E55A02F82A3B9001FEF6B /* IntegrationTestingTests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = IntegrationTestingTests; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 578E55902F82A3B9001FEF6B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 578E55992F82A3B9001FEF6B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 57DEAEDF2F83CB0A0050B4ED /* MLXLLM in Frameworks */, + 57408EBC2F82A947001E2121 /* Tokenizers in Frameworks */, + 57DEAEDD2F83CB0A0050B4ED /* MLXHuggingFace in Frameworks */, + 57DEAED72F83CB0A0050B4ED /* BenchmarkHelpers in Frameworks */, + 578E559D2F82A3B9001FEF6B /* IntegrationTesting.framework in Frameworks */, + 57DEAED92F83CB0A0050B4ED /* IntegrationTestHelpers in Frameworks */, + 57408EE52F82B8FB001E2121 /* MLXVLM in Frameworks */, + 57DEAEDB2F83CB0A0050B4ED /* MLXEmbedders in Frameworks */, + 57408EE32F82B8FB001E2121 /* MLXLMCommon in Frameworks */, + 57408EB82F82A947001E2121 /* HuggingFace in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 57408EB62F82A947001E2121 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; + 578E55892F82A3B9001FEF6B = { + isa = PBXGroup; + children = ( + 578E55952F82A3B9001FEF6B /* IntegrationTesting */, + 578E55A02F82A3B9001FEF6B /* IntegrationTestingTests */, + 57408EB62F82A947001E2121 /* Frameworks */, + 578E55942F82A3B9001FEF6B /* Products */, + ); + sourceTree = ""; + }; + 578E55942F82A3B9001FEF6B /* Products */ = { + isa = PBXGroup; + children = ( + 578E55932F82A3B9001FEF6B /* IntegrationTesting.framework */, + 578E559C2F82A3B9001FEF6B /* IntegrationTestingTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 578E558E2F82A3B9001FEF6B /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 578E55922F82A3B9001FEF6B /* IntegrationTesting */ = { + isa = PBXNativeTarget; + buildConfigurationList = 578E55A52F82A3B9001FEF6B /* Build configuration list for PBXNativeTarget "IntegrationTesting" */; + buildPhases = ( + 578E558E2F82A3B9001FEF6B /* Headers */, + 578E558F2F82A3B9001FEF6B /* Sources */, + 578E55902F82A3B9001FEF6B /* Frameworks */, + 578E55912F82A3B9001FEF6B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 578E55952F82A3B9001FEF6B /* IntegrationTesting */, + ); + name = IntegrationTesting; + packageProductDependencies = ( + ); + productName = IntegrationTesting; + productReference = 578E55932F82A3B9001FEF6B /* IntegrationTesting.framework */; + productType = "com.apple.product-type.framework"; + }; + 578E559B2F82A3B9001FEF6B /* IntegrationTestingTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 578E55A82F82A3B9001FEF6B /* Build configuration list for PBXNativeTarget "IntegrationTestingTests" */; + buildPhases = ( + 578E55982F82A3B9001FEF6B /* Sources */, + 578E55992F82A3B9001FEF6B /* Frameworks */, + 578E559A2F82A3B9001FEF6B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 578E559F2F82A3B9001FEF6B /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + 578E55A02F82A3B9001FEF6B /* IntegrationTestingTests */, + ); + name = IntegrationTestingTests; + packageProductDependencies = ( + 57408EB72F82A947001E2121 /* HuggingFace */, + 57408EBB2F82A947001E2121 /* Tokenizers */, + 57408EE22F82B8FB001E2121 /* MLXLMCommon */, + 57408EE42F82B8FB001E2121 /* MLXVLM */, + 57DEAED62F83CB0A0050B4ED /* BenchmarkHelpers */, + 57DEAED82F83CB0A0050B4ED /* IntegrationTestHelpers */, + 57DEAEDA2F83CB0A0050B4ED /* MLXEmbedders */, + 57DEAEDC2F83CB0A0050B4ED /* MLXHuggingFace */, + 57DEAEDE2F83CB0A0050B4ED /* MLXLLM */, + ); + productName = IntegrationTestingTests; + productReference = 578E559C2F82A3B9001FEF6B /* IntegrationTestingTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 578E558A2F82A3B9001FEF6B /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2630; + LastUpgradeCheck = 2630; + TargetAttributes = { + 578E55922F82A3B9001FEF6B = { + CreatedOnToolsVersion = 26.3; + }; + 578E559B2F82A3B9001FEF6B = { + CreatedOnToolsVersion = 26.3; + }; + }; + }; + buildConfigurationList = 578E558D2F82A3B9001FEF6B /* Build configuration list for PBXProject "IntegrationTesting" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 578E55892F82A3B9001FEF6B; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + 57408EAC2F82A8F0001E2121 /* XCRemoteSwiftPackageReference "swift-huggingface" */, + 57408EAF2F82A90E001E2121 /* XCRemoteSwiftPackageReference "swift-transformers" */, + 57DEAED52F83CB0A0050B4ED /* XCLocalSwiftPackageReference ".." */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = 578E55942F82A3B9001FEF6B /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 578E55922F82A3B9001FEF6B /* IntegrationTesting */, + 578E559B2F82A3B9001FEF6B /* IntegrationTestingTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 578E55912F82A3B9001FEF6B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 578E559A2F82A3B9001FEF6B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 578E558F2F82A3B9001FEF6B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 578E55982F82A3B9001FEF6B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 578E559F2F82A3B9001FEF6B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 578E55922F82A3B9001FEF6B /* IntegrationTesting */; + targetProxy = 578E559E2F82A3B9001FEF6B /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 578E55A32F82A3B9001FEF6B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 15.7; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 578E55A42F82A3B9001FEF6B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 15.7; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 578E55A62F82A3B9001FEF6B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUILD_LIBRARY_FOR_DISTRIBUTION = YES; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; + PRODUCT_BUNDLE_IDENTIFIER = mlx.IntegrationTesting; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_INSTALL_MODULE = YES; + SWIFT_INSTALL_OBJC_HEADER = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 578E55A72F82A3B9001FEF6B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUILD_LIBRARY_FOR_DISTRIBUTION = YES; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_MODULE_VERIFIER = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; + PRODUCT_BUNDLE_IDENTIFIER = mlx.IntegrationTesting; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_INSTALL_MODULE = YES; + SWIFT_INSTALL_OBJC_HEADER = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 578E55A92F82A3B9001FEF6B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = mlx.IntegrationTestingTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 578E55AA2F82A3B9001FEF6B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = mlx.IntegrationTestingTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 578E558D2F82A3B9001FEF6B /* Build configuration list for PBXProject "IntegrationTesting" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 578E55A32F82A3B9001FEF6B /* Debug */, + 578E55A42F82A3B9001FEF6B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 578E55A52F82A3B9001FEF6B /* Build configuration list for PBXNativeTarget "IntegrationTesting" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 578E55A62F82A3B9001FEF6B /* Debug */, + 578E55A72F82A3B9001FEF6B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 578E55A82F82A3B9001FEF6B /* Build configuration list for PBXNativeTarget "IntegrationTestingTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 578E55A92F82A3B9001FEF6B /* Debug */, + 578E55AA2F82A3B9001FEF6B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 57DEAED52F83CB0A0050B4ED /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 57408EAC2F82A8F0001E2121 /* XCRemoteSwiftPackageReference "swift-huggingface" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/huggingface/swift-huggingface"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 0.9.0; + }; + }; + 57408EAF2F82A90E001E2121 /* XCRemoteSwiftPackageReference "swift-transformers" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/huggingface/swift-transformers"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.3.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 57408EB72F82A947001E2121 /* HuggingFace */ = { + isa = XCSwiftPackageProductDependency; + package = 57408EAC2F82A8F0001E2121 /* XCRemoteSwiftPackageReference "swift-huggingface" */; + productName = HuggingFace; + }; + 57408EBB2F82A947001E2121 /* Tokenizers */ = { + isa = XCSwiftPackageProductDependency; + package = 57408EAF2F82A90E001E2121 /* XCRemoteSwiftPackageReference "swift-transformers" */; + productName = Tokenizers; + }; + 57408EE22F82B8FB001E2121 /* MLXLMCommon */ = { + isa = XCSwiftPackageProductDependency; + productName = MLXLMCommon; + }; + 57408EE42F82B8FB001E2121 /* MLXVLM */ = { + isa = XCSwiftPackageProductDependency; + productName = MLXVLM; + }; + 57DEAED62F83CB0A0050B4ED /* BenchmarkHelpers */ = { + isa = XCSwiftPackageProductDependency; + productName = BenchmarkHelpers; + }; + 57DEAED82F83CB0A0050B4ED /* IntegrationTestHelpers */ = { + isa = XCSwiftPackageProductDependency; + productName = IntegrationTestHelpers; + }; + 57DEAEDA2F83CB0A0050B4ED /* MLXEmbedders */ = { + isa = XCSwiftPackageProductDependency; + productName = MLXEmbedders; + }; + 57DEAEDC2F83CB0A0050B4ED /* MLXHuggingFace */ = { + isa = XCSwiftPackageProductDependency; + productName = MLXHuggingFace; + }; + 57DEAEDE2F83CB0A0050B4ED /* MLXLLM */ = { + isa = XCSwiftPackageProductDependency; + productName = MLXLLM; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 578E558A2F82A3B9001FEF6B /* Project object */; +} diff --git a/IntegrationTesting/IntegrationTesting.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/IntegrationTesting/IntegrationTesting.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000000..919434a625 --- /dev/null +++ b/IntegrationTesting/IntegrationTesting.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/IntegrationTesting/IntegrationTesting.xcodeproj/xcshareddata/xcschemes/IntegrationTesting.xcscheme b/IntegrationTesting/IntegrationTesting.xcodeproj/xcshareddata/xcschemes/IntegrationTesting.xcscheme new file mode 100644 index 0000000000..a1bea13f44 --- /dev/null +++ b/IntegrationTesting/IntegrationTesting.xcodeproj/xcshareddata/xcschemes/IntegrationTesting.xcscheme @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/IntegrationTesting/IntegrationTesting/IntegrationTesting.swift b/IntegrationTesting/IntegrationTesting/IntegrationTesting.swift new file mode 100644 index 0000000000..6d108fac7b --- /dev/null +++ b/IntegrationTesting/IntegrationTesting/IntegrationTesting.swift @@ -0,0 +1,5 @@ +// Copyright © 2026 Apple Inc. + +import Foundation + +public struct IntegrationTesting {} diff --git a/IntegrationTesting/IntegrationTestingTests/ToolCallIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/ToolCallIntegrationTests.swift new file mode 100644 index 0000000000..42aae454b2 --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/ToolCallIntegrationTests.swift @@ -0,0 +1,93 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import HuggingFace +import IntegrationTestHelpers +import MLXHuggingFace +import MLXLMCommon +import Testing +import Tokenizers + +private let models = IntegrationTestModels( + downloader: #hubDownloader(), + tokenizerLoader: #huggingFaceTokenizerLoader() +) + +@Suite(.serialized) +struct ToolCallIntegrationTests { + + // MARK: - LFM2 + + @Test func lfm2FormatAutoDetection() async throws { + let container = try await models.lfm2Container() + try await ToolCallTests.lfm2FormatAutoDetection(container: container) + } + + @Test func lfm2EndToEnd() async throws { + let container = try await models.lfm2Container() + try await ToolCallTests.lfm2EndToEndGeneration(container: container) + } + + // MARK: - GLM4 + + @Test func glm4FormatAutoDetection() async throws { + let container = try await models.glm4Container() + try await ToolCallTests.glm4FormatAutoDetection(container: container) + } + + @Test func glm4EndToEnd() async throws { + let container = try await models.glm4Container() + try await ToolCallTests.glm4EndToEndGeneration(container: container) + } + + // MARK: - Mistral3 + + @Test func mistral3FormatAutoDetection() async throws { + let container = try await models.mistral3Container() + try await ToolCallTests.mistral3FormatAutoDetection(container: container) + } + + @Test func mistral3EndToEnd() async throws { + let container = try await models.mistral3Container() + try await ToolCallTests.mistral3EndToEndGeneration(container: container) + } + + @Test func mistral3MultiTool() async throws { + let container = try await models.mistral3Container() + try await ToolCallTests.mistral3MultiToolGeneration(container: container) + } + + // MARK: - Nemotron + + @Test func nemotronFormatAutoDetection() async throws { + let container = try await models.nemotronContainer() + try await ToolCallTests.nemotronFormatAutoDetection(container: container) + } + + @Test func nemotronEndToEnd() async throws { + let container = try await models.nemotronContainer() + try await ToolCallTests.nemotronEndToEndGeneration(container: container) + } + + @Test func nemotronMultiTool() async throws { + let container = try await models.nemotronContainer() + try await ToolCallTests.nemotronMultiToolGeneration(container: container) + } + + // MARK: - Qwen3.5 + + @Test func qwen35FormatAutoDetection() async throws { + let container = try await models.qwen35Container() + try await ToolCallTests.qwen35FormatAutoDetection(container: container) + } + + @Test func qwen35EndToEnd() async throws { + let container = try await models.qwen35Container() + try await ToolCallTests.qwen35EndToEndGeneration(container: container) + } + + @Test func qwen35MultiTool() async throws { + let container = try await models.qwen35Container() + try await ToolCallTests.qwen35MultiToolGeneration(container: container) + } +} diff --git a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift index ed4089134d..53c7744e24 100644 --- a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift +++ b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift @@ -35,6 +35,9 @@ public enum IntegrationTestModelIDs { public static let vlm = "mlx-community/Qwen3-VL-4B-Instruct-4bit" public static let lfm2 = "mlx-community/LFM2-2.6B-Exp-4bit" public static let glm4 = "mlx-community/GLM-4-9B-0414-4bit" + public static let mistral3 = "mlx-community/Ministral-3-3B-Instruct-2512-4bit" + public static let nemotron = "mlx-community/NVIDIA-Nemotron-3-Nano-30B-A3B-4bit" + public static let qwen35 = "mlx-community/Qwen3.5-2B-4bit" } // MARK: - Model Loading @@ -48,6 +51,9 @@ public actor IntegrationTestModels { private var vlmTask: Task? private var lfm2Task: Task? private var glm4Task: Task? + private var mistral3Task: Task? + private var nemotronTask: Task? + private var qwen35Task: Task? public init(downloader: any Downloader, tokenizerLoader: any TokenizerLoader) { self.downloader = downloader @@ -138,6 +144,69 @@ public actor IntegrationTestModels { return try await task.value } + public func mistral3Container() async throws -> LMModelContainer { + if let task = mistral3Task { + return try await task.value + } + let downloader = self.downloader + let tokenizerLoader = self.tokenizerLoader + let id = IntegrationTestModelIDs.mistral3 + let task = Task { + print("Loading Mistral3: \(id)") + let container = try await LLMModelFactory.shared.loadContainer( + from: downloader, using: tokenizerLoader, + configuration: .init(id: id), + progressHandler: logProgress(id) + ) + print("Loaded Mistral3: \(id)") + return container + } + mistral3Task = task + return try await task.value + } + + public func nemotronContainer() async throws -> LMModelContainer { + if let task = nemotronTask { + return try await task.value + } + let downloader = self.downloader + let tokenizerLoader = self.tokenizerLoader + let id = IntegrationTestModelIDs.nemotron + let task = Task { + print("Loading Nemotron: \(id)") + let container = try await LLMModelFactory.shared.loadContainer( + from: downloader, using: tokenizerLoader, + configuration: .init(id: id), + progressHandler: logProgress(id) + ) + print("Loaded Nemotron: \(id)") + return container + } + nemotronTask = task + return try await task.value + } + + public func qwen35Container() async throws -> LMModelContainer { + if let task = qwen35Task { + return try await task.value + } + let downloader = self.downloader + let tokenizerLoader = self.tokenizerLoader + let id = IntegrationTestModelIDs.qwen35 + let task = Task { + print("Loading Qwen3.5: \(id)") + let container = try await LLMModelFactory.shared.loadContainer( + from: downloader, using: tokenizerLoader, + configuration: .init(id: id), + progressHandler: logProgress(id) + ) + print("Loaded Qwen3.5: \(id)") + return container + } + qwen35Task = task + return try await task.value + } + public func embeddingContainer() async throws -> EmbeddingModelContainer { let downloader = self.downloader let tokenizerLoader = self.tokenizerLoader @@ -470,6 +539,8 @@ public enum EmbedderTests { public enum ToolCallTests { + // MARK: LFM2 + public static func lfm2FormatAutoDetection(container: LMModelContainer) async throws { let config = await container.configuration try check( @@ -486,21 +557,23 @@ public enum ToolCallTests { print("LFM2 Output:", result) print("LFM2 Tool Calls:", toolCalls) - if !toolCalls.isEmpty { - let toolCall = toolCalls[0] - try check( - toolCall.function.name == "get_weather", - "Expected tool name 'get_weather', got: \(toolCall.function.name)" - ) - if case .string(let location) = toolCall.function.arguments["location"] { - try check( - location.lowercased().contains("tokyo"), - "Expected location containing 'Tokyo', got: \(location)" - ) - } + try check(!toolCalls.isEmpty, "Expected at least one tool call, got none") + let toolCall = toolCalls[0] + try check( + toolCall.function.name == "get_weather", + "Expected tool name 'get_weather', got: \(toolCall.function.name)" + ) + guard case .string(let location) = toolCall.function.arguments["location"] else { + throw IntegrationTestFailure("Expected string 'location' argument") } + try check( + location.lowercased().contains("tokyo"), + "Expected location containing 'Tokyo', got: \(location)" + ) } + // MARK: GLM4 + public static func glm4FormatAutoDetection(container: LMModelContainer) async throws { let config = await container.configuration try check( @@ -517,42 +590,257 @@ public enum ToolCallTests { print("GLM4 Output:", result) print("GLM4 Tool Calls:", toolCalls) - if !toolCalls.isEmpty { - let toolCall = toolCalls[0] + try check(!toolCalls.isEmpty, "Expected at least one tool call, got none") + let toolCall = toolCalls[0] + try check( + toolCall.function.name == "get_weather", + "Expected tool name 'get_weather', got: \(toolCall.function.name)" + ) + guard case .string(let location) = toolCall.function.arguments["location"] else { + throw IntegrationTestFailure("Expected string 'location' argument") + } + try check( + location.lowercased().contains("paris"), + "Expected location containing 'Paris', got: \(location)" + ) + } + + // MARK: Mistral3 + + public static func mistral3FormatAutoDetection(container: LMModelContainer) async throws { + let config = await container.configuration + try check( + config.toolCallFormat == ToolCallFormat.mistral, + "Expected .mistral tool call format, got: \(String(describing: config.toolCallFormat))" + ) + } + + public static func mistral3EndToEndGeneration(container: LMModelContainer) async throws { + let input = UserInput( + chat: [ + .system( + "You are a helpful assistant with access to tools. When asked about weather, use the get_weather function." + ), + .user("What's the weather in Tokyo?"), + ], + tools: [weatherToolSchema] + ) + + let (result, toolCalls) = try await generateWithTools( + container: container, input: input, maxTokens: 150) + + print("Mistral3 Output:", result) + print("Mistral3 Tool Calls:", toolCalls) + + try check(!toolCalls.isEmpty, "Expected at least one tool call, got none") + let toolCall = toolCalls[0] + try check( + toolCall.function.name == "get_weather", + "Expected tool name 'get_weather', got: \(toolCall.function.name)" + ) + guard case .string(let location) = toolCall.function.arguments["location"] else { + throw IntegrationTestFailure("Expected string 'location' argument") + } + try check( + location.lowercased().contains("tokyo"), + "Expected location containing 'Tokyo', got: \(location)" + ) + } + + public static func mistral3MultiToolGeneration(container: LMModelContainer) async throws { + let input = UserInput( + chat: [ + .system( + "You are a helpful assistant with access to tools. Always use the available tools to answer questions. Call multiple tools in parallel when needed." + ), + .user("What's the weather in Tokyo and what time is it there?"), + ], + tools: multiToolSchemas + ) + + let (result, toolCalls) = try await generateWithTools( + container: container, input: input, maxTokens: 150) + + print("Mistral3 Output:", result) + print("Mistral3 Calls:", toolCalls) + + let validNames: Set = ["get_weather", "get_time"] + for toolCall in toolCalls { try check( - toolCall.function.name == "get_weather", - "Expected tool name 'get_weather', got: \(toolCall.function.name)" + validNames.contains(toolCall.function.name), + "Unexpected tool call: \(toolCall.function.name)" ) - if case .string(let location) = toolCall.function.arguments["location"] { - try check( - location.lowercased().contains("paris"), - "Expected location containing 'Paris', got: \(location)" - ) - } } + + try check( + toolCalls.count > 1, + "Expected multiple tool calls, got \(toolCalls.count)" + ) + } + + // MARK: Nemotron + + public static func nemotronFormatAutoDetection(container: LMModelContainer) async throws { + let config = await container.configuration + try check( + config.toolCallFormat == ToolCallFormat.xmlFunction, + "Expected .xmlFunction tool call format, got: \(String(describing: config.toolCallFormat))" + ) + } + + public static func nemotronEndToEndGeneration(container: LMModelContainer) async throws { + let input = UserInput( + chat: [ + .system( + "You are a helpful assistant with access to tools. When asked about weather, use the get_weather function." + ), + .user("What's the weather in Tokyo?"), + ], + tools: [weatherToolSchema], + additionalContext: ["enable_thinking": false] + ) + + let (result, toolCalls) = try await generateWithTools( + container: container, input: input, maxTokens: 150) + + print("Nemotron Output:", result) + print("Nemotron Tool Calls:", toolCalls) + + try check(!toolCalls.isEmpty, "Expected at least one tool call, got none") + let toolCall = toolCalls[0] + try check( + toolCall.function.name == "get_weather", + "Expected tool name 'get_weather', got: \(toolCall.function.name)" + ) + guard case .string(let location) = toolCall.function.arguments["location"] else { + throw IntegrationTestFailure("Expected string 'location' argument") + } + try check( + location.lowercased().contains("tokyo"), + "Expected location containing 'Tokyo', got: \(location)" + ) + } + + public static func nemotronMultiToolGeneration(container: LMModelContainer) async throws { + let input = UserInput( + chat: [ + .system( + "You are a helpful assistant with access to tools. Always use the available tools to answer questions. Call multiple tools in parallel when needed." + ), + .user("What's the weather in Tokyo and what time is it there?"), + ], + tools: multiToolSchemas, + additionalContext: ["enable_thinking": false] + ) + + let (result, toolCalls) = try await generateWithTools( + container: container, input: input, maxTokens: 600) + + print("Nemotron Output:", result) + print("Nemotron Calls:", toolCalls) + + let validNames: Set = ["get_weather", "get_time"] + for toolCall in toolCalls { + try check( + validNames.contains(toolCall.function.name), + "Unexpected tool call: \(toolCall.function.name)" + ) + } + + try check( + toolCalls.count > 1, + "Expected multiple tool calls, got \(toolCalls.count)" + ) } + // MARK: Qwen3.5 + + public static func qwen35FormatAutoDetection(container: LMModelContainer) async throws { + let config = await container.configuration + try check( + config.toolCallFormat == ToolCallFormat.xmlFunction, + "Expected .xmlFunction tool call format, got: \(String(describing: config.toolCallFormat))" + ) + } + + public static func qwen35EndToEndGeneration(container: LMModelContainer) async throws { + let input = UserInput( + chat: [ + .system( + "You are a helpful assistant with access to tools. When asked about weather, use the get_weather function." + ), + .user("What's the weather in Tokyo?"), + ], + tools: [weatherToolSchema] + ) + + let (result, toolCalls) = try await generateWithTools( + container: container, input: input, maxTokens: 150) + + print("Qwen3.5 Output:", result) + print("Qwen3.5 Tool Calls:", toolCalls) + + try check(!toolCalls.isEmpty, "Expected at least one tool call, got none") + let toolCall = toolCalls[0] + try check( + toolCall.function.name == "get_weather", + "Expected tool name 'get_weather', got: \(toolCall.function.name)" + ) + guard case .string(let location) = toolCall.function.arguments["location"] else { + throw IntegrationTestFailure("Expected string 'location' argument") + } + try check( + location.lowercased().contains("tokyo"), + "Expected location containing 'Tokyo', got: \(location)" + ) + } + + public static func qwen35MultiToolGeneration(container: LMModelContainer) async throws { + let input = UserInput( + chat: [ + .system( + "You are a helpful assistant with access to tools. Always use the available tools to answer questions. Call multiple tools in parallel when needed." + ), + .user("What's the weather in Tokyo and what time is it there?"), + ], + tools: multiToolSchemas, + additionalContext: ["enable_thinking": true] + ) + + let (result, toolCalls) = try await generateWithTools( + container: container, input: input, maxTokens: 300) + + print("Qwen3.5 Output:", result) + print("Qwen3.5 Calls:", toolCalls) + + let validNames: Set = ["get_weather", "get_time"] + for toolCall in toolCalls { + try check( + validNames.contains(toolCall.function.name), + "Unexpected tool call: \(toolCall.function.name)" + ) + } + + try check( + toolCalls.count > 1, + "Expected multiple tool calls, got \(toolCalls.count)" + ) + } + + // MARK: Helpers + private static func generateWithTools( container: LMModelContainer, - userMessage: String + input: UserInput, + maxTokens: Int = 100 ) async throws -> (text: String, toolCalls: [ToolCall]) { - try await container.perform { context in - let input = UserInput( - chat: [ - .system( - "You are a helpful assistant with access to tools. When asked about weather, use the get_weather function." - ), - .user(userMessage), - ], - tools: [weatherToolSchema] - ) + try await container.perform(nonSendable: input) { context, input in let lmInput = try await context.processor.prepare(input: input) let stream = try generate( input: lmInput, - parameters: GenerateParameters(maxTokens: 100), + parameters: GenerateParameters(maxTokens: maxTokens), context: context ) - var text = "" var toolCalls: [ToolCall] = [] for try await generation in stream { @@ -568,6 +856,23 @@ public enum ToolCallTests { return (text, toolCalls) } } + + private static func generateWithTools( + container: LMModelContainer, + userMessage: String + ) async throws -> (text: String, toolCalls: [ToolCall]) { + let input = UserInput( + chat: [ + .system( + "You are a helpful assistant with access to tools. When asked about weather, use the get_weather function." + ), + .user(userMessage), + ], + tools: [weatherToolSchema] + ) + return try await generateWithTools( + container: container, input: input) + } } // MARK: - Progress Logging @@ -612,3 +917,23 @@ private let weatherToolSchema: ToolSpec = [ ] as [String: any Sendable], ] as [String: any Sendable], ] + +private let timeToolSchema: ToolSpec = [ + "type": "function", + "function": [ + "name": "get_time", + "description": "Get the current time in a given timezone", + "parameters": [ + "type": "object", + "properties": [ + "timezone": [ + "type": "string", + "description": "The timezone, e.g. America/New_York, Asia/Tokyo", + ] as [String: any Sendable] + ] as [String: any Sendable], + "required": ["timezone"], + ] as [String: any Sendable], + ] as [String: any Sendable], +] + +private let multiToolSchemas: [ToolSpec] = [weatherToolSchema, timeToolSchema] diff --git a/Libraries/IntegrationTestHelpers/README.md b/Libraries/IntegrationTestHelpers/README.md index 39ec6ff140..d050c66758 100644 --- a/Libraries/IntegrationTestHelpers/README.md +++ b/Libraries/IntegrationTestHelpers/README.md @@ -2,9 +2,32 @@ `IntegrationTestHelpers` and `BenchmarkHelpers` provide shared test logic for verifying end-to-end model loading, inference, tokenizer performance, and download performance. They are designed to be used by integration packages that supply their own `Downloader` and `TokenizerLoader` implementations. -## Integration packages +## Running integration tests locally + +The `IntegrationTesting/IntegrationTesting.xcodeproj` Xcode project in this repo uses [Swift Hugging Face](https://github.com/huggingface/swift-huggingface) and [Swift Transformers](https://github.com/huggingface/swift-transformers) via the `MLXHuggingFace` macros to provide `Downloader` and `TokenizerLoader` implementations. Models are downloaded from Hugging Face Hub on first run and cached in `~/.cache/huggingface/`. + +To run integration tests, open `IntegrationTesting/IntegrationTesting.xcodeproj` in Xcode and run the test target (`Cmd+U` or via the Test Navigator), or use `xcodebuild`: + +```bash +# Run all integration tests (requires macOS with Metal) +xcodebuild test \ + -project IntegrationTesting/IntegrationTesting.xcodeproj \ + -scheme IntegrationTesting \ + -destination 'platform=macOS' + +# Run a single test +xcodebuild test \ + -project IntegrationTesting/IntegrationTesting.xcodeproj \ + -scheme IntegrationTesting \ + -destination 'platform=macOS' \ + -only-testing:IntegrationTestingTests/ToolCallIntegrationTests/qwen35FormatAutoDetection\(\) +``` + +These tests do not run in CI. + +## External integration packages + +Integration tests and benchmarks can also be run from external packages: - [Swift Tokenizers MLX](https://github.com/DePasqualeOrg/swift-tokenizers-mlx): Uses [Swift Tokenizers](https://github.com/DePasqualeOrg/swift-tokenizers) and [Swift HF API](https://github.com/DePasqualeOrg/swift-hf-api) - [Swift Transformers MLX](https://github.com/DePasqualeOrg/swift-transformers-mlx): Uses [Swift Transformers](https://github.com/huggingface/swift-transformers) and [Swift Hugging Face](https://github.com/huggingface/swift-huggingface) - -Integration tests and benchmarks are run from those packages. diff --git a/Libraries/MLXLLM/LLMModel.swift b/Libraries/MLXLLM/LLMModel.swift index d686b7ef7d..e25cb5efe1 100644 --- a/Libraries/MLXLLM/LLMModel.swift +++ b/Libraries/MLXLLM/LLMModel.swift @@ -16,22 +16,43 @@ extension LLMModel { /// Default prepare step for ``LLMModel``. /// - /// This will evaluate the prompt in chunks until there is a small number of - /// tokens left to feed into the `TokenIterator`. + /// Matches Python mlx-lm's `generate_step` prefill loop: process every + /// prompt token except the LAST one through chunked prefill (with + /// `eval(cache)` + `clearCache()` between chunks). The trailing token is + /// returned to the iterator's "primes the pump" call. public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws -> PrepareResult { let prefillStepSize = windowSize ?? 512 var y = input.text - // Prepare the prompt in chunks if larger than the prefill size - while y.tokens.size > prefillStepSize { - let input = y[.newAxis, .. 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. PrepareResult + { + let prefillStepSize = max(windowSize ?? 512, 2048) + var y = input.text + + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. [any KVCache] { var caches: [KVCache] = [] for lt in model.layerTypes { if lt == "full_attention" { - caches.append(StandardKVCache()) + if let maxKVSize = parameters?.maxKVSize { + // Bound full-attention KV cache to prevent unbounded growth + // in multi-turn sessions. keep: 4 preserves attention sink tokens. + caches.append(RotatingKVCache(maxSize: maxKVSize, keep: 4)) + } else { + caches.append(StandardKVCache()) + } } else { caches.append( RotatingKVCache(maxSize: configuration.slidingWindow, keep: 0) diff --git a/Libraries/MLXLLM/Models/GatedDelta.swift b/Libraries/MLXLLM/Models/GatedDelta.swift index 7ddf39cba9..d5938720a9 100644 --- a/Libraries/MLXLLM/Models/GatedDelta.swift +++ b/Libraries/MLXLLM/Models/GatedDelta.swift @@ -12,8 +12,9 @@ import MLXNN // MARK: - Compute G func computeGatedDeltaG(_ aLog: MLXArray, _ a: MLXArray, _ dtBias: MLXArray) -> MLXArray { - let decay = exp(-exp(aLog.asType(.float32)) * softplus(a + dtBias)) - return decay.asType(a.dtype) + // Stay in model dtype (bf16) — no fp32 promotion needed. + // The double-exp is numerically safe in bf16 for the typical aLog range (-1 to -8). + return exp(-exp(aLog) * softplus(a + dtBias)) } // MARK: - Metal Kernel @@ -86,7 +87,7 @@ private func makeGatedDeltaKernel(hasMask: Bool) -> MLXFast.MLXFastKernel? { } for (int i = 0; i < n_per_t; ++i) { auto s_idx = n_per_t * dk_idx + i; - o_state[s_idx] = static_cast(state[i]); + o_state[s_idx] = static_cast(state[i]); } """ @@ -135,6 +136,7 @@ func gatedDeltaKernel( let Hv = v.dim(2) let Dv = v.dim(3) let inputType = q.dtype + let stateType = state.dtype let selectedKernel: MLXFast.MLXFastKernel? var inputs: [MLXArray] = [q, k, v, g, beta, state, MLXArray(T)] @@ -153,6 +155,7 @@ func gatedDeltaKernel( inputs, template: [ ("InT", inputType), + ("StT", stateType), ("Dk", Dk), ("Dv", Dv), ("Hk", Hk), @@ -161,7 +164,7 @@ func gatedDeltaKernel( grid: (32, Dv, B * Hv), threadGroup: (32, 4, 1), outputShapes: [[B, T, Hv, Dv], state.shape], - outputDTypes: [inputType, inputType] + outputDTypes: [inputType, stateType] ) return (outputs[0], outputs[1]) @@ -238,6 +241,17 @@ func gatedDeltaOps( var state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: q.dtype) + // Process in sub-chunks with eval barriers to bound peak memory. + // Without this, the lazy graph grows to T * (intermediates per step), + // causing peak memory proportional to T during prefill. + // + // 128 beats 64 by ~20% on Qwen3.6-35B-A3B prefill (297 vs 247 tok/s at + // ctx=1024 on M5 Max) with no increase in GPU peak memory. The 64-token + // cadence was syncing the GPU pipeline too aggressively (30 GDN layers + // × 8 syncs per 512-token chunk = 240 syncs per prefill chunk). Still + // overridable via GDN_EVAL_INTERVAL for experimentation. + let evalInterval = + Int(ProcessInfo.processInfo.environment["GDN_EVAL_INTERVAL"] ?? "") ?? 128 var ys = [MLXArray]() ys.reserveCapacity(T) @@ -260,14 +274,82 @@ func gatedDeltaOps( ) ys.append(y) state = newState + + // Eval barrier: materialize state and accumulated outputs to free + // intermediate graph nodes. Caps graph at O(evalInterval) instead of O(T). + if T > 1 && (t + 1) % evalInterval == 0 { + eval(state) + eval(ys) + MLX.Memory.clearCache() + } } let y = MLX.stacked(ys, axis: 1) return (y, state) } +// MARK: - Fused framework kernel dispatch + +/// Fused MLXFast.gatedDeltaStepFused wrapper: takes RAW (unnormalized) q, k and +/// computes rmsNorm, g = exp(-exp(aLog)*softplus(a+dtBias)), beta = sigmoid(b) +/// inside the Metal kernel. Eliminates ~4-6 separate dispatches per call +/// compared to computing norms/gates on the Swift side. +private func fusedGatedDeltaKernel( + qRaw: MLXArray, + kRaw: MLXArray, + v: MLXArray, + a: MLXArray, + b: MLXArray, + aLog: MLXArray, + dtBias: MLXArray, + state: MLXArray, + mask: MLXArray? = nil +) -> (MLXArray, MLXArray) { + let T = kRaw.dim(1) + let Hk = kRaw.dim(2) + let Dk = kRaw.dim(3) + let Hv = v.dim(2) + let Dv = v.dim(3) + + let outputs = MLXFast.gatedDeltaStepFused( + qRaw: qRaw, kRaw: kRaw, v: v, + a: a, bInput: b, aLog: aLog, dtBias: dtBias, + state: state, mask: mask, + T: T, Dk: Dk, Dv: Dv, Hk: Hk, Hv: Hv) + return (outputs[0], outputs[1]) +} + // MARK: - Public API +/// Fused entry point: takes RAW (unnormalized) q, k and absorbs rmsNorm, g, beta +/// into the Metal kernel. Call this from the model layer instead of +/// ``gatedDeltaUpdate`` when rmsNorm + g/beta computation can be fused. +/// +/// Falls back to the ops-based path if the framework kernel is unavailable. +func fusedGatedDeltaUpdate( + qRaw: MLXArray, + kRaw: MLXArray, + v: MLXArray, + a: MLXArray, + b: MLXArray, + aLog: MLXArray, + dtBias: MLXArray, + state: MLXArray? = nil, + mask: MLXArray? = nil +) -> (MLXArray, MLXArray) { + let B = qRaw.dim(0) + let Dk = qRaw.dim(3) + let Hv = v.dim(2) + let Dv = v.dim(3) + + let state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: qRaw.dtype) + + return fusedGatedDeltaKernel( + qRaw: qRaw, kRaw: kRaw, v: v, + a: a, b: b, aLog: aLog, dtBias: dtBias, + state: state, mask: mask) +} + func gatedDeltaUpdate( q: MLXArray, k: MLXArray, @@ -287,11 +369,16 @@ func gatedDeltaUpdate( let Hv = v.dim(2) let Dv = v.dim(3) - let state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: q.dtype) - - if GatedDeltaKernelManager.shared.kernel != nil { - return gatedDeltaKernel(q: q, k: k, v: v, g: g, beta: beta, state: state, mask: mask) + // State kept in fp32 (matches Python mlx-lm). Previously Swift used q.dtype + // (bf16) for state, which lost precision across the T-step recurrence and + // was the reason the Metal kernel was flagged "correctness bug at T>1" + // (~0.25 max diff). With fp32 state, the kernel path is correct AND much + // faster: one Metal dispatch for all T timesteps instead of a Swift-side + // T-loop. + var state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: .float32) + if state.dtype != .float32 { + state = state.asType(.float32) } - return gatedDeltaOps(q: q, k: k, v: v, g: g, beta: beta, state: state, mask: mask) + return gatedDeltaKernel(q: q, k: k, v: v, g: g, beta: beta, state: state, mask: mask) } diff --git a/Libraries/MLXLLM/Models/Gemma3nText.swift b/Libraries/MLXLLM/Models/Gemma3nText.swift index 727aeb1227..0738df05d4 100644 --- a/Libraries/MLXLLM/Models/Gemma3nText.swift +++ b/Libraries/MLXLLM/Models/Gemma3nText.swift @@ -801,7 +801,9 @@ public class Gemma3nLanguageModel: Module { h = inputsEmbeds } else if let inputs { h = embedTokens(inputs) - h = (h * MLXArray(_embedTokensScale, dtype: .float32)).asType(h.dtype) + // Use bare Float scalar to avoid fp32 promotion. The explicit + // .float32 + .asType round-trip adds 2 needless AsType dispatches. + h = h * _embedTokensScale } else { fatalError("Either inputs or inputsEmbeds must be provided") } @@ -915,8 +917,8 @@ public class Gemma3nLanguageModel: Module { ) let tokens = MLX.where(perLayerInputsMask, inputIds, MLXArray.zeros(like: inputIds)) var result = embedTokensPerLayer(tokens) - result = (result * MLXArray(_embedTokensPerLayerScale, dtype: .float32)).asType( - result.dtype) + // Use bare Float scalar to avoid fp32 promotion (see Gemma3n PLE fix). + result = result * _embedTokensPerLayerScale result = result.reshaped( Array(inputIds.shape) + [config.numHiddenLayers, config.hiddenSizePerLayerInput] ) diff --git a/Libraries/MLXLLM/Models/Gemma4.swift b/Libraries/MLXLLM/Models/Gemma4.swift new file mode 100644 index 0000000000..2709c4bb8d --- /dev/null +++ b/Libraries/MLXLLM/Models/Gemma4.swift @@ -0,0 +1,1315 @@ +// +// Gemma4.swift +// mlx-swift-lm +// +// Created by Claude on 2026/4/6. +// + +// Port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/gemma4_text.py + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +// MARK: - Gemma Prefill Bridge (C++ dylib via dlopen) + +/// Lazy-loaded bridge to native C++ prefill. +/// Uses dlopen to load the bridge dylib, avoiding SPM's link-time optimization +/// which miscompiles quantized_matmul. The dylib uses -undefined dynamic_lookup +/// to share the host's MLX allocator (no dual-allocator OOM). +/// +/// Activated by setting NATIVE_PREFILL=1 environment variable. +private final class GemmaPrefillBridge: @unchecked Sendable { + nonisolated(unsafe) static let shared = GemmaPrefillBridge() + + private var handle: UnsafeMutableRawPointer? + private var initialized = false + + // Function pointer types matching the C API + private typealias InitFn = @convention(c) (Int32, Int32, Int32, Int32, Int32, Int32) -> Int32 + private typealias SetWeightFn = @convention(c) (UnsafePointer, UnsafeMutableRawPointer) -> Int32 + private typealias FinalizeFn = @convention(c) () -> Int32 + private typealias RunFn = @convention(c) (UnsafePointer, Int32, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 + private typealias RunArrayFn = @convention(c) (UnsafeMutableRawPointer, UnsafeMutablePointer, UnsafeMutablePointer) -> Int32 + private typealias GetKVFn = @convention(c) (Int32, UnsafeMutablePointer, UnsafeMutablePointer) -> Void + private typealias NumLayersFn = @convention(c) () -> Int32 + + // Resolved symbols + private var fnInit: InitFn? + private var fnSetWeight: SetWeightFn? + private var fnFinalize: FinalizeFn? + private var fnRun: RunFn? + private var fnRunArray: RunArrayFn? + private var fnGetKV: GetKVFn? + private var fnNumLayers: NumLayersFn? + + private func loadDylib() -> Bool { + if handle != nil { return true } + let searchPaths = [ + Bundle.main.executableURL?.deletingLastPathComponent() + .appendingPathComponent("libprefill_bridge_gemma.dylib").path, + "Sources/NativePrefillBridge/libprefill_bridge_gemma.dylib", + ".build/arm64-apple-macosx/release/libprefill_bridge_gemma.dylib", + ].compactMap { $0 } + + for path in searchPaths { + if let h = dlopen(path, RTLD_NOW) { + handle = h + print("[GemmaPrefill] Loaded dylib: \(path)") + break + } + } + guard let h = handle else { + print("[GemmaPrefill] dylib not found. Run: ./scripts/build-prefill-bridge.sh") + return false + } + + fnInit = unsafeBitCast(dlsym(h, "gemma_init"), to: InitFn.self) + fnSetWeight = unsafeBitCast(dlsym(h, "gemma_set_weight"), to: SetWeightFn.self) + fnFinalize = unsafeBitCast(dlsym(h, "gemma_finalize"), to: FinalizeFn.self) + fnRun = unsafeBitCast(dlsym(h, "gemma_run"), to: RunFn.self) + fnRunArray = unsafeBitCast(dlsym(h, "gemma_run_array"), to: RunArrayFn.self) + fnGetKV = unsafeBitCast(dlsym(h, "gemma_get_kv_handles"), to: GetKVFn.self) + fnNumLayers = unsafeBitCast(dlsym(h, "gemma_num_layers"), to: NumLayersFn.self) + return true + } + + func ensureInitialized(model: Gemma4ModelInner, config: Gemma4TextConfiguration) -> Bool { + if initialized { return true } + guard loadDylib(), let fnInit, let fnSetWeight, let fnFinalize, let fnRun else { return false } + + let pattern = config.layerTypes.prefix(while: { $0 != "full_attention" }).count + 1 + let nonShared = config.hiddenLayers - config.numKvSharedLayers + let rc = fnInit( + Int32(nonShared), Int32(config.hiddenSize), + Int32(config.attentionHeads), Int32(config.kvHeads), + Int32(config.slidingWindow), Int32(pattern)) + if rc != 0 { print("[GemmaPrefill] init failed"); return false } + + let params = model.parameters().flattened() + var weightCount = 0 + for (key, arr) in params { + let rawPtr = arr.ctx.ctx + let status = key.withCString { cKey in + fnSetWeight(cKey, rawPtr!) + } + if status == 0 { weightCount += 1 } + } + print("[GemmaPrefill] Passed \(weightCount) weights") + + let finRC = fnFinalize() + if finRC != 0 { print("[GemmaPrefill] finalize failed"); return false } + + initialized = true + print("[GemmaPrefill] Initialized") + + // Pre-warm + do { + var warmMs: Double = 0; var warmCk: Float = 0 + let warmTokens: [Int32] = [1, 2, 3, 4] + warmTokens.withUnsafeBufferPointer { buf in + let _ = fnRun(buf.baseAddress!, 4, &warmMs, &warmCk) + } + print(String(format: "[GemmaPrefill] Pre-warmed in %.0fms", warmMs)) + } + + return true + } + + func run(tokenIds: [Int32]) -> (elapsedMs: Double, checksum: Float)? { + guard initialized, let fnRun else { return nil } + var ms: Double = 0 + var ck: Float = 0 + let rc = tokenIds.withUnsafeBufferPointer { buf in + fnRun(buf.baseAddress!, Int32(buf.count), &ms, &ck) + } + return rc == 0 ? (ms, ck) : nil + } + + func runZeroCopy(tokenArray: MLXArray) -> (elapsedMs: Double, checksum: Float)? { + guard initialized, let fnRunArray else { return nil } + var ms: Double = 0 + var ck: Float = 0 + let rc = fnRunArray(tokenArray.ctx.ctx, &ms, &ck) + return rc == 0 ? (ms, ck) : nil + } + + /// Run native prefill and inject K/V into Swift caches. + /// Returns (elapsed_ms, success). Caches are populated on success. + func runAndInjectKV(tokenArray: MLXArray, cache: [KVCache], numLayers: Int) -> (Double, Bool) { + guard initialized else { return (0, false) } + + // Run native prefill — zero-copy, token array stays on GPU + guard let result = runZeroCopy(tokenArray: tokenArray) else { return (0, false) } + + // Zero-copy K/V injection: gemma_get_kv_handles creates heap-allocated + // mlx::core::array copies (via `new array(attn.last_k)`) that share the + // underlying GPU data buffer via shared_ptr. No memcpy of tensor data. + // MLXArray.fromCppArray() wraps the pointer, taking ownership. + for i in 0.. ( + values: MLXArray, indices: MLXArray +) { + let partitionedIndices = argPartition(a, kth: -k, axis: axis) + let topKIndices = partitionedIndices[.ellipsis, (-k)...] + let topKValues = takeAlong(a, topKIndices, axis: axis) + return (topKValues, topKIndices) +} + +// v_norm uses MLXFast.rmsNorm with a ones weight (no learnable scale). +// This fuses the 3-dispatch manual implementation (square, mean, rsqrt*mul) +// into a single optimized kernel dispatch. + +// MARK: - ProportionalRoPE + +/// Proportional RoPE: rotates `rotatedDims` out of `dims` dimensions, using the +/// FULL `dims` for both frequency computation and dimension pairing. +/// +/// Matches Python's `ProportionalRoPE` in `rope_utils.py`. +/// +/// **Why this exists:** `RoPE(dimensions: 128)` on a 512-dim head pairs `(x[0], x[64])`, +/// `(x[1], x[65])`, etc. — within the first 128 dims. But the model weights were trained +/// with `ProportionalRoPE(dims=512, rotatedDims=128)` which pairs `(x[0], x[256])`, +/// `(x[1], x[257])`, etc. — across the first and second halves of the full 512-dim head. +/// Non-rotated dimensions get `inf` frequency → zero rotation → pass-through. +class ProportionalRoPE: Module, OffsetLayer { + let dims: Int + let traditional: Bool + let _freqs: MLXArray + + init(dims: Int, rotatedDims: Int, traditional: Bool = false, base: Float, factor: Float = 1.0) { + precondition(rotatedDims <= dims, "rotatedDims must be ≤ dims") + self.dims = dims + self.traditional = traditional + + // Exponents use the FULL dims as denominator (the "proportional" aspect) + let exponents = MLXArray( + stride(from: Float(0), to: Float(rotatedDims), by: 2) + ) / Float(dims) + let realFreqs = factor * pow(MLXArray(base), exponents) + + // Pad with inf for non-rotated pairs (zero rotation angle per position) + let paddingCount = (dims - rotatedDims) / 2 + let infPadding = MLXArray(Array(repeating: Float.infinity, count: paddingCount)) + self._freqs = concatenated([realFreqs, infPadding], axis: 0) + + super.init() + } + + func callAsFunction(_ x: MLXArray, offset: Int) -> MLXArray { + MLXFast.RoPE( + x, dimensions: dims, traditional: traditional, base: nil, + scale: 1.0, offset: offset, freqs: _freqs) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + callAsFunction(x, offset: 0) + } +} + +// MARK: - Attention + +class Gemma4Attention: Module { + let isSliding: Bool + let attentionKEqV: Bool + let nHeads: Int + let nKVHeads: Int + let repeats: Int + let headDim: Int + let scale: Float + + @ModuleInfo(key: "q_proj") var qProj: Linear + // Always has k_proj. When attention_k_eq_v and NOT sliding, values = keys (no v_proj). + // When attention_k_eq_v is False OR this is a sliding layer, v_proj is separate. + @ModuleInfo(key: "k_proj") var kProj: Linear + @ModuleInfo(key: "v_proj") var vProj: Linear? + @ModuleInfo(key: "o_proj") var oProj: Linear + + + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + @ModuleInfo(key: "k_norm") var kNorm: RMSNorm + + let rmsNormEps: Float + let rope: any OffsetLayer + + // Inverse frequencies for fused RMSNorm + RoPE (MLXFast.rmsNormRoPE framework kernel). + // Computed at init, not loaded from checkpoint. Underscore prefix prevents + // Module weight loading from looking for this key in the checkpoint. + let _fusedInvFreqs: MLXArray? + + /// Set GEMMA4_FUSED_NORM_ROPE=0 to disable for A/B testing. + private static let useFusedNormRoPE: Bool = { + ProcessInfo.processInfo.environment["GEMMA4_FUSED_NORM_ROPE"] != "0" + }() + + init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + self.isSliding = config.layerTypes[layerIdx] == "sliding_attention" + // attention_k_eq_v only applies to non-sliding (global) layers + self.attentionKEqV = config.attentionKEqV && !isSliding + + self.nHeads = config.attentionHeads + + if isSliding { + self.headDim = config.headDim + self.nKVHeads = config.kvHeads + } else { + self.headDim = config.globalHeadDim + self.nKVHeads = config.globalKvHeads + } + + self.repeats = nHeads / nKVHeads + // Gemma4 uses scale=1.0, NOT 1/sqrt(head_dim) + self.scale = 1.0 + + let dim = config.hiddenSize + self._qProj.wrappedValue = Linear(dim, nHeads * headDim, bias: false) + // k_proj always exists; v_proj only when NOT using k_eq_v + self._kProj.wrappedValue = Linear(dim, nKVHeads * headDim, bias: false) + if !attentionKEqV { + self._vProj.wrappedValue = Linear(dim, nKVHeads * headDim, bias: false) + } + + self._oProj.wrappedValue = Linear(nHeads * headDim, dim, bias: false) + + self._qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: config.rmsNormEps) + self._kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: config.rmsNormEps) + self.rmsNormEps = config.rmsNormEps + + if isSliding { + self.rope = RoPE(dimensions: headDim, traditional: false, base: config.ropeTheta) + // Standard RoPE: all pairs rotated with base-derived frequencies + if Self.useFusedNormRoPE { + let exponents = MLXArray( + stride(from: Float(0), to: Float(headDim), by: 2) + ) / Float(headDim) + let freqs = pow(MLXArray(config.ropeTheta), exponents) + self._fusedInvFreqs = 1.0 / freqs + } else { + self._fusedInvFreqs = nil + } + } else { + // ProportionalRoPE: pairs are formed across the full head_dim (e.g., 512), + // not just the rotated portion. Using plain RoPE(dims=128) would pair + // (0,64),(1,65),... instead of the correct (0,256),(1,257),... + let ropeDim = Int(Float(headDim) * config.partialRotaryFactor) + self.rope = ProportionalRoPE( + dims: headDim, rotatedDims: ropeDim, + traditional: false, base: config.globalRopeTheta) + // ProportionalRoPE: use 1/_freqs (inf → 0 for unrotated dims → identity) + if Self.useFusedNormRoPE { + let propExponents = MLXArray( + stride(from: Float(0), to: Float(ropeDim), by: 2) + ) / Float(headDim) + let realFreqs = pow(MLXArray(config.globalRopeTheta), propExponents) + let paddingCount = (headDim - ropeDim) / 2 + let infPadding = MLXArray(Array(repeating: Float.infinity, count: paddingCount)) + let allFreqs = concatenated([realFreqs, infPadding], axis: 0) + self._fusedInvFreqs = 1.0 / allFreqs + } else { + self._fusedInvFreqs = nil + } + } + + super.init() + } + + /// Forward pass with KV sharing support. + /// - Parameters: + /// - useSharedKV: When true, skip K/V projection and read cached K/V from the + /// donor's cache (passed as `cache`). Only compute Q, apply RoPE, and run SDPA. + /// - donorOffset: The donor layer's pre-update cache offset, captured before + /// `attentionWithCacheUpdate` ran. Shared layers must use this — NOT `cache.offset`, + /// which is the post-update value and would produce wrong RoPE positions. + /// Compiled Q+K+V projections: 3 Linear dispatches compiled into 1 traced graph. + private var _compiledQKV: (@Sendable ([MLXArray]) -> [MLXArray])? + + private func compiledQKVProjection(_ x: MLXArray) -> (MLXArray, MLXArray, MLXArray) { + if _compiledQKV == nil { + if attentionKEqV { + _compiledQKV = compile( + inputs: [self], outputs: [], shapeless: true + ) { [self] (arrays: [MLXArray]) -> [MLXArray] in + let q = qProj(arrays[0]) + let k = kProj(arrays[0]) + return [q, k, k] // V = K when attentionKEqV + } + } else { + _compiledQKV = compile( + inputs: [self], outputs: [], shapeless: true + ) { [self] (arrays: [MLXArray]) -> [MLXArray] in + return [qProj(arrays[0]), kProj(arrays[0]), vProj!(arrays[0])] + } + } + } + let results = _compiledQKV!([x]) + return (results[0], results[1], results[2]) + } + + /// Apply fused RMSNorm + quantized GEMV if the linear layer is quantized. + /// Falls back to separate norm + matmul for non-quantized models. + private func fusedNormProj( + _ x: MLXArray, normWeight: MLXArray, eps: Float, proj: Linear + ) -> MLXArray { + if let qProj = proj as? QuantizedLinear, qProj.bits == 4, + let biases = qProj.biases, + x.dim(-1) == x.size, // T=1 decode only (GEMV, not GEMM) + x.dtype == .float16 || x.dtype == .bfloat16 // float32 not instantiated + { + return MLXFast.rmsNormQuantizedGEMV( + x, normWeight: normWeight, + w: qProj.weight, scales: qProj.scales, biases: biases, + eps: eps, groupSize: qProj.groupSize) + } + // Fallback: separate norm + projection + let normed = MLXFast.rmsNorm(x, weight: normWeight, eps: eps) + return proj(normed) + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? = nil, + useSharedKV: Bool = false, + sharedKVArrays: (MLXArray, MLXArray)? = nil, + donorOffset: Int? = nil, + inputNormWeight: MLXArray? = nil + ) -> MLXArray { + let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) + + var queries = qProj(x).reshaped(B, L, nHeads, -1) + + if useSharedKV, let sharedKV = sharedKVArrays { + let (cachedKeys, cachedValues) = sharedKV + let offset = donorOffset ?? cache?.offset ?? 0 + if let _fusedInvFreqs { + queries = MLXFast.rmsNormRoPE( + queries, weight: qNorm.weight, invFreqs: _fusedInvFreqs, + eps: rmsNormEps, offset: offset, nHeads: nHeads, seqLen: L) + queries = queries.transposed(0, 2, 1, 3) + } else { + queries = qNorm(queries) + queries = queries.transposed(0, 2, 1, 3) + queries = rope(queries, offset: offset) + } + + let output = MLXFast.scaledDotProductAttention( + queries: queries, + keys: cachedKeys, + values: cachedValues, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return oProj(output) + } + + // Normal path: compute own K/V + var keys = kProj(x).reshaped(B, L, nKVHeads, -1) + var values: MLXArray + if attentionKEqV { + values = keys + } else { + values = vProj!(x).reshaped(B, L, nKVHeads, -1) + } + + // v_norm stays separate (no RoPE on values) + values = MLXFast.rmsNorm(values, weight: MLXArray.mlxNone, eps: rmsNormEps) + + let offset = cache?.offset ?? 0 + if let _fusedInvFreqs { + // Fused norm+rope via framework kernel: 2 dispatches instead of 4 + let invFreqs = _fusedInvFreqs + queries = MLXFast.rmsNormRoPE( + queries, weight: qNorm.weight, invFreqs: invFreqs, + eps: rmsNormEps, offset: offset, nHeads: nHeads, seqLen: L) + queries = queries.transposed(0, 2, 1, 3) + keys = MLXFast.rmsNormRoPE( + keys, weight: kNorm.weight, invFreqs: invFreqs, + eps: rmsNormEps, offset: offset, nHeads: nKVHeads, seqLen: L) + keys = keys.transposed(0, 2, 1, 3) + } else { + // Separate norm -> transpose -> rope (4 dispatches) + queries = qNorm(queries) + keys = kNorm(keys) + queries = queries.transposed(0, 2, 1, 3) + keys = keys.transposed(0, 2, 1, 3) + queries = rope(queries, offset: offset) + keys = rope(keys, offset: offset) + } + + values = values.transposed(0, 2, 1, 3) + + let output = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: cache, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return oProj(output) + } +} + +// MARK: - Compiled fused ops (matching Python mlx-lm) + +/// Fused logit softcapping: tanh(x / softcap) * softcap as a single compiled kernel. +private let compiledLogitSoftcap: @Sendable (MLXArray, MLXArray) -> MLXArray = + compile(shapeless: true) { softcap, x in + tanh(x / softcap) * softcap + } + +/// Fused GEGLU activation: gelu_approx(gate) * x as a single compiled kernel. +private let compiledGeglu: @Sendable (MLXArray, MLXArray) -> MLXArray = + compile(shapeless: true) { gate, x in + geluApproximate(gate) * x + } + +/// Fused RMSNorm + residual add: residual + rmsNorm(x, weight, eps). +/// Saves 1 encoder dispatch per call (norm and add fused into single kernel). +/// Applied at every post-attention and post-FFN norm+add site in the decoder layer. +/// compiledNormResidual is UNUSED — kept for reference. +/// compile() cannot fuse across fast::RMSNorm (opaque custom primitive). +/// Use MLXFast.rmsNormResidual() framework kernel instead (rms_norm_residual.metal). +private let compiledNormResidual: @Sendable (MLXArray, MLXArray, MLXArray) -> MLXArray = + compile(shapeless: true) { x, residual, weight in + residual + MLXFast.rmsNorm(x, weight: weight, eps: 1e-6) + } + +/// Fused gelu_approx(gate) * pli for PLE gate activation. +private let compiledGeluMul: @Sendable (MLXArray, MLXArray) -> MLXArray = + compile(shapeless: true) { gate, x in + geluApproximate(gate) * x + } + +// MARK: - Shared MLP + +class Gemma4SharedMLP: Module { + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "up_proj") var upProj: Linear + @ModuleInfo(key: "down_proj") var downProj: Linear + + init(dimensions: Int, hiddenDimensions: Int, isDoubleWide: Bool = false) { + let effectiveHidden = isDoubleWide ? hiddenDimensions * 2 : hiddenDimensions + self._gateProj.wrappedValue = Linear(dimensions, effectiveHidden, bias: false) + self._upProj.wrappedValue = Linear(dimensions, effectiveHidden, bias: false) + self._downProj.wrappedValue = Linear(effectiveHidden, dimensions, bias: false) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + downProj(compiledGeglu(gateProj(x), upProj(x))) + } +} + +// MARK: - Router + +class Gemma4Router: Module { + @ModuleInfo(key: "proj") var proj: Linear + @ParameterInfo(key: "scale") var scale: MLXArray + @ParameterInfo(key: "per_expert_scale") var perExpertScale: MLXArray + + let rootSize: Float + let eps: Float + + init(dimensions: Int, numExperts: Int, eps: Float) { + self.rootSize = pow(Float(dimensions), -0.5) + self.eps = eps + self._proj.wrappedValue = Linear(dimensions, numExperts, bias: false) + self._scale.wrappedValue = MLXArray.ones([dimensions]) + self._perExpertScale.wrappedValue = MLXArray.ones([numExperts]) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + let normWeight = scale * MLXArray(rootSize) + let normed = MLXFast.rmsNorm(x, weight: normWeight, eps: eps) + return proj(normed) + } +} + +// MARK: - Transformer Block + +class Gemma4TransformerBlock: Module { + let enableMoeBlock: Bool + + @ModuleInfo(key: "self_attn") var selfAttention: Gemma4Attention + @ModuleInfo(key: "mlp") var sharedMLP: Gemma4SharedMLP + // MoE components live directly on the layer (no moe_block wrapper) to match weight keys + @ModuleInfo(key: "experts") var experts: FusedGateUpSwitchGLU? + @ModuleInfo(key: "router") var router: Gemma4Router? + let topKExperts: Int + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + @ModuleInfo(key: "pre_feedforward_layernorm") var preFeedforwardLayerNorm: RMSNorm + @ModuleInfo(key: "post_feedforward_layernorm") var postFeedforwardLayerNorm: RMSNorm + @ModuleInfo(key: "pre_feedforward_layernorm_2") var preFeedforwardLayerNorm2: RMSNorm? + @ModuleInfo(key: "post_feedforward_layernorm_1") var postFeedforwardLayerNorm1: RMSNorm? + @ModuleInfo(key: "post_feedforward_layernorm_2") var postFeedforwardLayerNorm2: RMSNorm? + + // Per-layer scalar (learnable output scaling, loaded from weights if present) + @ParameterInfo(key: "layer_scalar") var layerScalar: MLXArray + + // Per-Layer Embeddings (PLE) + @ModuleInfo(key: "per_layer_input_gate") var perLayerInputGate: Linear? + @ModuleInfo(key: "per_layer_projection") var perLayerProjection: Linear? + @ModuleInfo(key: "post_per_layer_input_norm") var postPerLayerInputNorm: RMSNorm? + + init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + self.enableMoeBlock = config.enableMoeBlock + self.topKExperts = config.topKExperts + + self._selfAttention.wrappedValue = Gemma4Attention(config, layerIdx: layerIdx) + // use_double_wide_mlp only applies to KV-shared layers (near the end of the model) + let firstKvSharedIdx = config.hiddenLayers - config.numKvSharedLayers + let isKvSharedLayer = config.numKvSharedLayers > 0 && layerIdx >= firstKvSharedIdx + let isDoubleWide = config.useDoubleWideMlp && isKvSharedLayer + + self._sharedMLP.wrappedValue = Gemma4SharedMLP( + dimensions: config.hiddenSize, hiddenDimensions: config.intermediateSize, + isDoubleWide: isDoubleWide) + + if config.enableMoeBlock { + self._experts.wrappedValue = FusedGateUpSwitchGLU( + inputDims: config.hiddenSize, + hiddenDims: config.moeIntermediateSize, + numExperts: config.numExperts, + activation: geluApproximate, + bias: false + ) + self._router.wrappedValue = Gemma4Router( + dimensions: config.hiddenSize, numExperts: config.numExperts, eps: config.rmsNormEps) + self._preFeedforwardLayerNorm2.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm1.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm2.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + self._inputLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postAttentionLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._preFeedforwardLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + + // layer_scalar: initialized to [1.0] shape [1], overwritten by checkpoint if present + self._layerScalar.wrappedValue = MLXArray([Float(1.0)]) + + // PLE components (only when enabled) + if config.hiddenSizePerLayerInput > 0 { + self._perLayerInputGate.wrappedValue = Linear( + config.hiddenSize, config.hiddenSizePerLayerInput, bias: false) + self._perLayerProjection.wrappedValue = Linear( + config.hiddenSizePerLayerInput, config.hiddenSize, bias: false) + self._postPerLayerInputNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? = nil, + perLayerInput: MLXArray? = nil, + useSharedKV: Bool = false, + sharedKVArrays: (MLXArray, MLXArray)? = nil, + donorOffset: Int? = nil + ) -> MLXArray { + let inputNorm = inputLayerNorm(x) + let attnOut = selfAttention(inputNorm, mask: mask, cache: cache, useSharedKV: useSharedKV, sharedKVArrays: sharedKVArrays, donorOffset: donorOffset) + // Fused RMSNorm + residual add via framework Metal kernel (rms_norm_residual.metal). + // Single dispatch replaces separate rmsNorm + add (saves 90 dispatches/token). + var h = MLXFast.rmsNormResidual( + attnOut, residual: x, + weight: postAttentionLayerNorm.weight, + eps: postAttentionLayerNorm.eps) + + // FFN with pre/post norms: shared MLP + MoE + if let experts, let router, + let postNorm1 = postFeedforwardLayerNorm1, + let preNorm2 = preFeedforwardLayerNorm2, + let postNorm2 = postFeedforwardLayerNorm2 + { + // MoE path: separate norms for shared MLP and expert MoE + let preFFNNorm = preFeedforwardLayerNorm(h) + var h1 = sharedMLP(preFFNNorm) + h1 = postNorm1(h1) + + // Route through experts: router gets h (pre-norm), experts get normed input + let routerLogits = router(h) + let (topKLogits, topKIndices) = gemma4TopK(routerLogits, k: topKExperts, axis: -1) + let stopIndices = MLX.stopGradient(topKIndices) + var expertWeights = softmax(topKLogits, axis: -1, precise: true) + expertWeights = expertWeights * router.perExpertScale[topKIndices] + let preFFNNorm2 = preNorm2(h) + var h2 = experts(preFFNNorm2, stopIndices) + h2 = h2 * expandedDimensions(expertWeights, axis: -1) + h2 = h2.sum(axis: -2) + h2 = postNorm2(h2) + + let ffnOut = h1 + h2 + h = MLXFast.rmsNormResidual( + ffnOut, residual: h, + weight: postFeedforwardLayerNorm.weight, + eps: postFeedforwardLayerNorm.eps) + } else { + let preFFNNorm = preFeedforwardLayerNorm(h) + let ffnOut = sharedMLP(preFFNNorm) + h = MLXFast.rmsNormResidual( + ffnOut, residual: h, + weight: postFeedforwardLayerNorm.weight, + eps: postFeedforwardLayerNorm.eps) + } + + // Per-Layer Embeddings (PLE) — fuse gelu + mul + if let gate = perLayerInputGate, + let proj = perLayerProjection, + let norm = postPerLayerInputNorm, + let pli = perLayerInput + { + let residual = h + var g = compiledGeluMul(gate(h), pli) + g = proj(g) + g = norm(g) + h = residual + g + } + + // Per-layer scalar + h = h * layerScalar + + return h + } +} + +// MARK: - Inner Model + +public class Gemma4ModelInner: Module { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo var layers: [Gemma4TransformerBlock] + @ModuleInfo var norm: RMSNorm + + // Per-Layer Embeddings (PLE) + @ModuleInfo(key: "embed_tokens_per_layer") var embedTokensPerLayer: Embedding? + @ModuleInfo(key: "per_layer_model_projection") var perLayerModelProjection: Linear? + @ModuleInfo(key: "per_layer_projection_norm") var perLayerProjectionNorm: RMSNorm? + + // PLE scaling factors — computed constants, NOT learned parameters + let embedTokensPerLayerScale: Float // sqrt(hidden_size_per_layer_input) + let perLayerProjectionScale: Float // hidden_size^(-0.5) + let perLayerInputScale: Float // 2^(-0.5) ≈ 0.707 + + let config: Gemma4TextConfiguration + let layerTypes: [String] + let slidingAttentionIndex: Int + let fullAttentionIndex: Int + let hiddenSizePerLayerInput: Int + /// KV sharing: maps each layer to its KV donor layer index. + /// previousKVs[i] == i means the layer computes its own KV. + /// previousKVs[i] != i means it reuses KV from layer previousKVs[i]. + let previousKVs: [Int] + + init(_ config: Gemma4TextConfiguration) { + self.config = config + self.layerTypes = config.layerTypes + + self._embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) + + self._layers.wrappedValue = (0 ..< config.hiddenLayers).map { layerIdx in + Gemma4TransformerBlock(config, layerIdx: layerIdx) + } + + self.norm = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + + // Cache representative layer indices for mask creation + self.slidingAttentionIndex = layerTypes.firstIndex(of: "sliding_attention") ?? 0 + self.fullAttentionIndex = layerTypes.firstIndex(of: "full_attention") ?? 0 + + // KV sharing: build donor mapping + let N = config.hiddenLayers + let M = N - config.numKvSharedLayers + var mapping = Array(0 ..< N) + if config.numKvSharedLayers > 0 { + var kvsByType: [String: Int] = [:] + for i in 0 ..< M { + kvsByType[config.layerTypes[i]] = i + } + for j in M ..< N { + if let donor = kvsByType[config.layerTypes[j]] { + mapping[j] = donor + } + } + } + self.previousKVs = mapping + + // PLE scaling constants (computed, not learned) + self.hiddenSizePerLayerInput = config.hiddenSizePerLayerInput + self.embedTokensPerLayerScale = sqrt(Float(max(config.hiddenSizePerLayerInput, 1))) + self.perLayerProjectionScale = pow(Float(config.hiddenSize), -0.5) + self.perLayerInputScale = pow(2.0, -0.5) // ≈ 0.707 + + // Per-Layer Embeddings (PLE) + if config.hiddenSizePerLayerInput > 0 { + let plEmbedDim = config.hiddenLayers * config.hiddenSizePerLayerInput + self._embedTokensPerLayer.wrappedValue = Embedding( + embeddingCount: config.vocabSizePerLayerInput, dimensions: plEmbedDim) + self._perLayerModelProjection.wrappedValue = Linear( + config.hiddenSize, plEmbedDim, bias: false) + self._perLayerProjectionNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSizePerLayerInput, eps: config.rmsNormEps) + } + + super.init() + } + + func callAsFunction( + _ inputs: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, + cache: [KVCache?]? = nil, + prefillMode: Bool = false + ) -> MLXArray { + var h = embedTokens(inputs) + + // Gemma embedding scaling (plain float — no dtype conversion needed) + let embedScale = sqrt(Float(config.hiddenSize)) + h = h * embedScale + + let cache: [KVCache?] = cache ?? [KVCache?](repeating: nil, count: layers.count) + + // Per-Layer Embeddings (PLE): compute per-layer inputs from token IDs + var perLayerInputs: MLXArray? = nil + if hiddenSizePerLayerInput > 0, let embedPL = embedTokensPerLayer { + // 1. Embed token IDs through per-layer embedding table + var pli = embedPL(inputs) + // Use Float scalar directly (not MLXArray(Float)) to avoid an + // implicit fp32 promotion. MLXArray(Float) defaults to fp32; the + // bf16 * fp32 multiply then promotes the result to fp32 and the + // entire per-layer-input cascade runs in fp32 instead of bf16, + // which forces ~800 bf16<->fp32 AsType conversions per token. + // The Swift `*` overload for `MLXArray * scalar` calls + // `rhs.asMLXArray(dtype: lhs.dtype)` so this stays in bf16. + pli = pli * embedTokensPerLayerScale + // Reshape: [B, T, numLayers * plDim] -> [B, T, numLayers, plDim] + pli = pli.reshaped( + pli.dim(0), pli.dim(1), config.hiddenLayers, hiddenSizePerLayerInput) + + // 2. Project hidden states and combine with per-layer embeddings + if let proj = perLayerModelProjection { + var plProj = proj(h) + // Scale the projection output BEFORE reshaping (see note above). + plProj = plProj * perLayerProjectionScale + plProj = plProj.reshaped( + plProj.dim(0), plProj.dim(1), config.hiddenLayers, hiddenSizePerLayerInput) + if let norm = perLayerProjectionNorm { + plProj = norm(plProj) + } + // Combine: (projection + embedding) * scale (see note above). + pli = (plProj + pli) * perLayerInputScale + } + perLayerInputs = pli + } + + // NOTE: Previously we pre-sliced perLayerInputs into a 35-element array + // upfront. That held 35 strong refs to slice views of the parent 4D + // tensor for the entire forward pass, keeping the full pli alive in + // GPU memory across all layer iterations. Switched to lazy on-demand + // slicing inside the loop so each per-layer slice can be released as + // soon as the layer that consumed it is done. Matches Python's pattern + // (Python's list comprehension is also eager but Python doesn't have + // ARC closure capture semantics, so the lifetime ends earlier). + + // Pre-compute masks once per forward pass (GPTOSS pattern) + let seqLen = h.dim(1) + var fullMask: MLXFast.ScaledDotProductAttentionMaskMode? + var slidingMask: MLXFast.ScaledDotProductAttentionMaskMode? + + // Pre-update offsets captured from each donor layer before attentionWithCacheUpdate runs. + // Python threads this explicitly via an `intermediates` array; here we replicate that by + // snapshotting cache.offset just before each donor layer executes. + // Shared layers need these to apply query RoPE at the same positions as their donor — + // by the time a shared layer runs, cache.offset has already been incremented by the donor. + var donorPreUpdateOffsets = [Int](repeating: 0, count: layers.count) + // Match Python: store (kvs, offset) per layer so shared layers reuse + // the donor's K/V arrays directly instead of re-slicing from cache. + // This eliminates ~450 redundant graph ops (Slice, SDPA, etc). + var intermediateKVs: [(MLXArray, MLXArray)?] = Array(repeating: nil, count: layers.count) + + for (i, layer) in layers.enumerated() { + let maskMode: MLXFast.ScaledDotProductAttentionMaskMode + if let mask { + maskMode = mask + } else if layerTypes[i] == "full_attention" { + if fullMask == nil { + fullMask = makeAttentionMask( + n: seqLen, + cache: cache[fullAttentionIndex], + windowSize: nil + ) + } + maskMode = fullMask! + } else { + if slidingMask == nil { + slidingMask = makeAttentionMask( + n: seqLen, + cache: cache[slidingAttentionIndex], + windowSize: config.slidingWindow + ) + } + maskMode = slidingMask! + } + + let pli: MLXArray? = perLayerInputs.map { $0[0..., 0..., i, 0...] } + + let donorIdx = previousKVs[i] + let isShared = donorIdx != i + + if isShared { + // In prefill mode, skip shared layers entirely. Their output feeds only + // into h (which is discarded by prepare()) and NOT into any cache. + // This matches Python's lazy eval behavior: eval(cache_state) prunes + // shared layer ops because they're not ancestors of the cache arrays. + // Saves ~580 graph ops per chunk (1318→738) = ~44% fewer GPU dispatches. + if prefillMode { + // Shared layers don't write to cache — skip during prefill + continue + } + h = layer(h, mask: maskMode, cache: nil, perLayerInput: pli, + useSharedKV: true, sharedKVArrays: intermediateKVs[donorIdx], + donorOffset: donorPreUpdateOffsets[donorIdx]) + } else { + donorPreUpdateOffsets[i] = cache[i]?.offset ?? 0 + h = layer(h, mask: maskMode, cache: cache[i], perLayerInput: pli) + // Store donor's K/V from cache.update() return value for shared layers. + // peek() creates redundant Slice ops — use the cache's stored arrays directly. + if let c = cache[i] as? StandardKVCache, let k = c.lastReturnedKeys, let v = c.lastReturnedValues { + intermediateKVs[i] = (k, v) + } else if let c = cache[i] as? RotatingKVCache, let k = c.lastReturnedKeys, let v = c.lastReturnedValues { + intermediateKVs[i] = (k, v) + } + } + } + + return norm(h) + } +} + +// MARK: - Gemma4 Text Model + +public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { + public let vocabularySize: Int + public let kvHeads: [Int] + + @ModuleInfo public var model: Gemma4ModelInner + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + let config: Gemma4TextConfiguration + + public init(_ config: Gemma4TextConfiguration) { + self.config = config + self.vocabularySize = config.vocabularySize + self.model = Gemma4ModelInner(config) + + // Per-layer KV head counts for KVCacheDimensionProvider + self.kvHeads = config.layerTypes.map { layerType in + layerType == "full_attention" ? config.globalKvHeads : config.kvHeads + } + + if !config.tieWordEmbeddings { + self._lmHead.wrappedValue = Linear( + config.hiddenSize, config.vocabularySize, bias: false) + } + + super.init() + } + + /// Pure attention model — use larger prefill chunks (4096) since there's no + /// GatedDeltaNet sequential bottleneck. Reduces TTFT by processing more tokens per step. + public func prepare(_ input: LMInput, cache: [KVCache], windowSize: Int?) throws + -> PrepareResult + { + // Larger chunks reduce per-chunk overhead (graph building, eval barriers, + // weight re-reads). 4096 balances speed and memory for pure attention models. + let prefillStepSize = max(windowSize ?? 512, 4096) + var y = input.text + + // Native prefill offload (opt-in via NATIVE_PREFILL=1) + if ProcessInfo.processInfo.environment["NATIVE_PREFILL"] == "1" { + let bridge = GemmaPrefillBridge.shared + if bridge.ensureInitialized(model: model, config: config) { + let allTokens = input.text.tokens + let prefillCount = allTokens.size - 1 + if prefillCount > 0 { + // Zero-copy: pass MLXArray directly to bridge (stays on GPU). + // Avoids eval() + .asArray() GPU→CPU→GPU roundtrip. + let tokenSlice = allTokens[0 ..< prefillCount].reshaped(-1) + let nonShared = config.hiddenLayers - config.numKvSharedLayers + + let (ms, ok) = bridge.runAndInjectKV( + tokenArray: tokenSlice, cache: cache, numLayers: nonShared) + + if ok, ms > 0 { + let bridgeTokS = Double(prefillCount) / (ms / 1000.0) + print(String(format: "[GemmaPrefill] bridge: %.1fms = %.0f tok/s (%d tokens)", ms, bridgeTokS, prefillCount)) + let lastToken = allTokens[prefillCount ..< allTokens.size] + return .tokens(LMInput.Text(tokens: lastToken)) + } + } + } + // Fall through to Swift prefill on failure + } + + // Only eval non-shared caches — shared layers don't update any cache, + // so their computation is dead code that lazy eval will prune. + // Matches Python's behavior where make_cache() creates only non-shared caches. + let nonSharedCount = config.hiddenLayers - config.numKvSharedLayers + + while y.tokens.size > 1 { + let chunkSize = min(prefillStepSize, y.tokens.size - 1) + let input = y[.newAxis, .. MLXArray { + var out = model(inputs, cache: cache) + if config.tieWordEmbeddings { + out = model.embedTokens.asLinear(out) + } else { + out = lmHead!(out) + } + + // Final logit softcapping (compiled fused kernel) + if let softcap = config.finalLogitSoftcapping, softcap > 0 { + out = compiledLogitSoftcap(MLXArray(softcap), out) + } + + return out + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var processedWeights = weights + + // Strip language_model.model. prefix from VLM weights + let unflattened = ModuleParameters.unflattened(weights) + if let lm = unflattened["language_model"] { + processedWeights = Dictionary(uniqueKeysWithValues: lm.flattened()) + } + + // Trim vocabulary tensors to expected size + let expectedVocab = config.vocabularySize + let keysToCheck = [ + "model.embed_tokens.weight", "model.embed_tokens.scales", + "model.embed_tokens.biases", + "lm_head.weight", "lm_head.scales", "lm_head.biases", + ] + + for key in keysToCheck { + if let tensor = processedWeights[key], tensor.dim(0) > expectedVocab { + processedWeights[key] = tensor[0 ..< expectedVocab] + } + } + + // When tied, remove any lm_head weights (we use embed_tokens.asLinear instead) + if config.tieWordEmbeddings { + processedWeights.keys + .filter { $0.hasPrefix("lm_head.") } + .forEach { processedWeights.removeValue(forKey: $0) } + } + + // Remap expert weight names: experts.switch_glu.X -> experts.X + let expertKeys = processedWeights.keys.filter { $0.contains(".switch_glu.") } + for key in expertKeys { + let newKey = key.replacingOccurrences(of: ".switch_glu.", with: ".") + processedWeights[newKey] = processedWeights.removeValue(forKey: key) + } + + // Fuse gate_proj + up_proj into gate_up_proj for SwitchGLU. + // Handles weight, scales, and biases (quantized models). + let gateKeys = processedWeights.keys.filter { $0.contains(".experts.gate_proj.") } + for gateKey in gateKeys { + let upKey = gateKey.replacingOccurrences(of: "gate_proj", with: "up_proj") + guard let gateVal = processedWeights[gateKey], + let upVal = processedWeights[upKey] else { continue } + + let fusedKey = gateKey.replacingOccurrences(of: "gate_proj", with: "gate_up_proj") + // Concat on output dimension (axis 1): [E, outDim, ...] → [E, 2*outDim, ...] + processedWeights[fusedKey] = concatenated([gateVal, upVal], axis: 1) + processedWeights.removeValue(forKey: gateKey) + processedWeights.removeValue(forKey: upKey) + } + + return processedWeights + } + + /// Strip the `language_model.` prefix from per-layer quantization keys so + /// they line up with the text-only Swift module paths. VLM configs (e.g. + /// Gemma 4 26B A4B with mixed 4-bit / 8-bit shared MLP) key overrides as + /// `language_model.model.layers.0.mlp.gate_proj`, but when this text model + /// is loaded stand-alone the paths are `model.layers.0.mlp.gate_proj`. + public func sanitize(perLayerQuantization: BaseConfiguration.PerLayerQuantization?) + -> BaseConfiguration.PerLayerQuantization? + { + guard let plq = perLayerQuantization else { return nil } + let prefix = "language_model." + var stripped: [String: BaseConfiguration.QuantizationOption] = [:] + for (key, value) in plq.perLayerQuantization { + if key.hasPrefix(prefix) { + stripped[String(key.dropFirst(prefix.count))] = value + } else { + stripped[key] = value + } + } + return BaseConfiguration.PerLayerQuantization( + quantization: plq.quantization, + perLayerQuantization: stripped) + } + + public func newCache(parameters: GenerateParameters? = nil) -> [KVCache] { + var caches = [KVCache]() + + for layerType in config.layerTypes { + if layerType == "full_attention" { + if let maxKVSize = parameters?.maxKVSize { + caches.append(RotatingKVCache(maxSize: maxKVSize, keep: 0)) + } else { + caches.append(StandardKVCache()) + } + } else { + caches.append( + RotatingKVCache(maxSize: config.slidingWindow, keep: 0) + ) + } + } + + return caches + } +} + +// MARK: - LoRA + +extension Gemma4TextModel: LoRAModel { + public var loraLayers: [Module] { + model.layers + } +} diff --git a/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift b/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift index 54aa9922b6..100502e3e4 100644 --- a/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift +++ b/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift @@ -124,7 +124,7 @@ class GraniteMoeHybridMamba2Mixer: Module { if let cache { let end = padded.dim(1) let start = max(0, end - (convKernelSize - 1)) - cache[0] = padded[0..., start ..< end, 0...] + cache[0] = padded[0..., start ..< end, 0...].contiguous() } let convOutput = conv1d(padded) diff --git a/Libraries/MLXLLM/Models/Jamba.swift b/Libraries/MLXLLM/Models/Jamba.swift index a9054684ef..4352e2f4bf 100644 --- a/Libraries/MLXLLM/Models/Jamba.swift +++ b/Libraries/MLXLLM/Models/Jamba.swift @@ -307,7 +307,7 @@ class JambaMambaMixer: Module { } let convOut = conv1d(xFull) - let newConvState = xFull[0..., (1 - K)..., 0...] + let newConvState = xFull[0..., (1 - K)..., 0...].contiguous() x = silu(convOut) let A = -exp(A_Log) diff --git a/Libraries/MLXLLM/Models/LFM2.swift b/Libraries/MLXLLM/Models/LFM2.swift index 8d7fc1b45e..b4dae40a65 100644 --- a/Libraries/MLXLLM/Models/LFM2.swift +++ b/Libraries/MLXLLM/Models/LFM2.swift @@ -221,7 +221,7 @@ class LFM2ShortConv: Module { Bx = concatenated([state!, Bx], axis: -2) if let cache { - cache[0] = Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...] + cache[0] = Bx[0..., (Bx.dim(1) - (lCache - 1))..., 0...].contiguous() } let convOut = conv(Bx) diff --git a/Libraries/MLXLLM/Models/LFM2MoE.swift b/Libraries/MLXLLM/Models/LFM2MoE.swift index fcefb2e017..8b078d2c5d 100644 --- a/Libraries/MLXLLM/Models/LFM2MoE.swift +++ b/Libraries/MLXLLM/Models/LFM2MoE.swift @@ -226,7 +226,7 @@ class LFM2MoEShortConv: Module { Bx = concatenated([state!, Bx], axis: -2) if let cache { let start = Bx.dim(1) - (lCache - 1) - cache[0] = Bx[0..., start..., 0...] + cache[0] = Bx[0..., start..., 0...].contiguous() } let convOut = conv(Bx) diff --git a/Libraries/MLXLLM/Models/MiniMaxM2.swift b/Libraries/MLXLLM/Models/MiniMaxM2.swift new file mode 100644 index 0000000000..ec5448c289 --- /dev/null +++ b/Libraries/MLXLLM/Models/MiniMaxM2.swift @@ -0,0 +1,326 @@ +// Port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/minimax.py +// MiniMax M2: MoE architecture with 62 layers, 256 local experts, 8 active per token. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - Configuration + +public struct MiniMaxM2Configuration: Codable, Sendable { + var modelType: String = "minimax_m2" + var hiddenSize: Int + var intermediateSize: Int + var attentionHeads: Int + var kvHeads: Int + var maxPositionEmbeddings: Int + var numExpertsPerTok: Int + var numLocalExperts: Int + var sharedIntermediateSize: Int + var hiddenLayers: Int + var rmsNormEps: Float + var ropeTheta: Float + var rotaryDim: Int + var vocabularySize: Int + var tieWordEmbeddings: Bool = false + var scoringFunc: String = "sigmoid" + var headDim: Int + var useQkNorm: Bool = true + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case hiddenSize = "hidden_size" + case intermediateSize = "intermediate_size" + case attentionHeads = "num_attention_heads" + case kvHeads = "num_key_value_heads" + case maxPositionEmbeddings = "max_position_embeddings" + case numExpertsPerTok = "num_experts_per_tok" + case numLocalExperts = "num_local_experts" + case sharedIntermediateSize = "shared_intermediate_size" + case hiddenLayers = "num_hidden_layers" + case rmsNormEps = "rms_norm_eps" + case ropeTheta = "rope_theta" + case rotaryDim = "rotary_dim" + case vocabularySize = "vocab_size" + case tieWordEmbeddings = "tie_word_embeddings" + case scoringFunc = "scoring_func" + case headDim = "head_dim" + case useQkNorm = "use_qk_norm" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + modelType = try container.decodeIfPresent(String.self, forKey: .modelType) ?? "minimax_m2" + hiddenSize = try container.decodeIfPresent(Int.self, forKey: .hiddenSize) ?? 3072 + intermediateSize = try container.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? 1536 + attentionHeads = try container.decodeIfPresent(Int.self, forKey: .attentionHeads) ?? 48 + kvHeads = try container.decodeIfPresent(Int.self, forKey: .kvHeads) ?? 8 + maxPositionEmbeddings = try container.decodeIfPresent(Int.self, forKey: .maxPositionEmbeddings) ?? 196608 + numExpertsPerTok = try container.decodeIfPresent(Int.self, forKey: .numExpertsPerTok) ?? 8 + numLocalExperts = try container.decodeIfPresent(Int.self, forKey: .numLocalExperts) ?? 256 + sharedIntermediateSize = try container.decodeIfPresent(Int.self, forKey: .sharedIntermediateSize) ?? 0 + hiddenLayers = try container.decodeIfPresent(Int.self, forKey: .hiddenLayers) ?? 62 + rmsNormEps = try container.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1e-6 + ropeTheta = try container.decodeIfPresent(Float.self, forKey: .ropeTheta) ?? 5_000_000 + rotaryDim = try container.decodeIfPresent(Int.self, forKey: .rotaryDim) ?? 64 + vocabularySize = try container.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 200064 + tieWordEmbeddings = try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? false + scoringFunc = try container.decodeIfPresent(String.self, forKey: .scoringFunc) ?? "sigmoid" + headDim = try container.decodeIfPresent(Int.self, forKey: .headDim) ?? 128 + useQkNorm = try container.decodeIfPresent(Bool.self, forKey: .useQkNorm) ?? true + } +} + +// MARK: - Attention + +class MiniMaxM2Attention: Module { + let scale: Float + let numAttentionHeads: Int + let numKeyValueHeads: Int + let headDim: Int + let useQkNorm: Bool + + @ModuleInfo(key: "q_proj") var wq: Linear + @ModuleInfo(key: "k_proj") var wk: Linear + @ModuleInfo(key: "v_proj") var wv: Linear + @ModuleInfo(key: "o_proj") var wo: Linear + + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm? + @ModuleInfo(key: "k_norm") var kNorm: RMSNorm? + + let rope: RoPE + + init(_ args: MiniMaxM2Configuration) { + self.numAttentionHeads = args.attentionHeads + self.numKeyValueHeads = args.kvHeads + self.headDim = args.headDim + self.scale = pow(Float(headDim), -0.5) + self.useQkNorm = args.useQkNorm + + _wq.wrappedValue = Linear(args.hiddenSize, numAttentionHeads * headDim, bias: false) + _wk.wrappedValue = Linear(args.hiddenSize, numKeyValueHeads * headDim, bias: false) + _wv.wrappedValue = Linear(args.hiddenSize, numKeyValueHeads * headDim, bias: false) + _wo.wrappedValue = Linear(numAttentionHeads * headDim, args.hiddenSize, bias: false) + + if useQkNorm { + _qNorm.wrappedValue = RMSNorm( + dimensions: numAttentionHeads * headDim, eps: args.rmsNormEps) + _kNorm.wrappedValue = RMSNorm( + dimensions: numKeyValueHeads * headDim, eps: args.rmsNormEps) + } + + self.rope = RoPE( + dimensions: args.rotaryDim, + traditional: false, + base: args.ropeTheta + ) + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + let (B, L) = (x.dim(0), x.dim(1)) + + var queries = wq(x) + var keys = wk(x) + let values = wv(x) + + // QK norm applied BEFORE reshape (per-layer norm) + if let qNorm, let kNorm { + queries = qNorm(queries) + keys = kNorm(keys) + } + + var q = queries.reshaped(B, L, numAttentionHeads, -1).transposed(0, 2, 1, 3) + var k = keys.reshaped(B, L, numKeyValueHeads, -1).transposed(0, 2, 1, 3) + let v = values.reshaped(B, L, numKeyValueHeads, -1).transposed(0, 2, 1, 3) + + q = applyRotaryPosition(rope, to: q, cache: cache) + k = applyRotaryPosition(rope, to: k, cache: cache) + + let output = attentionWithCacheUpdate( + queries: q, + keys: k, + values: v, + cache: cache, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return wo(output) + } +} + +// MARK: - MoE + +class MiniMaxM2SparseMoeBlock: Module { + let numExpertsPerTok: Int + + @ModuleInfo(key: "gate") var gate: Linear + @ModuleInfo(key: "switch_mlp") var switchMLP: SwitchGLU + @ParameterInfo(key: "e_score_correction_bias") var eScoreCorrectionBias: MLXArray + + init(_ args: MiniMaxM2Configuration) { + self.numExpertsPerTok = args.numExpertsPerTok + + _gate.wrappedValue = Linear(args.hiddenSize, args.numLocalExperts, bias: false) + _switchMLP.wrappedValue = SwitchGLU( + inputDims: args.hiddenSize, + hiddenDims: args.intermediateSize, + numExperts: args.numLocalExperts + ) + _eScoreCorrectionBias.wrappedValue = MLXArray.zeros([args.numLocalExperts]) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + let gates = gate(x.asType(.float32)) + + // Sigmoid scoring (not softmax) + var scores = sigmoid(gates) + let originalScores = scores + scores = scores + eScoreCorrectionBias + + // Top-k expert selection + let k = numExpertsPerTok + let inds = argPartition(-scores, kth: k - 1, axis: -1)[.ellipsis, .. MLXArray { + var hidden = x + selfAttn(inputLayerNorm(x), mask: mask, cache: cache) + hidden = hidden + blockSparseMoe(postAttentionLayerNorm(hidden)) + return hidden + } +} + +// MARK: - Model + +public class MiniMaxM2ModelInner: Module { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + let layers: [MiniMaxM2DecoderLayer] + @ModuleInfo(key: "norm") var norm: RMSNorm + + init(_ args: MiniMaxM2Configuration) { + _embedTokens.wrappedValue = Embedding( + embeddingCount: args.vocabularySize, dimensions: args.hiddenSize) + self.layers = (0 ..< args.hiddenLayers).map { _ in MiniMaxM2DecoderLayer(args) } + _norm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.rmsNormEps) + } + + func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + var h = embedTokens(inputs) + + let mask = createAttentionMask(h: h, cache: cache?.first) + + for (i, layer) in layers.enumerated() { + h = layer(h, mask: mask, cache: cache?[i]) + } + + return norm(h) + } +} + +// MARK: - LLM Model + +public class MiniMaxM2Model: Module, LLMModel, KVCacheDimensionProvider { + public let vocabularySize: Int + public let kvHeads: [Int] + + public let model: MiniMaxM2ModelInner + let configuration: MiniMaxM2Configuration + + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + public init(_ args: MiniMaxM2Configuration) { + self.configuration = args + self.vocabularySize = args.vocabularySize + self.kvHeads = Array(repeating: args.kvHeads, count: args.hiddenLayers) + self.model = MiniMaxM2ModelInner(args) + + if !args.tieWordEmbeddings { + _lmHead.wrappedValue = Linear(args.hiddenSize, args.vocabularySize, bias: false) + } + } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + let out = model(inputs, cache: cache) + if let lmHead { + return lmHead(out) + } + return model.embedTokens.asLinear(out) + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var sanitizedWeights = weights + + if configuration.tieWordEmbeddings { + sanitizedWeights["lm_head.weight"] = nil + } + + // Restructure MoE expert weights: experts.N.wX.weight -> switch_mlp.{gate,up,down}_proj.weight + if sanitizedWeights["model.layers.0.block_sparse_moe.experts.0.w1.weight"] == nil { + return sanitizedWeights + } + + for layerIndex in 0 ..< configuration.hiddenLayers { + let prefix = "model.layers.\(layerIndex)" + for (orig, updated) in [("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj")] { + for key in ["weight", "scales", "biases"] { + let firstKey = "\(prefix).block_sparse_moe.experts.0.\(orig).\(key)" + if sanitizedWeights[firstKey] != nil { + let toJoin = (0 ..< configuration.numLocalExperts).map { expertIndex in + sanitizedWeights.removeValue( + forKey: + "\(prefix).block_sparse_moe.experts.\(expertIndex).\(orig).\(key)" + )! + } + sanitizedWeights[ + "\(prefix).block_sparse_moe.switch_mlp.\(updated).\(key)" + ] = MLX.stacked(toJoin) + } + } + } + } + + return sanitizedWeights + } +} + +// MARK: - LoRA + +extension MiniMaxM2Model: LoRAModel { + public var loraLayers: [Module] { + model.layers + } +} diff --git a/Libraries/MLXLLM/Models/NemotronH.swift b/Libraries/MLXLLM/Models/NemotronH.swift index db846352e2..d1918ae6f9 100644 --- a/Libraries/MLXLLM/Models/NemotronH.swift +++ b/Libraries/MLXLLM/Models/NemotronH.swift @@ -77,10 +77,8 @@ private class NemotronHRMSNormGated: Module { let unflattened = states.reshaped(newShape) // Python: x = mx.fast.rms_norm(x, weight=None, eps=self.eps) - // Apply RMS norm per group WITHOUT scaling (pass ones as weight) - // Swift rmsNorm doesn't accept nil, so we use identity weight - let identityWeight = MLXArray.ones([groupSize]) - let normed = MLXFast.rmsNorm(unflattened, weight: identityWeight, eps: eps) + // Apply RMS norm per group WITHOUT scaling + let normed = MLXFast.rmsNorm(unflattened, weight: MLXArray.mlxNone, eps: eps) // Python: return self.weight * x.flatten(-2) // Flatten back to [..., hidden] and apply learned weight @@ -180,7 +178,7 @@ private class NemotronHMamba2Mixer: Module, NemotronHMixer { if let cache { let end = padded.dim(1) let start = max(0, end - (convKernelSize - 1)) - cache[0] = padded[0..., start ..< end, 0...] + cache[0] = padded[0..., start ..< end, 0...].contiguous() } let convOutput = conv1d(padded) @@ -675,6 +673,7 @@ private class NemotronHBackbone: Module { }() // Track which cache to use for each layer + let isPrefill = hidden.dim(1) > 1 var cacheCounter = 0 for layer in layers { let c: KVCache? @@ -686,6 +685,17 @@ private class NemotronHBackbone: Module { } hidden = layer(hidden, attentionMask: attentionMask, ssmMask: ssmMask, cache: c) + + // During prefill, asyncEval after each layer. Previously `eval` forced + // a CPU↔GPU sync per layer, stalling the CPU from building layer i+1's + // graph until the GPU finished layer i. `asyncEval` schedules the + // evaluation but lets the CPU keep building ahead — the GPU pipeline + // stays fed through the Mamba+attention+MoE stack. + if isPrefill, let c { + var toEval: [MLXArray] = [hidden] + toEval.append(contentsOf: c.innerState()) + asyncEval(toEval) + } } return normF(hidden) diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index 15fcd6556c..6249ebf44c 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -251,7 +251,10 @@ final class Qwen35GatedDeltaNet: Module { let convInput = concatenated([convState, qkv], axis: 1) if let cache { - cache[0] = convInput[0..., (-(convKernelSize - 1))...] + // .contiguous() breaks the lazy chain: without it, each decode step + // builds concat(prev_slice, qkv) -> slice, keeping ALL prior qkv arrays + // alive in the graph. This causes ~9GB/run memory growth for Qwen3.5-9B. + cache[0] = convInput[0..., (-(convKernelSize - 1))...].contiguous() } let convOut = silu(conv1d(convInput)) @@ -262,28 +265,49 @@ final class Qwen35GatedDeltaNet: Module { let v = convSplit[2].reshaped(B, S, numVHeads, headVDim) var state = cache?[1] - let dtype = q.dtype - let invScale = pow(Float(headKDim), -0.5) - let qNormed = - MLXArray(pow(invScale, 2)).asType(dtype) - * MLXFast.rmsNorm(q, weight: MLXArray.mlxNone, eps: 1e-6) - let kNormed = - MLXArray(invScale).asType(dtype) - * MLXFast.rmsNorm(k, weight: MLXArray.mlxNone, eps: 1e-6) - var out: MLXArray - (out, state) = gatedDeltaUpdate( - q: qNormed, - k: kNormed, - v: v, - a: a, - b: b, - aLog: aLog, - dtBias: dtBias, - state: state, - mask: mask - ) + if S == 1, state != nil { + // Decode (T=1): fused kernel absorbs rmsNorm(q), rmsNorm(k), + // sigmoid(b) → beta, and g = exp(-exp(aLog) * softplus(a + dtBias)) + // into a single Metal dispatch. Eliminates ~4-6 separate dispatches + // per GDN layer — dispatch overhead dominates at decode batch size. + (out, state) = fusedGatedDeltaUpdate( + qRaw: q, + kRaw: k, + v: v, + a: a, + b: b, + aLog: aLog, + dtBias: dtBias, + state: state, + mask: mask + ) + } else { + // Prefill (T>1): pre-compute norms as separate MLX ops. + // The fused kernel's extra register pressure hurts GPU occupancy at + // larger batch sizes; the ops-based gatedDeltaUpdate is faster there. + let dtype = q.dtype + let invScale = pow(Float(headKDim), -0.5) + let qNormed = + MLXArray(pow(invScale, 2)).asType(dtype) + * MLXFast.rmsNorm(q, weight: MLXArray.mlxNone, eps: 1e-6) + let kNormed = + MLXArray(invScale).asType(dtype) + * MLXFast.rmsNorm(k, weight: MLXArray.mlxNone, eps: 1e-6) + + (out, state) = gatedDeltaUpdate( + q: qNormed, + k: kNormed, + v: v, + a: a, + b: b, + aLog: aLog, + dtBias: dtBias, + state: state, + mask: mask + ) + } if let cache { cache[1] = state @@ -534,6 +558,8 @@ public class Qwen35TextModelInner: Module { let faMask = createAttentionMask(h: hiddenStates, cache: cacheArray?[faIdx]) let ssmMask = createSSMMask(h: hiddenStates, cache: cacheArray?[ssmIdx] as? MambaCache) + let modelDtype = hiddenStates.dtype + let isPrefill = hiddenStates.dim(1) > 1 for (i, layer) in layers.enumerated() { let mask = layer.isLinear ? ssmMask : nil let attnMask = @@ -541,6 +567,24 @@ public class Qwen35TextModelInner: Module { ? MLXFast.ScaledDotProductAttentionMaskMode.none : faMask hiddenStates = layer( hiddenStates, attentionMask: attnMask, ssmMask: mask, cache: cacheArray?[i]) + // Force dtype after every layer — quantized operations can promote + // bf16 -> fp32 inside the lazy graph (invisible to .dtype property). + // The unconditional asType adds a cast node that ensures downstream + // GDN/attention kernels receive bf16. When dtype is already correct, + // asType is a no-op (zero overhead). + hiddenStates = hiddenStates.asType(modelDtype) + + // During prefill, asyncEval after each layer. `eval` would force a + // CPU↔GPU sync per layer, stalling the CPU from building layer i+1's + // graph until the GPU finished layer i. `asyncEval` submits the + // evaluation but lets the CPU keep building ahead — the GPU pipeline + // stays fed through the 40-layer GDN+attention+MoE stack. + // Skip during decode (T=1) where the graph is tiny and eval overhead hurts tok/s. + if isPrefill, let c = cacheArray?[i] { + var toEval: [MLXArray] = [hiddenStates] + toEval.append(contentsOf: c.innerState()) + asyncEval(toEval) + } } return norm(hiddenStates) @@ -582,6 +626,9 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { if layer.isLinear { return MambaCache() } + if let maxKVSize = parameters?.maxKVSize { + return RotatingKVCache(maxSize: maxKVSize, keep: 0) + } return KVCacheSimple() } } diff --git a/Libraries/MLXLLM/Models/Qwen3Next.swift b/Libraries/MLXLLM/Models/Qwen3Next.swift index cfe0a985bd..a172afcf8a 100644 --- a/Libraries/MLXLLM/Models/Qwen3Next.swift +++ b/Libraries/MLXLLM/Models/Qwen3Next.swift @@ -257,7 +257,7 @@ public final class Qwen3NextGatedDeltaNet: Module { let convInput = concatenated([convState, mixedQKV], axis: 1) if let cache { - cache[0] = convInput[0..., (1 - convKernelSize)..., 0...] + cache[0] = convInput[0..., (1 - convKernelSize)..., 0...].contiguous() } let convOut = silu(conv1d(convInput)) diff --git a/Libraries/MLXLLM/Models/SSM.swift b/Libraries/MLXLLM/Models/SSM.swift index 7810766b66..d514f7b871 100644 --- a/Libraries/MLXLLM/Models/SSM.swift +++ b/Libraries/MLXLLM/Models/SSM.swift @@ -130,10 +130,12 @@ public func segsum(_ x: MLXArray, mask: MLXArray? = nil) -> MLXArray { var xSegsum = MLX.cumsum(x, axis: -2) if let mask = mask { + // Match xSegsum dtype to avoid fp32 promotion. + // A/B tested: bf16 segsum produces identical output to fp32 at 128-1024 context. xSegsum = which( mask[.ellipsis, .newAxis, 0...] * mask[.ellipsis, .newAxis], xSegsum, - MLXArray(-Float.infinity) + MLXArray(Float(-Float.infinity), dtype: xSegsum.dtype) ) } diff --git a/Libraries/MLXLMCommon/AttentionUtils.swift b/Libraries/MLXLMCommon/AttentionUtils.swift index 5b4e6c76bc..ed4b9d9b9c 100644 --- a/Libraries/MLXLMCommon/AttentionUtils.swift +++ b/Libraries/MLXLMCommon/AttentionUtils.swift @@ -51,7 +51,29 @@ public func attentionWithCacheUpdate( mask: mask ) } - if let quantizedKVCache = cache as? QuantizedKVCacheProtocol { + if let turboCache = cache as? TurboQuantKVCache { + // TurboQuant path: two modes depending on useCompressedAttention flag + if turboCache.useCompressedAttention { + // Compressed-domain Metal kernels — no FP16 materialization + return turboCache.compressedAttention( + queries: queries, keys: keys, values: values, + scale: scale, mask: mask + ) + } else { + // Dequant-first path: rotated FP16 cache + pre-rotated queries + MLX SDPA + let (cachedKeys, cachedValues) = turboCache.updateAndDequant( + keys: keys, values: values) + let rotatedQueries = turboCache.prepareQueries(queries) + let rotatedOutput = MLXFast.scaledDotProductAttention( + queries: rotatedQueries, + keys: cachedKeys, + values: cachedValues, + scale: scale, + mask: mask + ) + return turboCache.inverseRotateOutput(rotatedOutput) + } + } else if let quantizedKVCache = cache as? QuantizedKVCacheProtocol { let (quantizedKeys, quantizedValues) = quantizedKVCache.updateQuantized( keys: keys, values: values) return quantizedScaledDotProductAttention( diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index c59b03e716..c30e1d773f 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -102,6 +102,71 @@ public struct GenerateParameters: Sendable { /// number of tokens to consider for frequency penalty public var frequencyContextSize: Int + /// KV cache compression scheme. nil = use kvBits (affine quantization) if set. + /// "turbo1" through "turbo4" = TurboQuant compression at 1-4 bits. + /// When set, kvBits is ignored for cache creation. + public var kvScheme: String? + + /// Additional logit processors applied after built-in penalty processors. + /// Use this to inject custom processors (e.g., EOS suppression for thinking models). + public nonisolated(unsafe) var additionalProcessors: [any LogitProcessor] + + /// Reasoning effort hint (e.g., "low", "medium", "high") + public var reasoningEffort: String? + + /// N-gram size for prompt-lookup speculative decoding. When > 0, the iterator + /// searches for matching n-grams in the prompt text and uses continuations as + /// draft tokens, verifying them in a single batched forward pass. + /// + /// **Default: 0 (disabled).** The speculation path is a net-win only when the + /// generated text has enough repetition that the trigram table hits with a + /// reasonable acceptance rate. For novel prose / summarisation / chat, accept + /// rate is often low and the draft work becomes pure overhead. Enable + /// explicitly (`ngramSize: 3`, or higher) when your workload has been + /// validated to benefit — e.g. code-heavy output or repetitive templates. + public var ngramSize: Int + + /// Maximum draft tokens per n-gram speculation round. Defaults to 0 so that + /// a bare `GenerateParameters()` disables speculation end-to-end; must be + /// set in tandem with `ngramSize` when enabling. + public var maxNgramDraftTokens: Int + + /// Token ID marking the start of a thinking phase (e.g., token). + /// When set with thinkEndTokenId, log probabilities are tracked separately + /// for thinking vs. generation phases in GenerateCompletionInfo. + public var thinkStartTokenId: Int32? + + /// Token ID marking the end of a thinking phase (e.g., token). + public var thinkEndTokenId: Int32? + + /// When true, the iterator starts already inside the thinking phase. + /// Use this when was prepended as an assistant prefix in the prompt + /// rather than being generated — so the iterator never sees the start token. + public var thinkingPhasePrefilled: Bool + + /// Token ID of the harmony channel marker, typically `<|channel|>` (e.g. 200005 + /// on the GPT-OSS tokenizer). When set, phase labeling uses a harmony state + /// machine: the token immediately following the marker selects the phase via + /// ``harmonyThinkingChannelTokenIds`` / ``harmonyGenerationChannelTokenIds``. + /// Takes precedence over ``thinkStartTokenId`` / ``thinkEndTokenId``. + public var harmonyChannelMarkerTokenId: Int32? + + /// Token IDs whose appearance immediately after the harmony channel marker + /// transitions the phase to "think" (e.g. `analysis` → 35644 on GPT-OSS). + public var harmonyThinkingChannelTokenIds: [Int32] + + /// Token IDs whose appearance immediately after the harmony channel marker + /// transitions the phase to "gen" (e.g. `final` → 17196 on GPT-OSS). + public var harmonyGenerationChannelTokenIds: [Int32] + + /// When true, per-token log probs, token IDs, and phase labels are stored + /// in the TokenIterator for downstream KLD computation. + public var collectPerTokenData: Bool + + /// When true, accumulate log probabilities for perplexity computation. + /// Default: false. Set to true when perplexity tracking is needed. + public var trackPerplexity: Bool + public init( maxTokens: Int? = nil, maxKVSize: Int? = nil, @@ -118,7 +183,20 @@ public struct GenerateParameters: Sendable { presenceContextSize: Int = 20, frequencyPenalty: Float? = nil, frequencyContextSize: Int = 20, - prefillStepSize: Int = 512 + prefillStepSize: Int = 512, + kvScheme: String? = nil, + additionalProcessors: [any LogitProcessor] = [], + reasoningEffort: String? = nil, + ngramSize: Int = 0, + maxNgramDraftTokens: Int = 0, + thinkStartTokenId: Int32? = nil, + thinkEndTokenId: Int32? = nil, + thinkingPhasePrefilled: Bool = false, + harmonyChannelMarkerTokenId: Int32? = nil, + harmonyThinkingChannelTokenIds: [Int32] = [], + harmonyGenerationChannelTokenIds: [Int32] = [], + collectPerTokenData: Bool = false, + trackPerplexity: Bool = false ) { self.maxTokens = maxTokens self.maxKVSize = maxKVSize @@ -136,6 +214,19 @@ public struct GenerateParameters: Sendable { self.frequencyPenalty = frequencyPenalty self.frequencyContextSize = frequencyContextSize self.prefillStepSize = prefillStepSize + self.kvScheme = kvScheme + self.additionalProcessors = additionalProcessors + self.reasoningEffort = reasoningEffort + self.ngramSize = ngramSize + self.maxNgramDraftTokens = maxNgramDraftTokens + self.thinkStartTokenId = thinkStartTokenId + self.thinkEndTokenId = thinkEndTokenId + self.thinkingPhasePrefilled = thinkingPhasePrefilled + self.harmonyChannelMarkerTokenId = harmonyChannelMarkerTokenId + self.harmonyThinkingChannelTokenIds = harmonyThinkingChannelTokenIds + self.harmonyGenerationChannelTokenIds = harmonyGenerationChannelTokenIds + self.collectPerTokenData = collectPerTokenData + self.trackPerplexity = trackPerplexity } public func sampler() -> LogitSampler { @@ -152,46 +243,37 @@ public struct GenerateParameters: Sendable { } } - public func processor() -> LogitProcessor? { - let repetitionContext: RepetitionContext? + public func processor() -> (any LogitProcessor)? { + var all: [any LogitProcessor] = [] + if let repetitionPenalty, repetitionPenalty != 0, repetitionContextSize > 0 { - repetitionContext = RepetitionContext( - repetitionPenalty: repetitionPenalty, - repetitionContextSize: repetitionContextSize - ) - } else { - repetitionContext = nil + all.append( + RepetitionContext( + repetitionPenalty: repetitionPenalty, + repetitionContextSize: repetitionContextSize)) } - let presenceContext: PresencePenaltyContext? if let presencePenalty, presencePenalty != 0, presenceContextSize > 0 { - presenceContext = PresencePenaltyContext( - presencePenalty: presencePenalty, - presenceContextSize: presenceContextSize - ) - } else { - presenceContext = nil + all.append( + PresencePenaltyContext( + presencePenalty: presencePenalty, + presenceContextSize: presenceContextSize)) } - let frequencyContext: FrequencyPenaltyContext? if let frequencyPenalty, frequencyPenalty != 0, frequencyContextSize > 0 { - frequencyContext = FrequencyPenaltyContext( - frequencyPenalty: frequencyPenalty, - frequencyContextSize: frequencyContextSize - ) - } else { - frequencyContext = nil + all.append( + FrequencyPenaltyContext( + frequencyPenalty: frequencyPenalty, + frequencyContextSize: frequencyContextSize)) } - if repetitionContext == nil && presenceContext == nil && frequencyContext == nil { - return nil - } + all.append(contentsOf: additionalProcessors) - return PenaltyProcessor( - repetitionContext: repetitionContext, - presenceContext: presenceContext, - frequencyContext: frequencyContext - ) + switch all.count { + case 0: return nil + case 1: return all[0] + default: return CompositeLogitProcessor(processors: all) + } } } @@ -333,20 +415,24 @@ struct TokenRing { } /// Bulk-load from a prompt. Keeps the last `capacity` tokens. + /// + /// Accepts either a 1D `[seqLen]` or 2D `[1, seqLen]` prompt — `LMInput.text.tokens` + /// is typically 2D after `container.prepare(input:)`. Flatten first so `n` reflects + /// the sequence length regardless of whether a batch dimension is present. mutating func loadPrompt(_ prompt: MLXArray) { - let n = prompt.dim(0) - let promptTokens = prompt.asType(.int32) + let promptTokens = prompt.asType(.int32).reshaped(-1) + let n = promptTokens.dim(0) if n <= capacity { if n < capacity { let padding = MLXArray.zeros([capacity - n], type: Int32.self) - buffer = concatenated([promptTokens.reshaped(-1), padding]) + buffer = concatenated([promptTokens, padding]) } else { - buffer = promptTokens.reshaped(-1) + buffer = promptTokens } count = n writeIndex = n % capacity } else { - buffer = promptTokens[(-capacity)...].reshaped(-1) + buffer = promptTokens[(-capacity)...] count = capacity writeIndex = 0 } @@ -490,11 +576,111 @@ public struct PenaltyProcessor: LogitProcessor { } } +/// Composes multiple logit processors into a single processor. +public struct CompositeLogitProcessor: LogitProcessor { + var processors: [any LogitProcessor] + + public init(processors: [any LogitProcessor]) { + self.processors = processors + } + + mutating public func prompt(_ prompt: MLXArray) { + for i in 0.. MLXArray { + var logits = logits + for processor in processors { + logits = processor.process(logits: logits) + } + return logits + } + + mutating public func didSample(token: MLXArray) { + for i in 0.. PerTokenData? +} + +extension TokenIteratorProtocol { + /// Default: iterators that don't capture per-token data return nil. + public func finalizePerTokenData() -> PerTokenData? { nil } } /// Generator of tokens. @@ -526,7 +712,7 @@ public struct TokenIterator: TokenIteratorProtocol { var y: LMInput.Text var cache: [KVCache] - var processor: LogitProcessor? + var processor: (any LogitProcessor)? let sampler: LogitSampler var tokenCount = 0 @@ -536,6 +722,27 @@ public struct TokenIterator: TokenIteratorProtocol { let kvBits: Int? let kvGroupSize: Int let quantizedKVStart: Int + let kvScheme: String? + + // Phase tracking for per-token data capture (cheap Ints / Sets / Bool, + // only read at finalize time — no inference-loop cost). Three mutually + // exclusive modes: + // • harmonyChannelMarkerTokenId set → harmony channel transitions. + // • thinkStartTokenId + thinkEndTokenId set → bracket pair. + // • neither set → all tokens labelled "gen". + let thinkStartTokenId: Int? + let thinkEndTokenId: Int? + let thinkingPhasePrefilled: Bool + let harmonyChannelMarkerTokenId: Int? + let harmonyThinkingChannelTokenIds: Set + let harmonyGenerationChannelTokenIds: Set + + /// Lazy per-token logprob/id capture. Non-nil only when parameters enable + /// ``GenerateParameters/trackPerplexity`` or + /// ``GenerateParameters/collectPerTokenData``. The `if let` check in + /// ``convertToToken(logits:)`` is the only inference-path cost when + /// capture is disabled. + let perTokenCapture: PerTokenDataCapture? // Internal metrics var promptPrefillTime: TimeInterval = 0.0 @@ -564,6 +771,15 @@ public struct TokenIterator: TokenIteratorProtocol { self.kvBits = parameters.kvBits self.kvGroupSize = parameters.kvGroupSize self.quantizedKVStart = parameters.quantizedKVStart + self.kvScheme = parameters.kvScheme + + self.thinkStartTokenId = parameters.thinkStartTokenId.map { Int($0) } + self.thinkEndTokenId = parameters.thinkEndTokenId.map { Int($0) } + self.thinkingPhasePrefilled = parameters.thinkingPhasePrefilled + self.harmonyChannelMarkerTokenId = parameters.harmonyChannelMarkerTokenId.map { Int($0) } + self.harmonyThinkingChannelTokenIds = Set(parameters.harmonyThinkingChannelTokenIds.map { Int($0) }) + self.harmonyGenerationChannelTokenIds = Set(parameters.harmonyGenerationChannelTokenIds.map { Int($0) }) + self.perTokenCapture = parameters.needsPerTokenCapture ? PerTokenDataCapture() : nil self.promptPrefillTime = try measure { try prepare(input: .init(text: y), windowSize: parameters.prefillStepSize) @@ -597,6 +813,15 @@ public struct TokenIterator: TokenIteratorProtocol { self.kvBits = parameters.kvBits self.kvGroupSize = parameters.kvGroupSize self.quantizedKVStart = parameters.quantizedKVStart + self.kvScheme = parameters.kvScheme + + self.thinkStartTokenId = parameters.thinkStartTokenId.map { Int($0) } + self.thinkEndTokenId = parameters.thinkEndTokenId.map { Int($0) } + self.thinkingPhasePrefilled = parameters.thinkingPhasePrefilled + self.harmonyChannelMarkerTokenId = parameters.harmonyChannelMarkerTokenId.map { Int($0) } + self.harmonyThinkingChannelTokenIds = Set(parameters.harmonyThinkingChannelTokenIds.map { Int($0) }) + self.harmonyGenerationChannelTokenIds = Set(parameters.harmonyGenerationChannelTokenIds.map { Int($0) }) + self.perTokenCapture = parameters.needsPerTokenCapture ? PerTokenDataCapture() : nil self.promptPrefillTime = try measure { try prepare(input: input, windowSize: parameters.prefillStepSize) @@ -615,7 +840,7 @@ public struct TokenIterator: TokenIteratorProtocol { /// - maxTokens: maximum number of tokens to generate public init( input: LMInput, model: any LanguageModel, cache: [KVCache]? = nil, - processor: LogitProcessor?, sampler: LogitSampler, prefillStepSize: Int = 512, + processor: (any LogitProcessor)?, sampler: LogitSampler, prefillStepSize: Int = 512, maxTokens: Int? = nil ) throws { self.model = model @@ -630,6 +855,17 @@ public struct TokenIterator: TokenIteratorProtocol { self.kvBits = nil self.kvGroupSize = 64 self.quantizedKVStart = 0 + self.kvScheme = nil + + // The manual init does not carry thinking config or per-token capture. + // Callers that need PPL/KLD should use the `parameters:` init instead. + self.thinkStartTokenId = nil + self.thinkEndTokenId = nil + self.thinkingPhasePrefilled = false + self.harmonyChannelMarkerTokenId = nil + self.harmonyThinkingChannelTokenIds = [] + self.harmonyGenerationChannelTokenIds = [] + self.perTokenCapture = nil self.promptPrefillTime = try measure { try prepare(input: input, windowSize: prefillStepSize) @@ -646,7 +882,10 @@ public struct TokenIterator: TokenIteratorProtocol { // evaluate the remainder of the prompt -- this primes the pump let token = step(previous: y) y = .init(tokens: token) - asyncEval(y.tokens) + + // Sync-eval first decode token — asyncEval causes pad-token bug on Gemma 4 + // (second decode forward pass starts before prefill's KV writes commit). + eval(y.tokens) case .logits(let result): y = .init(tokens: convertToToken(logits: result.logits)) @@ -664,11 +903,157 @@ public struct TokenIterator: TokenIteratorProtocol { // transform logits back to a token let y = sampler.sample(logits: logits) + // Opt-in per-token data capture for PPL / KLD. + // + // Zero inference-path overhead when `perTokenCapture == nil` — the + // guard is a single pointer nil-check the optimizer can hoist. + // + // When enabled, we emit a scalar-output kernel chain per step: + // 1. `logSumExp(logits, axes: [-1])` — one reduction producing [1]. + // 2. `takeAlong(logits, y_exp, axis: -1)` — scalar gather producing [1, 1]. + // 3. subtract to get logprob[y] = logits[y] - logSumExp(logits). + // + // This avoids materialising a full-vocab logSoftmax output tensor + // (V can be 250k+ tokens → ~1MB per step on decode). Both branches + // depend on `logits` only — no data dependency on `y` for the + // reduction — so the reduction runs concurrently with sampling. + // `asyncEval(selected)` detaches the scalar subgraph from the + // token-eval pipeline so the next forward pass is not blocked on + // the logprob. + if let capture = perTokenCapture { + let logSumExpLogits = logSumExp(logits, axes: [-1]) + let yExpanded = y.expandedDimensions(axis: -1) + let yLogit = takeAlong(logits, yExpanded, axis: -1) + let selected = yLogit - logSumExpLogits + asyncEval(selected) + capture.logProbs.append(selected) + capture.tokenIds.append(y) + } + processor?.didSample(token: y) return y } + /// Flush lazy per-token data collected during generation. + /// + /// Called by the generation loop after `Stream().synchronize()` so all + /// captured logprob and token-id MLXArrays have finished evaluating on + /// the GPU. Performs one batched GPU→CPU transfer for the whole run, + /// assigns phase labels ("think" / "gen") based on the + /// model's configured `thinkStartTokenId` / `thinkEndTokenId`, and + /// computes `exp(-mean(logprobs))` per phase. + /// + /// Returns `nil` when per-token capture was not enabled for this run. + public func finalizePerTokenData() -> PerTokenData? { + guard let capture = perTokenCapture, !capture.logProbs.isEmpty else { + return nil + } + + // Batch the GPU→CPU transfer: concatenate all the 1-element logprob + // tensors into a single [N] tensor, then pull it to CPU once. + let reshapedLogProbs = capture.logProbs.map { $0.reshaped(1) } + let reshapedIds = capture.tokenIds.map { $0.reshaped(1) } + let stackedLogprobs = concatenated(reshapedLogProbs).asType(.float32) + let stackedIds = concatenated(reshapedIds).asType(.int32) + + let floatLogprobs = stackedLogprobs.asArray(Float.self) + let intIds = stackedIds.asArray(Int32.self).map { Int($0) } + + // Phase labels — pure Swift, zero GPU work. Three modes dispatched + // by which fields were populated at init time: + // 1. Harmony channel mode (GPT-OSS): <|channel|> + // <|message|> ... where the channel-name token flips phase. + // 2. Bracket mode (Qwen, Gemma 4): ... + // where a single token opens and another closes the block. + // 3. None: every token labelled + // "gen". + let phases: [String] = labelPhases(intIds) + + func perplexity(for phase: String) -> Float? { + var sum: Double = 0 + var count = 0 + for i in intIds.indices where phases[i] == phase { + sum += Double(floatLogprobs[i]) + count += 1 + } + guard count > 0 else { return nil } + return Float(exp(-sum / Double(count))) + } + + return PerTokenData( + tokenIds: intIds, + logProbs: floatLogprobs, + phases: phases, + thinkingPerplexity: perplexity(for: "think"), + generationPerplexity: perplexity(for: "gen") + ) + } + + /// Assign a phase label ("think" / "gen") to every generated token. + /// + /// Harmony mode (GPT-OSS and other harmony-format models) is a 2-state + /// state machine: on each token we check whether it is the channel marker + /// (e.g. `<|channel|>` → 200005). The very next token is the channel name + /// (`analysis` → thinking, `final` / `commentary` → generation). The + /// marker, name, and subsequent message tokens are all attributed to the + /// resolved phase. Unknown channel names keep the prior phase. + /// + /// Bracket mode (Qwen, Gemma 4) is a single-token boundary: seeing the + /// configured `thinkStartTokenId` opens the block, seeing the + /// `thinkEndTokenId` closes it; both markers themselves stay in the + /// "think" bucket. + private func labelPhases(_ intIds: [Int]) -> [String] { + if let markerId = harmonyChannelMarkerTokenId { + var phases: [String] = [] + phases.reserveCapacity(intIds.count) + var inThinking = thinkingPhasePrefilled + var awaitingChannelName = false + for id in intIds { + if id == markerId { + awaitingChannelName = true + // Attribute marker to current phase — transition hasn't + // been resolved yet. + phases.append(inThinking ? "think" : "gen") + continue + } + if awaitingChannelName { + awaitingChannelName = false + if harmonyThinkingChannelTokenIds.contains(id) { + inThinking = true + } else if harmonyGenerationChannelTokenIds.contains(id) { + inThinking = false + } + // Unknown channel names fall through with phase unchanged. + phases.append(inThinking ? "think" : "gen") + continue + } + phases.append(inThinking ? "think" : "gen") + } + return phases + } + + // Bracket mode. + var phases: [String] = [] + phases.reserveCapacity(intIds.count) + var inThinking = thinkStartTokenId != nil && thinkingPhasePrefilled + for id in intIds { + if !inThinking, let startId = thinkStartTokenId, id == startId { + inThinking = true + phases.append("think") + continue + } + if inThinking, let endId = thinkEndTokenId, id == endId { + inThinking = false + // The end-of-think token itself is part of the thinking phase. + phases.append("think") + continue + } + phases.append(inThinking ? "think" : "gen") + } + return phases + } + /// Evaluate the next token and return the new token (y), updating cache state mutating func step(previous: LMInput.Text) -> MLXArray { let result = model( @@ -743,7 +1128,7 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { var draftCache: [KVCache] let quantizeKVCache: (inout [KVCache]) -> Void - var processor: LogitProcessor? + var processor: (any LogitProcessor)? let sampler: LogitSampler var tokenCount = 0 @@ -757,6 +1142,18 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { // Internal metrics var promptPrefillTime: TimeInterval = 0.0 + /// Tokens accepted from draft model (for acceptance rate tracking). + public private(set) var draftAcceptedCount = 0 + + /// Total draft tokens proposed (for acceptance rate tracking). + public private(set) var draftProposedCount = 0 + + /// The acceptance rate of draft tokens (0.0 to 1.0). + public var acceptanceRate: Double { + guard draftProposedCount > 0 else { return 0 } + return Double(draftAcceptedCount) / Double(draftProposedCount) + } + /// Initialize a `SpeculativeTokenIterator` with the given input. /// /// - Parameters: @@ -845,11 +1242,17 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { return } + // Snapshot MambaCache layers before speculation (SSM state is cumulative, + // not trimmable, so we must restore on rejection) + snapshotMambaCaches(mainCache) + snapshotMambaCaches(draftCache) + // Draft generation: autoregressive loop with draft model var draftProcessor = processor // Copy to discard later var draftTokens = [MLXArray]() for _ in 0 ..< numDraft { let draftResult = draftModel(draftY[text: .newAxis], cache: draftCache, state: nil) + quantizeKVCache(&draftCache) var draftLogits = draftResult.logits[0..., -1, 0...] draftLogits = draftProcessor?.process(logits: draftLogits) ?? draftLogits let draftToken = sampler.sample(logits: draftLogits) @@ -900,16 +1303,29 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { accepted += 1 } + // Update acceptance metrics + draftAcceptedCount += accepted + draftProposedCount += numDraft + // Always emit the main model's token at position `accepted` // (either the correction token or the bonus token if all drafts matched) let finalToken = mainTokens[accepted ... accepted] processor?.didSample(token: finalToken) pendingTokens.append(mainTokensList[accepted]) - // Rewind caches for rejected tokens + // Rewind trimmable caches for rejected tokens trimPromptCache(mainCache, numTokens: numDraft - accepted) trimPromptCache(draftCache, numTokens: Swift.max(numDraft - accepted - 1, 0)) + // Restore MambaCache layers on rejection, discard snapshots on full acceptance + if accepted == numDraft { + discardMambaSnapshots(mainCache) + discardMambaSnapshots(draftCache) + } else { + restoreMambaCaches(mainCache) + restoreMambaCaches(draftCache) + } + // Apply dynamic cache quantization after rewind quantizeKVCache(&mainCache) quantizeKVCache(&draftCache) @@ -930,6 +1346,35 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { } } + // MARK: - MambaCache Helpers + + /// Snapshot all MambaCache layers for potential restoration on rejection. + private func snapshotMambaCaches(_ cache: [KVCache]) { + for c in cache { + if let mambaCache = c as? MambaCache { + mambaCache.snapshot() + } + } + } + + /// Restore all MambaCache layers from their snapshots (draft tokens rejected). + private func restoreMambaCaches(_ cache: [KVCache]) { + for c in cache { + if let mambaCache = c as? MambaCache { + mambaCache.restore() + } + } + } + + /// Discard MambaCache snapshots without restoring (all draft tokens accepted). + private func discardMambaSnapshots(_ cache: [KVCache]) { + for c in cache { + if let mambaCache = c as? MambaCache { + mambaCache.discardSnapshot() + } + } + } + mutating public func next() -> Int? { if let maxTokens, tokenCount >= maxTokens { return nil @@ -1297,12 +1742,23 @@ public func generate( didGenerate(token) } + // runSynchronousGenerationLoop already calls Stream().synchronize() so any + // lazy logprobs captured during the loop are safe to flush here. The + // capture box is a reference held by a class so the appends the loop made + // (through its own mutable copy of the iterator) are visible to us. + let perTokenData = iterator.finalizePerTokenData() + return GenerateCompletionInfo( promptTokenCount: input.text.tokens.size, generationTokenCount: result.generatedTokenIds.count, promptTime: result.promptTime + result.promptPrefillTime, generationTime: result.generateTime, - stopReason: result.stopReason + stopReason: result.stopReason, + perTokenLogProbs: perTokenData?.logProbs, + perTokenIds: perTokenData?.tokenIds, + perTokenPhases: perTokenData?.phases, + generationPerplexity: perTokenData?.generationPerplexity, + thinkingPerplexity: perTokenData?.thinkingPerplexity ) } @@ -1734,18 +2190,28 @@ private func generateLoopTask( let now = Date.timeIntervalSinceReferenceDate let generateTime = now - start + // Synchronize before flushing per-token data so the logprob + // MLXArrays captured during the loop have all been evaluated. + // The synchronize is required for asyncEval-driven safety + // anyway; we simply moved it ahead of the info-event emit. + Stream().synchronize() + + let perTokenData = iterator.finalizePerTokenData() + let info = GenerateCompletionInfo( promptTokenCount: promptTokenCount, generationTokenCount: tokenCount, promptTime: promptTime + iterator.promptPrefillTime, generationTime: generateTime, - stopReason: stopReason ?? .cancelled + stopReason: stopReason ?? .cancelled, + perTokenLogProbs: perTokenData?.logProbs, + perTokenIds: perTokenData?.tokenIds, + perTokenPhases: perTokenData?.phases, + generationPerplexity: perTokenData?.generationPerplexity, + thinkingPerplexity: perTokenData?.thinkingPerplexity ) _ = continuation.yield(handler.infoEvent(info)) - // Synchronize with the stream to ensure tasks are completed - Stream().synchronize() - // Finalize the stream continuation.finish() } @@ -1809,6 +2275,21 @@ public struct GenerateCompletionInfo: Sendable { /// Reason generation stopped. public let stopReason: GenerateStopReason + /// Per-token log probabilities collected during generation (when collectPerTokenData is true). + public var perTokenLogProbs: [Float]? + + /// Per-token IDs collected during generation (when collectPerTokenData is true). + public var perTokenIds: [Int]? + + /// Per-token phase labels ("think" or "gen") collected during generation. + public var perTokenPhases: [String]? + + /// Perplexity computed over the generation (non-thinking) phase. + public var generationPerplexity: Float? + + /// Perplexity computed over the thinking phase. + public var thinkingPerplexity: Float? + /// The number of tokens processed per second during the prompt phase. public var promptTokensPerSecond: Double { Double(promptTokenCount) / promptTime @@ -1824,13 +2305,23 @@ public struct GenerateCompletionInfo: Sendable { generationTokenCount: Int, promptTime: TimeInterval, generationTime: TimeInterval, - stopReason: GenerateStopReason = .stop + stopReason: GenerateStopReason = .stop, + perTokenLogProbs: [Float]? = nil, + perTokenIds: [Int]? = nil, + perTokenPhases: [String]? = nil, + generationPerplexity: Float? = nil, + thinkingPerplexity: Float? = nil ) { self.promptTokenCount = promptTokenCount self.generationTokenCount = generationTokenCount self.promptTime = promptTime self.generateTime = generationTime self.stopReason = stopReason + self.perTokenLogProbs = perTokenLogProbs + self.perTokenIds = perTokenIds + self.perTokenPhases = perTokenPhases + self.generationPerplexity = generationPerplexity + self.thinkingPerplexity = thinkingPerplexity } public func summary() -> String { diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index d72c18bafe..633aeab5b5 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -45,6 +45,11 @@ public protocol KVCache: Evaluatable { /// update the cache with new keys and values and return all keys/values func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) + /// Read the current cached keys and values without modifying the cache. + /// Used by KV sharing (Gemma 4) where shared layers read a donor's cached K/V. + /// Returns nil if the cache is empty. + func peek() -> (MLXArray, MLXArray)? + /// get the current state for serialization var state: [MLXArray] { get set } @@ -58,6 +63,10 @@ public protocol KVCache: Evaluatable { @discardableResult func trim(_ n: Int) -> Int + /// Actual memory footprint in bytes of all arrays held by this cache. + /// Computed directly from stored array shapes and dtypes — not from MLX memory pool. + var memoryBytes: Int { get } + /// Create an attention mask for this cache /// /// This method encapsulates cache-specific mask creation logic. Implementations should handle offset capping, window size logic, @@ -118,6 +127,28 @@ public protocol QuantizedKVCacheProtocol: KVCache { func getQuantizedState() -> ((MLXArray, MLXArray, MLXArray?), (MLXArray, MLXArray, MLXArray?))? } +/// Compute the byte size of an MLXArray from its shape and dtype. +func arrayBytes(_ array: MLXArray?) -> Int { + guard let array else { return 0 } + let elements = array.shape.reduce(1, *) + return elements * array.dtype.bytesPerElement +} + +extension DType { + var bytesPerElement: Int { + switch self { + case .bool: return 1 + case .uint8, .int8: return 1 + case .uint16, .int16, .float16, .bfloat16: return 2 + case .uint32, .int32, .float32: return 4 + case .uint64, .int64: return 8 + case .float64: return 8 + case .complex64: return 8 + default: return 4 + } + } +} + /// Base cache implementation providing default behaviors open class BaseKVCache: KVCache { public var offset: Int = 0 @@ -125,6 +156,11 @@ open class BaseKVCache: KVCache { public func innerState() -> [MLXArray] { [] } + /// Default: sum bytes of all state arrays. Subclasses should override for accuracy. + open var memoryBytes: Int { + state.reduce(0) { $0 + arrayBytes($1) } + } + open func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { fatalError("update(keys:values:) must be implemented by subclass") } @@ -152,6 +188,10 @@ open class BaseKVCache: KVCache { @discardableResult open func trim(_ n: Int) -> Int { 0 } + open func peek() -> (MLXArray, MLXArray)? { + return nil // Subclasses override to return their stored K/V + } + open func copy() -> any KVCache { fatalError("copy() must be implemented by subclass") } @@ -317,6 +357,11 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { internal var values: MLXArray? public var step = 256 + /// Last K/V returned from update() — used by Gemma 4 KV sharing to avoid + /// redundant peek() slice ops for donor layers. + public var lastReturnedKeys: MLXArray? + public var lastReturnedValues: MLXArray? + public override init() { super.init() } @@ -325,6 +370,11 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { [self.keys, self.values].compactMap { $0 } } + public override func peek() -> (MLXArray, MLXArray)? { + guard let keys, let values else { return nil } + return (keys[.ellipsis, .. (MLXArray, MLXArray) { let previous = self.offset @@ -353,6 +403,10 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { } self.keys = concatenated([currentKeys, newK], axis: 2) self.values = concatenated([currentValues, newV], axis: 2) + // Materialize to break the lazy graph chain — without this, + // each resize keeps all prior arrays alive in the compute graph, + // causing GPU memory to grow monotonically with context length. + eval(self.keys!, self.values!) } else { self.keys = newK self.values = newV @@ -367,6 +421,9 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { let returnedKeys = self.keys![.ellipsis, .. TurboQuantKVCache { + let turboCache = TurboQuantKVCache(bits: bits, keyBits: keyBits, valueBits: valueBits) + + if let keys = self.keys, let values = self.values, offset > 0 { + // Transfer raw K/V state — TurboQuantKVCache will compress on first decode + turboCache.state = [ + keys[.ellipsis, .. any KVCache { let new = KVCacheSimple() new.step = self.step @@ -450,6 +537,10 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { private var step: Int private var idx: Int = 0 + /// Last K/V returned from update() — used by Gemma 4 KV sharing. + public var lastReturnedKeys: MLXArray? + public var lastReturnedValues: MLXArray? + public override var maxSize: Int? { maxCacheSize } public init(maxSize: Int, keep: Int = 0, step: Int = 256) { @@ -584,9 +675,21 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { } else { updateConcat(keys: keys, values: values) } + self.lastReturnedKeys = result.0 + self.lastReturnedValues = result.1 return result } + /// Read the current cached keys and values in temporal order without modifying the cache. + /// Used by KV sharing (e.g., Gemma 4) where shared layers read a donor's cached K/V. + public override func peek() -> (MLXArray, MLXArray)? { + guard let keys, let values else { return nil } + let orderedKeys = temporalOrder(keys) + let orderedValues = temporalOrder(values) + let len = min(offset, orderedKeys.dim(2)) + return (orderedKeys[.ellipsis, .. (MLXArray, MLXArray) { @@ -1152,6 +1263,13 @@ public class ArraysCache: BaseKVCache { /// Simple cache for Mamba-style state space models public class MambaCache: ArraysCache { + + /// Saved state for snapshot/restore during speculative decoding. + /// MambaCache is not trimmable (SSM state is cumulative), so we + /// snapshot before speculation and restore on rejection. + private var snapshotState: [MLXArray]? + private var snapshotOffset: Int? + public init(leftPadding: [Int]? = nil) { super.init(size: 2, leftPadding: leftPadding) } @@ -1166,6 +1284,29 @@ public class MambaCache: ArraysCache { new.leftPadding = self.leftPadding return new } + + // MARK: - Speculative Decoding Support + + /// Save the current state so it can be restored if speculation is rejected. + public func snapshot() { + let s = self.state + snapshotState = s.isEmpty ? nil : s.map { $0[.ellipsis] } + snapshotOffset = self.offset + } + + /// Restore state from a previous snapshot (used when draft tokens are rejected). + public func restore() { + guard let savedState = snapshotState, let savedOffset = snapshotOffset else { return } + self.state = savedState + self.offset = savedOffset + discardSnapshot() + } + + /// Discard the snapshot without restoring (all draft tokens accepted). + public func discardSnapshot() { + snapshotState = nil + snapshotOffset = nil + } } /// Composite cache that manages multiple sub-caches diff --git a/Libraries/MLXLMCommon/LanguageModel.swift b/Libraries/MLXLMCommon/LanguageModel.swift index 822d7ac3ac..bb41a192b1 100644 --- a/Libraries/MLXLMCommon/LanguageModel.swift +++ b/Libraries/MLXLMCommon/LanguageModel.swift @@ -179,6 +179,17 @@ public protocol LanguageModel: Module { /// Models can override this to inspect metadata (e.g. check `metadata["format"] == "mlx"`) /// and skip or customize sanitization accordingly. func sanitize(weights: [String: MLXArray], metadata: [String: String]) -> [String: MLXArray] + + /// Optionally remap ``BaseConfiguration/PerLayerQuantization`` keys so they + /// match the Swift module paths for this model. + /// + /// VLM configs use Python-style paths like `language_model.model.layers.0...`, + /// but when the inner text model is loaded stand-alone, the Swift paths drop + /// the `language_model.` prefix. Override this to strip that prefix (or + /// perform any other remapping) so mixed-precision quantization overrides + /// resolve correctly. + func sanitize(perLayerQuantization: BaseConfiguration.PerLayerQuantization?) + -> BaseConfiguration.PerLayerQuantization? } extension LanguageModel { @@ -204,6 +215,12 @@ extension LanguageModel { { sanitize(weights: weights) } + + public func sanitize(perLayerQuantization: BaseConfiguration.PerLayerQuantization?) + -> BaseConfiguration.PerLayerQuantization? + { + perLayerQuantization + } } /// Optional protocol that can be implemented by ``LanguageModel`` and will diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 715f34e20b..e951b7430e 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -36,12 +36,17 @@ public func loadWeights( // per-model cleanup (models can inspect metadata to customize behavior) weights = model.sanitize(weights: weights, metadata: metadata) + // Allow the model to remap per-layer quantization keys to match its Swift + // module paths (e.g. Gemma4 text-only loads strip the `language_model.` prefix). + let effectivePerLayerQuantization = model.sanitize( + perLayerQuantization: perLayerQuantization) + // quantize if needed - if quantization != nil || perLayerQuantization != nil { + if quantization != nil || effectivePerLayerQuantization != nil { quantize(model: model) { path, module in if weights["\(path).scales"] != nil { - if let perLayerQuantization { - return perLayerQuantization.quantization(layer: path)?.asTuple + if let effectivePerLayerQuantization { + return effectivePerLayerQuantization.quantization(layer: path)?.asTuple } else { return quantization?.asTuple } diff --git a/Libraries/MLXLMCommon/ModelContainer.swift b/Libraries/MLXLMCommon/ModelContainer.swift index 9ecc309d76..7930a5ab19 100644 --- a/Libraries/MLXLMCommon/ModelContainer.swift +++ b/Libraries/MLXLMCommon/ModelContainer.swift @@ -183,10 +183,12 @@ public final class ModelContainer: Sendable { /// allowing non-Sendable types like `LMInput` to safely cross isolation boundaries. public func generate( input: consuming sending LMInput, + cache: consuming sending [KVCache]? = nil, parameters: GenerateParameters, wiredMemoryTicket: WiredMemoryTicket? = nil ) async throws -> AsyncStream { let input = SendableBox(input) + let cache = SendableBox(cache) // Note: this is only visiting the model exclusively // for the pre-fill time. Beyond that there is no @@ -198,6 +200,7 @@ public final class ModelContainer: Sendable { return try await context.read { context in try MLXLMCommon.generate( input: input.consume(), + cache: cache.consume(), parameters: parameters, context: context, wiredMemoryTicket: wiredMemoryTicket @@ -205,6 +208,58 @@ public final class ModelContainer: Sendable { } } + /// Generate raw token IDs from the model. + /// + /// Unlike `generate()` which yields detokenized `.chunk(String)` events, + /// this yields `.token(Int)` events with raw integer token IDs. This enables + /// downstream parsers that need token-level control. + /// + /// - Parameters: + /// - input: Prepared language model input + /// - cache: Optional pre-created KV cache + /// - parameters: Generation parameters + /// - includeStopToken: If true, stop/EOS tokens are yielded before termination + /// - wiredMemoryTicket: Optional wired memory ticket + /// - Returns: An AsyncStream of token generation events + public func generateTokens( + input: consuming sending LMInput, + cache: consuming sending [KVCache]? = nil, + parameters: GenerateParameters, + includeStopToken: Bool = false, + wiredMemoryTicket: WiredMemoryTicket? = nil + ) async throws -> AsyncStream { + let input = SendableBox(input) + let cache = SendableBox(cache) + + return try await context.read { context in + try MLXLMCommon.generateTokens( + input: input.consume(), + cache: cache.consume(), + parameters: parameters, + context: context, + includeStopToken: includeStopToken, + wiredMemoryTicket: wiredMemoryTicket + ) + } + } + + /// Create a new KV cache array for the model with the given parameters. + /// + /// Use this to pre-create caches for reuse across multiple generation calls. + /// The returned cache array matches the model's layer structure (one cache per layer). + /// + /// - Parameter parameters: Generation parameters (controls cache type: simple vs rotating) + /// - Returns: Array of KVCache instances, one per model layer + public func newCache(parameters: GenerateParameters? = nil) async -> [KVCache] { + // KVCache is not Sendable, but newCache creates fresh independent instances + // that are safe to transfer across isolation boundaries. + nonisolated(unsafe) var result: [KVCache] = [] + await context.read { context in + result = context.model.newCache(parameters: parameters) + } + return result + } + /// Decode token IDs to a string. /// /// - Parameter tokenIds: Array of token IDs diff --git a/Libraries/MLXLMCommon/ModelFactory.swift b/Libraries/MLXLMCommon/ModelFactory.swift index df8a8ccc34..876b9d37ba 100644 --- a/Libraries/MLXLMCommon/ModelFactory.swift +++ b/Libraries/MLXLMCommon/ModelFactory.swift @@ -65,7 +65,7 @@ public enum ModelFactoryError: LocalizedError { /// /// See also ``ModelFactory/loadContainer(from:using:configuration:useLatest:progressHandler:)`` and /// ``ModelContainer``. -public struct ModelContext { +public struct ModelContext: @unchecked Sendable { public var configuration: ModelConfiguration public var model: any LanguageModel public var processor: any UserInputProcessor diff --git a/Libraries/MLXLMCommon/SwitchLayers.swift b/Libraries/MLXLMCommon/SwitchLayers.swift index a4bfdbc447..e420b61acb 100644 --- a/Libraries/MLXLMCommon/SwitchLayers.swift +++ b/Libraries/MLXLMCommon/SwitchLayers.swift @@ -86,6 +86,67 @@ public class SwitchGLU: Module { } } +// MARK: - FusedGateUpSwitchGLU + +/// SwitchGLU variant with fused gate_up_proj weight — used by Gemma 4 MoE (26B) and +/// GPT-OSS. Models ship with a single `gate_up_proj` weight of shape +/// `[numExperts, 2*hiddenDims, inputDims]` instead of separate `gate_proj`/`up_proj`. +/// +/// Supports two activation modes: +/// - Single-argument (default): `activation(gate) * up` — silu-gated models +/// - Two-argument: `twoArgActivation(up, gate)` — GPT-OSS's clipped swiglu +public class FusedGateUpSwitchGLU: Module { + @ModuleInfo(key: "gate_up_proj") var gateUpProj: SwitchLinear + @ModuleInfo(key: "down_proj") var downProj: SwitchLinear + + let inputDims: Int + let hiddenDims: Int + let numExperts: Int + let activation: (MLXArray) -> MLXArray + let twoArgActivation: ((MLXArray, MLXArray) -> MLXArray)? + + public init( + inputDims: Int, + hiddenDims: Int, + numExperts: Int, + activation: @escaping (MLXArray) -> MLXArray = MLXNN.silu, + twoArgActivation: ((MLXArray, MLXArray) -> MLXArray)? = nil, + bias: Bool = false + ) { + self.inputDims = inputDims + self.hiddenDims = hiddenDims + self.numExperts = numExperts + self.activation = activation + self.twoArgActivation = twoArgActivation + + self._gateUpProj.wrappedValue = SwitchLinear( + inputDims: inputDims, outputDims: 2 * hiddenDims, numExperts: numExperts, bias: bias) + self._downProj.wrappedValue = SwitchLinear( + inputDims: hiddenDims, outputDims: inputDims, numExperts: numExperts, bias: bias) + + super.init() + } + + public func callAsFunction(_ x: MLXArray, _ indices: MLXArray) -> MLXArray { + var x = MLX.expandedDimensions(x, axes: [-2, -3]) + + // Single gatherQuantizedMM for both gate and up projections + let gateUp = gateUpProj(x, indices) + + let activated: MLXArray + if let twoArgActivation { + let parts = MLX.split(gateUp, parts: 2, axis: -1) + activated = twoArgActivation(parts[1], parts[0]) + } else { + let parts = MLX.split(gateUp, parts: 2, axis: -1) + activated = activation(parts[0]) * parts[1] + } + + x = downProj(activated, indices) + return MLX.squeezed(x, axis: -2) + } +} + public class SwitchLinear: Module, Quantizable { @ModuleInfo(key: "weight") var weight: MLXArray @ModuleInfo(key: "bias") var bias: MLXArray? diff --git a/Libraries/MLXLMCommon/Tool/Parsers/Llama3ToolCallParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/Llama3ToolCallParser.swift new file mode 100644 index 0000000000..cf30f80973 --- /dev/null +++ b/Libraries/MLXLMCommon/Tool/Parsers/Llama3ToolCallParser.swift @@ -0,0 +1,88 @@ +// Copyright © 2025 Apple Inc. + +import Foundation + +/// Parser for Llama 3 tool calls. +/// Llama 3 often outputs inline JSON without standard start/end tags, or preceded by `<|python_tag|>`. +/// It may also output native python function calls like `get_weather(location="San Francisco")`. +public struct Llama3ToolCallParser: ToolCallParser, Sendable { + public let startTag: String? = nil + public let endTag: String? = nil + + public init() {} + + private struct LlamaFunction: Codable { + let name: String + let parameters: [String: JSONValue]? + let arguments: [String: JSONValue]? + } + + public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? { + var text = content + + // If it outputs python tag, strip it + if let range = text.range(of: "<|python_tag|>") { + text = String(text[range.upperBound...]) + } + + let jsonStr = text.trimmingCharacters(in: .whitespacesAndNewlines) + + // Try JSON format first + if let data = jsonStr.data(using: .utf8), + let llamaFunc = try? JSONDecoder().decode(LlamaFunction.self, from: data) + { + let args = llamaFunc.parameters ?? llamaFunc.arguments ?? [:] + + let function = ToolCall.Function( + name: llamaFunc.name, + arguments: args + ) + return ToolCall(function: function) + } + + // Fallback to Pythonic format + let pythonicParser = PythonicToolCallParser() + return pythonicParser.parse(content: jsonStr, tools: tools) + } + + public func parseEOS(_ toolCallBuffer: String, tools: [[String: any Sendable]]?) -> [ToolCall] { + var text = toolCallBuffer + + // If it outputs python tag, strip it + if let range = text.range(of: "<|python_tag|>") { + text = String(text[range.upperBound...]) + } + + let jsonStr = text.trimmingCharacters(in: .whitespacesAndNewlines) + + guard let data = jsonStr.data(using: .utf8) else { + return [] + } + + // Try JSON list format + if let list = try? JSONDecoder().decode([LlamaFunction].self, from: data) { + return list.map { llamaFunc in + let args = llamaFunc.parameters ?? llamaFunc.arguments ?? [:] + let function = ToolCall.Function( + name: llamaFunc.name, + arguments: args + ) + return ToolCall(function: function) + } + } + + // Try single JSON format + if let llamaFunc = try? JSONDecoder().decode(LlamaFunction.self, from: data) { + let args = llamaFunc.parameters ?? llamaFunc.arguments ?? [:] + let function = ToolCall.Function( + name: llamaFunc.name, + arguments: args + ) + return [ToolCall(function: function)] + } + + // Try Pythonic list like [func1(args), func2(args)] or single func1(args) + let pythonicParser = PythonicToolCallParser() + return pythonicParser.parseEOS(jsonStr, tools: tools) + } +} diff --git a/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift index b0109e8580..e96d926a5a 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/PythonicToolCallParser.swift @@ -61,6 +61,42 @@ public struct PythonicToolCallParser: ToolCallParser, Sendable { return ToolCall(function: .init(name: funcName, arguments: arguments)) } + public func parseEOS(_ toolCallBuffer: String, tools: [[String: any Sendable]]?) -> [ToolCall] { + if let startTag { + return + toolCallBuffer + .components(separatedBy: startTag) + .filter { !$0.isEmpty } + .flatMap { parseMultiple(content: $0, tools: tools) } + } else { + return parseMultiple(content: toolCallBuffer, tools: tools) + } + } + + private func parseMultiple(content: String, tools: [[String: any Sendable]]?) -> [ToolCall] { + var text = content + + if let end = endTag, let endRange = text.range(of: end) { + text = String(text[..{ "name": "func", "parameters": {...} }` + case llama3 + // MARK: - Factory Methods /// Create the appropriate parser for this format. @@ -117,6 +121,8 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable { return MiniMaxM2ToolCallParser() case .mistral: return MistralToolCallParser() + case .llama3: + return Llama3ToolCallParser() } } @@ -125,11 +131,35 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable { /// This method maps known model types to their corresponding tool call formats, /// enabling automatic format detection when loading models. /// - /// - Parameter modelType: The `model_type` value from config.json + /// - Parameters: + /// - modelType: The `model_type` value from config.json + /// - configData: The raw config.json data for inspecting secondary signals (e.g. `rope_scaling` for Llama 3) /// - Returns: The appropriate `ToolCallFormat`, or `nil` to use the default format - public static func infer(from modelType: String) -> ToolCallFormat? { + public static func infer(from modelType: String, configData: Data? = nil) -> ToolCallFormat? { let type = modelType.lowercased() + // Llama family (need secondary signal for Llama 3 vs 1/2) + if type == "llama" { + guard let data = configData, + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + else { return nil } + + // Secondary signal 1: vocab_size >= 128000 (Llama 3 uses 128256, Llama 2 uses 32000) + if let vocabSize = json["vocab_size"] as? Int, vocabSize >= 128000 { + return .llama3 + } + + // Secondary signal 2: rope_scaling with rope_type == "llama3" + if let ropeScaling = json["rope_scaling"] as? [String: Any], + let ropeType = ropeScaling["rope_type"] as? String, + ropeType == "llama3" + { + return .llama3 + } + + return nil + } + // LFM2 family (lfm2, lfm2_moe, lfm2_5, lfm25, etc.) if type.hasPrefix("lfm2") { return .lfm2 diff --git a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift index 6589952a6e..d9a6bb89f8 100644 --- a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift +++ b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift @@ -101,17 +101,72 @@ public class ToolCallProcessor { // MARK: - Private Methods /// Process chunk for inline formats (no wrapper tags). + /// + /// Uses brace counting to detect when output looks like a JSON tool call. + /// While braces are unbalanced the content is buffered (returns `nil`) + /// so partial JSON is never leaked to the UI. private func processInlineChunk(_ chunk: String) -> String? { - toolCallBuffer += chunk + switch state { + case .normal: + // Check if this chunk starts what looks like a JSON tool call + if let braceIndex = chunk.firstIndex(of: "{") { + let leading = String(chunk[.. Bool { + var depth = 0 + for ch in text { + if ch == "{" { depth += 1 } else if ch == "}" { depth -= 1 } + } + return depth == 0 } /// Process chunk for tagged formats. diff --git a/Libraries/MLXLMCommon/TurboQuantKVCache.swift b/Libraries/MLXLMCommon/TurboQuantKVCache.swift new file mode 100644 index 0000000000..5547b3ea9f --- /dev/null +++ b/Libraries/MLXLMCommon/TurboQuantKVCache.swift @@ -0,0 +1,1455 @@ +// Copyright © 2026 Eric Kryski. TurboQuant KV cache compression. +// +// Implements TurboQuant Algorithm 1 (MSE-optimal, arXiv:2504.19874) for KV cache: +// rotation Π + optimal Lloyd-Max scalar codebook quantization on Beta distribution. +// +// Both keys and values use Algorithm 1 (MSE-only at b bits). QJL (Algorithm 2) +// is omitted — Tom Turney's research shows no quality benefit on Apple Silicon, +// and at 4-bit the MSE bias is negligible (paper Section 3.2: bias = 2/π, +// diminishing with bit-width). +// +// VERIFIED: No QJL, residual quantization, or random projection correction exists +// in this codebase. TurboQuant+ research proved QJL hurts autoregressive generation — +// random projection variance compounds across decode steps. MSE-only is correct. +// +// Enhancements beyond paper: +// - Norm extraction/restoration: paper assumes ||x||=1; we store norms for arbitrary vectors +// - Norm correction: store ||x|| / ||ỹ|| for dense rotation path (WHT skips — orthogonal preserves norms) +// - WHT rotation option: O(d log d) butterfly in Metal kernel for power-of-2 dims +// - Two-phase architecture: raw prefill → batch compress → compressed decode +// - Pre-rotated queries: q' = Π·q computed once, reused for all cached keys +// - Asymmetric K/V bit-widths: K precision dominates quality (softmax amplification), +// V compression is nearly free (linear averaging). Use "turbo4v2" for 4-bit K + 2-bit V. +// - Boundary layer protection: first/last N attention layers stay FP16 +// +// References: +// - TurboQuant: https://arxiv.org/abs/2504.19874 +// - QJL: https://arxiv.org/abs/2406.03482 +// - PolarQuant: https://arxiv.org/abs/2502.02617 + +import Foundation +import MLX +import MLXNN + +// MARK: - Codebook Generation + +/// Optimal Lloyd-Max codebook centroids for Beta-distributed coordinates. +/// +/// After random orthogonal rotation, each coordinate of a unit-sphere vector +/// follows Beta distribution f_X(x) ∝ (1-x²)^((d-3)/2) on [-1,1]. +/// For large d, this converges to N(0, 1/d). +public enum TurboQuantCodebook { + + // MARK: - Pre-computed Centroids + + /// Pre-computed Lloyd-Max centroids for common (dim, bits) pairs. + /// Generated offline via 100-iteration weighted k-means on 32K-point Beta PDF grid. + /// Avoids ~50ms runtime codebook generation per codec. + /// + /// Additional dims (80, 96) are lazily generated on first access to support + /// Qwen3-4B (head_dim=80) and similar models without startup cost for unused dims. + nonisolated(unsafe) private static var precomputed: [Int: [Int: [Float]]] = [ + 64: [ + 2: [-0.18745463, -0.05649366, 0.05649367, 0.18745449], + 3: [-0.26375133, -0.16599470, -0.09368263, -0.03040462, 0.03040464, 0.09368261, 0.16599482, 0.26375186], + 4: [-0.32913971, -0.25096416, -0.19681059, -0.15295772, -0.11478586, -0.08000945, -0.04726735, -0.01563822, 0.01563822, 0.04723797, 0.07994876, 0.11472529, 0.15289739, 0.19675052, 0.25090477, 0.32908401], + ], + 128: [ + 2: [-0.13302007, -0.03998107, 0.03998102, 0.13302033], + 3: [-0.18828832, -0.11801215, -0.06648001, -0.02156330, 0.02156329, 0.06648005, 0.11801218, 0.18828897], + 4: [-0.23639172, -0.17934021, -0.14023653, -0.10881814, -0.08157559, -0.05678632, -0.03350975, -0.01108178, 0.01108178, 0.03350975, 0.05678631, 0.08157560, 0.10881804, 0.14023650, 0.17934017, 0.23639278], + ], + 256: [ + 2: [-0.09420358, -0.02827190, 0.02827190, 0.09420330], + 3: [-0.13371243, -0.08361249, -0.04704370, -0.01524900, 0.01524901, 0.04704368, 0.08361248, 0.13371260], + 4: [-0.16852295, -0.12754069, -0.09961203, -0.07719406, -0.05781249, -0.04021866, -0.02370371, -0.00783269, 0.00783269, 0.02370371, 0.04021868, 0.05781246, 0.07719407, 0.09961203, 0.12754090, 0.16852276], + ], + ] + + /// Lock for thread-safe lazy population of precomputed centroids. + private static let centroidLock = NSLock() + + /// Dims that should be lazily pre-populated (non-power-of-2 dims used by real models). + /// These fall back to dense rotation path since WHT requires power-of-2, but still + /// benefit from cached centroids to avoid ~50ms runtime k-means per codec init. + /// + /// - 80: Qwen3-4B (head_dim=80) + /// - 96: Various smaller models + private static let lazyDims: [Int] = [80, 96] + private static let lazyBits: [Int] = [2, 3, 4, 8] + + /// Ensure centroids for a given dim are populated. Thread-safe, generates once. + private static func ensureCentroidsPopulated(dim: Int) { + centroidLock.lock() + let exists = precomputed[dim] != nil + centroidLock.unlock() + guard !exists else { return } + + // Generate all bit-widths for this dim + var dimTable: [Int: [Float]] = [:] + for bits in lazyBits { + dimTable[bits] = generateCentroids(dim: dim, bits: bits) + } + + centroidLock.lock() + // Double-check after lock (another thread may have populated) + if precomputed[dim] == nil { + precomputed[dim] = dimTable + } + centroidLock.unlock() + } + + // MARK: - N(0,1) Lloyd-Max Centroids (TurboQuant+ / llama.cpp) + + /// Standard Lloyd-Max optimal centroids for N(0,1) distribution. + /// Used in llama.cpp TurboQuant+ (ggml-turbo-quant.c). + /// These are scaled by 1/sqrt(dim) for unit-sphere comparison. + private static let n01Centroids: [Int: [Float]] = [ + 2: [-0.7979, 0.0, 0.0, 0.7979], // symmetric 2-bit + 3: [-1.748, -1.050, -0.5006, -0.1585, 0.1585, 0.5006, 1.050, 1.748], + 4: [-2.733, -2.069, -1.618, -1.256, -0.942, -0.657, -0.388, -0.128, + 0.128, 0.388, 0.657, 0.942, 1.256, 1.618, 2.069, 2.733], + ] + + nonisolated(unsafe) private static var _loggedN01 = false + + /// Whether to use N(0,1) centroids instead of Beta distribution. + /// Set TURBO_USE_N01_CENTROIDS=1 to enable for A/B testing. + private static let useN01Centroids: Bool = { + ProcessInfo.processInfo.environment["TURBO_USE_N01_CENTROIDS"] == "1" + }() + + /// Scale N(0,1) centroids to match unit-sphere normalization for a given dim. + private static func n01Codebook(dim: Int, bits: Int) -> [Float]? { + guard let raw = n01Centroids[bits] else { return nil } + let scale = 1.0 / Float(dim).squareRoot() + return raw.map { $0 * scale } + } + + // MARK: - Public API + + /// Codebook centroids for (dim, bits). Uses pre-computed table for common configs, + /// lazily generates and caches for known model dims (80, 96), falls back to + /// runtime generation for truly uncommon ones. + /// + /// Set TURBO_USE_N01_CENTROIDS=1 to use N(0,1) Lloyd-Max centroids instead of + /// Beta distribution centroids for A/B comparison. + public static func codebook(dim: Int, bits: Int) -> MLXArray { + // A/B test: use N(0,1) centroids if env var set + if useN01Centroids, let n01 = n01Codebook(dim: dim, bits: bits) { + if !_loggedN01 { print("[TURBO] Using N(0,1) Lloyd-Max centroids (TURBO_USE_N01_CENTROIDS=1)"); _loggedN01 = true } + return MLXArray(n01) + } + if let dimTable = precomputed[dim], let centroids = dimTable[bits] { + return MLXArray(centroids) + } + // Lazy populate for known model dims (Qwen3-4B dim=80, etc.) + if lazyDims.contains(dim) { + ensureCentroidsPopulated(dim: dim) + if let dimTable = precomputed[dim], let centroids = dimTable[bits] { + return MLXArray(centroids) + } + } + // TODO: Consider caching truly unknown dims too if they're hit repeatedly + let centroids = generateCentroids(dim: dim, bits: bits) + return MLXArray(centroids) + } + + /// Codebook boundaries (midpoints between adjacent centroids). + public static func boundaries(dim: Int, bits: Int) -> MLXArray { + let centroids: [Float] + // A/B test: use N(0,1) centroids if env var set + if useN01Centroids, let n01 = n01Codebook(dim: dim, bits: bits) { + centroids = n01 + } else if let dimTable = precomputed[dim], let cached = dimTable[bits] { + centroids = cached + } else if lazyDims.contains(dim) { + ensureCentroidsPopulated(dim: dim) + if let dimTable = precomputed[dim], let cached = dimTable[bits] { + centroids = cached + } else { + centroids = generateCentroids(dim: dim, bits: bits) + } + } else { + centroids = generateCentroids(dim: dim, bits: bits) + } + var bounds = [Float]() + for i in 0 ..< centroids.count - 1 { + bounds.append((centroids[i] + centroids[i + 1]) / 2.0) + } + return MLXArray(bounds) + } + + /// Generate codebook centroids via weighted k-means on Beta distribution. + /// Used as fallback for uncommon (dim, bits) pairs not in the pre-computed table. + static func generateCentroids(dim: Int, bits: Int) -> [Float] { + let levels = 1 << bits + let gridSize = 32768 + let sigma = 1.0 / sqrt(Float(dim)) + + // Generate grid points and PDF weights + var grid = [Float](repeating: 0, count: gridSize) + var weights = [Float](repeating: 0, count: gridSize) + for i in 0 ..< gridSize { + let x = -1.0 + 2.0 * Float(i) / Float(gridSize - 1) + grid[i] = x + // Beta PDF ∝ (1 - x²)^((d-3)/2), approximated by Gaussian for large d + let exponent = Float(dim - 3) / 2.0 + let w = pow(max(1.0 - x * x, 1e-30), exponent) + weights[i] = w + } + + // Initialize centroids via quantiles + let totalW = weights.reduce(0, +) + var centroids = [Float](repeating: 0, count: levels) + var cumW: Float = 0 + var ci = 0 + for i in 0 ..< gridSize { + cumW += weights[i] + let target = (Float(ci) + 0.5) / Float(levels) * totalW + if cumW >= target && ci < levels { + centroids[ci] = grid[i] + ci += 1 + } + } + // Fill remaining + while ci < levels { + centroids[ci] = centroids[ci - 1] + sigma + ci += 1 + } + + // K-means iterations + for _ in 0 ..< 100 { + var sums = [Float](repeating: 0, count: levels) + var counts = [Float](repeating: 0, count: levels) + for i in 0 ..< gridSize { + var bestJ = 0 + var bestDist = Float.infinity + for j in 0 ..< levels { + let d = abs(grid[i] - centroids[j]) + if d < bestDist { bestDist = d; bestJ = j } + } + sums[bestJ] += grid[i] * weights[i] + counts[bestJ] += weights[i] + } + for j in 0 ..< levels { + if counts[j] > 0 { centroids[j] = sums[j] / counts[j] } + } + } + + return centroids.sorted() + } +} + +// MARK: - Rotation Matrix + +/// Random orthogonal rotation matrix generation. +/// +/// TurboQuant Algorithm 1 line 2: Π ∈ ℝ^(d×d) via QR decomposition +/// on random Gaussian matrix. Sign-corrected for determinism. +public enum TurboQuantRotation { + + /// Generate a deterministic random orthogonal rotation matrix (dense, d×d). + /// Uses QR decomposition on CPU (not yet GPU-supported in MLX). + public static func rotationMatrix(dim: Int, seed: UInt64) -> MLXArray { + let key = MLXRandom.key(seed) + let gaussian = MLXRandom.normal([dim, dim], key: key) + + // QR on CPU (MLX GPU QR not supported yet) + let (q, r) = MLXLinalg.qr(gaussian, stream: .cpu) + let diagR = r.diagonal(stream: .cpu) + let signs = sign(diagR, stream: .cpu) + let result = q * expandedDimensions(signs, axis: 0) + return result + } + + /// Generate a Hadamard matrix of size dim × dim via recursive Kronecker product. + /// Requires dim to be a power of 2. The resulting matrix H satisfies H·H = dim·I. + public static func hadamardMatrix(dim: Int) -> MLXArray { + precondition(dim > 0 && (dim & (dim - 1)) == 0, "dim must be power of 2") + // Build recursively: H_1 = [[1]], H_2n = [[H_n, H_n], [H_n, -H_n]] + var h: [[Float]] = [[1.0]] + var size = 1 + while size < dim { + var newH = [[Float]](repeating: [Float](repeating: 0, count: size * 2), count: size * 2) + for i in 0 ..< size { + for j in 0 ..< size { + newH[i][j] = h[i][j] + newH[i][j + size] = h[i][j] + newH[i + size][j] = h[i][j] + newH[i + size][j + size] = -h[i][j] + } + } + h = newH + size *= 2 + } + let flat = h.flatMap { $0 } + let result = MLXArray(flat, [dim, dim]) + return result + } + + /// Generate WHT sign vector: random ±1 per dimension, length d. + /// Used with Walsh-Hadamard Transform for O(d log d) rotation. + public static func whtSigns(dim: Int, seed: UInt64) -> MLXArray { + let key = MLXRandom.key(seed) + // Random bits → ±1 + // Generate random ±1 signs using uniform random + let uniform = MLXRandom.uniform(low: 0, high: 1, [dim], key: key) + let signs = MLX.where(uniform .> Float(0.5), Float(1.0), Float(-1.0)) + return signs + } + + /// Apply WHT butterfly on the last dimension of x. Shape-preserving. + /// Computes unnormalized Walsh-Hadamard transform: H * x along last dim. + private static func whtButterfly(_ x: MLXArray) -> MLXArray { + let dim = x.dim(-1) + let logDim = Int(log2(Double(dim))) + let origShape = x.shape + // Flatten leading dims: [N, dim] + let N = origShape.dropLast().reduce(1, *) + var y = x.reshaped([N, dim]) + + for s in 0.. MLXArray { + let dim = x.dim(-1) + precondition(dim > 0 && (dim & (dim - 1)) == 0, "dim must be power of 2") + let signed = x * signs + let transformed = whtButterfly(signed) + let invSqrtDim = MLXArray(1.0 / sqrt(Float(dim)), dtype: x.dtype) + return transformed * invSqrtDim + } + + /// Apply SRHT inverse rotation: x = diag(signs) * H * y / sqrt(dim) + /// WHT is self-inverse up to scale. Inverse of (H·D/√d) is (D·H/√d). + public static func fwhtInverse(_ y: MLXArray, signs: MLXArray) -> MLXArray { + let dim = y.dim(-1) + precondition(dim > 0 && (dim & (dim - 1)) == 0, "dim must be power of 2") + let transformed = whtButterfly(y) + let invSqrtDim = MLXArray(1.0 / sqrt(Float(dim)), dtype: y.dtype) + return transformed * invSqrtDim * signs + } +} + +// MARK: - Bit Packing + +/// Efficient bit packing/unpacking for codebook indices. +public enum TurboQuantPacking { + + /// Number of uint32 words needed to pack `count` values at `bits` each. + public static func packedWidth(count: Int, bits: Int) -> Int { + (count * bits + 31) / 32 + } + + /// Pack b-bit indices into uint32 words. + /// Input: [rows, count] as uint32 (values 0..2^bits-1) + /// Output: [rows, packedWidth] as uint32 + public static func packLowBit(_ indices: MLXArray, bits: Int) -> MLXArray { + let count = indices.dim(-1) + let batchShape = Array(indices.shape.dropLast()) + let rows = batchShape.reduce(1, *) + let flat = indices.reshaped([rows, count]) + let pw = packedWidth(count: count, bits: bits) + let mask = UInt32((1 << bits) - 1) + + var wordArrays = [MLXArray]() + for w in 0 ..< pw { + var word = MLXArray.zeros([rows], dtype: .uint32) + for d in 0 ..< count { + let bitOffset = d * bits + let wordIdx = bitOffset / 32 + let offset = bitOffset % 32 + let spill = offset + bits - 32 + + if wordIdx == w { + let shifted = (flat[0..., d].asType(.uint32) & MLXArray(mask)) << MLXArray(UInt32(offset)) + word = word | shifted + } + if spill > 0 && wordIdx + 1 == w { + let shifted = (flat[0..., d].asType(.uint32) & MLXArray(mask)) >> MLXArray(UInt32(bits - spill)) + word = word | shifted + } + } + wordArrays.append(expandedDimensions(word, axis: -1)) + } + let packed = concatenated(wordArrays, axis: -1) // [rows, pw] + return packed.reshaped(batchShape + [pw]) + } + + /// Unpack b-bit indices from uint32 words. + /// Input: [rows, packedWidth] as uint32 + /// Output: [rows, count] as uint32 + public static func unpackLowBit(_ packed: MLXArray, bits: Int, count: Int) -> MLXArray { + let shape = packed.shape + let batchShape = Array(shape.dropLast()) + let rows = batchShape.reduce(1, *) + let flat = packed.reshaped([rows, -1]) + let mask = UInt32((1 << bits) - 1) + + var dimArrays = [MLXArray]() + for d in 0 ..< count { + let bitOffset = d * bits + let wordIdx = bitOffset / 32 + let offset = bitOffset % 32 + let spill = offset + bits - 32 + + var value = (flat[0..., wordIdx] >> MLXArray(UInt32(offset))) & MLXArray(mask) + if spill > 0 { + let high = (flat[0..., wordIdx + 1] << MLXArray(UInt32(bits - spill))) & MLXArray(mask) + value = value | high + } + dimArrays.append(expandedDimensions(value, axis: -1)) + } + let unpacked = concatenated(dimArrays, axis: -1) // [rows, count] + return unpacked.reshaped(batchShape + [count]) + } +} + +// MARK: - MSE Codec (TurboQuant Algorithm 1) + +/// State for MSE-quantized vectors. +public struct MSECodecState { + public var norms: MLXArray // [B, H, T] — original vector L2 norms + public var packedIndices: MLXArray // [B, H, T, PackedWidth] — packed codebook indices + public var tokenCount: Int + public let dim: Int + public let bits: Int +} + +/// MSE-optimal codec per TurboQuant Algorithm 1. +/// +/// QUANT: y ← Π·x, idx_j ← argmin|y_j - c_k| +/// DEQUANT: ỹ_j ← c_{idx_j}, x̃ ← Π^T · ỹ +public class MSECodec { + public let dim: Int + public let bits: Int + public let seed: UInt64 + + /// Codebook centroids [2^bits] + public let codebook: MLXArray + /// Codebook boundaries for fast quantization [2^bits - 1] + public let boundaries: MLXArray + + /// Whether to use WHT (power-of-2 dim) or dense rotation + public let useWHT: Bool + /// WHT sign vector [dim] — for O(d log d) Metal encode kernel (power-of-2 dims only) + public let whtSigns: MLXArray? + /// Dense rotation matrix Π [dim, dim] — used for decode/query rotation (single matmul, fast) + public let rotation: MLXArray + /// Π^T — for forward rotation + public let rotationT: MLXArray + + public init(dim: Int, bits: Int, seed: UInt64 = 42) { + self.dim = dim + self.bits = bits + self.seed = seed + self.codebook = TurboQuantCodebook.codebook(dim: dim, bits: bits) + self.boundaries = TurboQuantCodebook.boundaries(dim: dim, bits: bits) + + // Use WHT for power-of-2 dims (O(d log d) Metal encode kernel) + let isPowerOf2 = dim > 0 && (dim & (dim - 1)) == 0 + self.useWHT = isPowerOf2 && dim <= 1024 + if useWHT { + let signs = TurboQuantRotation.whtSigns(dim: dim, seed: seed) + self.whtSigns = signs + // Build dense WHT rotation matrix for decode/query path (single matmul is faster + // than FWHT butterfly via MLX ops due to graph overhead) + let hadamard = TurboQuantRotation.hadamardMatrix(dim: dim) + let signsDiag = expandedDimensions(signs, axis: 0) + let whtRot = hadamard * signsDiag / Float(sqrt(Float(dim))) + // Convert to bf16 — rotation matrices are computed in fp32 (QR, Hadamard) + // but must match model dtype to avoid promoting bf16 inputs through matmul. + // No eval() here — premature eval forces materialization of unrelated lazy + // ops (e.g., GDN state) which can lock in fp32 intermediates. + self.rotation = whtRot.asType(.bfloat16) + self.rotationT = self.rotation.transposed() + } else { + self.whtSigns = nil + let rot = TurboQuantRotation.rotationMatrix(dim: dim, seed: seed) + self.rotation = rot.asType(.bfloat16) + self.rotationT = self.rotation.transposed() + } + } + + /// Encode vectors (Algorithm 1 QUANT) with optional norm correction. + /// Input: [B, H, T, D] + /// Returns MSECodecState with norms and packed indices. + /// + /// WHT path: stores raw norms directly. WHT is an orthogonal transform that preserves + /// norms, so reconstruction_norm ≈ original_norm (within floating point error). + /// Skipping norm correction saves one codebook lookup, one norm computation, and one + /// division per encoded vector. + /// + /// Dense rotation path: stores `original_norm / reconstruction_norm` (norm correction). + /// This compensates for quantization error in the non-orthogonal rotation case. + /// + // TODO: Dual half-block scales (TQ4_1S format optimization) + // + // Our llama.cpp TQ4_1S format uses dual half-block scales (d0 for elements 0-15, + // d1 for elements 16-31) instead of a single per-block L2 norm. After WHT rotation, + // the two halves of a 32-element block can have very different energy distributions, + // so a single norm under-scales one half and over-scales the other. + // + // Dual scales reduce MSE by ~15-25% in our testing (see TurboQuant+ paper, Section 4.2). + // + // Implementing this requires changes to: + // 1. MSECodecState packing format — store two norms per block instead of one + // 2. This encode path — compute half-block norms separately: + // d0 = ||rotated[..., :16]||₂, d1 = ||rotated[..., 16:]||₂ + // 3. Metal dequant kernels — use d0/d1 during reconstruction + // 4. TurboFlash attention kernels — weighted dequant with two scales per block + // + // Too invasive for this PR, but high-value follow-up for accuracy-sensitive models. + public func encode(_ vectors: MLXArray) -> MSECodecState { + // Extract norms and normalize (paper assumes unit sphere; we store norms separately) + let norms = sqrt((vectors * vectors).sum(axis: -1)) + let safeNorms = maximum(norms, Float(1e-8)) + let unit = vectors / expandedDimensions(safeNorms, axis: -1) + + // Rotate: y ← Π · x (Algorithm 1 line 5) + let rotated = matmul(unit, rotationT) + + // Quantize via boundary comparison (fast, no broadcast) + let indices = boundaryQuantize(rotated) + + let storedNorms: MLXArray + if useWHT { + // WHT fast path: orthogonal transform preserves norms, skip correction + storedNorms = norms + } else { + // Dense rotation path: norm correction compensates for quantization error + let reconstructed = codebook[indices] // [B,H,T,D] — quantized approximation in rotated space + let reconNormSq = (reconstructed * reconstructed).sum(axis: -1) + let reconNorms = sqrt(maximum(reconNormSq, Float(1e-16))) + storedNorms = norms / reconNorms // original_norm / reconstruction_norm + } + + // Pack indices + let packed = TurboQuantPacking.packLowBit(indices, bits: bits) + + return MSECodecState( + norms: storedNorms, + packedIndices: packed, + tokenCount: vectors.dim(2), + dim: dim, + bits: bits + ) + } + + /// Decode from state (Algorithm 1 DEQUANT). + /// Returns: [B, H, T, D] + public func decode(_ state: MSECodecState) -> MLXArray { + // Unpack indices + let indices = TurboQuantPacking.unpackLowBit(state.packedIndices, bits: bits, count: dim) + + // Codebook lookup: ỹ_j ← c_{idx_j} (Algorithm 1 line 9) + let approx = codebook[indices] + + // Inverse rotate: x̃ ← Π^T · ỹ (Algorithm 1 line 10) + let unrotated = matmul(approx, rotation) + + // Rescale by stored norms + return expandedDimensions(state.norms, axis: -1) * unrotated + } + + /// Decode in rotated space (skip inverse rotation). + /// Returns centroid values scaled by norm, still in Π-rotated coordinate space. + /// Used with pre-rotated queries for dequant-first SDPA. + public func decodeRotated(_ state: MSECodecState) -> MLXArray { + let indices = TurboQuantPacking.unpackLowBit(state.packedIndices, bits: bits, count: dim) + let approx = codebook[indices] + return expandedDimensions(state.norms, axis: -1) * approx + } + + /// Pre-rotate queries for compressed-domain scoring. + /// q' ← Π · q (once per query, reused for all cached keys) + public func prepareQueries(_ queries: MLXArray) -> MLXArray { + return matmul(queries, rotationT) + } + + /// Fast quantization via boundary comparison instead of argmin broadcast. + /// boundaries = sorted midpoints between adjacent centroids. + /// Returns uint32 indices in [0, 2^bits - 1]. + func boundaryQuantize(_ rotated: MLXArray) -> MLXArray { + // For each coordinate, count how many boundaries it exceeds + // This gives the codebook index directly + let ndim = rotated.ndim + let expanded = expandedDimensions(rotated, axis: -1) // [..., D, 1] + // Reshape boundaries to broadcast: [1, 1, ..., 1, numBoundaries] + var bShape = [Int](repeating: 1, count: ndim + 1) + bShape[ndim] = boundaries.count + let b = boundaries.reshaped(bShape) + let greater = (expanded .> b).asType(.uint32) // compare against all boundaries + let indices = greater.sum(axis: -1) // count exceeded = index + return indices.asType(.uint32) + } +} + +// MARK: - TurboQuantKVCache + +/// KV cache using TurboQuant compression with two-phase architecture: +/// +/// **Phase 1 — Prefill** (L>1): Store raw K/V like KVCacheSimple. Zero overhead. +/// **Transition**: On first decode call, compress entire raw cache in one batch. +/// **Phase 2 — Decode** (L=1): Encode 1 new token. Metal kernel scores against +/// all compressed tokens. Zero dequantization. +/// +/// Both keys and values: Algorithm 1 (MSE at b bits, no QJL) +public class TurboQuantKVCache: BaseKVCache { + + // Profiling accumulators (static so they accumulate across all layers) + nonisolated(unsafe) static var profileEncodeMs: Double = 0 + nonisolated(unsafe) static var profileScoreMs: Double = 0 + nonisolated(unsafe) static var profileValueMs: Double = 0 + nonisolated(unsafe) static var profileRotateMs: Double = 0 + nonisolated(unsafe) static var profileOtherMs: Double = 0 + nonisolated(unsafe) static var profileCount: Int = 0 + + /// Print and reset profiling stats. + public static func printProfile() { + guard profileCount > 0 else { return } + let total = profileEncodeMs + profileScoreMs + profileValueMs + profileRotateMs + profileOtherMs + let perToken = total / Double(profileCount) + print("[TURBO-PROFILE] \(profileCount) decode steps across all layers:") + print("[TURBO-PROFILE] encode: \(String(format: "%.1f", profileEncodeMs))ms (\(String(format: "%.0f", profileEncodeMs / total * 100))%)") + print("[TURBO-PROFILE] score: \(String(format: "%.1f", profileScoreMs))ms (\(String(format: "%.0f", profileScoreMs / total * 100))%)") + print("[TURBO-PROFILE] value: \(String(format: "%.1f", profileValueMs))ms (\(String(format: "%.0f", profileValueMs / total * 100))%)") + print("[TURBO-PROFILE] rotate: \(String(format: "%.1f", profileRotateMs))ms (\(String(format: "%.0f", profileRotateMs / total * 100))%)") + print("[TURBO-PROFILE] other: \(String(format: "%.1f", profileOtherMs))ms (\(String(format: "%.0f", profileOtherMs / total * 100))%)") + print("[TURBO-PROFILE] total: \(String(format: "%.1f", total))ms (\(String(format: "%.2f", perToken))ms/step)") + profileEncodeMs = 0; profileScoreMs = 0; profileValueMs = 0 + profileRotateMs = 0; profileOtherMs = 0; profileCount = 0 + } + + public let bits: Int // Legacy: used when keyBits == valueBits + public let keyBits: Int // Bit-width for key compression (0 = raw FP16, no compression) + public let valueBits: Int // Bit-width for value compression (can be lower — V compression is nearly free) + private let seed: UInt64 + + /// Raw-K mode: keys stay at FP16 (uncompressed) while only values are TurboQuant compressed. + /// This is the single biggest quality finding from TurboQuant+ — K precision dominates + /// quality via softmax amplification, V compression is nearly free (linear averaging). + /// Enabled when keyBits == 0. + public let rawKeyMode: Bool + + // Codecs (lazy init) + private var keyMSECodec: MSECodec? // keyBits for keys + private var valueMSECodec: MSECodec? // valueBits for values + + // Phase 1: Raw K/V storage (like KVCacheSimple) — used during prefill + private var rawKeys: MLXArray? // [B, H, allocSteps, D] + private var rawValues: MLXArray? // [B, H, allocSteps, D] + private var rawAllocSteps = 0 + + // Phase 2: Compressed storage — used during decode + // MSE-only: packed indices + norms (no QJL — simpler, same quality) + private var keyPackedMSE: MLXArray? + private var keyNorms: MLXArray? + private var valPackedMSE: MLXArray? + private var valNorms: MLXArray? + private var compressedAllocSteps = 0 + + /// Whether we've transitioned from raw → compressed + public private(set) var isCompressed = false + + // Batch recompression: accumulate raw tokens and encode in batches instead of per-token. + // Reduces Metal kernel launches from 1/token to 1/recompressInterval. + private var pendingRawKeys: [MLXArray] = [] // Each: [B, H, 1, D] + private var pendingRawValues: [MLXArray] = [] // Each: [B, H, 1, D] + private var uncompressedCount = 0 + private let recompressInterval: Int + + /// Pre-allocation step size for buffer growth. Larger values reduce resize frequency + /// at the cost of upfront memory. At step=1024, a 16K context only resizes 16 times + /// (vs 64 times at step=256), eliminating 75% of allocation + copy overhead. + private let step: Int + + public init(bits: Int = 4, keyBits: Int? = nil, valueBits: Int? = nil, step: Int = 1024, recompressInterval: Int = 64, seed: UInt64 = 42) { + self.bits = bits + self.keyBits = keyBits ?? bits + self.valueBits = valueBits ?? bits + self.rawKeyMode = (keyBits ?? bits) == 0 + self.seed = seed + self.step = step + // Configurable via env var; default 64 tokens between batch recompression + if let env = ProcessInfo.processInfo.environment["TURBO_RECOMPRESS_INTERVAL"], + let val = Int(env) { + self.recompressInterval = max(1, val) + } else { + self.recompressInterval = recompressInterval + } + super.init() + } + + override public var isTrimmable: Bool { true } + + // MARK: - Shared Codec Cache + + /// Shared codec cache: all layers with the same (dim, bits, seed) reuse the same codec. + /// Eliminates 56 redundant [128,128] rotation matrices (~7 MB) across 28 layers. + private static let codecLock = NSLock() + nonisolated(unsafe) private static var sharedCodecs: [String: MSECodec] = [:] + + private static func getOrCreateCodec(dim: Int, bits: Int, seed: UInt64) -> MSECodec { + let key = "\(dim)_\(bits)_\(seed)" + codecLock.lock() + if let cached = sharedCodecs[key] { + codecLock.unlock() + return cached + } + codecLock.unlock() + let codec = MSECodec(dim: dim, bits: bits, seed: seed) + codecLock.lock() + sharedCodecs[key] = codec + codecLock.unlock() + return codec + } + + /// Initialize codecs if needed. Uses shared cache to avoid duplicating rotation matrices. + /// In rawKeyMode, key codec is nil — keys stay at FP16, no rotation/quantization needed. + private func ensureCodecs(headDim: Int) { + guard valueMSECodec == nil else { return } + if !rawKeyMode { + keyMSECodec = Self.getOrCreateCodec(dim: headDim, bits: keyBits, seed: seed) + } + valueMSECodec = Self.getOrCreateCodec(dim: headDim, bits: valueBits, seed: seed + 1) + } + + nonisolated(unsafe) private static var loggedEncodeKernel = false + + /// Dispatch to WHT or dense fused encode kernel based on codec configuration. + private func fusedEncodeDispatch( + input: MLXArray, codec: MSECodec, headDim: Int + ) -> (packed: MLXArray, norms: MLXArray) { + if !Self.loggedEncodeKernel { + Self.loggedEncodeKernel = true + print("[TURBO] Encode kernel: \(codec.useWHT ? "WHT butterfly" : "dense matmul"), dim=\(headDim), bits=\(codec.bits)") + } + if codec.useWHT, let signs = codec.whtSigns { + return TurboQuantKernelOps.fusedEncodeWHT( + input: input, whtSigns: signs, + boundaries: codec.boundaries, codebook: codec.codebook, + bits: codec.bits, dim: headDim + ) + } else { + return TurboQuantKernelOps.fusedEncode( + input: input, rotation: codec.rotation, + boundaries: codec.boundaries, codebook: codec.codebook, + bits: codec.bits, dim: headDim + ) + } + } + + // MARK: - Phase 1: Raw Prefill + + /// Prefill update: store raw K/V, return raw. Zero encoding overhead. + /// Uses KVCacheSimple-style allocation with concatenated growth. + override public func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + let previous = self.offset + + let reset = + if let currentKeys = self.rawKeys, (previous + keys.dim(2)) > currentKeys.dim(2) { + true + } else { + self.rawKeys == nil + } + if reset { + let B = keys.dim(0) + let kvHeads = keys.dim(1) + let kHeadDim = keys.dim(3) + let vHeadDim = values.dim(3) + + let nSteps = (step + keys.dim(2) - 1) / step + let kShape = [B, kvHeads, nSteps * step, kHeadDim] + let vShape = [B, kvHeads, nSteps * step, vHeadDim] + let newK = MLXArray.zeros(kShape, dtype: keys.dtype) + let newV = MLXArray.zeros(vShape, dtype: values.dtype) + + if var currentKeys = self.rawKeys, var currentValues = self.rawValues { + if previous % step != 0 { + currentKeys = currentKeys[.ellipsis, .. 0 else { return } + let allKeys = rk[.ellipsis, .. rawAllocSteps { + let newAlloc = ((prev + numSteps + step - 1) / step) * step + let newRK = MLXArray.zeros([B, H, newAlloc, headDim], dtype: keys.dtype) + if prev > 0, let rk = rawKeys { + newRK[.ellipsis, .. compressedAllocSteps { + let newAlloc = ((prev + numSteps + step - 1) / step) * step + let newVP = MLXArray.zeros([B, H, newAlloc, vpw], dtype: .uint32) + let newVN = MLXArray.zeros([B, H, newAlloc]) + if prev > 0 { + newVP[.ellipsis, .. compressedAllocSteps { + let newAlloc = ((prev + numSteps + step - 1) / step) * step + let newKP = MLXArray.zeros([B, H, newAlloc, kpw], dtype: .uint32) + let newKN = MLXArray.zeros([B, H, newAlloc]) + let newVP = MLXArray.zeros([B, H, newAlloc, vpw], dtype: .uint32) + let newVN = MLXArray.zeros([B, H, newAlloc]) + if prev > 0 { + newKP[.ellipsis, ..= recompressInterval, or on trim/serialize. + private func flushPendingEncode(headDim: Int) { + guard !pendingRawKeys.isEmpty else { return } + + // Concatenate pending tokens: list of [B, H, 1, D] → [B, H, N, D] + let batchKeys = concatenated(pendingRawKeys, axis: 2) + let batchValues = concatenated(pendingRawValues, axis: 2) + pendingRawKeys.removeAll(keepingCapacity: true) + pendingRawValues.removeAll(keepingCapacity: true) + + // Encode the batch — reuse encodeNewToken which handles buffer growth + let savedOffset = offset + let batchStart = savedOffset - uncompressedCount + offset = batchStart // Temporarily rewind so encodeNewToken writes to the right slot + encodeNewToken(keys: batchKeys, values: batchValues) + offset = savedOffset // Restore + uncompressedCount = 0 + } + + // FP16 dequant cache in ROTATED space — built incrementally, only new tokens dequanted each step. + // Keys and values stay in Π-rotated coordinates. Queries are pre-rotated to match. + // Output from SDPA is inverse-rotated once. This avoids per-token inverse rotation. + private var dequantKeys: MLXArray? // [B, H, T, D] in rotated space + private var dequantValues: MLXArray? // [B, H, T, D] in rotated space + + /// Encode new token, dequant to rotated space, append to FP16 cache using efficient + /// .ellipsis-style buffer management (matching KVCacheSimple for zero overhead). + /// + /// Returns (keys, values) in Π-ROTATED space. Caller must: + /// 1. Pre-rotate queries: q' = q @ Π^T (skip in rawKeyMode — queries stay raw) + /// 2. Run SDPA: output_rot = SDPA(q', keys_rot, values_rot) + /// 3. Inverse-rotate output: output = output_rot @ Π + /// + /// In rawKeyMode: keys are returned raw (unrotated). Values are in Π_value-rotated space. + /// Caller must NOT pre-rotate queries for K scoring (raw keys → raw queries). + /// Caller must still inverse-rotate the value component of the output. + public func updateAndDequant(keys newKeys: MLXArray, values newValues: MLXArray) -> (MLXArray, MLXArray) { + let headDim = newKeys.dim(-1) + ensureCodecs(headDim: headDim) + + guard let valueMSECodec else { + return (newKeys, newValues) + } + + // Transition: on first decode call, rotate the raw prefill cache into rotated space + if !isCompressed { + isCompressed = true + let tokenCount = offset + if tokenCount > 0, let rk = rawKeys, let rv = rawValues { + let rawK = rk[.ellipsis, ..= adaptiveInterval { + flushPendingEncode(headDim: newKeys.dim(-1)) + } + + // Rotate new token(s) into appropriate space + let dequantNewKeys: MLXArray + if rawKeyMode { + // Raw-K mode: keys stay unrotated + dequantNewKeys = newKeys + } else { + // Standard: rotate keys into key codec's rotated space + guard let keyMSECodec else { return (newKeys, newValues) } + dequantNewKeys = keyMSECodec.prepareQueries(newKeys) + } + let rotNewValues = valueMSECodec.prepareQueries(newValues) + + // Grow dequant buffer using KVCacheSimple pattern (concatenated growth) + let reset = + if let dk = self.dequantKeys, prevOffset + newKeys.dim(2) > dk.dim(2) { + true + } else { + self.dequantKeys == nil + } + if reset { + let B = newKeys.dim(0) + let H = newKeys.dim(1) + let nSteps = (step + newKeys.dim(2) - 1) / step + let kShape = [B, H, nSteps * step, headDim] + let newDK = MLXArray.zeros(kShape, dtype: newKeys.dtype) + let newDV = MLXArray.zeros(kShape, dtype: newKeys.dtype) + + if var currentKeys = self.dequantKeys, var currentValues = self.dequantValues { + if prevOffset % step != 0 { + currentKeys = currentKeys[.ellipsis, .. MLXArray { + if rawKeyMode { return queries } + guard let keyMSECodec else { return queries } + return keyMSECodec.prepareQueries(queries) + } + + /// Inverse-rotate SDPA output from value-rotated space back to original + public func inverseRotateOutput(_ rotatedOutput: MLXArray) -> MLXArray { + guard let valueMSECodec else { return rotatedOutput } + return matmul(rotatedOutput, valueMSECodec.rotation) + } + + /// Whether to use compressed-domain Metal kernels instead of dequant + SDPA. + /// Default false: dequant-first is simpler and uses MLX's optimized attention. + /// Set true for very long contexts where FP16 materialization costs too much memory. + public var useCompressedAttention: Bool = false + + /// Compressed-domain attention via Metal kernels. + /// + /// On first call: compresses raw prefill cache in one batch. + /// Then: encode 1 new token → fused attention kernel → inverse rotation. + /// + /// For L=1 (decode): uses TurboFlashAttention — a single Metal dispatch that fuses + /// Q×K scoring + online softmax + Attn×V aggregation. No intermediate score or weight + /// arrays are materialized. This reduces 3 dispatches (score + softmax + value) to 1. + /// + /// For L>1 (prefill chunks): falls back to separate score → softmax → value kernels + /// since causal masking across multiple query positions requires the full score matrix. + /// + /// In rawKeyMode: uses standard matmul for Q*K scoring (raw FP16 keys, no rotation), + /// then compressed-domain Metal kernel for Attn*V (TurboQuant compressed values). + /// TurboFlash is NOT used — it assumes both K and V are packed. + public func compressedAttention( + queries: MLXArray, + keys newKeys: MLXArray, + values newValues: MLXArray, + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode = .none + ) -> MLXArray { + let headDim = newKeys.dim(-1) + let B = queries.dim(0) + let nQHeads = queries.dim(1) + let nKVHeads = newKeys.dim(1) + let L = queries.dim(2) + let nRepeats = nQHeads / nKVHeads + + // Transition: compress raw cache on first decode call + if !isCompressed { + compressRawCache() + } + + let profiling = ProcessInfo.processInfo.environment["SAM_TURBO_PROFILE"] == "1" + var t0 = Date() + + // Phase A: Encode new token + flush any pending batch + pendingRawKeys.append(newKeys) + pendingRawValues.append(newValues) + uncompressedCount += newKeys.dim(2) + offset += newKeys.dim(2) + flushPendingEncode(headDim: newKeys.dim(-1)) + + guard let valueMSECodec else { + return queries + } + + let tokenCount = offset + + // Shared V slicing (used by all paths) + let flatValPacked = valPackedMSE![0..., 0..., .. 1 { + // [B, nKVHeads, T, D] → [B, nKVHeads, 1, T, D] → [B, nKVHeads, nRepeats, T, D] → [B, nQHeads, T, D] + let expanded = expandedDimensions(allKeys, axis: 2) + let tiledKeys = MLX.tiled(expanded, repetitions: [1, 1, nRepeats, 1, 1]) + expandedKeys = tiledKeys.reshaped([B, nQHeads, tokenCount, headDim]) + } else { + expandedKeys = allKeys + } + + // scores = Q * K^T * scale → [B, nQHeads, L, T] + var scores = matmul(queries, expandedKeys.transposed(0, 1, 3, 2)) * scale + if profiling { eval(scores); let t1 = Date(); Self.profileScoreMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + + // Mask + softmax + switch mask { + case .array(let maskArray): + if maskArray.dtype == .bool { + scores = MLX.where(maskArray, scores, MLXArray(Float.leastNormalMagnitude, dtype: scores.dtype)) + } else { scores = scores + maskArray } + case .causal: + // Build causal mask manually + let queryOffset = tokenCount - L + let causalMask = MLXArray.tri(L, m: tokenCount, k: queryOffset, type: Bool.self) + let expandedMask = expandedDimensions(expandedDimensions(causalMask, axis: 0), axis: 0) + scores = MLX.where(expandedMask, scores, MLXArray(Float.leastNormalMagnitude, dtype: scores.dtype)) + case .none: break + default: break + } + + let attnWeights = softmax(scores, axis: -1) + if profiling { eval(attnWeights); let t1 = Date(); Self.profileOtherMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + + // Attn*V: compressed-domain Metal kernel for weighted sum of TurboQuant values + let flatWeights = attnWeights.reshaped([B * nQHeads * L, tokenCount]) + let rotatedOutput = TurboQuantKernelOps.mseWeightedSum( + weights: flatWeights, packed: flatValPacked, norms: flatValNorms, + codebook: valueMSECodec.codebook, tokenCount: tokenCount, + repeatCount: nRepeats, bits: self.valueBits, dim: headDim + ) + if profiling { eval(rotatedOutput); let t1 = Date(); Self.profileValueMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + + // Inverse value rotation (V was encoded in rotated space) + output = matmul( + rotatedOutput.reshaped([B, nQHeads, L, headDim]), + valueMSECodec.rotation + ) + if profiling { eval(output); let t1 = Date(); Self.profileRotateMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + } else { + // ═══ Standard TurboQuant path: both K and V compressed ═══ + guard let keyMSECodec else { return queries } + + if profiling { eval(keyPackedMSE!, valPackedMSE!); let t1 = Date(); Self.profileEncodeMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + + // Pre-rotate query for compressed-domain K scoring + let qRot = keyMSECodec.prepareQueries(queries) * scale + let flatQ = qRot.reshaped([B * nQHeads * L, headDim]) + + // K slicing + let flatKeyPacked = keyPackedMSE![0..., 0..., ..1) + let queryOffset = tokenCount - L + output = TurboQuantKernelOps.turboFlashAttentionCausal( + rotatedQueries: flatQ, + keyPacked: flatKeyPacked, keyNorms: flatKeyNorms, + keyCodebook: keyMSECodec.codebook, + valPacked: flatValPacked, valNorms: flatValNorms, + valCodebook: valueMSECodec.codebook, + tokenCount: tokenCount, repeatCount: nRepeats, + keyBits: self.keyBits, valueBits: self.valueBits, dim: headDim, + queryChunkLength: L, queryOffset: queryOffset, + valRotation: valRotation + ).reshaped([B, nQHeads, L, headDim]) + if profiling { eval(output); let t1 = Date(); Self.profileScoreMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + } else { + // Separated path (L>1, non-causal masks) + var scores = TurboQuantKernelOps.mseScore( + rotatedQueries: flatQ, packed: flatKeyPacked, norms: flatKeyNorms, + codebook: keyMSECodec.codebook, tokenCount: tokenCount, + repeatCount: nRepeats, bits: self.keyBits, dim: headDim + ).reshaped([B, nQHeads, L, tokenCount]) + if profiling { eval(scores); let t1 = Date(); Self.profileScoreMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + + // Mask + softmax + switch mask { + case .array(let maskArray): + if maskArray.dtype == .bool { + scores = MLX.where(maskArray, scores, MLXArray(Float.leastNormalMagnitude, dtype: scores.dtype)) + } else { scores = scores + maskArray } + case .none: break + default: break + } + + let attnWeights = softmax(scores, axis: -1) + if profiling { eval(attnWeights); let t1 = Date(); Self.profileOtherMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + + // Metal value kernel + let flatWeights = attnWeights.reshaped([B * nQHeads * L, tokenCount]) + let rotatedOutput = TurboQuantKernelOps.mseWeightedSum( + weights: flatWeights, packed: flatValPacked, norms: flatValNorms, + codebook: valueMSECodec.codebook, tokenCount: tokenCount, + repeatCount: nRepeats, bits: self.valueBits, dim: headDim + ) + if profiling { eval(rotatedOutput); let t1 = Date(); Self.profileValueMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + + // Inverse rotation + output = matmul( + rotatedOutput.reshaped([B, nQHeads, L, headDim]), + valueMSECodec.rotation + ) + if profiling { eval(output); let t1 = Date(); Self.profileRotateMs += t1.timeIntervalSince(t0) * 1000; t0 = t1 } + } + } + + Self.profileCount += 1 + return output + } + + // MARK: - Memory Reporting + + /// Actual memory footprint: compressed storage (packed indices + norms) for K and V, + /// plus any raw FP16 buffers if still in prefill phase or rawKeyMode, plus dequant buffers. + /// Does NOT include codec overhead (rotation matrices, codebooks) which is shared across layers. + /// In rawKeyMode: rawKeys is always present (FP16 keys), no keyPackedMSE/keyNorms. + override public var memoryBytes: Int { + var total = 0 + // Raw FP16 buffers (always present in rawKeyMode for keys, or during prefill) + if let rk = rawKeys { total += rk.shape.reduce(1, *) * rk.dtype.bytesPerElement } + if let rv = rawValues { total += rv.shape.reduce(1, *) * rv.dtype.bytesPerElement } + // Compressed storage (K only present when NOT rawKeyMode) + if let kp = keyPackedMSE { total += kp.shape.reduce(1, *) * kp.dtype.bytesPerElement } + if let kn = keyNorms { total += kn.shape.reduce(1, *) * kn.dtype.bytesPerElement } + if let vp = valPackedMSE { total += vp.shape.reduce(1, *) * vp.dtype.bytesPerElement } + if let vn = valNorms { total += vn.shape.reduce(1, *) * vn.dtype.bytesPerElement } + // Dequant buffers (if using updateAndDequant path) + if let dk = dequantKeys { total += dk.shape.reduce(1, *) * dk.dtype.bytesPerElement } + if let dv = dequantValues { total += dv.shape.reduce(1, *) * dv.dtype.bytesPerElement } + return total + } + + // MARK: - State / Trim + + override public var state: [MLXArray] { + get { + if isCompressed { + if rawKeyMode { + // Raw-K mode compressed: [rawKeys, valPacked, valNorms] + guard let rk = rawKeys, + let vpm = valPackedMSE, let vn = valNorms, + offset > 0 else { return [] } + return [ + rk[0..., 0..., .. 0 else { return [] } + return [ + kpm[0..., 0..., .. 0 else { return [] } + return [rk[0..., 0..., .. Int { + guard n > 0, offset > 0 else { return 0 } + + // Flush any pending uncompressed tokens before trimming + if !pendingRawKeys.isEmpty { + flushPendingEncode(headDim: pendingRawKeys[0].dim(-1)) + } + + let trimCount = min(n, offset) + offset -= trimCount + if offset == 0 { + rawKeys = nil; rawValues = nil; rawAllocSteps = 0 + keyPackedMSE = nil; keyNorms = nil + valPackedMSE = nil; valNorms = nil + dequantKeys = nil; dequantValues = nil + compressedAllocSteps = 0; isCompressed = false + pendingRawKeys.removeAll(); pendingRawValues.removeAll() + uncompressedCount = 0 + } + return trimCount + } +} diff --git a/Libraries/MLXLMCommon/TurboQuantKernels.swift b/Libraries/MLXLMCommon/TurboQuantKernels.swift new file mode 100644 index 0000000000..32805e9042 --- /dev/null +++ b/Libraries/MLXLMCommon/TurboQuantKernels.swift @@ -0,0 +1,1642 @@ +// Copyright © 2026 Eric Kryski. TurboQuant Metal kernels for compressed-domain attention. +// +// Single Metal kernel computes Q×K attention scores directly from packed +// codebook indices, skipping full dequantization. Pre-rotated queries +// eliminate the per-token inverse rotation. +// +// Key formula: score[t] = norm[t] * Σ_j q_rot[j] * codebook[idx[t,j]] +// where q_rot = Π · q (pre-rotated once) and idx are b-bit packed indices. + +import Foundation +import MLX + +// MARK: - Metal Kernel Source + +enum TurboQuantMetalKernels { + + /// Scoring kernel: computes attention scores from packed codebook indices. + /// + /// Each SIMD group (32 threads) handles one (query, key_token) pair. + /// Codebook (8-16 entries) is loaded into thread-local registers. + /// Bit unpacking + codebook lookup + dot product all happen in-register. + /// + /// Grid: (32, totalQueries, tokenCount) + /// Threadgroup: (32, 1, 1) + /// + /// Template params: Bits, Dim, PackedWidth + static let scoreKernelSource = """ + // Template constants injected by MLXFast JIT + constexpr uint MASK = (1u << Bits) - 1u; + constexpr uint LEVELS = 1u << Bits; + + // Runtime params from input buffers (avoids per-token pipeline recompilation) + uint token_count = uint(tc_buf[0]); + uint repeat_count = uint(rc_buf[0]); + + uint lane = thread_position_in_grid.x; // SIMD lane (0-31) + uint q_idx = thread_position_in_grid.y; // query index (B*nQHeads*L) + uint k_idx = thread_position_in_grid.z; // key token index + + // Map query head to KV head (GQA) + uint kv_idx = q_idx / repeat_count; + + // Pointers + const device float* q_ptr = q_rot + q_idx * Dim; + const device uint32_t* packed_ptr = packed + kv_idx * token_count * PackedWidth + k_idx * PackedWidth; + float norm_val = norms[kv_idx * token_count + k_idx]; + + // Load codebook into registers (small: 4-16 entries) + float cb[LEVELS]; + for (uint i = 0; i < LEVELS; i++) { + cb[i] = codebook[i]; + } + + // Parallel dot product: each lane handles dims [lane, lane+32, lane+64, ...] + float acc = 0.0f; + for (uint d = lane; d < Dim; d += 32) { + // Unpack b-bit index for dimension d + uint bit_offset = d * Bits; + uint word_idx = bit_offset / 32; + uint shift = bit_offset % 32; + uint value = (packed_ptr[word_idx] >> shift); + + // Handle bits that spill across uint32 word boundary + int spill = (int)shift + (int)Bits - 32; + if (spill > 0) { + value |= (packed_ptr[word_idx + 1] << ((uint)Bits - (uint)spill)); + } + value &= MASK; + + // Codebook lookup + accumulate dot product + acc += q_ptr[d] * cb[value]; + } + + // SIMD reduction across 32 lanes + acc = simd_sum(acc); + + // Lane 0 writes final score (scaled by stored norm) + if (thread_index_in_simdgroup == 0) { + scores[q_idx * token_count + k_idx] = acc * norm_val; + } + """ + + /// Fused encode kernel: norm + rotate + quantize + pack + norm correction in ONE dispatch. + /// + /// For each input vector [D]: + /// 1. Compute L2 norm (SIMD reduction) + /// 2. Normalize to unit vector + /// 3. Rotate: y = Π · x_unit (shared memory matmul) + /// 4. Quantize: find codebook index via boundary comparison + /// 5. Pack bits into uint32 words (atomic OR) + /// 6. Norm correction: compute reconstruction norm, store original_norm / recon_norm + /// + /// Norm correction compensates for quantization error so that + /// centroid[idx] * corrected_norm more accurately reconstructs the original vector. + /// This is why TurboQuant beats q8_0 on perplexity. + /// + /// Grid: (Dim, numRows, 1) — one threadgroup per vector + /// Threadgroup: (Dim, 1, 1) — all D threads cooperate + /// + /// Template params: Bits, Dim, PackedWidth, NumBoundaries (= 2^Bits - 1) + static let fusedEncodeSource = """ + constexpr uint LEVELS = 1u << Bits; + + uint d = thread_position_in_threadgroup.x; // dimension index (0..Dim-1) + uint row = thread_position_in_grid.y; // vector index (B*H*T) + + // --- Step 1: Load input value --- + float val = input[row * Dim + d]; + + // --- Step 2: Compute L2 norm (SIMD reduction) --- + float sq = val * val; + float norm_sq = simd_sum(sq); + // For Dim > 32, need threadgroup reduction + threadgroup float shared_norm[4]; // up to 4 SIMD groups + uint sg_id = d / 32; + if (d % 32 == 0) { + shared_norm[sg_id] = norm_sq; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float total_norm_sq = 0; + uint num_groups = (Dim + 31) / 32; + for (uint i = 0; i < num_groups; i++) { + total_norm_sq += shared_norm[i]; + } + float norm_val = sqrt(total_norm_sq); + float inv_norm = (norm_val > 1e-8f) ? (1.0f / norm_val) : 0.0f; + + // --- Step 3: Normalize --- + float unit_val = val * inv_norm; + + // --- Step 4: Rotate (y = Π · x_unit) via shared memory matmul --- + // Each thread d computes: y[d] = Σ_j rotation[d * Dim + j] * x_unit[j] + threadgroup float shared_unit[1024]; // max Dim = 1024 + shared_unit[d] = unit_val; + threadgroup_barrier(mem_flags::mem_threadgroup); + + float rotated = 0.0f; + for (uint j = 0; j < Dim; j++) { + rotated += rotation[d * Dim + j] * shared_unit[j]; + } + + // --- Step 5: Quantize via branchless boundary comparison --- + // V2.1 optimization: use arithmetic sum of comparisons instead of branching. + // Metal compiles (rotated > boundaries[b]) to a predicated 0/1 — summing these + // is branchless and avoids SIMD lane divergence. + uint idx = 0; + for (uint b = 0; b < LEVELS - 1; b++) { + idx += (uint)(rotated > boundaries[b]); + } + + // --- Step 6: Pack bits into uint32 word (atomic OR) --- + uint bit_offset = d * Bits; + uint word_idx = bit_offset / 32; + uint shift = bit_offset % 32; + uint masked = idx & ((1u << Bits) - 1u); + + // Pack bits — use threadgroup shared memory to avoid atomic contention + // Each thread writes its index bits to shared, then thread 0 per word writes output + threadgroup uint shared_packed[64]; // max PackedWidth = 64 words + if (d < PackedWidth) shared_packed[d] = 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Each dimension contributes its bits via atomic OR on threadgroup memory + uint primary_val = masked << shift; + atomic_fetch_or_explicit((threadgroup atomic_uint*)&shared_packed[word_idx], primary_val, memory_order_relaxed); + + int spill = (int)shift + (int)Bits - 32; + if (spill > 0) { + uint spill_val = masked >> ((uint)Bits - (uint)spill); + atomic_fetch_or_explicit((threadgroup atomic_uint*)&shared_packed[word_idx + 1], spill_val, memory_order_relaxed); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Write packed words to output (one thread per word) + if (d < PackedWidth) { + packed_out[row * PackedWidth + d] = shared_packed[d]; + } + + // --- Step 7: Norm correction --- + // Compute reconstruction norm: ||codebook[idx]||₂ for the quantized unit vector. + // Store corrected_norm = original_norm / recon_norm so that + // decode(centroid[idx] * corrected_norm) better approximates the original vector. + float centroid_val = codebook[idx]; + float recon_sq = centroid_val * centroid_val; + float recon_norm_sq = simd_sum(recon_sq); + // Threadgroup reduction for Dim > 32 + if (d % 32 == 0) { + shared_norm[sg_id] = recon_norm_sq; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float total_recon_sq = 0; + for (uint i = 0; i < num_groups; i++) { + total_recon_sq += shared_norm[i]; + } + float recon_norm = sqrt(total_recon_sq); + float corrected_norm = (recon_norm > 1e-8f) ? (norm_val / recon_norm) : norm_val; + + if (d == 0) { + norms_out[row] = corrected_norm; + } + """ + + /// Fused WHT encode kernel: norm + WHT rotation + quantize + pack (NO norm correction). + /// + /// Same as fusedEncodeSource but replaces dense O(d²) matmul with Fast Walsh-Hadamard + /// Transform O(d log d) butterfly + random sign flip. 18× fewer ops for dim=128. + /// + /// WHT is orthogonal → norms are preserved through rotation. Reconstruction norm ≈ + /// original norm (within FP error), so norm correction is wasted compute. We store + /// raw norms directly, saving one codebook lookup + norm computation + division per vector. + /// + /// WHT forward rotation: y = WHT(signs * x_unit) / sqrt(Dim) + /// The butterfly pattern: for each stage s in 0.. 1e-8f) ? (1.0f / norm_val) : 0.0f; + + // --- Step 3: Normalize + sign flip (fused) --- + // V2.1 optimization: pre-compute inv_norm * sign to eliminate one multiply per element. + // Instead of: unit_val = val * inv_norm; wht_val = sign * unit_val (2 muls) + // We do: wht_val = val * (inv_norm * sign) (1 mul + 1 FMA-friendly product) + float inv_norm_sign = inv_norm * wht_signs[d]; + float wht_val = val * inv_norm_sign; + + // --- Step 4: WHT rotation via cooperative SIMD shuffle --- + // V2.1 optimization: use simd_shuffle_xor for intra-SIMD butterfly stages + // (register-to-register, no shared memory or barriers needed for first 5 stages) + + // Phase 1: Intra-SIMD butterfly via simd_shuffle_xor (stages 0..min(LogDim,5)-1) + // Each stage s XORs lane indices at distance 2^s — effectively free on Apple GPU + // Use metal::min: MLX-injected headers add overloads named `min` (bf16_math.h), so + // unqualified min(LogDim, 5u) is ambiguous vs metal::min on newer toolchains. + uint log_dim_u = static_cast(LogDim); + uint simd_stages = metal::min(log_dim_u, 5u); // 5 stages covers 32 lanes (2^5 = 32) + uint lane_in_simd = d % 32; + for (uint s = 0; s < simd_stages; s++) { + uint step = 1u << s; + float other = simd_shuffle_xor(wht_val, step); + wht_val = (lane_in_simd & step) ? (other - wht_val) : (other + wht_val); + } + + // Phase 2: Cross-SIMD-group butterfly via shared memory (stages 5..LogDim-1) + // Only needed when Dim > 32 — these stages cross SIMD group boundaries + threadgroup float shared_buf[1024]; // max Dim = 1024 + if (log_dim_u > 5u) { + shared_buf[d] = wht_val; + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (uint s = simd_stages; s < log_dim_u; s++) { + uint half_block = 1u << s; + uint block_size = half_block << 1; + uint block_id = d / block_size; + uint pos_in_block = d % block_size; + + float a, b; + if (pos_in_block < half_block) { + a = shared_buf[block_id * block_size + pos_in_block]; + b = shared_buf[block_id * block_size + pos_in_block + half_block]; + shared_buf[d] = a + b; + } else { + a = shared_buf[block_id * block_size + pos_in_block - half_block]; + b = shared_buf[block_id * block_size + pos_in_block]; + shared_buf[d] = a - b; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + wht_val = shared_buf[d]; + } + + // Normalize: WHT has scale factor sqrt(Dim) + float inv_sqrt_dim = 1.0f / sqrt((float)Dim); + float rotated = wht_val * inv_sqrt_dim; + + // --- Step 5: Quantize via branchless boundary comparison --- + // V2.1 optimization: arithmetic sum avoids SIMD lane divergence + uint idx = 0; + for (uint b = 0; b < LEVELS - 1; b++) { + idx += (uint)(rotated > boundaries[b]); + } + + // --- Step 6: Pack bits into uint32 word (atomic OR) --- + uint bit_offset = d * Bits; + uint word_idx = bit_offset / 32; + uint shift = bit_offset % 32; + uint masked = idx & ((1u << Bits) - 1u); + + threadgroup uint shared_packed[64]; + if (d < PackedWidth) shared_packed[d] = 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + + uint primary_val = masked << shift; + atomic_fetch_or_explicit((threadgroup atomic_uint*)&shared_packed[word_idx], primary_val, memory_order_relaxed); + + int spill = (int)shift + (int)Bits - 32; + if (spill > 0) { + uint spill_val = masked >> ((uint)Bits - (uint)spill); + atomic_fetch_or_explicit((threadgroup atomic_uint*)&shared_packed[word_idx + 1], spill_val, memory_order_relaxed); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (d < PackedWidth) { + packed_out[row * PackedWidth + d] = shared_packed[d]; + } + + // --- Step 7: Store raw norm (WHT is orthogonal — no norm correction needed) --- + // WHT preserves norms: ||WHT(x)||₂ = ||x||₂. Reconstruction norm ≈ original norm, + // so the correction ratio ≈ 1.0. Skipping saves codebook lookup + norm + division. + if (d == 0) { + norms_out[row] = norm_val; + } + """ + + /// TurboFlashAttention Pass 1: Per-block partial attention with online softmax. + /// + /// Parallelizes across both query heads AND token blocks. Each SIMD group (32 lanes) + /// handles one (query, block) pair, producing partial online softmax state (m, l, o[D]). + /// Pass 2 merges partials across blocks. + /// + /// Grid: (32, totalQueries, numBlocks) + /// Threadgroup: (32, 1, 1) + /// + /// Template params: KeyBits, ValueBits, Dim, KeyPackedWidth, ValuePackedWidth + static let turboFlashPass1Source = """ + constexpr uint KEY_MASK = (1u << KeyBits) - 1u; + constexpr uint KEY_LEVELS = 1u << KeyBits; + constexpr uint VAL_MASK = (1u << ValueBits) - 1u; + constexpr uint VAL_LEVELS = 1u << ValueBits; + constexpr uint DIMS_PER_LANE = (Dim + 31) / 32; + + // Runtime params from input buffers (avoids per-token pipeline recompilation) + uint token_count = uint(tc_buf[0]); + uint repeat_count = uint(rc_buf[0]); + uint num_blocks = uint(nb_buf[0]); + uint BlockSize = uint(bs_buf[0]); + + uint lane = thread_position_in_grid.x; // SIMD lane (0-31) + uint q_idx = thread_position_in_grid.y; // query index (B*nQHeads*L) + uint block_idx = thread_position_in_grid.z; // token block index + uint kv_idx = q_idx / repeat_count; // map to KV head (GQA) + + // Token range for this block + uint t_start = block_idx * BlockSize; + uint t_end = t_start + BlockSize; + if (t_end > token_count) t_end = token_count; + + // Load key codebook into registers + float key_cb[KEY_LEVELS]; + for (uint i = 0; i < KEY_LEVELS; i++) { + key_cb[i] = key_codebook[i]; + } + + // Load value codebook into registers + float val_cb[VAL_LEVELS]; + for (uint i = 0; i < VAL_LEVELS; i++) { + val_cb[i] = val_codebook[i]; + } + + // Load query values for this lane's dimensions + float q_vals[DIMS_PER_LANE]; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + q_vals[i] = (d < Dim) ? q_rot[q_idx * Dim + d] : 0.0f; + } + + // Online softmax state for this block + float m = -INFINITY; + float l = 0.0f; + float o[DIMS_PER_LANE]; + for (uint i = 0; i < DIMS_PER_LANE; i++) o[i] = 0.0f; + + // Process tokens in this block + for (uint t = t_start; t < t_end; t++) { + // --- Score: Q×K dot product --- + const device uint32_t* k_packed_ptr = key_packed + kv_idx * token_count * KeyPackedWidth + t * KeyPackedWidth; + float k_norm = key_norms[kv_idx * token_count + t]; + + float dot_partial = 0.0f; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) break; + + uint k_bit_offset = d * KeyBits; + uint k_word_idx = k_bit_offset / 32; + uint k_shift = k_bit_offset % 32; + uint k_value = (k_packed_ptr[k_word_idx] >> k_shift); + int k_spill = (int)k_shift + (int)KeyBits - 32; + if (k_spill > 0) { + k_value |= (k_packed_ptr[k_word_idx + 1] << ((uint)KeyBits - (uint)k_spill)); + } + k_value &= KEY_MASK; + + dot_partial += q_vals[i] * key_cb[k_value]; + } + + float score = simd_sum(dot_partial) * k_norm; + + // --- Online softmax update + V accumulation --- + float new_m = max(m, score); + float exp_diff = exp(m - new_m); + float exp_score = exp(score - new_m); + + const device uint32_t* v_packed_ptr = val_packed + kv_idx * token_count * ValuePackedWidth + t * ValuePackedWidth; + float v_norm = val_norms[kv_idx * token_count + t]; + + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) break; + + uint v_bit_offset = d * ValueBits; + uint v_word_idx = v_bit_offset / 32; + uint v_shift = v_bit_offset % 32; + uint v_value = (v_packed_ptr[v_word_idx] >> v_shift); + int v_spill = (int)v_shift + (int)ValueBits - 32; + if (v_spill > 0) { + v_value |= (v_packed_ptr[v_word_idx + 1] << ((uint)ValueBits - (uint)v_spill)); + } + v_value &= VAL_MASK; + + o[i] = o[i] * exp_diff + exp_score * (val_cb[v_value] * v_norm); + } + + l = l * exp_diff + exp_score; + m = new_m; + } + + // Write partial results: o[D], m, l + uint partial_base = (q_idx * num_blocks + block_idx) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + o_partials[partial_base + d] = o[i]; + } + } + if (lane == 0) { + uint ml_idx = q_idx * num_blocks + block_idx; + m_partials[ml_idx] = m; + l_partials[ml_idx] = l; + } + """ + + /// TurboFlashAttention Pass 1 (Causal): Per-block partial attention with causal masking. + /// + /// Same as turboFlashPass1Source but supports L>1 query chunks with causal masking. + /// Each query position q_within_L only attends to tokens where t <= q_offset + q_within_L. + /// Blocks that are entirely future-masked exit early. + /// + /// Grid: (32, totalQueries, numBlocks) where totalQueries = B * nQHeads * L + /// Threadgroup: (32, 1, 1) + /// + /// Template params: KeyBits, ValueBits, Dim, KeyPackedWidth, ValuePackedWidth + static let turboFlashPass1CausalSource = """ + constexpr uint KEY_MASK = (1u << KeyBits) - 1u; + constexpr uint KEY_LEVELS = 1u << KeyBits; + constexpr uint VAL_MASK = (1u << ValueBits) - 1u; + constexpr uint VAL_LEVELS = 1u << ValueBits; + constexpr uint DIMS_PER_LANE = (Dim + 31) / 32; + + // Runtime params from input buffers + uint token_count = uint(tc_buf[0]); + uint repeat_count = uint(rc_buf[0]); + uint num_blocks = uint(nb_buf[0]); + uint BlockSize = uint(bs_buf[0]); + uint L = uint(L_buf[0]); + uint q_offset = uint(qo_buf[0]); + + uint lane = thread_position_in_grid.x; // SIMD lane (0-31) + uint q_idx = thread_position_in_grid.y; // query index (B*nQHeads*L) + uint block_idx = thread_position_in_grid.z; // token block index + + uint q_within_L = q_idx % L; + uint q_head_idx = q_idx / L; + uint kv_idx = q_head_idx / repeat_count; + + uint q_abs = q_offset + q_within_L; + + uint t_start = block_idx * BlockSize; + uint t_end = t_start + BlockSize; + if (t_end > token_count) t_end = token_count; + + // Early exit: entire block is future-masked + if (t_start > q_abs) { + uint partial_base = (q_idx * num_blocks + block_idx) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) o_partials[partial_base + d] = 0.0f; + } + if (lane == 0) { + uint ml_idx = q_idx * num_blocks + block_idx; + m_partials[ml_idx] = -INFINITY; + l_partials[ml_idx] = 0.0f; + } + return; + } + + // Clamp t_end to causal boundary + if (t_end > q_abs + 1) t_end = q_abs + 1; + + // Load key codebook into registers + float key_cb[KEY_LEVELS]; + for (uint i = 0; i < KEY_LEVELS; i++) { + key_cb[i] = key_codebook[i]; + } + + // Load value codebook into registers + float val_cb[VAL_LEVELS]; + for (uint i = 0; i < VAL_LEVELS; i++) { + val_cb[i] = val_codebook[i]; + } + + // Load query values for this lane's dimensions + float q_vals[DIMS_PER_LANE]; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + q_vals[i] = (d < Dim) ? q_rot[q_idx * Dim + d] : 0.0f; + } + + // Online softmax state for this block + float m = -INFINITY; + float l = 0.0f; + float o[DIMS_PER_LANE]; + for (uint i = 0; i < DIMS_PER_LANE; i++) o[i] = 0.0f; + + // Process tokens in this block (up to causal boundary) + for (uint t = t_start; t < t_end; t++) { + // --- Score: Q×K dot product --- + const device uint32_t* k_packed_ptr = key_packed + kv_idx * token_count * KeyPackedWidth + t * KeyPackedWidth; + float k_norm = key_norms[kv_idx * token_count + t]; + + float dot_partial = 0.0f; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) break; + + uint k_bit_offset = d * KeyBits; + uint k_word_idx = k_bit_offset / 32; + uint k_shift = k_bit_offset % 32; + uint k_value = (k_packed_ptr[k_word_idx] >> k_shift); + int k_spill = (int)k_shift + (int)KeyBits - 32; + if (k_spill > 0) { + k_value |= (k_packed_ptr[k_word_idx + 1] << ((uint)KeyBits - (uint)k_spill)); + } + k_value &= KEY_MASK; + + dot_partial += q_vals[i] * key_cb[k_value]; + } + + float score = simd_sum(dot_partial) * k_norm; + + // --- Online softmax update + V accumulation --- + float new_m = max(m, score); + float exp_diff = exp(m - new_m); + float exp_score = exp(score - new_m); + + const device uint32_t* v_packed_ptr = val_packed + kv_idx * token_count * ValuePackedWidth + t * ValuePackedWidth; + float v_norm = val_norms[kv_idx * token_count + t]; + + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) break; + + uint v_bit_offset = d * ValueBits; + uint v_word_idx = v_bit_offset / 32; + uint v_shift = v_bit_offset % 32; + uint v_value = (v_packed_ptr[v_word_idx] >> v_shift); + int v_spill = (int)v_shift + (int)ValueBits - 32; + if (v_spill > 0) { + v_value |= (v_packed_ptr[v_word_idx + 1] << ((uint)ValueBits - (uint)v_spill)); + } + v_value &= VAL_MASK; + + o[i] = o[i] * exp_diff + exp_score * (val_cb[v_value] * v_norm); + } + + l = l * exp_diff + exp_score; + m = new_m; + } + + // Write partial results: o[D], m, l + uint partial_base = (q_idx * num_blocks + block_idx) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + o_partials[partial_base + d] = o[i]; + } + } + if (lane == 0) { + uint ml_idx = q_idx * num_blocks + block_idx; + m_partials[ml_idx] = m; + l_partials[ml_idx] = l; + } + """ + + /// TurboFlashAttention Pass 1 NR0=2: Multi-row amortized KV dequant. + /// + /// Ported from llama.cpp V2.1 fused decode kernel concept. Each SIMD group processes + /// NR0=2 queries against one KV block simultaneously. The key win: packed index unpacking + /// + codebook lookup for K and V is done ONCE and reused across both queries. + /// + /// Register budget per thread (NR0=2, DIMS_PER_LANE=4 for dim=128): + /// - 2 × DIMS_PER_LANE q_vals = 8 floats (query data) + /// - 2 × 1 m/l = 4 floats (online softmax state) + /// - 2 × DIMS_PER_LANE o = 8 floats (value accumulators) + /// - codebook regs shared = KEY_LEVELS + VAL_LEVELS floats + /// Total: ~24 extra floats vs NR0=1. Well within Apple GPU register file. + /// + /// Zero threadgroup memory (ported from llama.cpp V2.1): all score computation, + /// online softmax, and V accumulation happen entirely in SIMD registers via simd_sum. + /// No shared memory needed in pass 1 (same as NR0=1 baseline). This is possible because + /// the dot product reduction (simd_sum) is the only cross-lane operation needed. + /// + /// Note: pass 2 fused rotation still needs threadgroup memory for dim>32 because the + /// rotation matmul requires cross-SIMD-group communication. See turboFlashPass2FusedRotSource. + /// The non-fused pass 2 is also zero-smem. + /// + /// Grid: (32, totalQueries/NR0, numBlocks) + /// Threadgroup: (32, 1, 1) + /// + /// Template params: KeyBits, ValueBits, Dim, KeyPackedWidth, ValuePackedWidth, NR0 + static let turboFlashPass1NR0Source = """ + constexpr uint KEY_MASK = (1u << KeyBits) - 1u; + constexpr uint KEY_LEVELS = 1u << KeyBits; + constexpr uint VAL_MASK = (1u << ValueBits) - 1u; + constexpr uint VAL_LEVELS = 1u << ValueBits; + constexpr uint DIMS_PER_LANE = (Dim + 31) / 32; + + // Runtime params from input buffers (avoids per-token pipeline recompilation) + uint token_count = uint(tc_buf[0]); + uint repeat_count = uint(rc_buf[0]); + uint num_blocks = uint(nb_buf[0]); + uint BlockSize = uint(bs_buf[0]); + + uint lane = thread_position_in_grid.x; // SIMD lane (0-31) + uint query_group = thread_position_in_grid.y; // which group of NR0 queries + uint block_idx = thread_position_in_grid.z; // which KV block + + // Token range for this block + uint t_start = block_idx * BlockSize; + uint t_end = t_start + BlockSize; + if (t_end > token_count) t_end = token_count; + + // Load key codebook into registers (shared across all NR0 queries) + float key_cb[KEY_LEVELS]; + for (uint i = 0; i < KEY_LEVELS; i++) { + key_cb[i] = key_codebook[i]; + } + + // Load value codebook into registers (shared across all NR0 queries) + float val_cb[VAL_LEVELS]; + for (uint i = 0; i < VAL_LEVELS; i++) { + val_cb[i] = val_codebook[i]; + } + + // Load query values for ALL NR0 rows — each row's dims interleaved in registers + float q_vals[NR0 * DIMS_PER_LANE]; + for (uint r = 0; r < NR0; r++) { + uint q_idx = query_group * NR0 + r; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + q_vals[r * DIMS_PER_LANE + i] = (d < Dim) ? q_rot[q_idx * Dim + d] : 0.0f; + } + } + + // Per-query KV head mapping (for GQA — each query may map to different KV head) + uint kv_indices[NR0]; + for (uint r = 0; r < NR0; r++) { + kv_indices[r] = (query_group * NR0 + r) / repeat_count; + } + + // Online softmax state — NR0 independent streams, all in registers + float m_state[NR0]; + float l_state[NR0]; + float o_state[NR0 * DIMS_PER_LANE]; + for (uint r = 0; r < NR0; r++) { + m_state[r] = -INFINITY; + l_state[r] = 0.0f; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + o_state[r * DIMS_PER_LANE + i] = 0.0f; + } + } + + // Process tokens in this block — KV dequant done ONCE, reused across NR0 queries + for (uint t = t_start; t < t_end; t++) { + // --- Dequant K for this token ONCE (amortized across NR0 queries) --- + // Each lane unpacks its dims' codebook values into registers + float k_decoded[DIMS_PER_LANE]; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) { k_decoded[i] = 0.0f; continue; } + + // TODO: Could precompute bit_offset/word_idx/shift tables for hot dims + uint k_bit_offset = d * KeyBits; + uint k_word_idx = k_bit_offset / 32; + uint k_shift = k_bit_offset % 32; + + // All NR0 queries hitting the same KV head read the same packed data. + // For GQA with different KV heads per query, we use kv_indices[0] here + // since within a SIMD group all queries typically map to the same KV head. + // TODO: Handle edge case where NR0 queries span KV head boundary + const device uint32_t* k_packed_ptr = key_packed + kv_indices[0] * token_count * KeyPackedWidth + t * KeyPackedWidth; + + uint k_value = (k_packed_ptr[k_word_idx] >> k_shift); + int k_spill = (int)k_shift + (int)KeyBits - 32; + if (k_spill > 0) { + k_value |= (k_packed_ptr[k_word_idx + 1] << ((uint)KeyBits - (uint)k_spill)); + } + k_value &= KEY_MASK; + k_decoded[i] = key_cb[k_value]; + } + float k_norm = key_norms[kv_indices[0] * token_count + t]; + + // --- Dequant V for this token ONCE --- + float v_decoded[DIMS_PER_LANE]; + const device uint32_t* v_packed_ptr = val_packed + kv_indices[0] * token_count * ValuePackedWidth + t * ValuePackedWidth; + float v_norm = val_norms[kv_indices[0] * token_count + t]; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) { v_decoded[i] = 0.0f; continue; } + + uint v_bit_offset = d * ValueBits; + uint v_word_idx = v_bit_offset / 32; + uint v_shift = v_bit_offset % 32; + uint v_value = (v_packed_ptr[v_word_idx] >> v_shift); + int v_spill = (int)v_shift + (int)ValueBits - 32; + if (v_spill > 0) { + v_value |= (v_packed_ptr[v_word_idx + 1] << ((uint)ValueBits - (uint)v_spill)); + } + v_value &= VAL_MASK; + v_decoded[i] = val_cb[v_value] * v_norm; + } + + // --- Score + softmax + V accumulate for each of NR0 queries --- + // K/V dequant above is the expensive part — this loop is cheap ALU + for (uint r = 0; r < NR0; r++) { + // Dot product: q[r] · k (both already in registers) + float dot_partial = 0.0f; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + dot_partial += q_vals[r * DIMS_PER_LANE + i] * k_decoded[i]; + } + float score = simd_sum(dot_partial) * k_norm; + + // Online softmax update + float new_m = max(m_state[r], score); + float exp_diff = exp(m_state[r] - new_m); + float exp_score = exp(score - new_m); + + // V accumulation (reusing pre-decoded values) + for (uint i = 0; i < DIMS_PER_LANE; i++) { + o_state[r * DIMS_PER_LANE + i] = o_state[r * DIMS_PER_LANE + i] * exp_diff + exp_score * v_decoded[i]; + } + + l_state[r] = l_state[r] * exp_diff + exp_score; + m_state[r] = new_m; + } + } + + // Write partial results for all NR0 queries + for (uint r = 0; r < NR0; r++) { + uint q_idx = query_group * NR0 + r; + uint partial_base = (q_idx * num_blocks + block_idx) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + o_partials[partial_base + d] = o_state[r * DIMS_PER_LANE + i]; + } + } + if (lane == 0) { + uint ml_idx = q_idx * num_blocks + block_idx; + m_partials[ml_idx] = m_state[r]; + l_partials[ml_idx] = l_state[r]; + } + } + """ + + /// TurboFlashAttention Pass 1 NR0 Causal: Multi-row amortized KV dequant with causal masking. + /// + /// Same as turboFlashPass1NR0Source but each query within the NR0 group has its own + /// causal boundary. For L>1 prefill, q_within_L differs per row so each row may attend + /// to a different number of tokens. We compute the conservative (minimum) causal boundary + /// across the NR0 group for the shared K/V dequant, then mask per-row in the score loop. + /// + /// Grid: (32, totalQueries/NR0, numBlocks) + /// Threadgroup: (32, 1, 1) + /// + /// Template params: KeyBits, ValueBits, Dim, KeyPackedWidth, ValuePackedWidth, NR0 + static let turboFlashPass1NR0CausalSource = """ + constexpr uint KEY_MASK = (1u << KeyBits) - 1u; + constexpr uint KEY_LEVELS = 1u << KeyBits; + constexpr uint VAL_MASK = (1u << ValueBits) - 1u; + constexpr uint VAL_LEVELS = 1u << ValueBits; + constexpr uint DIMS_PER_LANE = (Dim + 31) / 32; + + // Runtime params from input buffers (avoids per-token pipeline recompilation) + uint token_count = uint(tc_buf[0]); + uint repeat_count = uint(rc_buf[0]); + uint num_blocks = uint(nb_buf[0]); + uint BlockSize = uint(bs_buf[0]); + uint L = uint(L_buf[0]); + uint q_offset = uint(qo_buf[0]); + + uint lane = thread_position_in_grid.x; + uint query_group = thread_position_in_grid.y; + uint block_idx = thread_position_in_grid.z; + + // Token range for this block + uint t_start = block_idx * BlockSize; + uint t_end = t_start + BlockSize; + if (t_end > token_count) t_end = token_count; + + // Compute per-row causal boundaries and find the maximum (most permissive) + // for the shared token loop. Per-row masking happens inside the score loop. + uint q_abs[NR0]; + uint max_q_abs = 0; + for (uint r = 0; r < NR0; r++) { + uint q_idx = query_group * NR0 + r; + uint q_within_L = q_idx % L; + q_abs[r] = q_offset + q_within_L; + if (q_abs[r] > max_q_abs) max_q_abs = q_abs[r]; + } + + // Early exit: entire block is future-masked for ALL NR0 queries + if (t_start > max_q_abs) { + for (uint r = 0; r < NR0; r++) { + uint q_idx = query_group * NR0 + r; + uint partial_base = (q_idx * num_blocks + block_idx) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) o_partials[partial_base + d] = 0.0f; + } + if (lane == 0) { + uint ml_idx = q_idx * num_blocks + block_idx; + m_partials[ml_idx] = -INFINITY; + l_partials[ml_idx] = 0.0f; + } + } + return; + } + + // Clamp t_end to the most permissive causal boundary + if (t_end > max_q_abs + 1) t_end = max_q_abs + 1; + + // Load codebooks (shared across all NR0 queries) + float key_cb[KEY_LEVELS]; + for (uint i = 0; i < KEY_LEVELS; i++) key_cb[i] = key_codebook[i]; + float val_cb[VAL_LEVELS]; + for (uint i = 0; i < VAL_LEVELS; i++) val_cb[i] = val_codebook[i]; + + // Load query values for all NR0 rows + float q_vals[NR0 * DIMS_PER_LANE]; + for (uint r = 0; r < NR0; r++) { + uint q_idx = query_group * NR0 + r; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + q_vals[r * DIMS_PER_LANE + i] = (d < Dim) ? q_rot[q_idx * Dim + d] : 0.0f; + } + } + + // KV head mapping (use first query's head — same assumption as non-causal NR0) + uint q_head_idx_0 = (query_group * NR0) / L; + uint kv_idx = q_head_idx_0 / repeat_count; + + // Online softmax state — NR0 independent streams + float m_state[NR0]; + float l_state[NR0]; + float o_state[NR0 * DIMS_PER_LANE]; + for (uint r = 0; r < NR0; r++) { + m_state[r] = -INFINITY; + l_state[r] = 0.0f; + for (uint i = 0; i < DIMS_PER_LANE; i++) o_state[r * DIMS_PER_LANE + i] = 0.0f; + } + + // Process tokens — KV dequant once, score per-row with causal mask + for (uint t = t_start; t < t_end; t++) { + // Dequant K once + float k_decoded[DIMS_PER_LANE]; + const device uint32_t* k_packed_ptr = key_packed + kv_idx * token_count * KeyPackedWidth + t * KeyPackedWidth; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) { k_decoded[i] = 0.0f; continue; } + uint k_bit_offset = d * KeyBits; + uint k_word_idx = k_bit_offset / 32; + uint k_shift = k_bit_offset % 32; + uint k_value = (k_packed_ptr[k_word_idx] >> k_shift); + int k_spill = (int)k_shift + (int)KeyBits - 32; + if (k_spill > 0) { + k_value |= (k_packed_ptr[k_word_idx + 1] << ((uint)KeyBits - (uint)k_spill)); + } + k_value &= KEY_MASK; + k_decoded[i] = key_cb[k_value]; + } + float k_norm = key_norms[kv_idx * token_count + t]; + + // Dequant V once + float v_decoded[DIMS_PER_LANE]; + const device uint32_t* v_packed_ptr = val_packed + kv_idx * token_count * ValuePackedWidth + t * ValuePackedWidth; + float v_norm = val_norms[kv_idx * token_count + t]; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d >= Dim) { v_decoded[i] = 0.0f; continue; } + uint v_bit_offset = d * ValueBits; + uint v_word_idx = v_bit_offset / 32; + uint v_shift = v_bit_offset % 32; + uint v_value = (v_packed_ptr[v_word_idx] >> v_shift); + int v_spill = (int)v_shift + (int)ValueBits - 32; + if (v_spill > 0) { + v_value |= (v_packed_ptr[v_word_idx + 1] << ((uint)ValueBits - (uint)v_spill)); + } + v_value &= VAL_MASK; + v_decoded[i] = val_cb[v_value] * v_norm; + } + + // Score + softmax + V for each query row (with per-row causal mask) + for (uint r = 0; r < NR0; r++) { + // Per-row causal: skip if this token is future for this specific query + if (t > q_abs[r]) continue; + + float dot_partial = 0.0f; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + dot_partial += q_vals[r * DIMS_PER_LANE + i] * k_decoded[i]; + } + float score = simd_sum(dot_partial) * k_norm; + + float new_m = max(m_state[r], score); + float exp_diff = exp(m_state[r] - new_m); + float exp_score = exp(score - new_m); + + for (uint i = 0; i < DIMS_PER_LANE; i++) { + o_state[r * DIMS_PER_LANE + i] = o_state[r * DIMS_PER_LANE + i] * exp_diff + exp_score * v_decoded[i]; + } + l_state[r] = l_state[r] * exp_diff + exp_score; + m_state[r] = new_m; + } + } + + // Write partial results for all NR0 queries + for (uint r = 0; r < NR0; r++) { + uint q_idx = query_group * NR0 + r; + uint partial_base = (q_idx * num_blocks + block_idx) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) o_partials[partial_base + d] = o_state[r * DIMS_PER_LANE + i]; + } + if (lane == 0) { + uint ml_idx = q_idx * num_blocks + block_idx; + m_partials[ml_idx] = m_state[r]; + l_partials[ml_idx] = l_state[r]; + } + } + """ + + /// TurboFlashAttention Pass 2: Cross-block reduction. + /// + /// Merges partial online softmax states from pass 1 across token blocks. + /// Each SIMD group handles one query, iterating over all blocks to produce + /// the final normalized output. + /// + /// This kernel is already zero-threadgroup-memory — all state (m, l, o[DIMS_PER_LANE]) + /// lives in SIMD registers. No shared memory needed since output is written directly + /// without rotation. This matches the llama.cpp V2.1 zero-smem design. + /// + /// Grid: (32, totalQueries, 1) + /// Threadgroup: (32, 1, 1) + /// + /// Template params: Dim + static let turboFlashPass2Source = """ + constexpr uint DIMS_PER_LANE = (Dim + 31) / 32; + + // Runtime params from input buffers (avoids per-token pipeline recompilation) + uint num_blocks = uint(nb_buf[0]); + + uint lane = thread_position_in_grid.x; + uint q_idx = thread_position_in_grid.y; + + float m = -INFINITY; + float l = 0.0f; + float o[DIMS_PER_LANE]; + for (uint i = 0; i < DIMS_PER_LANE; i++) o[i] = 0.0f; + + for (uint b = 0; b < num_blocks; b++) { + uint ml_idx = q_idx * num_blocks + b; + + // All lanes read the same m/l (broadcast read from device memory) + float block_m = m_partials[ml_idx]; + float block_l = l_partials[ml_idx]; + + // Skip empty blocks + if (block_l == 0.0f) continue; + + float new_m = max(m, block_m); + float exp_old = exp(m - new_m); + float exp_block = exp(block_m - new_m); + + uint partial_base = (q_idx * num_blocks + b) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + o[i] = o[i] * exp_old + o_partials[partial_base + d] * exp_block; + } + } + + l = l * exp_old + block_l * exp_block; + m = new_m; + } + + // Write normalized output + float inv_l = (l > 0.0f) ? (1.0f / l) : 0.0f; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + output[q_idx * Dim + d] = o[i] * inv_l; + } + } + """ + + /// TurboFlashAttention Pass 2 with fused output rotation. + /// + /// Same as turboFlashPass2Source but applies inverse value rotation (Π_val) in-kernel + /// after merging partials, eliminating a separate MLX matmul dispatch. + /// Uses threadgroup shared memory to gather the full output vector across SIMD lanes, + /// then each lane computes rotated output as dot product with rotation matrix rows. + /// + /// ## Zero-threadgroup-memory analysis (from llama.cpp V2.1 port) + /// + /// In llama.cpp V2.1, the fused decode kernel achieves zero threadgroup memory by using + /// simd_shuffle_xor for all cross-lane communication. This works because WHT butterfly + /// and score reduction only need power-of-2 strided communication within a SIMD group. + /// + /// For this pass 2 kernel, zero-smem is **only possible when Dim <= 32** (single SIMD group): + /// - Dim <= 32: each lane owns exactly 1 output dimension. The full output vector lives + /// in SIMD registers and can be gathered via simd_shuffle for the rotation matmul. + /// - Dim > 32 (typical: 128): each lane owns DIMS_PER_LANE=4 values. The rotation + /// `output[d] = Σ_j shared_out[j] * rotation[j * Dim + d]` needs ALL Dim values + /// accessible to each lane. With Dim=128 across 4 SIMD groups, this requires + /// cross-SIMD-group communication → threadgroup shared memory is unavoidable. + /// + /// Conclusion: shared_out[Dim] threadgroup memory in this kernel is already optimal for + /// the common case (dim=128). The llama.cpp zero-smem trick doesn't apply here because + /// Apple Metal SIMD groups are 32 wide and typical head dims are 128. + /// + /// Grid: (32, totalQueries, 1) + /// Threadgroup: (32, 1, 1) + /// + /// Template params: Dim + static let turboFlashPass2FusedRotSource = """ + constexpr uint DIMS_PER_LANE = (Dim + 31) / 32; + + // Runtime params from input buffers (avoids per-token pipeline recompilation) + uint num_blocks = uint(nb_buf[0]); + + uint lane = thread_position_in_grid.x; + uint q_idx = thread_position_in_grid.y; + + float m = -INFINITY; + float l = 0.0f; + float o[DIMS_PER_LANE]; + for (uint i = 0; i < DIMS_PER_LANE; i++) o[i] = 0.0f; + + for (uint b = 0; b < num_blocks; b++) { + uint ml_idx = q_idx * num_blocks + b; + + float block_m = m_partials[ml_idx]; + float block_l = l_partials[ml_idx]; + + if (block_l == 0.0f) continue; + + float new_m = max(m, block_m); + float exp_old = exp(m - new_m); + float exp_block = exp(block_m - new_m); + + uint partial_base = (q_idx * num_blocks + b) * Dim; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + o[i] = o[i] * exp_old + o_partials[partial_base + d] * exp_block; + } + } + + l = l * exp_old + block_l * exp_block; + m = new_m; + } + + // Normalize + float inv_l = (l > 0.0f) ? (1.0f / l) : 0.0f; + + // Gather normalized output into threadgroup shared memory for rotation + threadgroup float shared_out[Dim]; + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + shared_out[d] = o[i] * inv_l; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Apply inverse value rotation: output[d] = Σ_j shared_out[j] * Π_val[j][d] + // matmul(x, Π_val) reads column d of Π_val for output dimension d. + // Π_val is stored row-major [Dim, Dim], so column d = val_rotation[j * Dim + d] + for (uint i = 0; i < DIMS_PER_LANE; i++) { + uint d = lane + i * 32; + if (d < Dim) { + float acc = 0.0f; + for (uint j = 0; j < Dim; j++) { + acc += shared_out[j] * val_rotation[j * Dim + d]; + } + output[q_idx * Dim + d] = acc; + } + } + """ + + /// Sparse V skip threshold for the value aggregation kernel. + /// Attention weights below this threshold are skipped entirely, saving memory bandwidth + /// on the V codebook lookup. Default 1e-6 works well for most models. + /// + /// Override via environment variable `TURBO_SPARSE_V_THRESHOLD` (e.g. "1e-5", "0.0"). + /// Set to "0.0" to disable sparse V skipping entirely. + /// + /// From llama.cpp TurboQuant+ research: this threshold matters for quality/perf tradeoff. + /// Too aggressive (e.g. 1e-4) can clip meaningful attention weights in long contexts. + /// Too conservative (e.g. 0) loses the 15-30% decode speedup from sparse V. + static let sparseVThreshold: Float = { + if let envValue = ProcessInfo.processInfo.environment["TURBO_SPARSE_V_THRESHOLD"], + let parsed = Float(envValue) { + return parsed + } + return 1e-6 // default, validated in llama.cpp benchmarks + }() + + /// Value aggregation kernel: weighted sum of codebook-quantized values. + /// + /// output[d] = Σ_t weights[t] * norm[t] * codebook[val_idx[t,d]] + /// Result is in rotated space — caller applies inverse rotation. + /// Sparse V: tokens with attention weight < sparseVThreshold are skipped. + /// + /// Grid: (32, totalHeads, ceil(Dim/32)) + /// Threadgroup: (32, 1, 1) + static var valueKernelSource: String { + let threshold = String(format: "%e", sparseVThreshold) + return """ + constexpr uint MASK = (1u << Bits) - 1u; + constexpr uint LEVELS = 1u << Bits; + + // Runtime params from input buffers (avoids per-token pipeline recompilation) + uint token_count = uint(tc_buf[0]); + uint repeat_count = uint(rc_buf[0]); + + uint lane = thread_position_in_grid.x; + uint head_idx = thread_position_in_grid.y; + uint dim_block = thread_position_in_grid.z; + + uint d = dim_block * 32 + lane; + if (d >= Dim) return; + + uint kv_head = head_idx / repeat_count; + + // Load codebook + float cb[LEVELS]; + for (uint i = 0; i < LEVELS; i++) { + cb[i] = codebook[i]; + } + + float acc = 0.0f; + for (uint t = 0; t < token_count; t++) { + float w = weights[head_idx * token_count + t]; + if (w < \(threshold)f) continue; // Sparse V: skip negligible attention weights + + float norm_val = norms[kv_head * token_count + t]; + const device uint32_t* packed_ptr = packed + kv_head * token_count * PackedWidth + t * PackedWidth; + + uint bit_offset = d * Bits; + uint word_idx = bit_offset / 32; + uint shift = bit_offset % 32; + uint value = (packed_ptr[word_idx] >> shift); + + int spill = (int)shift + (int)Bits - 32; + if (spill > 0) { + value |= (packed_ptr[word_idx + 1] << ((uint)Bits - (uint)spill)); + } + value &= MASK; + + acc += w * norm_val * cb[value]; + } + + output[head_idx * Dim + d] = acc; + """ + } +} + +// MARK: - Kernel Dispatch Wrappers + +public enum TurboQuantKernelOps { + + // Kernel caches + nonisolated(unsafe) private static var encodeKernels: [String: MLXFast.MLXFastKernel] = [:] + nonisolated(unsafe) private static var scoreKernels: [String: MLXFast.MLXFastKernel] = [:] + nonisolated(unsafe) private static var valueKernels: [String: MLXFast.MLXFastKernel] = [:] + private static let lock = NSLock() + + /// Fused encode: norm + rotate + quantize + pack + norm correction in single GPU dispatch. + /// + /// - Parameters: + /// - input: Raw vectors [numRows, D] float32 + /// - rotation: Rotation matrix Π [D, D] float32 + /// - boundaries: Codebook boundaries [2^bits - 1] float32 + /// - codebook: Centroids [2^bits] float32 (needed for norm correction) + /// - bits: Quantization bit-width + /// - dim: Vector dimension + /// - Returns: (packed: [numRows, PackedWidth] uint32, norms: [numRows] float32) + /// norms are norm-corrected: original_norm / reconstruction_norm + public static func fusedEncode( + input: MLXArray, + rotation: MLXArray, + boundaries: MLXArray, + codebook: MLXArray, + bits: Int, + dim: Int + ) -> (packed: MLXArray, norms: MLXArray) { + // Framework dispatch — pre-compiled Metal kernel from metallib + let results = MLXFast.turboEncode( + input, rotation: rotation, boundaries: boundaries, codebook: codebook, + bits: bits, dim: dim) + return (packed: results[0], norms: results[1]) + } + + /// Fused WHT encode: norm + WHT rotation + quantize + pack (raw norms, no correction). + /// + /// Same as fusedEncode but uses O(d log d) Walsh-Hadamard butterfly instead of + /// O(d²) dense matmul. Only works for power-of-2 dimensions. + /// + /// WHT is orthogonal so norms are preserved — no norm correction needed. + /// Codebook is NOT passed to the kernel (saves one buffer bind + GPU transfer). + /// + /// - Parameters: + /// - input: Raw vectors [numRows, D] float32 + /// - whtSigns: Random ±1 signs [D] float32 + /// - boundaries: Codebook boundaries [2^bits - 1] float32 + /// - codebook: Centroids [2^bits] float32 (unused by kernel, kept in API for caller convenience) + /// - bits: Quantization bit-width + /// - dim: Vector dimension (must be power of 2) + /// - Returns: (packed: [numRows, PackedWidth] uint32, norms: [numRows] float32 — raw norms) + public static func fusedEncodeWHT( + input: MLXArray, + whtSigns: MLXArray, + boundaries: MLXArray, + codebook: MLXArray, + bits: Int, + dim: Int + ) -> (packed: MLXArray, norms: MLXArray) { + // Framework dispatch — pre-compiled Metal kernel from metallib + let results = MLXFast.turboEncodeWHT( + input, whtSigns: whtSigns, boundaries: boundaries, + bits: bits, dim: dim) + return (packed: results[0], norms: results[1]) + } + + // Flash attention kernel caches + nonisolated(unsafe) private static var flashPass1Kernels: [String: MLXFast.MLXFastKernel] = [:] + nonisolated(unsafe) private static var flashPass1NR0Kernels: [String: MLXFast.MLXFastKernel] = [:] + nonisolated(unsafe) private static var flashPass2Kernels: [String: MLXFast.MLXFastKernel] = [:] + + /// NR0: number of query rows processed per SIMD group in the multi-row amortized kernel. + /// + /// Ported from llama.cpp V2.1: each threadgroup loads K/V packed data once and reuses + /// it across NR0 queries. At NR0=2, the KV dequant cost is halved per query. + /// + /// NR0=2 is conservative — register pressure is ~24 extra floats per thread (for dim=128). + /// Apple M-series GPUs have 96 registers per thread (384 bytes), so this fits comfortably. + /// TODO: Benchmark NR0=4 and NR0=8 once NR0=2 is validated correct. + /// + /// Override via environment variable `TURBO_FLASH_NR0` (must be power of 2). + public static let flashNR0: Int = { + if let envValue = ProcessInfo.processInfo.environment["TURBO_FLASH_NR0"], + let parsed = Int(envValue), parsed > 0, (parsed & (parsed - 1)) == 0 { + return parsed + } + return 2 // default, conservative starting point + }() + + /// Default block size for TurboFlashAttention two-pass approach. + /// Each SIMD group processes this many tokens per block. + /// Tuned for M1 Max via sweep: B=64 wins or ties at all token counts (512-8192+). + /// Smaller blocks = more parallelism but more pass-2 merge work. + /// + /// Override via environment variable `TURBO_FLASH_BLOCK_SIZE` to tune for different + /// GPU configurations. M5 Max (more GPU cores, higher bandwidth) may benefit from + /// larger block sizes (e.g. 128) to reduce pass-2 merge overhead, while older chips + /// with fewer cores may prefer smaller blocks (e.g. 32) for better parallelism. + /// + /// Example: `TURBO_FLASH_BLOCK_SIZE=128 ./my_app` + public static let flashBlockSize: Int = { + if let envValue = ProcessInfo.processInfo.environment["TURBO_FLASH_BLOCK_SIZE"], + let parsed = Int(envValue), parsed > 0 { + return parsed + } + return 64 // default, tuned for M1 Max + }() + + /// Current sparse V skip threshold. Reads from `TurboQuantMetalKernels.sparseVThreshold`. + /// Attention weights below this value are skipped in the value aggregation kernel. + /// Configurable via `TURBO_SPARSE_V_THRESHOLD` environment variable. + public static var sparseVThreshold: Float { TurboQuantMetalKernels.sparseVThreshold } + + /// Shared pass 1 dispatch — framework kernels for non-causal and causal. + private static func dispatchFlashPass1( + source: String, cachePrefix: String, + rotatedQueries: MLXArray, + keyPacked: MLXArray, keyNorms: MLXArray, keyCodebook: MLXArray, + valPacked: MLXArray, valNorms: MLXArray, valCodebook: MLXArray, + tokenCount: Int, repeatCount: Int, + keyBits: Int, valueBits: Int, dim: Int, + blockSize: Int, + extraInputNames: [String] = [], + extraInputBuffers: [MLXArray] = [] + ) -> (oPartials: MLXArray, mPartials: MLXArray, lPartials: MLXArray) { + let numBlocks = (tokenCount + blockSize - 1) / blockSize + + let partials: [MLXArray] + if cachePrefix.contains("causal") { + // Causal variant — extraInputBuffers has [L_buf, qo_buf] + let L = extraInputBuffers.count > 0 ? extraInputBuffers[0].item(Int32.self) : Int32(1) + let qOffset = extraInputBuffers.count > 1 ? extraInputBuffers[1].item(Int32.self) : Int32(0) + partials = MLXFast.turboFlashPass1Causal( + rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + numBlocks: numBlocks, blockSize: blockSize, + L: Int(L), qOffset: Int(qOffset), + keyBits: keyBits, valueBits: valueBits, dim: dim) + } else { + // Non-causal variant + partials = MLXFast.turboFlashPass1( + rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + numBlocks: numBlocks, blockSize: blockSize, + keyBits: keyBits, valueBits: valueBits, dim: dim) + } + + return (oPartials: partials[0], mPartials: partials[1], lPartials: partials[2]) + } + + /// NR0 multi-row pass 1 dispatch — processes NR0 queries per SIMD group. + /// + /// Each SIMD group loads K/V packed data once and computes scores for NR0 queries. + /// The grid Y dimension is totalQueries/NR0 instead of totalQueries. + /// Output shapes are the same as NR0=1 (partials indexed by original q_idx). + /// + /// Precondition: totalQueries must be divisible by NR0. + private static func dispatchFlashPass1NR0( + rotatedQueries: MLXArray, + keyPacked: MLXArray, keyNorms: MLXArray, keyCodebook: MLXArray, + valPacked: MLXArray, valNorms: MLXArray, valCodebook: MLXArray, + tokenCount: Int, repeatCount: Int, + keyBits: Int, valueBits: Int, dim: Int, + blockSize: Int, nr0: Int + ) -> (oPartials: MLXArray, mPartials: MLXArray, lPartials: MLXArray) { + let numBlocks = (tokenCount + blockSize - 1) / blockSize + // Framework dispatch — pre-compiled Metal kernel from metallib + let partials = MLXFast.turboFlashPass1NR0( + rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + numBlocks: numBlocks, blockSize: blockSize, + keyBits: keyBits, valueBits: valueBits, dim: dim, nr0: nr0) + return (oPartials: partials[0], mPartials: partials[1], lPartials: partials[2]) + } + + /// NR0 multi-row causal pass 1 dispatch — processes NR0 queries with per-row causal masking. + /// + /// Same as dispatchFlashPass1NR0 but supports causal masking for L>1 prefill. + /// Each query in the NR0 group has its own causal boundary. + /// + /// Precondition: totalQueries must be divisible by NR0. + private static func dispatchFlashPass1NR0Causal( + rotatedQueries: MLXArray, + keyPacked: MLXArray, keyNorms: MLXArray, keyCodebook: MLXArray, + valPacked: MLXArray, valNorms: MLXArray, valCodebook: MLXArray, + tokenCount: Int, repeatCount: Int, + keyBits: Int, valueBits: Int, dim: Int, + blockSize: Int, nr0: Int, + queryChunkLength: Int, queryOffset: Int + ) -> (oPartials: MLXArray, mPartials: MLXArray, lPartials: MLXArray) { + let numBlocks = (tokenCount + blockSize - 1) / blockSize + // Framework dispatch — pre-compiled Metal kernel from metallib + let partials = MLXFast.turboFlashPass1NR0Causal( + rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + numBlocks: numBlocks, blockSize: blockSize, + L: queryChunkLength, qOffset: queryOffset, + keyBits: keyBits, valueBits: valueBits, dim: dim, nr0: nr0) + return (oPartials: partials[0], mPartials: partials[1], lPartials: partials[2]) + } + + /// Shared pass 2 dispatch — with optional fused output rotation. + /// + /// When `valRotation` is provided, the inverse value rotation (Π_val) is applied + /// in-kernel using threadgroup shared memory, eliminating a separate MLX matmul dispatch. + /// Output is in original (non-rotated) space. + /// + /// When `valRotation` is nil, output is in rotated V space (caller must apply inverse rotation). + private static func dispatchFlashPass2( + oPartials: MLXArray, mPartials: MLXArray, lPartials: MLXArray, + dim: Int, numBlocks: Int, totalQ: Int, + valRotation: MLXArray? = nil + ) -> MLXArray { + // Framework dispatch — pre-compiled Metal kernel from metallib + if let valRotation { + return MLXFast.turboFlashPass2Fused( + oPartials: oPartials, mPartials: mPartials, lPartials: lPartials, + valRotation: valRotation, + numBlocks: numBlocks, dim: dim) + } else { + return MLXFast.turboFlashPass2( + oPartials: oPartials, mPartials: mPartials, lPartials: lPartials, + numBlocks: numBlocks, dim: dim) + } + } + + /// TurboFlashAttention: two-pass fused Score + Online Softmax + Value. + /// + /// Pass 1: Parallelizes across (query × token_block) pairs. Each SIMD group processes + /// BlockSize tokens, producing partial online softmax state (m, l, o[D]). + /// Pass 2: Merges partial states across blocks to produce final normalized output. + /// + /// Eliminates intermediate score and attention weight arrays entirely. + /// + /// - Parameter valRotation: Optional [D, D] inverse value rotation matrix. When provided, + /// rotation is fused into pass 2, eliminating a separate MLX matmul dispatch. + /// Output is in original space. When nil, output is in rotated V space. + /// - Parameter blockSize: Tokens per block (default: flashBlockSize). Smaller = more parallelism + /// but more pass-2 merge work. Must be > 0. + /// - Returns: Output [totalQ, D] float32 + public static func turboFlashAttention( + rotatedQueries: MLXArray, + keyPacked: MLXArray, + keyNorms: MLXArray, + keyCodebook: MLXArray, + valPacked: MLXArray, + valNorms: MLXArray, + valCodebook: MLXArray, + tokenCount: Int, + repeatCount: Int, + keyBits: Int, + valueBits: Int, + dim: Int, + valRotation: MLXArray? = nil, + blockSize: Int? = nil + ) -> MLXArray { + let blockSize = blockSize ?? flashBlockSize + let numBlocks = (tokenCount + blockSize - 1) / blockSize + let totalQ = rotatedQueries.dim(0) + let nr0 = flashNR0 + + // Use NR0 multi-row kernel when totalQ is evenly divisible by NR0 and NR0 > 1. + // Falls back to NR0=1 (original kernel) for remainder queries or when NR0=1. + let useNR0 = nr0 > 1 && totalQ % nr0 == 0 && totalQ >= nr0 + + let oPartials: MLXArray + let mPartials: MLXArray + let lPartials: MLXArray + + if useNR0 { + (oPartials, mPartials, lPartials) = dispatchFlashPass1NR0( + rotatedQueries: rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + keyBits: keyBits, valueBits: valueBits, dim: dim, + blockSize: blockSize, nr0: nr0 + ) + } else { + (oPartials, mPartials, lPartials) = dispatchFlashPass1( + source: TurboQuantMetalKernels.turboFlashPass1Source, + cachePrefix: "flash_p1", + rotatedQueries: rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + keyBits: keyBits, valueBits: valueBits, dim: dim, + blockSize: blockSize + ) + } + + return dispatchFlashPass2( + oPartials: oPartials, mPartials: mPartials, lPartials: lPartials, + dim: dim, numBlocks: numBlocks, totalQ: totalQ, + valRotation: valRotation + ) + } + + /// TurboFlashAttention with causal masking for L>1 prefill chunks. + /// + /// Same as turboFlashAttention but each query position only attends to tokens + /// where t <= queryOffset + q_within_L. Eliminates the need to materialize + /// the full [nQHeads, L, T] score matrix for causal masking. + /// + /// - Parameter queryChunkLength: Number of query positions in the chunk (L) + /// - Parameter queryOffset: Absolute position of the first query in the chunk + /// - Returns: Output [totalQ, D] float32 + public static func turboFlashAttentionCausal( + rotatedQueries: MLXArray, + keyPacked: MLXArray, + keyNorms: MLXArray, + keyCodebook: MLXArray, + valPacked: MLXArray, + valNorms: MLXArray, + valCodebook: MLXArray, + tokenCount: Int, + repeatCount: Int, + keyBits: Int, + valueBits: Int, + dim: Int, + queryChunkLength: Int, + queryOffset: Int, + valRotation: MLXArray? = nil, + blockSize: Int? = nil + ) -> MLXArray { + let blockSize = blockSize ?? flashBlockSize + let numBlocks = (tokenCount + blockSize - 1) / blockSize + let totalQ = rotatedQueries.dim(0) + let nr0 = flashNR0 + + let useNR0 = nr0 > 1 && totalQ % nr0 == 0 && totalQ >= nr0 + + let oPartials: MLXArray + let mPartials: MLXArray + let lPartials: MLXArray + + if useNR0 { + (oPartials, mPartials, lPartials) = dispatchFlashPass1NR0Causal( + rotatedQueries: rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + keyBits: keyBits, valueBits: valueBits, dim: dim, + blockSize: blockSize, nr0: nr0, + queryChunkLength: queryChunkLength, queryOffset: queryOffset + ) + } else { + (oPartials, mPartials, lPartials) = dispatchFlashPass1( + source: TurboQuantMetalKernels.turboFlashPass1CausalSource, + cachePrefix: "flash_p1_causal", + rotatedQueries: rotatedQueries, + keyPacked: keyPacked, keyNorms: keyNorms, keyCodebook: keyCodebook, + valPacked: valPacked, valNorms: valNorms, valCodebook: valCodebook, + tokenCount: tokenCount, repeatCount: repeatCount, + keyBits: keyBits, valueBits: valueBits, dim: dim, + blockSize: blockSize, + extraInputNames: ["L_buf", "qo_buf"], + extraInputBuffers: [MLXArray([Int32(queryChunkLength)]), MLXArray([Int32(queryOffset)])] + ) + } + + return dispatchFlashPass2( + oPartials: oPartials, mPartials: mPartials, lPartials: lPartials, + dim: dim, numBlocks: numBlocks, totalQ: totalQ, + valRotation: valRotation + ) + } + + /// Compute Q×K attention scores from packed codebook indices. + /// + /// - Parameters: + /// - rotatedQueries: Pre-rotated queries [totalQ, D] (already scaled) + /// - packed: Packed key indices [totalKVHeads, T, PackedWidth] uint32 + /// - norms: Key norms [totalKVHeads, T] float32 + /// - codebook: Centroids [2^bits] float32 + /// - tokenCount: Number of cached tokens + /// - repeatCount: GQA repeat factor (nQHeads / nKVHeads) + /// - bits: MSE bit-width + /// - dim: Vector dimension + /// - Returns: Scores [totalQ, T] float32 + public static func mseScore( + rotatedQueries: MLXArray, + packed: MLXArray, + norms: MLXArray, + codebook: MLXArray, + tokenCount: Int, + repeatCount: Int, + bits: Int, + dim: Int + ) -> MLXArray { + // Framework dispatch — pre-compiled Metal kernel from metallib + return MLXFast.turboScore( + rotatedQueries, packed: packed, norms: norms, codebook: codebook, + tokenCount: tokenCount, repeatCount: repeatCount, + bits: bits, dim: dim) + } + + /// Compute weighted sum of values from packed codebook indices. + /// + /// Result is in ROTATED space — caller must apply inverse rotation. + /// + /// - Returns: [totalHeads, D] float32 (rotated space) + public static func mseWeightedSum( + weights: MLXArray, + packed: MLXArray, + norms: MLXArray, + codebook: MLXArray, + tokenCount: Int, + repeatCount: Int, + bits: Int, + dim: Int + ) -> MLXArray { + // Framework dispatch — pre-compiled Metal kernel from metallib + return MLXFast.turboValue( + weights, packed: packed, norms: norms, codebook: codebook, + tokenCount: tokenCount, repeatCount: repeatCount, + sparseThreshold: TurboQuantMetalKernels.sparseVThreshold, + bits: bits, dim: dim) + } +} diff --git a/Libraries/MLXLMCommon/WiredMemoryUtils.swift b/Libraries/MLXLMCommon/WiredMemoryUtils.swift index 70602cb16e..c19d2e8ca3 100644 --- a/Libraries/MLXLMCommon/WiredMemoryUtils.swift +++ b/Libraries/MLXLMCommon/WiredMemoryUtils.swift @@ -23,6 +23,18 @@ public struct WiredMemoryMeasurement: Sendable { public var totalBytes: Int { max(0, weightBytes) + max(0, kvBytes) + max(0, workspaceBytes) } + + public init( + weightBytes: Int, kvBytes: Int, workspaceBytes: Int, + peakActiveBytes: Int, tokenCount: Int, prefillStepSize: Int + ) { + self.weightBytes = weightBytes + self.kvBytes = kvBytes + self.workspaceBytes = workspaceBytes + self.peakActiveBytes = peakActiveBytes + self.tokenCount = tokenCount + self.prefillStepSize = prefillStepSize + } } /// Helpers for deriving wired memory budgets from real runtime measurements. @@ -245,4 +257,113 @@ public enum WiredMemoryUtils { resetPeakMemory: resetPeakMemory ) } + + /// Create an optimally-sized wired memory ticket from a measurement. + /// + /// Uses `WiredBudgetPolicy` with the measured weights + workspace as the base budget + /// and the KV cache size as the active ticket size. The total budget is clamped to + /// the GPU's recommended working set size. + /// + /// - Parameters: + /// - measurement: A measurement from `tune()`. + /// - headroom: Fractional headroom above measured total (default: 0.1 = 10%). + /// - Returns: A ticket sized for the measured workload. + public static func ticket( + from measurement: WiredMemoryMeasurement, + headroom: Double = 0.1 + ) -> WiredMemoryTicket { + let budget = Int(Double(measurement.totalBytes) * (1.0 + headroom)) + let cap = GPU.maxRecommendedWorkingSetBytes() ?? budget + let clampedBudget = min(budget, cap) + + return WiredMemoryTicket( + size: clampedBudget, + policy: WiredSumPolicy(cap: cap) + ) + } + + /// Estimate memory budget from model parameters without running a measurement pass. + /// + /// Computes: model_weights + kv_cache(maxTokens, kvConfig) + workspace. + /// The KV cache estimate uses the actual cache structure (respects KV quantization, + /// rotating cache limits, and hybrid architectures with mixed cache types). + /// + /// - Parameters: + /// - model: The loaded language model (for weight byte computation). + /// - maxTokens: Maximum context length to budget for (prefill + generation). + /// - parameters: Generation parameters (KV bits, scheme, maxKVSize, etc.). + /// - workspaceFraction: Fraction of weight bytes to add for workspace (default: 0.15). + /// - Returns: Estimated total bytes needed. + public static func estimateBudget( + model: any LanguageModel, + maxTokens: Int, + parameters: GenerateParameters, + workspaceFraction: Double = 0.15 + ) -> Int { + let weightBytes = model.parameters().flattened().reduce(0) { $0 + $1.1.nbytes } + + // KV cache estimate: create actual cache structure, estimate per-token storage + let cache = model.newCache(parameters: parameters) + + var kvBytesEstimate = 0 + for c in cache { + if c is KVCacheSimple { + // Conservative: 512 bytes per token per layer (covers most configs) + let effectiveTokens: Int + if let maxKV = parameters.maxKVSize { + effectiveTokens = min(maxTokens, maxKV) + } else { + effectiveTokens = maxTokens + } + kvBytesEstimate += effectiveTokens * 512 + } + // MambaCache: fixed-size state, negligible compared to KV cache + } + + // Adjust for KV compression schemes + if let scheme = parameters.kvScheme, scheme.hasPrefix("turbo") { + let compressionRatio: Double + if scheme.contains("4v2") { compressionRatio = 5.0 } + else if scheme.hasSuffix("4") { compressionRatio = 4.0 } + else if scheme.hasSuffix("3") { compressionRatio = 5.3 } + else if scheme.hasSuffix("2") { compressionRatio = 8.0 } + else { compressionRatio = 4.0 } + kvBytesEstimate = Int(Double(kvBytesEstimate) / compressionRatio) + } else if let bits = parameters.kvBits, bits > 0 { + kvBytesEstimate = kvBytesEstimate * bits / 16 + } + + let workspaceEstimate = Int(Double(weightBytes) * workspaceFraction) + + return weightBytes + kvBytesEstimate + workspaceEstimate + } + + /// Create a ticket from a static estimate (no measurement pass required). + /// + /// The ticket size is: estimateBudget() * (1 + headroom), clamped to GPU capacity. + /// + /// - Parameters: + /// - model: The loaded language model. + /// - maxTokens: Maximum context length to budget for. + /// - parameters: Generation parameters (KV config affects cache size). + /// - headroom: Fractional headroom above estimate (default: 0.1 = 10%). + /// - Returns: A ticket sized for the estimated workload. + public static func estimatedTicket( + model: any LanguageModel, + maxTokens: Int, + parameters: GenerateParameters, + headroom: Double = 0.1 + ) -> WiredMemoryTicket { + let budget = estimateBudget( + model: model, maxTokens: maxTokens, parameters: parameters) + let total = Int(Double(budget) * (1.0 + headroom)) + + let gpuCap = GPU.maxRecommendedWorkingSetBytes() ?? total + let clampedTotal = min(total, gpuCap) + + return WiredMemoryTicket( + size: clampedTotal, + policy: WiredSumPolicy(cap: gpuCap) + ) + } } diff --git a/Libraries/MLXVLM/MediaProcessing.swift b/Libraries/MLXVLM/MediaProcessing.swift index 0cd9a5b6db..4d69939a9e 100644 --- a/Libraries/MLXVLM/MediaProcessing.swift +++ b/Libraries/MLXVLM/MediaProcessing.swift @@ -341,7 +341,7 @@ public enum MediaProcessing { static public func asProcessedSequence( _ video: UserInput.Video, samplesPerSecond: Int, - frameProcessing: (VideoFrame) throws -> VideoFrame = { $0 }, + frameProcessing: (VideoFrame) throws -> VideoFrame = { $0 } ) async throws -> ProcessedFrames { return try await asProcessedSequence( video, diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift new file mode 100644 index 0000000000..26df86d2e6 --- /dev/null +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -0,0 +1,1533 @@ +import CoreImage +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// Port of Gemma 4 VLM: SigLIP vision encoder + Gemma 4 text decoder +// Based on the Gemma3 VLM wrapper pattern in this repo + +// MARK: - Text Configuration + +public struct Gemma4TextConfiguration: Codable, Sendable { + let modelType: String + let hiddenSize: Int + let hiddenLayers: Int + let intermediateSize: Int + let moeIntermediateSize: Int + let attentionHeads: Int + let headDim: Int + let globalHeadDim: Int + let rmsNormEps: Float + let vocabularySize: Int + let kvHeads: Int + let globalKvHeads: Int + let numExperts: Int + let topKExperts: Int + let slidingWindow: Int + let layerTypes: [String] + let enableMoeBlock: Bool + let attentionKEqV: Bool + let useDoubleWideMlp: Bool + let numKvSharedLayers: Int + let hiddenSizePerLayerInput: Int + let vocabSizePerLayerInput: Int + let finalLogitSoftcapping: Float? + let tieWordEmbeddings: Bool + let ropeTheta: Float + let globalRopeTheta: Float + let partialRotaryFactor: Float + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case hiddenSize = "hidden_size" + case hiddenLayers = "num_hidden_layers" + case intermediateSize = "intermediate_size" + case moeIntermediateSize = "moe_intermediate_size" + case attentionHeads = "num_attention_heads" + case headDim = "head_dim" + case globalHeadDim = "global_head_dim" + case rmsNormEps = "rms_norm_eps" + case vocabularySize = "vocab_size" + case kvHeads = "num_key_value_heads" + case globalKvHeads = "num_global_key_value_heads" + case numExperts = "num_experts" + case topKExperts = "top_k_experts" + case slidingWindow = "sliding_window" + case layerTypes = "layer_types" + case enableMoeBlock = "enable_moe_block" + case attentionKEqV = "attention_k_eq_v" + case useDoubleWideMlp = "use_double_wide_mlp" + case numKvSharedLayers = "num_kv_shared_layers" + case hiddenSizePerLayerInput = "hidden_size_per_layer_input" + case vocabSizePerLayerInput = "vocab_size_per_layer_input" + case finalLogitSoftcapping = "final_logit_softcapping" + case tieWordEmbeddings = "tie_word_embeddings" + case ropeTheta = "rope_theta" + case globalRopeTheta = "global_rope_theta" + case partialRotaryFactor = "partial_rotary_factor" + case ropeParameters = "rope_parameters" + } + + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + modelType = try container.decode(String.self, forKey: .modelType) + hiddenSize = try container.decodeIfPresent(Int.self, forKey: .hiddenSize) ?? 2816 + hiddenLayers = try container.decodeIfPresent(Int.self, forKey: .hiddenLayers) ?? 30 + intermediateSize = + try container.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? 2112 + moeIntermediateSize = + try container.decodeIfPresent(Int.self, forKey: .moeIntermediateSize) ?? 704 + attentionHeads = try container.decodeIfPresent(Int.self, forKey: .attentionHeads) ?? 16 + headDim = try container.decodeIfPresent(Int.self, forKey: .headDim) ?? 256 + globalHeadDim = try container.decodeIfPresent(Int.self, forKey: .globalHeadDim) ?? 512 + rmsNormEps = try container.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1e-6 + vocabularySize = + try container.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 262144 + kvHeads = try container.decodeIfPresent(Int.self, forKey: .kvHeads) ?? 8 + // globalKvHeads: null/missing in E2B/E4B -> fall back to kvHeads + let decodedGlobalKvHeads = try container.decodeIfPresent( + Int.self, forKey: .globalKvHeads) + slidingWindow = try container.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 1024 + layerTypes = try container.decode([String].self, forKey: .layerTypes) + enableMoeBlock = + try container.decodeIfPresent(Bool.self, forKey: .enableMoeBlock) ?? false + attentionKEqV = try container.decodeIfPresent(Bool.self, forKey: .attentionKEqV) ?? false + useDoubleWideMlp = + try container.decodeIfPresent(Bool.self, forKey: .useDoubleWideMlp) ?? false + numKvSharedLayers = + try container.decodeIfPresent(Int.self, forKey: .numKvSharedLayers) ?? 0 + hiddenSizePerLayerInput = + try container.decodeIfPresent(Int.self, forKey: .hiddenSizePerLayerInput) ?? 0 + vocabSizePerLayerInput = + try container.decodeIfPresent(Int.self, forKey: .vocabSizePerLayerInput) ?? 262144 + numExperts = try container.decodeIfPresent(Int.self, forKey: .numExperts) ?? 0 + topKExperts = try container.decodeIfPresent(Int.self, forKey: .topKExperts) ?? 0 + finalLogitSoftcapping = + try container.decodeIfPresent(Float.self, forKey: .finalLogitSoftcapping) + tieWordEmbeddings = + try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + + globalKvHeads = decodedGlobalKvHeads ?? kvHeads + + // RoPE: try nested rope_parameters first, then top-level fallbacks + if let ropeParams = try container.decodeIfPresent( + [String: [String: StringOrNumber]].self, forKey: .ropeParameters) + { + let slidingRope = ropeParams["sliding_attention"] ?? [:] + let fullRope = ropeParams["full_attention"] ?? [:] + ropeTheta = slidingRope["rope_theta"]?.asFloat() ?? 10_000.0 + globalRopeTheta = fullRope["rope_theta"]?.asFloat() ?? 1_000_000.0 + partialRotaryFactor = fullRope["partial_rotary_factor"]?.asFloat() ?? 0.25 + } else { + ropeTheta = try container.decodeIfPresent(Float.self, forKey: .ropeTheta) ?? 10_000.0 + globalRopeTheta = + try container.decodeIfPresent(Float.self, forKey: .globalRopeTheta) ?? 1_000_000.0 + partialRotaryFactor = + try container.decodeIfPresent(Float.self, forKey: .partialRotaryFactor) ?? 0.25 + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(modelType, forKey: .modelType) + try container.encode(hiddenSize, forKey: .hiddenSize) + try container.encode(hiddenLayers, forKey: .hiddenLayers) + try container.encode(intermediateSize, forKey: .intermediateSize) + try container.encode(moeIntermediateSize, forKey: .moeIntermediateSize) + try container.encode(attentionHeads, forKey: .attentionHeads) + try container.encode(headDim, forKey: .headDim) + try container.encode(globalHeadDim, forKey: .globalHeadDim) + try container.encode(rmsNormEps, forKey: .rmsNormEps) + try container.encode(vocabularySize, forKey: .vocabularySize) + try container.encode(kvHeads, forKey: .kvHeads) + try container.encode(globalKvHeads, forKey: .globalKvHeads) + try container.encode(numExperts, forKey: .numExperts) + try container.encode(topKExperts, forKey: .topKExperts) + try container.encode(slidingWindow, forKey: .slidingWindow) + try container.encode(layerTypes, forKey: .layerTypes) + try container.encode(enableMoeBlock, forKey: .enableMoeBlock) + try container.encode(attentionKEqV, forKey: .attentionKEqV) + try container.encode(useDoubleWideMlp, forKey: .useDoubleWideMlp) + try container.encode(numKvSharedLayers, forKey: .numKvSharedLayers) + try container.encode(hiddenSizePerLayerInput, forKey: .hiddenSizePerLayerInput) + try container.encode(vocabSizePerLayerInput, forKey: .vocabSizePerLayerInput) + try container.encodeIfPresent(finalLogitSoftcapping, forKey: .finalLogitSoftcapping) + try container.encode(tieWordEmbeddings, forKey: .tieWordEmbeddings) + try container.encode(ropeTheta, forKey: .ropeTheta) + try container.encode(globalRopeTheta, forKey: .globalRopeTheta) + try container.encode(partialRotaryFactor, forKey: .partialRotaryFactor) + } +} + +// MARK: - Vision Configuration + +public struct Gemma4VisionConfiguration: Codable, Sendable { + public let modelType: String + public let hiddenLayers: Int + public let hiddenSize: Int + public let intermediateSize: Int + public let attentionHeads: Int + public let patchSize: Int + public let imageSize: Int + + public let numChannels: Int = 3 + public let layerNormEps: Float = 1e-6 + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case hiddenLayers = "num_hidden_layers" + case hiddenSize = "hidden_size" + case intermediateSize = "intermediate_size" + case attentionHeads = "num_attention_heads" + case patchSize = "patch_size" + case imageSize = "image_size" + } +} + +// MARK: - Model Configuration + +public struct Gemma4Configuration: Codable, Sendable { + public let textConfiguration: Gemma4TextConfiguration + public let visionConfiguration: Gemma4VisionConfiguration + public let modelType: String + public let mmTokensPerImage: Int + public let quantization: BaseConfiguration.Quantization? + + private let _vocabularySize: Int? + private let _padTokenId: Int? + + public var vocabularySize: Int { + _vocabularySize ?? textConfiguration.vocabularySize + } + + public var hiddenSize: Int { + textConfiguration.hiddenSize + } + + public var padTokenId: Int { + _padTokenId ?? 0 + } + + enum CodingKeys: String, CodingKey { + case textConfiguration = "text_config" + case visionConfiguration = "vision_config" + case modelType = "model_type" + case mmTokensPerImage = "mm_tokens_per_image" + case quantization + + case _vocabularySize = "vocab_size" + case _padTokenId = "pad_token_id" + } +} + +// MARK: - Top-K helper + +private func gemma4TopK(_ a: MLXArray, k: Int, axis: Int = -1) -> ( + values: MLXArray, indices: MLXArray +) { + let partitionedIndices = argPartition(a, kth: -k, axis: axis) + let topKIndices = partitionedIndices[.ellipsis, (-k)...] + let topKValues = takeAlong(a, topKIndices, axis: axis) + return (topKValues, topKIndices) +} + +// MARK: - ProportionalRoPE + +/// Proportional RoPE for Gemma 4 global attention layers. +/// Rotates `rotatedDims` out of `dims` dimensions using the full `dims` as +/// the frequency denominator. Non-rotated dimensions get inf frequency (pass-through). +private class Gemma4ProportionalRoPE: Module, OffsetLayer { + let dims: Int + let traditional: Bool + let _freqs: MLXArray + + init(dims: Int, rotatedDims: Int, traditional: Bool = false, base: Float) { + precondition(rotatedDims <= dims, "rotatedDims must be <= dims") + self.dims = dims + self.traditional = traditional + + let exponents = MLXArray( + stride(from: Float(0), to: Float(rotatedDims), by: 2) + ) / Float(dims) + let realFreqs = pow(MLXArray(base), exponents) + + let paddingCount = (dims - rotatedDims) / 2 + let infPadding = MLXArray(Array(repeating: Float.infinity, count: paddingCount)) + self._freqs = concatenated([realFreqs, infPadding], axis: 0) + + super.init() + } + + func callAsFunction(_ x: MLXArray, offset: Int) -> MLXArray { + MLXFast.RoPE( + x, dimensions: dims, traditional: traditional, base: nil, + scale: 1.0, offset: offset, freqs: _freqs) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + callAsFunction(x, offset: 0) + } +} + +// MARK: - Text Attention + +private class Gemma4TextAttention: Module { + let isSliding: Bool + let attentionKEqV: Bool + let nHeads: Int + let nKVHeads: Int + let repeats: Int + let headDim: Int + let scale: Float + + @ModuleInfo(key: "q_proj") var qProj: Linear + @ModuleInfo(key: "k_proj") var kProj: Linear + @ModuleInfo(key: "v_proj") var vProj: Linear? + @ModuleInfo(key: "o_proj") var oProj: Linear + + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + @ModuleInfo(key: "k_norm") var kNorm: RMSNorm + + let rmsNormEps: Float + let rope: any OffsetLayer + + init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + self.isSliding = config.layerTypes[layerIdx] == "sliding_attention" + self.attentionKEqV = config.attentionKEqV && !isSliding + + self.nHeads = config.attentionHeads + + if isSliding { + self.headDim = config.headDim + self.nKVHeads = config.kvHeads + } else { + self.headDim = config.globalHeadDim + self.nKVHeads = config.globalKvHeads + } + + self.repeats = nHeads / nKVHeads + // Gemma4 uses scale=1.0, NOT 1/sqrt(head_dim) + self.scale = 1.0 + + let dim = config.hiddenSize + self._qProj.wrappedValue = Linear(dim, nHeads * headDim, bias: false) + self._kProj.wrappedValue = Linear(dim, nKVHeads * headDim, bias: false) + if !attentionKEqV { + self._vProj.wrappedValue = Linear(dim, nKVHeads * headDim, bias: false) + } + + self._oProj.wrappedValue = Linear(nHeads * headDim, dim, bias: false) + + self._qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: config.rmsNormEps) + self._kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: config.rmsNormEps) + self.rmsNormEps = config.rmsNormEps + + if isSliding { + self.rope = RoPE(dimensions: headDim, traditional: false, base: config.ropeTheta) + } else { + let ropeDim = Int(Float(headDim) * config.partialRotaryFactor) + self.rope = Gemma4ProportionalRoPE( + dims: headDim, rotatedDims: ropeDim, + traditional: false, base: config.globalRopeTheta) + } + + super.init() + } + + /// Forward pass with KV sharing support. + /// - Parameters: + /// - useSharedKV: When true, skip K/V projection and use donor's cached K/V. + /// - sharedKVArrays: The donor layer's cached (keys, values) from peek(). + /// - donorOffset: The donor layer's cache offset for correct RoPE positioning. + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? = nil, + useSharedKV: Bool = false, + sharedKVArrays: (MLXArray, MLXArray)? = nil, + donorOffset: Int? = nil + ) -> MLXArray { + let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) + + var queries = qProj(x).reshaped(B, L, nHeads, -1) + + if useSharedKV, let (cachedKeys, cachedValues) = sharedKVArrays { + let offset = donorOffset ?? cache?.offset ?? 0 + queries = qNorm(queries) + queries = queries.transposed(0, 2, 1, 3) + queries = rope(queries, offset: offset) + + let output = MLXFast.scaledDotProductAttention( + queries: queries, + keys: cachedKeys, + values: cachedValues, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return oProj(output) + } + + // Normal path: compute own K/V + var keys = kProj(x).reshaped(B, L, nKVHeads, -1) + var values: MLXArray + if attentionKEqV { + values = keys + } else { + values = vProj!(x).reshaped(B, L, nKVHeads, -1) + } + + // v_norm: RMSNorm with no learnable scale (mlxNone weight) + values = MLXFast.rmsNorm(values, weight: MLXArray.mlxNone, eps: rmsNormEps) + + queries = qNorm(queries) + keys = kNorm(keys) + + queries = queries.transposed(0, 2, 1, 3) + keys = keys.transposed(0, 2, 1, 3) + + let offset = cache?.offset ?? 0 + queries = rope(queries, offset: offset) + keys = rope(keys, offset: offset) + + values = values.transposed(0, 2, 1, 3) + + let output = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: cache, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return oProj(output) + } +} + +// MARK: - Text Shared MLP (GeGLU) + +private class Gemma4TextSharedMLP: Module { + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "up_proj") var upProj: Linear + @ModuleInfo(key: "down_proj") var downProj: Linear + + init(dimensions: Int, hiddenDimensions: Int, isDoubleWide: Bool = false) { + let effectiveHidden = isDoubleWide ? hiddenDimensions * 2 : hiddenDimensions + self._gateProj.wrappedValue = Linear(dimensions, effectiveHidden, bias: false) + self._upProj.wrappedValue = Linear(dimensions, effectiveHidden, bias: false) + self._downProj.wrappedValue = Linear(effectiveHidden, dimensions, bias: false) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + downProj(geluApproximate(gateProj(x)) * upProj(x)) + } +} + +// MARK: - Text Router + +private class Gemma4TextRouter: Module { + @ModuleInfo(key: "proj") var proj: Linear + @ParameterInfo(key: "scale") var scale: MLXArray + @ParameterInfo(key: "per_expert_scale") var perExpertScale: MLXArray + + let rootSize: Float + let eps: Float + + init(dimensions: Int, numExperts: Int, eps: Float) { + self.rootSize = pow(Float(dimensions), -0.5) + self.eps = eps + self._proj.wrappedValue = Linear(dimensions, numExperts, bias: false) + self._scale.wrappedValue = MLXArray.ones([dimensions]) + self._perExpertScale.wrappedValue = MLXArray.ones([numExperts]) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + let normWeight = scale * MLXArray(rootSize) + let normed = MLXFast.rmsNorm(x, weight: normWeight, eps: eps) + return proj(normed) + } +} + +// MARK: - Text Transformer Block + +private class Gemma4TextTransformerBlock: Module { + let enableMoeBlock: Bool + + @ModuleInfo(key: "self_attn") var selfAttention: Gemma4TextAttention + @ModuleInfo(key: "mlp") var sharedMLP: Gemma4TextSharedMLP + @ModuleInfo(key: "experts") var experts: SwitchGLU? + @ModuleInfo(key: "router") var router: Gemma4TextRouter? + let topKExperts: Int + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + @ModuleInfo(key: "pre_feedforward_layernorm") var preFeedforwardLayerNorm: RMSNorm + @ModuleInfo(key: "post_feedforward_layernorm") var postFeedforwardLayerNorm: RMSNorm + @ModuleInfo(key: "pre_feedforward_layernorm_2") var preFeedforwardLayerNorm2: RMSNorm? + @ModuleInfo(key: "post_feedforward_layernorm_1") var postFeedforwardLayerNorm1: RMSNorm? + @ModuleInfo(key: "post_feedforward_layernorm_2") var postFeedforwardLayerNorm2: RMSNorm? + + // Per-layer scalar (learnable output scaling) + @ParameterInfo(key: "layer_scalar") var layerScalar: MLXArray + + // Per-Layer Embeddings (PLE) + @ModuleInfo(key: "per_layer_input_gate") var perLayerInputGate: Linear? + @ModuleInfo(key: "per_layer_projection") var perLayerProjection: Linear? + @ModuleInfo(key: "post_per_layer_input_norm") var postPerLayerInputNorm: RMSNorm? + + init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + self.enableMoeBlock = config.enableMoeBlock + self.topKExperts = config.topKExperts + + self._selfAttention.wrappedValue = Gemma4TextAttention(config, layerIdx: layerIdx) + + // use_double_wide_mlp only applies to KV-shared layers + let firstKvSharedIdx = config.hiddenLayers - config.numKvSharedLayers + let isKvSharedLayer = config.numKvSharedLayers > 0 && layerIdx >= firstKvSharedIdx + let isDoubleWide = config.useDoubleWideMlp && isKvSharedLayer + + self._sharedMLP.wrappedValue = Gemma4TextSharedMLP( + dimensions: config.hiddenSize, hiddenDimensions: config.intermediateSize, + isDoubleWide: isDoubleWide) + + if config.enableMoeBlock { + self._experts.wrappedValue = SwitchGLU( + inputDims: config.hiddenSize, + hiddenDims: config.moeIntermediateSize, + numExperts: config.numExperts, + activation: geluApproximate, + bias: false + ) + self._router.wrappedValue = Gemma4TextRouter( + dimensions: config.hiddenSize, numExperts: config.numExperts, + eps: config.rmsNormEps) + self._preFeedforwardLayerNorm2.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm1.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm2.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + self._inputLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postAttentionLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._preFeedforwardLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + + self._layerScalar.wrappedValue = MLXArray([Float(1.0)]) + + // PLE components (only when enabled) + if config.hiddenSizePerLayerInput > 0 { + self._perLayerInputGate.wrappedValue = Linear( + config.hiddenSize, config.hiddenSizePerLayerInput, bias: false) + self._perLayerProjection.wrappedValue = Linear( + config.hiddenSizePerLayerInput, config.hiddenSize, bias: false) + self._postPerLayerInputNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? = nil, + perLayerInput: MLXArray? = nil, + useSharedKV: Bool = false, + sharedKVArrays: (MLXArray, MLXArray)? = nil, + donorOffset: Int? = nil + ) -> MLXArray { + let inputNorm = inputLayerNorm(x) + let attnOut = selfAttention( + inputNorm, mask: mask, cache: cache, + useSharedKV: useSharedKV, sharedKVArrays: sharedKVArrays, + donorOffset: donorOffset) + + var h = postAttentionLayerNorm(attnOut) + x + + // FFN: shared MLP + optional MoE + if let experts, let router, + let postNorm1 = postFeedforwardLayerNorm1, + let preNorm2 = preFeedforwardLayerNorm2, + let postNorm2 = postFeedforwardLayerNorm2 + { + let preFFNNorm = preFeedforwardLayerNorm(h) + var h1 = sharedMLP(preFFNNorm) + h1 = postNorm1(h1) + + let routerLogits = router(h) + let (topKLogits, topKIndices) = gemma4TopK(routerLogits, k: topKExperts, axis: -1) + let stopIndices = MLX.stopGradient(topKIndices) + var expertWeights = softmax(topKLogits, axis: -1, precise: true) + expertWeights = expertWeights * router.perExpertScale[topKIndices] + let preFFNNorm2 = preNorm2(h) + var h2 = experts(preFFNNorm2, stopIndices) + h2 = h2 * expandedDimensions(expertWeights, axis: -1) + h2 = h2.sum(axis: -2) + h2 = postNorm2(h2) + + let ffnOut = h1 + h2 + h = postFeedforwardLayerNorm(ffnOut) + h + } else { + let preFFNNorm = preFeedforwardLayerNorm(h) + let ffnOut = sharedMLP(preFFNNorm) + h = postFeedforwardLayerNorm(ffnOut) + h + } + + // Per-Layer Embeddings (PLE) + if let gate = perLayerInputGate, + let proj = perLayerProjection, + let norm = postPerLayerInputNorm, + let pli = perLayerInput + { + let residual = h + var g = geluApproximate(gate(h)) * pli + g = proj(g) + g = norm(g) + h = residual + g + } + + h = h * layerScalar + + return h + } +} + +// MARK: - Text Inner Model + +private class Gemma4TextModelInner: Module { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo var layers: [Gemma4TextTransformerBlock] + @ModuleInfo var norm: RMSNorm + + // Per-Layer Embeddings (PLE) + @ModuleInfo(key: "embed_tokens_per_layer") var embedTokensPerLayer: Embedding? + @ModuleInfo(key: "per_layer_model_projection") var perLayerModelProjection: Linear? + @ModuleInfo(key: "per_layer_projection_norm") var perLayerProjectionNorm: RMSNorm? + + // PLE scaling factors -- computed constants, NOT learned parameters + let embedTokensPerLayerScale: Float + let perLayerProjectionScale: Float + let perLayerInputScale: Float + + let config: Gemma4TextConfiguration + let hiddenSizePerLayerInput: Int + let layerTypes: [String] + let slidingAttentionIndex: Int + let fullAttentionIndex: Int + let previousKVs: [Int] + + init(_ config: Gemma4TextConfiguration) { + self.config = config + self.hiddenSizePerLayerInput = config.hiddenSizePerLayerInput + self.layerTypes = config.layerTypes + + self._embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) + + self._layers.wrappedValue = (0 ..< config.hiddenLayers).map { layerIdx in + Gemma4TextTransformerBlock(config, layerIdx: layerIdx) + } + + self.norm = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + + self.slidingAttentionIndex = layerTypes.firstIndex(of: "sliding_attention") ?? 0 + self.fullAttentionIndex = layerTypes.firstIndex(of: "full_attention") ?? 0 + + // KV sharing: build donor mapping + let N = config.hiddenLayers + let M = N - config.numKvSharedLayers + var mapping = Array(0 ..< N) + if config.numKvSharedLayers > 0 { + var kvsByType: [String: Int] = [:] + for i in 0 ..< M { + kvsByType[config.layerTypes[i]] = i + } + for j in M ..< N { + if let donor = kvsByType[config.layerTypes[j]] { + mapping[j] = donor + } + } + } + self.previousKVs = mapping + + // PLE scaling constants + self.embedTokensPerLayerScale = sqrt(Float(max(config.hiddenSizePerLayerInput, 1))) + self.perLayerProjectionScale = pow(Float(config.hiddenSize), -0.5) + self.perLayerInputScale = pow(2.0, -0.5) + + // Per-Layer Embeddings (PLE) + if config.hiddenSizePerLayerInput > 0 { + let plEmbedDim = config.hiddenLayers * config.hiddenSizePerLayerInput + self._embedTokensPerLayer.wrappedValue = Embedding( + embeddingCount: config.vocabSizePerLayerInput, dimensions: plEmbedDim) + self._perLayerModelProjection.wrappedValue = Linear( + config.hiddenSize, plEmbedDim, bias: false) + self._perLayerProjectionNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSizePerLayerInput, eps: config.rmsNormEps) + } + + super.init() + } + + func callAsFunction( + _ inputs: MLXArray? = nil, + inputEmbedding: MLXArray? = nil, + mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, + cache: [KVCache?]? = nil + ) -> MLXArray { + var h: MLXArray + if let inputEmbedding { + h = inputEmbedding + } else if let inputs { + h = embedTokens(inputs) + } else { + fatalError("Either inputs or inputEmbedding must be provided") + } + + // Gemma embedding scaling + let embedScale = sqrt(Float(config.hiddenSize)) + h = h * embedScale + + let cache: [KVCache?] = cache ?? [KVCache?](repeating: nil, count: layers.count) + + // Per-Layer Embeddings (PLE): compute per-layer inputs from token IDs + var perLayerInputs: MLXArray? = nil + if hiddenSizePerLayerInput > 0, let embedPL = embedTokensPerLayer, let inputs { + var pli = embedPL(inputs) + pli = pli * embedTokensPerLayerScale + pli = pli.reshaped( + pli.dim(0), pli.dim(1), config.hiddenLayers, hiddenSizePerLayerInput) + + if let proj = perLayerModelProjection { + var plProj = proj(h) + plProj = plProj * perLayerProjectionScale + plProj = plProj.reshaped( + plProj.dim(0), plProj.dim(1), config.hiddenLayers, hiddenSizePerLayerInput) + if let norm = perLayerProjectionNorm { + plProj = norm(plProj) + } + pli = (plProj + pli) * perLayerInputScale + } + perLayerInputs = pli + } + + // Pre-compute masks once per forward pass + let seqLen = h.dim(1) + var fullMask: MLXFast.ScaledDotProductAttentionMaskMode? + var slidingMask: MLXFast.ScaledDotProductAttentionMaskMode? + + // Track donor offsets and K/V for shared layers + var donorPreUpdateOffsets = [Int](repeating: 0, count: layers.count) + var donorKVs: [(MLXArray, MLXArray)?] = Array(repeating: nil, count: layers.count) + + for (i, layer) in layers.enumerated() { + let maskMode: MLXFast.ScaledDotProductAttentionMaskMode + if let mask { + maskMode = mask + } else if layerTypes[i] == "full_attention" { + if fullMask == nil { + fullMask = makeAttentionMask( + n: seqLen, + cache: cache[fullAttentionIndex], + windowSize: nil + ) + } + maskMode = fullMask! + } else { + if slidingMask == nil { + slidingMask = makeAttentionMask( + n: seqLen, + cache: cache[slidingAttentionIndex], + windowSize: config.slidingWindow + ) + } + maskMode = slidingMask! + } + + let pli: MLXArray? = perLayerInputs.map { $0[0..., 0..., i, 0...] } + + let donorIdx = previousKVs[i] + let isShared = donorIdx != i + + if isShared { + h = layer( + h, mask: maskMode, cache: nil, perLayerInput: pli, + useSharedKV: true, sharedKVArrays: donorKVs[donorIdx], + donorOffset: donorPreUpdateOffsets[donorIdx]) + } else { + donorPreUpdateOffsets[i] = cache[i]?.offset ?? 0 + h = layer(h, mask: maskMode, cache: cache[i], perLayerInput: pli) + + if let c = cache[i] { + donorKVs[i] = c.peek() + } + } + } + + return norm(h) + } +} + +// MARK: - Text Language Model + +private class Gemma4LanguageModel: Module, KVCacheDimensionProvider { + @ModuleInfo var model: Gemma4TextModelInner + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + let config: Gemma4TextConfiguration + var kvHeads: [Int] + + init(_ config: Gemma4TextConfiguration) { + self.config = config + self.model = Gemma4TextModelInner(config) + + self.kvHeads = config.layerTypes.map { layerType in + layerType == "full_attention" ? config.globalKvHeads : config.kvHeads + } + + if !config.tieWordEmbeddings { + self._lmHead.wrappedValue = Linear( + config.hiddenSize, config.vocabularySize, bias: false) + } + + super.init() + } + + func newCache(parameters: GenerateParameters?) -> [any KVCache] { + var caches = [KVCache]() + + for layerType in config.layerTypes { + if layerType == "full_attention" { + if let maxKVSize = parameters?.maxKVSize { + caches.append(RotatingKVCache(maxSize: maxKVSize, keep: 0)) + } else { + caches.append(KVCacheSimple()) + } + } else { + caches.append( + RotatingKVCache(maxSize: config.slidingWindow, keep: 0) + ) + } + } + + return caches + } + + func callAsFunction( + _ inputs: MLXArray? = nil, + cache: [KVCache]? = nil, + inputEmbedding: MLXArray? = nil, + mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil + ) -> LMOutput { + let optionalCache = cache?.map { $0 as KVCache? } + var out = model( + inputs, inputEmbedding: inputEmbedding, mask: mask, cache: optionalCache) + + if config.tieWordEmbeddings { + out = model.embedTokens.asLinear(out) + } else { + out = lmHead!(out) + } + + // Final logit softcapping + if let softcap = config.finalLogitSoftcapping, softcap > 0 { + let scale = MLXArray(softcap) + out = tanh(out / scale) * scale + } + + return LMOutput(logits: out) + } + + func sanitize( + weights: [String: MLXArray], quantizationConfig: BaseConfiguration.Quantization? = nil + ) -> [String: MLXArray] { + var processedWeights = weights + + // Handle weight tying + if config.tieWordEmbeddings { + processedWeights.keys + .filter { $0.hasPrefix("language_model.lm_head.") } + .forEach { processedWeights.removeValue(forKey: $0) } + } + + // Trim vocabulary tensors to expected size + let expectedVocab = config.vocabularySize + let keysToCheck = [ + "language_model.model.embed_tokens.weight", + "language_model.model.embed_tokens.scales", + "language_model.model.embed_tokens.biases", + "language_model.lm_head.weight", + "language_model.lm_head.scales", + "language_model.lm_head.biases", + ] + + for key in keysToCheck { + if let tensor = processedWeights[key], tensor.dim(0) > expectedVocab { + processedWeights[key] = tensor[0 ..< expectedVocab] + } + } + + // Remap expert weight names: experts.switch_glu.X -> experts.X + let expertKeys = processedWeights.keys.filter { $0.contains(".switch_glu.") } + for key in expertKeys { + let newKey = key.replacingOccurrences(of: ".switch_glu.", with: ".") + processedWeights[newKey] = processedWeights.removeValue(forKey: key) + } + + // Remove unused precomputed rotary freqs + return processedWeights.filter { key, _ in + !key.contains("self_attn.rotary_emb.inv_freq") + } + } +} + +// MARK: - Vision Model Components (SigLIP-based) + +private class Gemma4VisionAttention: Module { + @ModuleInfo(key: "q_proj") var queryProj: Linear + @ModuleInfo(key: "k_proj") var keyProj: Linear + @ModuleInfo(key: "v_proj") var valueProj: Linear + @ModuleInfo(key: "out_proj") var outputProj: Linear + + let numHeads: Int + let scale: Float + + init(dimensions: Int, numHeads: Int, bias: Bool = true) { + self.numHeads = numHeads + let headDim = dimensions / numHeads + self.scale = pow(Float(headDim), -0.5) + + self._queryProj.wrappedValue = Linear(dimensions, dimensions, bias: bias) + self._keyProj.wrappedValue = Linear(dimensions, dimensions, bias: bias) + self._valueProj.wrappedValue = Linear(dimensions, dimensions, bias: bias) + self._outputProj.wrappedValue = Linear(dimensions, dimensions, bias: bias) + } + + func callAsFunction(_ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode = .none) + -> MLXArray + { + var queries = queryProj(x) + var keys = keyProj(x) + var values = valueProj(x) + + let (B, L, _) = (queries.dim(0), queries.dim(1), queries.dim(2)) + let S = keys.dim(1) + + queries = queries.reshaped(B, L, numHeads, -1).transposed(0, 2, 1, 3) + keys = keys.reshaped(B, S, numHeads, -1).transposed(0, 2, 1, 3) + values = values.reshaped(B, S, numHeads, -1).transposed(0, 2, 1, 3) + + let output = MLXFast.scaledDotProductAttention( + queries: queries, + keys: keys, + values: values, + scale: scale, + mask: mask + ) + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return outputProj(output) + } +} + +private class Gemma4VisionMLP: Module, UnaryLayer { + @ModuleInfo(key: "fc1") var fc1: Linear + @ModuleInfo(key: "fc2") var fc2: Linear + @ModuleInfo var activationFn: GELU + + init(config: Gemma4VisionConfiguration) { + self.activationFn = GELU(approximation: .precise) + self._fc1.wrappedValue = Linear(config.hiddenSize, config.intermediateSize, bias: true) + self._fc2.wrappedValue = Linear(config.intermediateSize, config.hiddenSize, bias: true) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + var x = fc1(x) + x = activationFn(x) + return fc2(x) + } +} + +private class Gemma4VisionEncoderLayer: Module { + @ModuleInfo(key: "self_attn") var selfAttention: Gemma4VisionAttention + @ModuleInfo(key: "layer_norm1") var layerNorm1: LayerNorm + @ModuleInfo var mlp: Gemma4VisionMLP + @ModuleInfo(key: "layer_norm2") var layerNorm2: LayerNorm + + let embedDim: Int + + init(config: Gemma4VisionConfiguration) { + self.embedDim = config.hiddenSize + + self._selfAttention.wrappedValue = Gemma4VisionAttention( + dimensions: config.hiddenSize, + numHeads: config.attentionHeads, + bias: true + ) + + self._layerNorm1.wrappedValue = LayerNorm(dimensions: embedDim, eps: config.layerNormEps) + self.mlp = Gemma4VisionMLP(config: config) + self._layerNorm2.wrappedValue = LayerNorm(dimensions: embedDim, eps: config.layerNormEps) + } + + func callAsFunction(_ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode = .none) + -> MLXArray + { + let r = selfAttention(layerNorm1(x), mask: mask) + let h = x + r + let r2 = mlp(layerNorm2(h)) + return h + r2 + } +} + +private class Gemma4VisionEncoder: Module { + @ModuleInfo var layers: [Gemma4VisionEncoderLayer] + + init(config: Gemma4VisionConfiguration) { + self._layers.wrappedValue = (0 ..< config.hiddenLayers).map { _ in + Gemma4VisionEncoderLayer(config: config) + } + } + + func callAsFunction( + _ x: MLXArray, + outputHiddenStates: Bool = false, + mask: MLXFast.ScaledDotProductAttentionMaskMode = .none + ) -> (MLXArray, [MLXArray]?) { + var encoderStates: [MLXArray]? = outputHiddenStates ? [x] : nil + var h = x + + for layer in layers { + h = layer(h, mask: mask) + if outputHiddenStates { + encoderStates?.append(h) + } + } + + return (h, encoderStates) + } +} + +private class Gemma4VisionEmbeddings: Module, UnaryLayer { + @ModuleInfo(key: "patch_embedding") var patchEmbedding: Conv2d + @ModuleInfo(key: "position_embedding") var positionEmbedding: Embedding + + let config: Gemma4VisionConfiguration + let embedDim: Int + let imageSize: Int + let patchSize: Int + let numPatches: Int + let numPositions: Int + + init(config: Gemma4VisionConfiguration) { + self.config = config + self.embedDim = config.hiddenSize + self.imageSize = config.imageSize + self.patchSize = config.patchSize + + self._patchEmbedding.wrappedValue = Conv2d( + inputChannels: config.numChannels, + outputChannels: embedDim, + kernelSize: IntOrPair(patchSize), + stride: IntOrPair(patchSize) + ) + + self.numPatches = (imageSize / patchSize) * (imageSize / patchSize) + self.numPositions = numPatches + + self._positionEmbedding.wrappedValue = Embedding( + embeddingCount: numPositions, + dimensions: embedDim + ) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + var patchEmbeddings = patchEmbedding(x) + patchEmbeddings = flattened(patchEmbeddings, start: 1, end: 2) + + let actualNumPatches = patchEmbeddings.dim(1) + let useNumPositions = min(actualNumPatches, numPositions) + + let positionIds = MLXArray(Array(0 ..< useNumPositions))[.newAxis, 0...] + var embeddings = patchEmbeddings + + if useNumPositions == actualNumPatches { + embeddings = embeddings + positionEmbedding(positionIds) + } else { + let positionedPatches = + embeddings[0..., .. (MLXArray, MLXArray, [MLXArray]?) { + let x = embeddings(x) + let (encoderOutput, encoderStates) = encoder( + x, outputHiddenStates: outputHiddenStates, mask: .none) + let poolerOutput = postLayerNorm(encoderOutput) + return (poolerOutput, x, encoderStates) + } +} + +private class Gemma4VisionModel: Module { + @ModuleInfo(key: "vision_model") var visionModel: Gemma4SigLipVisionModel + + let modelType: String + + init(config: Gemma4VisionConfiguration) { + self.modelType = config.modelType + self._visionModel.wrappedValue = Gemma4SigLipVisionModel(config: config) + } + + func callAsFunction( + _ x: MLXArray, + outputHiddenStates: Bool = false + ) -> (MLXArray, MLXArray, [MLXArray]?) { + visionModel(x, outputHiddenStates: outputHiddenStates) + } + + private func checkArrayShape(_ arr: MLXArray) -> Bool { + let shape = arr.shape + guard shape.count == 4 else { return false } + let (outChannels, kH, kW, _) = (shape[0], shape[1], shape[2], shape[3]) + return (outChannels >= kH) && (outChannels >= kW) && (kH == kW) + } + + func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var sanitizedWeights = [String: MLXArray]() + + for (k, v) in weights { + if k.contains("patch_embedding.weight") { + // PyTorch conv2d: [out_channels, in_channels, kH, kW] + // MLX conv2d: [out_channels, kH, kW, in_channels] + if checkArrayShape(v) { + sanitizedWeights[k] = v + } else { + sanitizedWeights[k] = v.transposed(0, 2, 3, 1) + } + } else { + sanitizedWeights[k] = v + } + } + + return sanitizedWeights + } +} + +// MARK: - Multimodal Projector + +class Gemma4MultiModalProjector: Module, UnaryLayer { + @ModuleInfo(key: "mm_input_projection_weight") var mmInputProjectionWeight: MLXArray + @ModuleInfo(key: "mm_soft_emb_norm") var mmSoftEmbNorm: RMSNorm + @ModuleInfo var avgPool: AvgPool2d + + let config: Gemma4Configuration + let patchesPerImage: Int + let tokensPerSide: Int + let kernelSize: Int + + init(config: Gemma4Configuration) { + self.config = config + + self._mmInputProjectionWeight.wrappedValue = ones([ + config.visionConfiguration.hiddenSize, + config.textConfiguration.hiddenSize, + ]) + + self._mmSoftEmbNorm.wrappedValue = RMSNorm( + dimensions: config.visionConfiguration.hiddenSize, + eps: config.visionConfiguration.layerNormEps + ) + + self.patchesPerImage = + config.visionConfiguration.imageSize / config.visionConfiguration.patchSize + + self.tokensPerSide = Int(sqrt(Double(config.mmTokensPerImage))) + self.kernelSize = patchesPerImage / tokensPerSide + + self.avgPool = AvgPool2d( + kernelSize: IntOrPair(kernelSize), + stride: IntOrPair(kernelSize) + ) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + let (b, _, l) = (x.dim(0), x.dim(1), x.dim(2)) + + var reshapedVisionOutputs = x.transposed(0, 2, 1) + reshapedVisionOutputs = reshapedVisionOutputs.reshaped( + b, l, patchesPerImage, patchesPerImage + ) + + reshapedVisionOutputs = reshapedVisionOutputs.transposed(0, 2, 3, 1) + var pooledVisionOutputs = avgPool(reshapedVisionOutputs) + pooledVisionOutputs = pooledVisionOutputs.transposed(0, 3, 1, 2).flattened(start: 2) + pooledVisionOutputs = pooledVisionOutputs.transposed(0, 2, 1) + + let normedVisionOutputs = mmSoftEmbNorm(pooledVisionOutputs) + + let projectedVisionOutputs = einsum( + "btm,md->btd", + normedVisionOutputs, + mmInputProjectionWeight + ) + + return projectedVisionOutputs.asType(x.dtype) + } +} + +/// Inserts image features into text embeddings at specified token positions +private func gemma4MaskedScatter( + finalEmbedding: MLXArray, + imageMaskExpanded: MLXArray, + scaledImageFeatures: MLXArray +) -> MLXArray { + let finalEmbeddingShape = finalEmbedding.shape + let scaledImageFeaturesFlattened = scaledImageFeatures.flattened() + let finalEmbeddingFlattened = finalEmbedding.flattened() + let imageMaskExpandedFlattened = imageMaskExpanded.flattened() + + let maskValues = imageMaskExpandedFlattened.asArray(Bool.self) + let imagePositionIndices = maskValues.enumerated().compactMap { index, value in + value ? UInt32(index) : nil + } + + guard !imagePositionIndices.isEmpty else { + return finalEmbedding + } + + let imagePositions = MLXArray(imagePositionIndices) + guard scaledImageFeaturesFlattened.shape[0] == imagePositions.shape[0] else { + fatalError( + """ + gemma4MaskedScatter: Size mismatch between image features and positions. + Image features: \(scaledImageFeaturesFlattened.shape[0]) + Image positions: \(imagePositions.shape[0]) + """) + } + finalEmbeddingFlattened[imagePositions] = scaledImageFeaturesFlattened + return finalEmbeddingFlattened.reshaped(finalEmbeddingShape) +} + +// MARK: - Gemma4 VLM Model + +public class Gemma4: Module, VLMModel, KVCacheDimensionProvider { + @ModuleInfo(key: "vision_tower") private var visionTower: Gemma4VisionModel + @ModuleInfo(key: "language_model") private var languageModel: Gemma4LanguageModel + @ModuleInfo(key: "multi_modal_projector") var multiModalProjector: Gemma4MultiModalProjector + + public let config: Gemma4Configuration + + public var vocabularySize: Int { config.vocabularySize } + public var kvHeads: [Int] { languageModel.kvHeads } + + public func newCache(parameters: GenerateParameters?) -> [any KVCache] { + return languageModel.newCache(parameters: parameters) + } + + public init(_ config: Gemma4Configuration) { + self.config = config + + self._visionTower.wrappedValue = Gemma4VisionModel(config: config.visionConfiguration) + self._languageModel.wrappedValue = Gemma4LanguageModel(config.textConfiguration) + self._multiModalProjector.wrappedValue = Gemma4MultiModalProjector(config: config) + } + + private func getInputEmbeddings( + inputIds: MLXArray? = nil, + pixelValues: MLXArray? = nil, + mask: MLXArray? = nil + ) -> (MLXArray, MLXArray?) { + guard let pixelValues else { + return (languageModel.model.embedTokens(inputIds!), nil) + } + + let inputsEmbeds = languageModel.model.embedTokens(inputIds!) + + // Process image through vision tower + let processedPixels = pixelValues.transposed(0, 2, 3, 1).asType(inputsEmbeds.dtype) + + let (hiddenState, _, _) = visionTower( + processedPixels, + outputHiddenStates: true + ) + + let imageFeatures = multiModalProjector(hiddenState) + + let (finalEmbedding, finalAttentionMask4d) = prepareInputsForMultimodal( + imageFeatures: imageFeatures, + inputsEmbeds: inputsEmbeds, + inputIds: inputIds!, + attentionMask: mask + ) + + return (finalEmbedding, finalAttentionMask4d) + } + + private func prepareInputsForMultimodal( + imageFeatures: MLXArray, + inputsEmbeds: MLXArray, + inputIds: MLXArray, + attentionMask: MLXArray? + ) -> (MLXArray, MLXArray?) { + let embedDim = inputsEmbeds.dim(2) + + // Scale image features to match text embedding magnitude + let scaledImageFeatures = + imageFeatures / sqrt(Float(config.textConfiguration.hiddenSize)) + + var finalEmbedding = inputsEmbeds + + let padTokenId = config.padTokenId + let imageTokenId = 262144 // Image token used after expansion + + // Create masks for different token types + let imageMask = MLX.equal(inputIds, MLXArray(imageTokenId)) + let padMask = MLX.equal(inputIds, MLXArray(padTokenId)) + + // Expand masks to match embedding dimension + var imageMaskExpanded = expandedDimensions(imageMask, axis: -1) + imageMaskExpanded = repeated(imageMaskExpanded, count: embedDim, axis: -1) + + var padMaskExpanded = expandedDimensions(padMask, axis: -1) + padMaskExpanded = repeated(padMaskExpanded, count: embedDim, axis: -1) + finalEmbedding = MLX.where( + padMaskExpanded, MLXArray.zeros(like: finalEmbedding), finalEmbedding) + + // Insert image token embeddings using masked scatter + finalEmbedding = gemma4MaskedScatter( + finalEmbedding: finalEmbedding, + imageMaskExpanded: imageMaskExpanded, + scaledImageFeatures: scaledImageFeatures + ) + + var finalAttentionMask4d: MLXArray? = nil + if let attentionMask = attentionMask { + let attentionMaskExpanded1 = expandedDimensions(attentionMask, axis: 1) + let attentionMaskExpanded2 = expandedDimensions(attentionMask, axis: 2) + finalAttentionMask4d = attentionMaskExpanded1 * attentionMaskExpanded2 + finalAttentionMask4d = expandedDimensions(finalAttentionMask4d!, axis: 1) + } + + return (finalEmbedding.asType(inputsEmbeds.dtype), finalAttentionMask4d) + } + + public func prepare(_ input: LMInput, cache: [any KVCache], windowSize: Int?) throws + -> PrepareResult + { + guard let imagePixels = input.image?.pixels else { + // Text-only input + let convertedCache = cache.compactMap { $0 as KVCache } + let result = languageModel( + input.text.tokens, cache: convertedCache, inputEmbedding: nil, mask: nil) + return .logits(result) + } + + let (inputEmbeddings, _) = getInputEmbeddings( + inputIds: input.text.tokens, + pixelValues: imagePixels, + mask: input.text.mask + ) + + let convertedCache = cache.compactMap { $0 as KVCache } + let maskMode: MLXFast.ScaledDotProductAttentionMaskMode = .causal + + let result = languageModel( + nil, + cache: convertedCache, + inputEmbedding: inputEmbeddings, + mask: maskMode + ) + + return .logits(result) + } + + public func callAsFunction(_ inputs: MLXArray, cache: [any KVCache]?) -> MLXArray { + return languageModel(inputs, cache: cache).logits + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var processedWeights = languageModel.sanitize( + weights: weights, quantizationConfig: config.quantization) + processedWeights = visionTower.sanitize(weights: processedWeights) + return processedWeights + } +} + +// MARK: - Processor + +public struct Gemma4Processor: UserInputProcessor { + private let config: Gemma4ProcessorConfiguration + private let tokenizer: any Tokenizer + + public init(_ config: Gemma4ProcessorConfiguration, tokenizer: any Tokenizer) { + self.config = config + self.tokenizer = tokenizer + } + + public func preprocess(images: [CIImage], processing: UserInput.Processing?) throws -> ( + MLXArray, THW + ) { + var userProcessing = processing ?? UserInput.Processing() + let targetSize = CGSize(width: config.imageSize, height: config.imageSize) + + userProcessing.resize = targetSize + + let processedImages = images.map { image in + let processedImage = MediaProcessing.apply(image, processing: userProcessing) + let srgbImage = MediaProcessing.inSRGBToneCurveSpace(processedImage) + let resizedImage = MediaProcessing.resampleBicubic(srgbImage, to: targetSize) + let normalizedImage = MediaProcessing.normalize( + resizedImage, mean: config.imageMeanTuple, std: config.imageStdTuple) + return MediaProcessing.asMLXArray(normalizedImage) + } + + let pixelValues = concatenated(processedImages) + + return (pixelValues, THW(images.count, config.imageSize, config.imageSize)) + } + + public func prepare(input: UserInput) async throws -> LMInput { + let messages = Qwen2VLMessageGenerator().generate(from: input) + + var promptTokens = try tokenizer.applyChatTemplate( + messages: messages, tools: input.tools, + additionalContext: input.additionalContext) + + var processedImage: LMInput.ProcessedImage? + + if !input.images.isEmpty { + let imagePixelsAndFrames = try input.images.map { + try preprocess(images: [$0.asCIImage()], processing: input.processing) + } + let imagePixelsConcatenated = concatenated(imagePixelsAndFrames.map { $0.0 }) + processedImage = LMInput.ProcessedImage( + pixels: imagePixelsConcatenated, + frames: imagePixelsAndFrames.map { $0.1 } + ) + + // Expand single token to multiple image tokens + let startOfImageTokenId = 255999 + let imageTokenId = 262144 + let numImageTokens = config.imageSeqLength + + var expandedTokens: [Int] = [] + + for token in promptTokens { + if token == startOfImageTokenId { + expandedTokens.append( + contentsOf: Array(repeating: imageTokenId, count: numImageTokens)) + } else { + expandedTokens.append(token) + } + } + + promptTokens = expandedTokens + } + + let promptArray = MLXArray(promptTokens).expandedDimensions(axis: 0) + let mask = ones(like: promptArray).asType(.int8) + return LMInput( + text: .init(tokens: promptArray, mask: mask), + image: processedImage + ) + } +} + +public struct Gemma4ProcessorConfiguration: Codable, Sendable { + public let processorClass: String + public let imageProcessorType: String + public let doNormalize: Bool + public let doRescale: Bool + public let doResize: Bool + public let imageMean: [CGFloat] + public let imageStd: [CGFloat] + public let imageSeqLength: Int + public let resample: Int + public let rescaleFactor: Float + public let size: ImageSize + + public let doConvertRgb: Bool? + public let doPanAndScan: Bool? + public let panAndScanMaxNumCrops: Int? + public let panAndScanMinCropSize: Int? + public let panAndScanMinRatioToActivate: Float? + + public let imageTokenId: Int = 262144 + + public struct ImageSize: Codable, Sendable { + public let height: Int + public let width: Int + } + + public var imageSize: Int { size.height } + + public var imageMeanTuple: (CGFloat, CGFloat, CGFloat) { + (imageMean[0], imageMean[1], imageMean[2]) + } + + public var imageStdTuple: (CGFloat, CGFloat, CGFloat) { + (imageStd[0], imageStd[1], imageStd[2]) + } + + enum CodingKeys: String, CodingKey { + case processorClass = "processor_class" + case imageProcessorType = "image_processor_type" + case doNormalize = "do_normalize" + case doRescale = "do_rescale" + case doResize = "do_resize" + case doConvertRgb = "do_convert_rgb" + case doPanAndScan = "do_pan_and_scan" + case imageMean = "image_mean" + case imageStd = "image_std" + case imageSeqLength = "image_seq_length" + case resample + case rescaleFactor = "rescale_factor" + case size + case panAndScanMaxNumCrops = "pan_and_scan_max_num_crops" + case panAndScanMinCropSize = "pan_and_scan_min_crop_size" + case panAndScanMinRatioToActivate = "pan_and_scan_min_ratio_to_activate" + } +} + +// MARK: - LoRA + +extension Gemma4: LoRAModel { + public var loraLayers: [Module] { + languageModel.model.layers + } +} diff --git a/Libraries/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index ffba9444a6..fd72099a27 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -88,6 +88,7 @@ public enum VLMTypeRegistry { "qwen3_5_moe": create(Qwen35Configuration.self, Qwen35MoE.init), "idefics3": create(Idefics3Configuration.self, Idefics3.init), "gemma3": create(Gemma3Configuration.self, Gemma3.init), + "gemma4": create(Gemma4Configuration.self, Gemma4.init), "smolvlm": create(SmolVLM2Configuration.self, SmolVLM2.init), // TODO: see if we can make it work with fastvlm rather than llava_qwen2 "fastvlm": create(FastVLMConfiguration.self, FastVLM.init), @@ -116,6 +117,8 @@ public enum VLMProcessorTypeRegistry { Idefics3ProcessorConfiguration.self, Idefics3Processor.init), "Gemma3Processor": create( Gemma3ProcessorConfiguration.self, Gemma3Processor.init), + "Gemma4Processor": create( + Gemma4ProcessorConfiguration.self, Gemma4Processor.init), "SmolVLMProcessor": create( SmolVLMProcessorConfiguration.self, SmolVLMProcessor.init), "FastVLMProcessor": create( diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..e5e6781e1a --- /dev/null +++ b/Makefile @@ -0,0 +1,268 @@ +# Makefile — Smart build orchestrator for mlx-swift-lm +# +# Swift Package Manager doesn't track Metal shaders, native dylibs, or changes +# deep in git submodules (mlx, mlx-c). This Makefile fills the gaps using +# file-timestamp dependencies so only stale targets rebuild. +# +# Quick reference: +# make — full incremental build for tests/benchmarks +# make metal — recompile Metal shaders only +# make bridge — recompile prefill bridge dylib only +# make spm — Swift build only (with Cmlx cache invalidation) +# make status — show what's built and what's stale +# make clean — remove build artifacts (keep checkouts) +# make clean-all — full reset (re-fetches dependencies) +# make clean-cmlx — force SPM to recompile C/C++ on next build + +SHELL := /bin/bash +.DEFAULT_GOAL := build-tests + +# ─── Configuration ──────────────────────────────────────────────────────────── + +PROJECT_ROOT := $(CURDIR) +BUILD_DIR := $(PROJECT_ROOT)/.build +STAMP_DIR := $(BUILD_DIR)/.stamps +RELEASE_DIR := $(BUILD_DIR)/arm64-apple-macosx/release +XCTEST_DIR := $(RELEASE_DIR)/mlx-swift-lmPackageTests.xctest/Contents/MacOS + +CONFIG ?= release +SWIFT_FLAGS ?= -Xswiftc -enable-testing + +# ─── Locate mlx-swift (local override > sibling > SPM checkout) ─────────────── + +MLX_SWIFT_DIR := $(or \ + $(wildcard $(MLX_SWIFT_PATH)), \ + $(wildcard $(PROJECT_ROOT)/../mlx-swift), \ + $(BUILD_DIR)/checkouts/mlx-swift) + +METAL_SRC_DIR := $(MLX_SWIFT_DIR)/Source/Cmlx/mlx-generated/metal +CMLX_SRC_DIR := $(MLX_SWIFT_DIR)/Source/Cmlx + +# ─── Source file discovery (evaluated each invocation) ──────────────────────── +# Make re-expands $(shell ...) every time you run `make`, so new/deleted files +# are picked up automatically. + +METAL_SOURCES := $(shell find "$(METAL_SRC_DIR)" \( -name '*.metal' -o -name '*.h' \) -type f 2>/dev/null) +CMLX_SOURCES := $(shell find "$(CMLX_SRC_DIR)/mlx" "$(CMLX_SRC_DIR)/mlx-c" \ + \( -name '*.cpp' -o -name '*.c' -o -name '*.h' \) -type f 2>/dev/null) +SWIFT_SOURCES := $(shell find "$(PROJECT_ROOT)/Libraries" "$(PROJECT_ROOT)/Sources" \ + -name '*.swift' -type f 2>/dev/null) + +# NativePrefillBridge C++ — SPM compiles these; list them so `make` reruns swift build when they change. +NATIVE_PREFILL_SOURCES := $(shell find "$(PROJECT_ROOT)/Sources/NativePrefillBridge" \ + \( -name '*.cpp' -o -name '*.h' \) -type f 2>/dev/null) + +# Bridge sources — alpha has split gemma + qwen bridges that share generic_prefill. +BRIDGE_SRC_DIR := $(PROJECT_ROOT)/Sources/NativePrefillBridge +BRIDGE_SRCS := $(BRIDGE_SRC_DIR)/prefill_bridge_gemma.cpp \ + $(BRIDGE_SRC_DIR)/prefill_bridge_qwen.cpp \ + $(BRIDGE_SRC_DIR)/generic_prefill.cpp +BRIDGE_HDRS := $(BRIDGE_SRC_DIR)/prefill_bridge_gemma.h \ + $(BRIDGE_SRC_DIR)/prefill_bridge_qwen.h \ + $(BRIDGE_SRC_DIR)/generic_prefill.h +BRIDGE_DYLIBS := $(BRIDGE_SRC_DIR)/libprefill_bridge_gemma.dylib \ + $(BRIDGE_SRC_DIR)/libprefill_bridge_qwen.dylib + +# Output artifacts +METALLIB := $(RELEASE_DIR)/mlx.metallib +BRIDGE_RELEASES := $(RELEASE_DIR)/libprefill_bridge_gemma.dylib \ + $(RELEASE_DIR)/libprefill_bridge_qwen.dylib + +# Stamp files — touch-files that record when each step last succeeded +STAMP_METAL := $(STAMP_DIR)/metallib +STAMP_SPM := $(STAMP_DIR)/spm-build +STAMP_BRIDGE := $(STAMP_DIR)/prefill-bridge +STAMP_CMLX := $(STAMP_DIR)/cmlx-check + +# ─── Directory creation ────────────────────────────────────────────────────── + +$(STAMP_DIR): + @mkdir -p $@ + +# ─── Metal shader compilation ──────────────────────────────────────────────── +# SPM cannot compile .metal files. We compile them into mlx.metallib ourselves. +# Only recompiles when a .metal or kernel .h file changes. + +.PHONY: metal +metal: $(STAMP_METAL) + +$(STAMP_METAL): $(METAL_SOURCES) | $(STAMP_DIR) + @echo "==> Metal sources changed — recompiling shaders..." + @bash "$(PROJECT_ROOT)/scripts/build-metallib.sh" $(CONFIG) + @touch $@ + +# ─── Cmlx cache invalidation ──────────────────────────────────────────────── +# When C/C++ files inside the mlx or mlx-c submodules change, SPM's build.db +# may still consider Cmlx "up to date" (it caches content signatures keyed by +# the dependency revision in workspace-state.json). +# +# Fix: delete just .build/.../Cmlx.build/ — this forces SPM to recompile the +# C target on the next `swift build` while leaving all Swift targets cached. + +$(STAMP_CMLX): $(CMLX_SOURCES) | $(STAMP_DIR) + @if [ -f "$@" ] && [ -d "$(RELEASE_DIR)/Cmlx.build" ]; then \ + echo "==> Cmlx sources changed since last build — invalidating SPM Cmlx cache..."; \ + rm -rf "$(RELEASE_DIR)/Cmlx.build"; \ + elif [ ! -f "$@" ]; then \ + echo "==> Seeding Cmlx stamp (first run — not invalidating existing cache)"; \ + fi + @touch $@ + +# ─── SPM build ─────────────────────────────────────────────────────────────── +# Runs `swift build --build-tests` only if Swift sources changed OR the Cmlx +# cache was invalidated (which updates the STAMP_CMLX sentinel). + +.PHONY: spm +spm: $(STAMP_SPM) + +$(STAMP_SPM): $(SWIFT_SOURCES) $(NATIVE_PREFILL_SOURCES) $(STAMP_CMLX) | $(STAMP_DIR) + @echo "==> Building Swift targets ($(CONFIG))..." + swift build --build-tests -c $(CONFIG) $(SWIFT_FLAGS) + @touch $@ + +# ─── Prefill bridge dylib ─────────────────────────────────────────────────── +# Compiled via clang++ against MLX. Only rebuilds when source or header changes. + +.PHONY: bridge +bridge: $(STAMP_BRIDGE) + +$(STAMP_BRIDGE): $(BRIDGE_SRCS) $(BRIDGE_HDRS) | $(STAMP_DIR) + @echo "==> Prefill bridge source changed — recompiling dylibs..." + @bash "$(PROJECT_ROOT)/scripts/build-prefill-bridge.sh" + @touch $@ + +# ─── Artifact installation ────────────────────────────────────────────────── +# Copies metallib and dylib into .build/release/ and the .xctest bundle. +# Must run AFTER spm because `swift build --build-tests` can regenerate the +# test bundle directory, wiping previously-copied files. + +.PHONY: install-artifacts +install-artifacts: $(STAMP_SPM) $(STAMP_METAL) + @mkdir -p "$(RELEASE_DIR)" + @# --- metallib --- + @if [ -f "$(METALLIB)" ] && [ -d "$(XCTEST_DIR)" ]; then \ + cp "$(METALLIB)" "$(XCTEST_DIR)/mlx.metallib"; \ + echo " copied mlx.metallib -> test bundle"; \ + fi + @# --- bridge dylibs -> release dir + test bundle --- + @for dylib in $(BRIDGE_DYLIBS); do \ + if [ -f "$$dylib" ]; then \ + name=$$(basename "$$dylib"); \ + cp "$$dylib" "$(RELEASE_DIR)/$$name"; \ + echo " copied $$name -> $(RELEASE_DIR)/"; \ + if [ -d "$(XCTEST_DIR)" ]; then \ + cp "$$dylib" "$(XCTEST_DIR)/$$name"; \ + echo " copied $$name -> test bundle"; \ + fi; \ + fi; \ + done + +# ─── Main targets ─────────────────────────────────────────────────────────── + +.PHONY: build +# NativePrefillBridge C++ is built via SPM (`swift build`). Optional standalone gemma/qwen bridge dylibs: `make bridge`. +build: spm metal + +.PHONY: build-tests +build-tests: build install-artifacts + @echo "" + @echo "Build complete — all artifacts in place." + +# ─── Clean targets ─────────────────────────────────────────────────────────── + +.PHONY: clean +clean: + swift package clean + rm -rf "$(STAMP_DIR)" + @echo "Cleaned build artifacts. Dependency checkouts preserved." + +.PHONY: clean-all +clean-all: + swift package reset + rm -rf "$(STAMP_DIR)" + @echo "Full reset. Run 'swift package resolve' or 'make' to re-fetch." + +# Surgical: force SPM to recompile just the C/C++ target on next build +.PHONY: clean-cmlx +clean-cmlx: + rm -rf "$(RELEASE_DIR)/Cmlx.build" + rm -f "$(STAMP_CMLX)" "$(STAMP_SPM)" + @echo "Cmlx cache invalidated. Next 'make' will recompile C/C++ sources." + +.PHONY: clean-metal +clean-metal: + rm -f "$(METALLIB)" + rm -f "$(STAMP_METAL)" + @echo "Metal cache cleared. Next 'make' will recompile shaders." + +.PHONY: clean-bridge +clean-bridge: + rm -f $(BRIDGE_DYLIBS) $(BRIDGE_RELEASES) + rm -f "$(STAMP_BRIDGE)" + @echo "Bridge cache cleared. Next 'make bridge' will recompile dylibs." + +# ─── Status ────────────────────────────────────────────────────────────────── + +.PHONY: status +status: + @echo "mlx-swift-lm build status" + @echo "=========================" + @echo "" + @echo "mlx-swift location: $(MLX_SWIFT_DIR)" + @echo "" + @echo "Stamps (last successful build):" + @if [ -d "$(STAMP_DIR)" ]; then \ + for f in $(STAMP_DIR)/*; do \ + [ -f "$$f" ] && echo " $$(basename $$f): $$(stat -f '%Sm' -t '%Y-%m-%d %H:%M:%S' $$f)"; \ + done; \ + else \ + echo " (none — run 'make' to build)"; \ + fi + @echo "" + @echo "Artifacts:" + @[ -f "$(METALLIB)" ] \ + && echo " mlx.metallib (release): OK" \ + || echo " mlx.metallib (release): MISSING" + @[ -f "$(XCTEST_DIR)/mlx.metallib" ] 2>/dev/null \ + && echo " mlx.metallib (test bundle): OK" \ + || echo " mlx.metallib (test bundle): MISSING" + @for dylib in $(BRIDGE_DYLIBS); do \ + name=$$(basename "$$dylib"); \ + [ -f "$$dylib" ] \ + && echo " $$name (source): OK" \ + || echo " $$name (source): MISSING"; \ + done + @for dylib in $(BRIDGE_RELEASES); do \ + name=$$(basename "$$dylib"); \ + [ -f "$$dylib" ] \ + && echo " $$name (release): OK" \ + || echo " $$name (release): MISSING"; \ + done + @echo "" + @echo "SPM Cmlx cache:" + @[ -d "$(RELEASE_DIR)/Cmlx.build" ] \ + && echo " Cmlx.build: present ($$(du -sh "$(RELEASE_DIR)/Cmlx.build" | cut -f1))" \ + || echo " Cmlx.build: empty (will recompile on next build)" + +# ─── Help ──────────────────────────────────────────────────────────────────── + +.PHONY: help +help: + @echo "mlx-swift-lm build targets:" + @echo "" + @echo " make Full incremental build for tests/benchmarks" + @echo " make spm Swift build (Swift + NativePrefillBridge C++, Cmlx invalidation)" + @echo " make metal Recompile Metal shaders only" + @echo " make bridge Build standalone prefill_bridge_gemma + prefill_bridge_qwen dylibs" + @echo " make status Show build state and artifact locations" + @echo "" + @echo " make clean Remove build artifacts (keep dependency checkouts)" + @echo " make clean-all Full reset (re-fetches everything)" + @echo " make clean-cmlx Force recompile of C/C++ sources (mlx, mlx-c)" + @echo " make clean-metal Force recompile of Metal shaders" + @echo " make clean-bridge Force recompile of prefill bridge" + @echo "" + @echo "Environment:" + @echo " MLX_SWIFT_PATH Override mlx-swift dependency location" + @echo " CONFIG release (default) or debug" + @echo " SWIFT_FLAGS Extra flags for swift build" diff --git a/Package.swift b/Package.swift index 8dcf54c517..4192a51dfa 100644 --- a/Package.swift +++ b/Package.swift @@ -34,10 +34,15 @@ let package = Package( .library( name: "IntegrationTestHelpers", targets: ["IntegrationTestHelpers"]), + .executable( + name: "MLXServer", + targets: ["MLXServer"]), ], dependencies: [ - .package(url: "https://github.com/ml-explore/mlx-swift", .upToNextMinor(from: "0.31.3")), + .package(url: "https://github.com/ekryski/mlx-swift", branch: "alpha"), .package(url: "https://github.com/swiftlang/swift-syntax.git", from: "600.0.0-latest"), + .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"), + .package(url: "https://github.com/huggingface/swift-huggingface.git", from: "0.2.0"), ], targets: [ .target( @@ -130,6 +135,20 @@ let package = Package( ], resources: [.process("Resources/1080p_30.mov"), .process("Resources/audio_only.mov")] ), + .testTarget( + name: "Benchmarks", + dependencies: [ + .product(name: "MLX", package: "mlx-swift"), + .product(name: "MLXNN", package: "mlx-swift"), + .product(name: "Transformers", package: "swift-transformers"), + "MLXLMCommon", + "MLXLLM", + "MLXVLM", + "MLXHuggingFace", + ], + path: "Tests/Benchmarks", + resources: [.copy("Resources")] + ), .macro( name: "MLXHuggingFaceMacros", dependencies: [ @@ -146,6 +165,23 @@ let package = Package( ], path: "Libraries/MLXHuggingFace" ), + .executableTarget( + name: "MLXServer", + dependencies: [ + .product(name: "MLX", package: "mlx-swift"), + .product(name: "MLXNN", package: "mlx-swift"), + .product(name: "Tokenizers", package: "swift-transformers"), + .product(name: "HuggingFace", package: "swift-huggingface"), + "MLXLLM", + "MLXVLM", + "MLXLMCommon", + "MLXHuggingFace", + ], + path: "Sources/MLXServer", + swiftSettings: [ + .swiftLanguageMode(.v5), + ] + ), ] ) diff --git a/README.md b/README.md index bf4e54f17a..60300d648b 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,17 @@ For some example applications and tools that use MLX Swift LM, check out [MLX Sw ## Usage +This package integrates with a variety of tokenizer and downloader packages through protocol conformance. Users can pick from three ways to integrate with these packages, which offer different tradeoffs between freedom and convenience: + +- Maximum freedom + - Copy the protocol conformance code (~100 lines) from the [integration packages](#Tokenizer-and-Downloader-Integrations) +- Freedom and convenience + - Use the [integration packages](#Tokenizer-and-Downloader-Integrations) for your preferred tokenizer and downloader packages +- Convenience + - Use the macros for integration with Swift Transformers and Swift Hugging Face + +### Installation + Add the core package to your `Package.swift`: ```swift @@ -44,19 +55,20 @@ And add the libraries to your target: ### Tokenizer and Downloader Integrations -MLX Swift LM focuses on model implementations. Tokenization and model downloading are handled by separate packages. Adapters make it easy to use your preferred downloader and tokenizer packages. +Tokenization and model downloading are handled by separate packages. Adapters make it easy to use your preferred tokenizer and downloader packages. For instructions on how to use them, see the readmes in the respective packages. + +| Tokenizer package | Adapter | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [DePasqualeOrg/swift-tokenizers](https://github.com/DePasqualeOrg/swift-tokenizers) | [DePasqualeOrg/swift-tokenizers-mlx](https://github.com/DePasqualeOrg/swift-tokenizers-mlx) | +| [huggingface/swift-transformers](https://github.com/huggingface/swift-transformers) | [DePasqualeOrg/swift-transformers-mlx](https://github.com/DePasqualeOrg/swift-transformers-mlx) | | Downloader package | Adapter | | ------------------------------------------------------------ | ------------------------------------------------------------ | | [huggingface/swift-huggingface](https://github.com/huggingface/swift-huggingface) | [DePasqualeOrg/swift-huggingface-mlx](https://github.com/DePasqualeOrg/swift-huggingface-mlx) | | [DePasqualeOrg/swift-hf-api](https://github.com/DePasqualeOrg/swift-hf-api) | [DePasqualeOrg/swift-hf-api-mlx](https://github.com/DePasqualeOrg/swift-hf-api-mlx) | -| Tokenizer package | Adapter | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| [DePasqualeOrg/swift-tokenizers](https://github.com/DePasqualeOrg/swift-tokenizers) | [DePasqualeOrg/swift-tokenizers-mlx](https://github.com/DePasqualeOrg/swift-tokenizers-mlx) | -| [huggingface/swift-transformers](https://github.com/huggingface/swift-transformers) | [DePasqualeOrg/swift-transformers-mlx](https://github.com/DePasqualeOrg/swift-transformers-mlx) | -> **Note:** The adapters are offered for convenience and are not required. You can also use tokenizer and downloader packages directly by setting up the required protocol conformance for MLX Swift LM. See the integration packages for examples of how to do this. +> **Note:** The adapters are offered for convenience and are not required. You can also use tokenizer and downloader packages directly by setting up the required protocol conformance for MLX Swift LM, just like the code in the integration packages. Alternatively, you can use the macros provided by this package to integrate with Swift Transformers and Swift Hugging Face. ### Quick Start @@ -136,7 +148,7 @@ Or use the underlying API to control every aspect of the evaluation. ## Migrating to Version 3 -Version 3 of MLX Swift LM decouples the tokenizer and downloader implementations. See the [integrations](#Tokenizer and Downloader Integrations) section for details. +Version 3 of MLX Swift LM decouples the tokenizer and downloader implementations. See the [integrations](#Tokenizer-and-Downloader-Integrations) section for details. ### New dependencies @@ -253,6 +265,93 @@ let text = tokenizer.decode(tokens: ids) let text = tokenizer.decode(tokenIds: ids) ``` +## Development Setup + +Run once after cloning (or after fetching new `mlx-swift` changes): + +```bash +./scripts/setup-dev.sh +``` + +### Why `make` instead of `swift build` + +Swift Package Manager (SPM) does not handle several parts of this repo's build pipeline: + +- **Metal shaders** — SPM cannot compile `.metal` files. The MLX Metal kernels must be compiled separately into `mlx.metallib` and copied into the test bundle. +- **Native C++ dylibs** — The prefill bridges (`libprefill_bridge_gemma.dylib`, `libprefill_bridge_qwen.dylib`) are built via `clang++` and must be placed in the build output and test bundle manually. +- **Submodule staleness** — When you modify C/C++ files deep in git submodules (`mlx-swift` → `mlx` → `mlx-c`), SPM's build cache may not detect the change. It tracks content signatures keyed by the dependency's git revision, so edits within a submodule can go stale. +- **Test bundle regeneration** — `swift build --build-tests` can regenerate the `.xctest` bundle, wiping previously-copied Metal shaders and dylibs. + +The project [Makefile](Makefile) wraps SPM and fills these gaps using file-timestamp dependency tracking. It only rebuilds what actually changed: + +| What changed | What rebuilds | What stays cached | +|---|---|---| +| A `.metal` or kernel `.h` file | Metal shaders only | SPM targets, bridge dylibs | +| A `.cpp`/`.c`/`.h` in `mlx` or `mlx-c` | SPM's Cmlx target only | Swift targets, Metal, bridges | +| Swift sources | SPM incremental rebuild | Metal, bridges | +| A bridge `.cpp`/`.h` in `Sources/NativePrefillBridge/` | Bridge dylibs only | SPM, Metal | +| Nothing | Artifact copy only (~instant) | Everything | + +After every build, artifacts (metallib, dylibs) are copied to the release directory and test bundle automatically. + +You do not need to use `make` directly for typical workflows — `setup-dev.sh` and `benchmark.sh` both call it internally. For manual builds or targeted rebuilds, see `make help`. + +#### Manual builds + +For targeted rebuilds when working on specific parts of the stack: + +```bash +make # Full incremental build (only rebuilds what changed) +make metal # Recompile Metal shaders only +make bridge # Recompile prefill bridge dylibs only +make spm # Swift build only (with Cmlx cache invalidation) +make status # Show what's built and what's stale +make clean-cmlx # Force SPM to recompile C/C++ on next build +make help # Full reference +``` + +## Testing + +Tests require Metal and must be run via Xcode's build system so that the MLX Metal shaders (`default.metallib`) are built and available. Running `swift test` directly will fail with "Failed to load the default metallib" because SwiftPM does not build Metal shaders. + +In Xcode: open the package and run tests (Cmd-U), or from the command line: + +```bash +xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS' +``` + +Benchmarks are an exception — they're gated behind a Swift Testing filter (`swift test --filter benchmark`) and invoked via `./scripts/benchmark.sh`, which handles the Metal shader build via `make`. See the next section. + +## Benchmarking + +Inference benchmarks measure prefill throughput, decode tok/s, TTFT, perplexity, KL divergence, and GPU memory across models, quantization levels, and KV cache configurations. Benchmarks run in **release mode** and write markdown reports to `benchmarks/`. + +See [`benchmarks/README.md`](benchmarks/README.md) for the complete CLI reference, methodology details, and environment variable API. + +This resolves Swift packages, compiles Metal shaders, does an initial release build, and copies all artifacts into the test bundle. After setup, all benchmark commands work immediately. + +### Basic benchmark + +Benchmark any registered model family or HuggingFace repo directly: + +```bash +# Known model family (downloads automatically on first run) +./scripts/benchmark.sh --model qwen35-0.8b --context 128 + +# Any HuggingFace model by repo ID +./scripts/benchmark.sh --model mlx-community/Qwen3-4B-4bit --context 128 + +# With perplexity tracking +./scripts/benchmark.sh --model mlx-community/Qwen3-4B-4bit --context 128 --ppl + +# Multi-model sweep — all rows land in one hardware-dated report file +./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 --quick +``` + +Results are saved as hardware-dated markdown files in `benchmarks/`, one file per sweep per day (e.g. `benchmarks/m1-max-64gb-2026-04-16.md`). All runs for the same model across the sweep are grouped together in that file. + +For more advanced benchmark combinations and options see [`benchmarks/README.md`](benchmarks/README.md). + ## Documentation Developers can use these examples in their own programs -- just import the swift package! diff --git a/Sources/MLXServer/main.swift b/Sources/MLXServer/main.swift new file mode 100644 index 0000000000..da38ebefb6 --- /dev/null +++ b/Sources/MLXServer/main.swift @@ -0,0 +1,1434 @@ +import Foundation +import MLX +import MLXLLM +import MLXVLM +import MLXLMCommon +import MLXHuggingFace +import MLXNN +import HuggingFace +import Tokenizers + +func log(_ msg: String) { + FileHandle.standardError.write(Data("[MLXServer] \(msg)\n".utf8)) +} + +// MARK: - OpenAI Types + +struct ChatMessage: Codable { + let role: String + let content: String? + + init(from decoder: Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + role = try container.decode(String.self, forKey: .role) + // Content can be string, null, or array — just grab string or nil + if let str = try? container.decode(String.self, forKey: .content) { + content = str + } else { + content = nil + } + } + + enum CodingKeys: String, CodingKey { case role, content } +} + +struct ChatRequest: Codable { + let model: String? + let messages: [ChatMessage] + let max_tokens: Int? + let temperature: Float? + let stream: Bool? + // Accept but ignore extra fields + let tools: AnyCodable? + let tool_choice: AnyCodable? + let top_p: Float? + let frequency_penalty: Float? + let presence_penalty: Float? + let stop: AnyCodable? + let n: Int? + + enum CodingKeys: String, CodingKey { + case model, messages, max_tokens, temperature, stream + case tools, tool_choice, top_p, frequency_penalty, presence_penalty, stop, n + } +} + +/// Wraps any JSON value so we can accept arbitrary fields without failing to decode. +struct AnyCodable: Codable { + let value: Any? + init(from decoder: Swift.Decoder) throws { + let container = try decoder.singleValueContainer() + if let arr = try? container.decode([JSONValue].self) { + value = arr.map { $0.toAny() } + } else if let dict = try? container.decode([String: JSONValue].self) { + value = dict.mapValues { $0.toAny() } + } else { + value = nil + } + } + func encode(to encoder: Swift.Encoder) throws { + var container = encoder.singleValueContainer() + try container.encodeNil() + } +} + +/// Recursive JSON value for preserving tools structure. +enum JSONValue: Codable { + case string(String), int(Int), double(Double), bool(Bool), null + case array([JSONValue]), object([String: JSONValue]) + + init(from decoder: Swift.Decoder) throws { + let c = try decoder.singleValueContainer() + if let v = try? c.decode(Bool.self) { self = .bool(v) } + else if let v = try? c.decode(Int.self) { self = .int(v) } + else if let v = try? c.decode(Double.self) { self = .double(v) } + else if let v = try? c.decode(String.self) { self = .string(v) } + else if let v = try? c.decode([JSONValue].self) { self = .array(v) } + else if let v = try? c.decode([String: JSONValue].self) { self = .object(v) } + else if c.decodeNil() { self = .null } + else { self = .null } + } + + func encode(to encoder: Swift.Encoder) throws { + var c = encoder.singleValueContainer() + switch self { + case .string(let v): try c.encode(v) + case .int(let v): try c.encode(v) + case .double(let v): try c.encode(v) + case .bool(let v): try c.encode(v) + case .null: try c.encodeNil() + case .array(let v): try c.encode(v) + case .object(let v): try c.encode(v) + } + } + + func toAny() -> Any { + switch self { + case .string(let v): return v + case .int(let v): return v + case .double(let v): return v + case .bool(let v): return v + case .null: return NSNull() + case .array(let v): return v.map { $0.toAny() } + case .object(let v): return v.mapValues { $0.toAny() } as [String: Any] + } + } +} + +struct ChatResponse: Codable { + let id: String + let object: String + let created: Int + let model: String + let system_fingerprint: String + let choices: [Choice] + let usage: Usage? + + struct Choice: Codable { + let index: Int + let message: Message? + let delta: Message? + let finish_reason: String? + } + + struct Message: Codable { + let role: String? + let content: String? + let reasoning_content: String? + + init(role: String? = nil, content: String? = nil, reasoning_content: String? = nil) { + self.role = role + self.content = content + self.reasoning_content = reasoning_content + } + + func encode(to encoder: Swift.Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(role, forKey: .role) + try container.encodeIfPresent(content, forKey: .content) + try container.encodeIfPresent(reasoning_content, forKey: .reasoning_content) + } + + enum CodingKeys: String, CodingKey { + case role, content, reasoning_content + } + } + + struct Usage: Codable { + let prompt_tokens: Int + let completion_tokens: Int + let total_tokens: Int + } +} + +// MARK: - Server Prompt Cache (Multi-Session) + +struct CachedSession { + let id: UUID = UUID() + var tokenIds: [Int] + var kvCache: [KVCache] + var lastUsed: Date +} + +struct CacheMetrics { + var totalRequests: Int = 0 + var cacheHits: Int = 0 + var cacheMisses: Int = 0 + var trimFailures: Int = 0 + var totalPrefillTokens: Int = 0 + var totalReusedTokens: Int = 0 + var totalPrefillMs: Double = 0 + var totalDecodeMs: Double = 0 + var totalDecodeTokens: Int = 0 + var evictions: Int = 0 + + var hitRate: Double { totalRequests > 0 ? Double(cacheHits) / Double(totalRequests) : 0 } + var avgPrefillTokens: Double { totalRequests > 0 ? Double(totalPrefillTokens) / Double(totalRequests) : 0 } + var avgPrefillMs: Double { totalRequests > 0 ? totalPrefillMs / Double(totalRequests) : 0 } + var avgDecodeTokensPerSec: Double { totalDecodeMs > 0 ? Double(totalDecodeTokens) / (totalDecodeMs / 1000) : 0 } +} + +/// Multi-session prompt cache with LCP (longest common prefix) matching. +/// Keeps up to `maxSessions` cached KV states. When a new request arrives, +/// finds the session with the longest matching token prefix, trims KV to +/// that prefix, and returns only the new tokens to prefill. +actor ServerPromptCache { + var sessions: [CachedSession] = [] + let maxSessions: Int + let kvScheme: String? + var metrics = CacheMetrics() + + init(maxSessions: Int = 3, kvScheme: String? = nil) { + self.maxSessions = maxSessions + self.kvScheme = kvScheme + } + + func recordRequest(hit: Bool, prefillTokens: Int, reusedTokens: Int) { + metrics.totalRequests += 1 + if hit { metrics.cacheHits += 1 } else { metrics.cacheMisses += 1 } + metrics.totalPrefillTokens += prefillTokens + metrics.totalReusedTokens += reusedTokens + } + + func recordTiming(prefillMs: Double, decodeMs: Double, decodeTokens: Int) { + metrics.totalPrefillMs += prefillMs + metrics.totalDecodeMs += decodeMs + metrics.totalDecodeTokens += decodeTokens + } + + func recordEviction() { metrics.evictions += 1 } + func recordTrimFailure() { metrics.trimFailures += 1 } + func getMetrics() -> CacheMetrics { metrics } + func getSessionCount() -> Int { sessions.count } + + /// Find the session with the longest common prefix match. + /// Returns (kvCache, newTokensToProcess, cacheStatus, sessionId). + func fetch(tokens newTokens: [Int], model: any LanguageModel) -> ([KVCache], [Int], CacheStatus, UUID) { + var bestIdx = -1 + var bestPrefix = 0 + + for (i, session) in sessions.enumerated() { + let prefix = commonPrefix(session.tokenIds, newTokens) + if prefix > bestPrefix { + bestPrefix = prefix + bestIdx = i + } + } + + if bestIdx >= 0 && bestPrefix > 0 { + let session = sessions[bestIdx] + // Trim based on actual KV cache size, not tokenIds.count. + // The cache may have extra decode tokens from interrupted generation. + let actualCacheSize = session.kvCache.first?.offset ?? session.tokenIds.count + let trimAmount = actualCacheSize - bestPrefix + + // If the new request extends the cached session (same prefix, more tokens), + // use in-place. If it diverges (different suffix), deep copy so the + // original stays intact for future reuse. + let isExtension = (bestPrefix == session.tokenIds.count) || (trimAmount == 0) + + if isExtension { + if trimAmount > 0 { + for c in session.kvCache { + if c.trim(trimAmount) == 0 { + metrics.trimFailures += 1 + return freshCache(tokens: newTokens, model: model) + } + } + } + sessions[bestIdx].lastUsed = Date() + sessions[bestIdx].tokenIds = Array(newTokens[0.. 0 { + for c in copiedCache { + if c.trim(trimAmount) == 0 { + metrics.trimFailures += 1 + return freshCache(tokens: newTokens, model: model) + } + } + } + + evictIfNeeded() + let newSession = CachedSession(tokenIds: Array(newTokens[0.. ([KVCache], [Int], CacheStatus, UUID) { + evictIfNeeded() + var cacheParams: GenerateParameters? = nil + if let scheme = kvScheme { + var p = GenerateParameters() + p.kvScheme = scheme + cacheParams = p + } + let cache = model.newCache(parameters: cacheParams) + let session = CachedSession(tokenIds: [], kvCache: cache, lastUsed: Date()) + sessions.append(session) + let status = CacheStatus.miss(totalTokens: tokens.count, sessionsCount: sessions.count) + recordRequest(hit: false, prefillTokens: tokens.count, reusedTokens: 0) + return (cache, tokens, status, session.id) + } + + /// Save token state after generation completes. + func save(sessionId: UUID, tokens: [Int]) { + if let idx = sessions.firstIndex(where: { $0.id == sessionId }) { + sessions[idx].tokenIds = tokens + sessions[idx].lastUsed = Date() + } + } + + private func evictIfNeeded() { + while sessions.count >= maxSessions { + if let oldest = sessions.enumerated().min(by: { $0.element.lastUsed < $1.element.lastUsed }) { + log("Evicting session \(oldest.offset) (\(oldest.element.tokenIds.count) tokens, idle \(Int(-oldest.element.lastUsed.timeIntervalSinceNow))s)") + sessions.remove(at: oldest.offset) + } + } + } + + /// Evict idle sessions, keeping at most `keep` sessions. + func evictIdle(keep: Int) { + while sessions.count > keep { + if let oldest = sessions.enumerated().min(by: { $0.element.lastUsed < $1.element.lastUsed }) { + log("Memory pressure eviction: session \(oldest.offset)") + sessions.remove(at: oldest.offset) + metrics.evictions += 1 + } + } + } + + /// Flush all cached sessions (e.g., on model change or critical memory pressure). + func flush() { + let count = sessions.count + sessions.removeAll() + metrics.evictions += count + log("Flushed all \(count) cached sessions") + } + + private func commonPrefix(_ a: [Int], _ b: [Int]) -> Int { + let maxLen = min(a.count, b.count) + for i in 0..] = [] + // Prefill semaphore: only one slot prefills at a time to avoid GPU contention + private var prefillBusy = false + private var prefillWaiters: [CheckedContinuation] = [] + + init(slotCount: Int) { + self.slotCount = slotCount + var s: [ServerSlot] = [] + for i in 0.. ServerSlot { + if let slot = slots.first(where: { $0.state == .idle }) { + slot.state = .prefilling + return slot + } + return await withCheckedContinuation { cont in + slotWaiters.append(cont) + } + } + + /// Try to acquire a slot without waiting. Returns nil if all busy (for 503 responses). + func tryAcquireSlot() -> ServerSlot? { + if let slot = slots.first(where: { $0.state == .idle }) { + slot.state = .prefilling + return slot + } + return nil + } + + /// Release a slot back to idle and wake the next queued waiter, if any. + func releaseSlot(_ slot: ServerSlot) { + slot.reset() + if let waiter = slotWaiters.first { + slotWaiters.removeFirst() + slot.state = .prefilling + waiter.resume(returning: slot) + } + } + + /// Get a snapshot of all slot states for the /slots endpoint. + func slotStatus() -> [(id: Int, state: String, requestId: String, promptTokens: Int, genTokens: Int, elapsed: Double)] { + slots.map { slot in + let elapsed = slot.state == .idle ? 0 : CFAbsoluteTimeGetCurrent() - slot.startTime + return (id: slot.id, state: slot.state.rawValue, requestId: slot.requestId, + promptTokens: slot.promptTokenCount, genTokens: slot.generationTokenCount, + elapsed: elapsed) + } + } + + /// Count of active (non-idle) slots. + func activeSlotCount() -> Int { + slots.filter { $0.state != .idle }.count + } + + /// Number of requests waiting in the queue. + func queueDepth() -> Int { + slotWaiters.count + } +} + +// MARK: - HTTP Server + +final class SimpleHTTPServer { + let port: UInt16 + let container: ModelContainer + let modelId: String + let promptCache: ServerPromptCache + let slotManager: SlotManager + let slotCount: Int + let kvScheme: String? + private var serverSocket: Int32 = -1 + private var memoryPressureSource: DispatchSourceMemoryPressure? + static let maxBodySize = 10 * 1024 * 1024 + + /// Compute max sessions based on available physical memory. + /// Conservative: assume ~1.5GB per cached session (14K tokens FP16 KV for 30B MoE). + static func autoMaxSessions() -> Int { + let totalGB = Double(ProcessInfo.processInfo.physicalMemory) / (1024 * 1024 * 1024) + let available = max(totalGB - 20, 2) + let sessions = Int(available / 1.5) + return max(2, min(sessions, 10)) + } + + init(port: UInt16, container: ModelContainer, modelId: String, slotCount: Int = 4, kvScheme: String? = nil) { + self.port = port + self.container = container + self.modelId = modelId + self.slotCount = slotCount + self.kvScheme = kvScheme + let maxSess = SimpleHTTPServer.autoMaxSessions() + self.promptCache = ServerPromptCache(maxSessions: maxSess, kvScheme: kvScheme) + self.slotManager = SlotManager(slotCount: slotCount) + log("Cache: \(maxSess) max sessions (\(ProcessInfo.processInfo.physicalMemory / (1024*1024*1024))GB RAM)") + log("Slots: \(slotCount) parallel inference slots") + } + + func start() throws { + serverSocket = socket(AF_INET, SOCK_STREAM, 0) + guard serverSocket >= 0 else { throw ServerError.socketCreation } + + var opt: Int32 = 1 + setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, socklen_t(MemoryLayout.size)) + + var addr = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = port.bigEndian + addr.sin_addr.s_addr = INADDR_ANY + + let bindResult = withUnsafePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(serverSocket, $0, socklen_t(MemoryLayout.size)) } + } + guard bindResult == 0 else { throw ServerError.bind(port) } + guard listen(serverSocket, 64) == 0 else { throw ServerError.listen } + + log("Listening on http://127.0.0.1:\(port)") + log("Endpoints: GET /v1/models, POST /v1/chat/completions, POST /v1/completions, GET /health, GET /metrics, GET /slots") + + // Monitor macOS memory pressure — evict idle sessions under pressure + let source = DispatchSource.makeMemoryPressureSource( + eventMask: [.warning, .critical], queue: .global()) + source.setEventHandler { [promptCache] in + Task { + let event = source.data + if event.contains(.critical) { + log("MEMORY PRESSURE: critical — flushing all cached sessions") + await promptCache.flush() + } else if event.contains(.warning) { + log("MEMORY PRESSURE: warning — evicting idle sessions") + await promptCache.evictIdle(keep: 1) + } + } + } + source.resume() + memoryPressureSource = source + + while true { + let client = accept(serverSocket, nil, nil) + guard client >= 0 else { continue } + Task { await handleClient(client) } + } + } + + // MARK: - Request Routing + + func handleClient(_ fd: Int32) async { + defer { close(fd) } + + let requestStart = CFAbsoluteTimeGetCurrent() + var method = "?" + var path = "?" + var originHeader: String? = nil + + do { + // Read headers + var headerData = Data() + var byte: UInt8 = 0 + while headerData.count < 65536 { + let n = read(fd, &byte, 1) + guard n == 1 else { return } + headerData.append(byte) + if headerData.count >= 4 && + headerData[headerData.count-4] == 0x0D && headerData[headerData.count-3] == 0x0A && + headerData[headerData.count-2] == 0x0D && headerData[headerData.count-1] == 0x0A { + break + } + } + + let headerStr = String(data: headerData, encoding: .utf8) ?? "" + let lines = headerStr.split(separator: "\r\n", omittingEmptySubsequences: false) + guard let firstLine = lines.first else { return } + + let parts = firstLine.split(separator: " ") + guard parts.count >= 2 else { return } + method = String(parts[0]) + path = String(parts[1]).split(separator: "?").first.map(String.init) ?? String(parts[1]) + + // Parse Content-Length and Origin + var contentLength = 0 + for line in lines { + let lower = line.lowercased() + if lower.hasPrefix("content-length:") { + contentLength = Int(lower.dropFirst(15).trimmingCharacters(in: .whitespaces)) ?? 0 + } + if lower.hasPrefix("origin:") { + originHeader = String(line.dropFirst(7)).trimmingCharacters(in: .whitespaces) + } + } + let corsOrigin = originHeader ?? "*" + + if contentLength > SimpleHTTPServer.maxBodySize { + sendResponse(fd: fd, status: 413, + body: "{\"error\":{\"message\":\"request body too large (max \(SimpleHTTPServer.maxBodySize / 1024 / 1024)MB)\",\"type\":\"invalid_request_error\",\"code\":413}}", + contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + return + } + + // Read body + var bodyData = Data() + if contentLength > 0 { + bodyData.reserveCapacity(contentLength) + var remaining = contentLength + var buf = [UInt8](repeating: 0, count: min(remaining, 65536)) + while remaining > 0 { + let toRead = min(remaining, buf.count) + let n = read(fd, &buf, toRead) + guard n > 0 else { break } + bodyData.append(contentsOf: buf[0.. any Sendable { + if let s = v as? String { return s } + if let n = v as? Int { return n } + if let b = v as? Bool { return b } + if let d = v as? Double { return d } + if let arr = v as? [Any] { return arr.map { convert($0) } as [any Sendable] } + if let dict = v as? [String: Any] { + return dict.mapValues { convert($0) } as [String: any Sendable] + } + return String(describing: v) + } + return tool.mapValues { convert($0) } as [String: any Sendable] + } + // Try with tools first; fall back if template doesn't support them + do { + let thinkCtx: [String: any Sendable] = ["enable_thinking": false] + tokens = try ctx.tokenizer.applyChatTemplate(messages: messages, tools: toolSpecs, additionalContext: thinkCtx) + } catch { + log("Chat template with tools failed, retrying without") + var toolDesc = "Available tools:\n" + for tool in toolSpecs { + if let fn = tool["function"] as? [String: Any], + let name = fn["name"] as? String { + let desc = fn["description"] as? String ?? "" + toolDesc += "- \(name): \(desc)\n" + } + } + if var sys = messages.first, sys["role"] == "system" { + sys["content"] = (sys["content"] ?? "") + "\n\n" + toolDesc + var adjusted = messages + adjusted[0] = sys + tokens = try ctx.tokenizer.applyChatTemplate(messages: adjusted) + } else { + var adjusted = messages + adjusted.insert(["role": "system", "content": toolDesc], at: 0) + tokens = try ctx.tokenizer.applyChatTemplate(messages: adjusted) + } + } + } else { + let thinkingContext: [String: any Sendable] = ["enable_thinking": false] + tokens = try ctx.tokenizer.applyChatTemplate(messages: messages, tools: nil, additionalContext: thinkingContext) + } + + // Prompt caching: reuse KV state from previous requests + let prefillStart = CFAbsoluteTimeGetCurrent() + let (reusedCache, newTokens, cacheStatus, sessionId) = await promptCache.fetch(tokens: tokens, model: ctx.model) + let tokenArray = MLXArray(newTokens.isEmpty ? tokens : newTokens) + let input = LMInput(text: LMInput.Text(tokens: tokenArray)) + + var params = GenerateParameters(temperature: request.temperature ?? 0.6) + if let maxTokens = request.max_tokens { + params.maxTokens = maxTokens + } + params.kvScheme = self.kvScheme + + if toolsAny != nil { + ctx.configuration.toolCallFormat = .xmlFunction + } + + slot.promptTokenCount = tokens.count + slot.state = .generating + log("slot[\(slot.id)] \(cacheStatus.logString) stream=\(isStreaming)") + + // Keepalive timer: sends SSE chunks every 2s during prefill to prevent + // client ReadTimeout. Uses GCD because generate() blocks the cooperative + // thread pool during GPU inference. + var keepaliveTimer: DispatchSourceTimer? = nil + if isStreaming { + let header = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream; charset=utf-8\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: \(corsOrigin)\r\nAccess-Control-Allow-Credentials: true\r\n\r\n" + _ = header.withCString { write(fd, $0, Int(strlen($0))) } + + let timer = DispatchSource.makeTimerSource(queue: .global()) + let keepaliveFd = fd + timer.schedule(deadline: .now() + 2, repeating: 2.0) + timer.setEventHandler { + let chunk = "data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":null}]}\n\n" + _ = chunk.withCString { write(keepaliveFd, $0, Int(strlen($0))) } + } + timer.resume() + keepaliveTimer = timer + } + + if isStreaming { + var prefillDone = false + let reqModel = request.model + var hadToolCall = false + + // Send role chunk immediately so client knows we're alive + writeSSE(fd: fd, requestId: requestId, role: "assistant", content: nil, finishReason: nil, requestModel: reqModel, includeNullContent: true) + + do { + var fullText = "" + var thinkText = "" + var emittedUpTo = 0 + var inThinkBlock = false + + var tokenCount = 0 + for try await generation in try generate( + input: input, cache: reusedCache, parameters: params, context: ctx + ) { + if !prefillDone { + prefillDone = true + keepaliveTimer?.cancel() + await releasePrefillOnce() + } + tokenCount += 1 + + switch generation { + case .chunk(let text): + fullText += text + + // Handle ... blocks from thinking models + if emittedUpTo == 0 && !inThinkBlock { + let trimmed = fullText.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.hasPrefix("") { + if let range = fullText.range(of: "") { + var thinkContent = String(fullText[..") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + let newThink = thinkContent.count > thinkText.count ? String(thinkContent[thinkContent.index(thinkContent.startIndex, offsetBy: thinkText.count)...]) : "" + if !newThink.isEmpty { + writeSSE(fd: fd, requestId: requestId, role: nil, content: nil, finishReason: nil, reasoningContent: newThink, requestModel: reqModel) + } + thinkText = thinkContent + + let afterThink = String(fullText[range.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) + fullText = afterThink + emittedUpTo = 0 + inThinkBlock = false + if fullText.isEmpty { continue } + } + } else { + // Still in think block — stream as reasoning_content + var thinkContent = fullText + if let tagEnd = thinkContent.range(of: "") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + let newThink = thinkContent.count > thinkText.count ? String(thinkContent[thinkContent.index(thinkContent.startIndex, offsetBy: thinkText.count)...]) : "" + if !newThink.isEmpty { + writeSSE(fd: fd, requestId: requestId, role: nil, content: nil, finishReason: nil, reasoningContent: newThink, requestModel: reqModel) + thinkText = thinkContent + } + continue + } + } + + // After tool calls, suppress trailing XML tags + if hadToolCall { + let remaining = String(fullText[fullText.index(fullText.startIndex, offsetBy: emittedUpTo)...]) + let stripped = remaining + .replacingOccurrences(of: "", with: "") + .replacingOccurrences(of: "", with: "") + .replacingOccurrences(of: "", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + if stripped.isEmpty { + emittedUpTo = fullText.count + continue + } + } + + // Skip leading whitespace after think-block removal + if emittedUpTo == 0 && !fullText.isEmpty { + let trimmed = fullText.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { continue } + if trimmed.count < fullText.count { + fullText = trimmed + } + } + + // Check for potential tool call in un-emitted portion + let unemitted = String(fullText[fullText.index(fullText.startIndex, offsetBy: emittedUpTo)...]) + + if unemitted.contains("") || unemitted.contains("") || unemitted.contains("") || unemitted.contains("") || unemitted.contains("") || unemitted.contains("") { + // Complete tool call — parse and emit + let tcs = parseAllToolCalls(unemitted) + if !tcs.isEmpty { + hadToolCall = true + for tc in tcs { + emitToolCallSSE(fd: fd, requestId: requestId, name: tc.name, arguments: tc.arguments, requestModel: reqModel) + } + } else { + writeSSE(fd: fd, requestId: requestId, role: nil, content: unemitted, finishReason: nil, requestModel: reqModel) + } + emittedUpTo = fullText.count + } + // Incomplete — keep buffering + } else if unemitted.contains("<") { + // Hold back only if `<` looks like start of a known tag + let tagPrefixes = ["= maxTok ? "length" : "stop") + let responseModel = reqModel ?? modelId + let usageJSON = ",\"usage\":{\"prompt_tokens\":\(info.promptTokenCount),\"completion_tokens\":\(info.generationTokenCount),\"total_tokens\":\(info.promptTokenCount + info.generationTokenCount)}" + let finalEvent = "data: {\"id\":\"\(requestId)\",\"object\":\"chat.completion.chunk\",\"created\":\(Int(Date().timeIntervalSince1970)),\"model\":\"\(responseModel)\",\"system_fingerprint\":\"mlx-swift-v1\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"\(fr)\"}]\(usageJSON)}\n\ndata: [DONE]\n\n" + _ = finalEvent.withCString { write(fd, $0, Int(strlen($0))) } + } + } + } catch { + await releasePrefillOnce() + log("ERROR streaming generation: \(error)") + let errMsg = error.localizedDescription.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + let errEvent = "data: {\"error\":{\"message\":\"\(errMsg)\",\"type\":\"server_error\",\"code\":500}}\n\ndata: [DONE]\n\n" + _ = errEvent.withCString { write(fd, $0, Int(strlen($0))) } + } + + let elapsed = (CFAbsoluteTimeGetCurrent() - prefillStart) * 1000 + await promptCache.recordTiming(prefillMs: 0, decodeMs: elapsed, decodeTokens: 0) + await promptCache.save(sessionId: sessionId, tokens: tokens) + } else { + keepaliveTimer?.cancel() + + // Non-streaming: collect all text + var fullText = "" + var completionTokens = 0 + var toolCalls: [(name: String, args: String)] = [] + for try await generation in try generate( + input: input, cache: reusedCache, parameters: params, context: ctx + ) { + if !prefillReleased { await releasePrefillOnce() } + switch generation { + case .chunk(let text): + fullText += text + completionTokens += 1 + case .toolCall(let tc): + let argsDict = tc.function.arguments.mapValues { $0.anyValue } + let argsJSON = (try? JSONSerialization.data(withJSONObject: argsDict)) ?? Data() + toolCalls.append((name: tc.function.name, args: String(data: argsJSON, encoding: .utf8) ?? "{}")) + default: break + } + } + + // Strip ... blocks, preserving as reasoning_content + var reasoningContent: String? = nil + if let thinkEnd = fullText.range(of: "") { + var thinkContent = String(fullText[..") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + reasoningContent = thinkContent.trimmingCharacters(in: .whitespacesAndNewlines) + fullText = String(fullText[thinkEnd.upperBound...]).trimmingCharacters(in: .whitespacesAndNewlines) + } else if fullText.hasPrefix("") { + var thinkContent = fullText + if let tagEnd = thinkContent.range(of: "") { + thinkContent = String(thinkContent[tagEnd.upperBound...]) + } + reasoningContent = thinkContent.trimmingCharacters(in: .whitespacesAndNewlines) + if reasoningContent?.isEmpty == true { reasoningContent = nil } + fullText = "" + } + + // Parse tool calls from accumulated text (XML formats) + if toolCalls.isEmpty { + let parsed = parseAllToolCalls(fullText) + if !parsed.isEmpty { + for tc in parsed { + toolCalls.append((name: tc.name, args: tc.arguments)) + } + fullText = "" + } + } + + let responseModel = request.model ?? modelId + let maxTok = request.max_tokens ?? Int.max + let finishReason: String + if !toolCalls.isEmpty { + finishReason = "tool_calls" + } else if completionTokens >= maxTok { + finishReason = "length" + } else { + finishReason = "stop" + } + + var responseBody: String + if toolCalls.isEmpty { + let response = ChatResponse( + id: requestId, object: "chat.completion", + created: Int(Date().timeIntervalSince1970), model: responseModel, + system_fingerprint: "mlx-swift-v1", + choices: [.init(index: 0, message: .init(role: "assistant", content: fullText, reasoning_content: reasoningContent), + delta: nil, finish_reason: finishReason)], + usage: .init(prompt_tokens: tokens.count, completion_tokens: completionTokens, + total_tokens: tokens.count + completionTokens)) + responseBody = String(data: try JSONEncoder().encode(response), encoding: .utf8)! + } else { + let tcJSON = toolCalls.enumerated().map { (i, tc) in + "{\"id\":\"call_\(UUID().uuidString.prefix(8))\",\"type\":\"function\",\"function\":{\"name\":\"\(tc.name)\",\"arguments\":\(tc.args)}}" + }.joined(separator: ",") + let content = "\"\(fullText.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\r", with: "\\r"))\"" + let rcField: String + if let rc = reasoningContent { + let rcEscaped = rc.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\r", with: "\\r") + rcField = ",\"reasoning_content\":\"\(rcEscaped)\"" + } else { + rcField = "" + } + responseBody = "{\"id\":\"\(requestId)\",\"object\":\"chat.completion\",\"created\":\(Int(Date().timeIntervalSince1970)),\"model\":\"\(responseModel)\",\"system_fingerprint\":\"mlx-swift-v1\",\"choices\":[{\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\(content)\(rcField),\"tool_calls\":[\(tcJSON)]},\"finish_reason\":\"\(finishReason)\"}],\"usage\":{\"prompt_tokens\":\(tokens.count),\"completion_tokens\":\(completionTokens),\"total_tokens\":\(tokens.count + completionTokens)}}" + } + sendResponse(fd: fd, status: 200, body: responseBody, + contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + + let elapsed = (CFAbsoluteTimeGetCurrent() - prefillStart) * 1000 + await promptCache.recordTiming(prefillMs: 0, decodeMs: elapsed, decodeTokens: 0) + await promptCache.save(sessionId: sessionId, tokens: tokens) + } + } catch { + log("ERROR handleChat: \(error)") + let errMsg = error.localizedDescription.replacingOccurrences(of: "\"", with: "'") + let err = "{\"error\":{\"message\":\"\(errMsg)\",\"type\":\"server_error\",\"code\":500}}" + sendResponse(fd: fd, status: 500, body: err, contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + } + } + + // MARK: - Text Completions + + func handleCompletions(fd: Int32, prompt: String, maxTokens: Int, temperature: Float, stream: Bool, corsOrigin: String = "*") async { + let requestId = "cmpl-\(UUID().uuidString.prefix(8))" + + let slot = await slotManager.acquireSlot() + slot.requestId = requestId + slot.startTime = CFAbsoluteTimeGetCurrent() + slot.state = .generating + defer { Task { await slotManager.releaseSlot(slot) } } + + do { + let ctx = await container.perform { ctx in ctx } + let tokens = ctx.tokenizer.encode(text: prompt) + let tokenArray = MLXArray(tokens) + let input = LMInput(text: LMInput.Text(tokens: tokenArray)) + + var params = GenerateParameters(temperature: temperature) + params.maxTokens = maxTokens + params.kvScheme = self.kvScheme + + log("completions: \(tokens.count) prompt tokens, max=\(maxTokens), stream=\(stream)") + + if stream { + let header = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream; charset=utf-8\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: \(corsOrigin)\r\nAccess-Control-Allow-Credentials: true\r\n\r\n" + _ = header.withCString { write(fd, $0, Int(strlen($0))) } + + let result = try await container.generate(input: input, parameters: params) + for try await event in result { + if let chunk = event.chunk { + let escaped = chunk.replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + let sseData = "{\"id\":\"\(requestId)\",\"object\":\"text_completion\",\"choices\":[{\"index\":0,\"text\":\"\(escaped)\",\"finish_reason\":null}]}" + let sse = "data: \(sseData)\n\n" + _ = sse.withCString { write(fd, $0, Int(strlen($0))) } + } + if event.info != nil { + let sseData = "{\"id\":\"\(requestId)\",\"object\":\"text_completion\",\"choices\":[{\"index\":0,\"text\":\"\",\"finish_reason\":\"stop\"}]}" + let sse = "data: \(sseData)\n\ndata: [DONE]\n\n" + _ = sse.withCString { write(fd, $0, Int(strlen($0))) } + } + } + } else { + var fullText = "" + let result = try await container.generate(input: input, parameters: params) + var usage: (prompt: Int, completion: Int) = (tokens.count, 0) + for try await event in result { + if let chunk = event.chunk { fullText += chunk; usage.completion += 1 } + } + let escaped = fullText.replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + let body = "{\"id\":\"\(requestId)\",\"object\":\"text_completion\",\"model\":\"\(modelId)\",\"choices\":[{\"index\":0,\"text\":\"\(escaped)\",\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":\(usage.prompt),\"completion_tokens\":\(usage.completion),\"total_tokens\":\(usage.prompt + usage.completion)}}" + sendResponse(fd: fd, status: 200, body: body, contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + } + } catch { + let errMsg = String(describing: error).replacingOccurrences(of: "\"", with: "'") + sendResponse(fd: fd, status: 500, body: "{\"error\":{\"message\":\"\(errMsg)\",\"type\":\"server_error\",\"code\":500}}", contentType: "application/json; charset=utf-8", corsOrigin: corsOrigin) + } + } + + // MARK: - Tool Call Parsing + + /// Parse ALL tool calls from text. Supports MiniMax XML, generic XML, and formats. + func parseAllToolCalls(_ text: String) -> [(name: String, arguments: String)] { + let minimax = parseAllMiniMaxToolCalls(text) + if !minimax.isEmpty { return minimax } + if let tc = parseToolCallXML(text) { return [tc] } + return [] + } + + /// Parse generic XML tool call: `value` + func parseToolCallXML(_ text: String) -> (name: String, arguments: String)? { + // Try MiniMax format first + let all = parseAllMiniMaxToolCalls(text) + if let first = all.first { return first } + + guard let funcStart = text.range(of: "", range: funcStart.upperBound..", range: paramStart.upperBound..", range: pNameEnd.upperBound..` blocks from MiniMax tool call XML (supports multiple tools per response). + func parseAllMiniMaxToolCalls(_ text: String) -> [(name: String, arguments: String)] { + guard text.contains("", range: invokeStart.upperBound.. but no ") else { break } + let paramName = String(afterParam[afterParam.startIndex..", range: valueStart.....` block. + func parseSingleMiniMaxInvoke(_ text: String) -> (name: String, arguments: String)? { + guard let invokeStart = text.range(of: "") else { break } + let paramName = String(afterParam[afterParam.startIndex..", range: valueStart.. String { + s.replacingOccurrences(of: "\\", with: "\\\\") + .replacingOccurrences(of: "\"", with: "\\\"") + .replacingOccurrences(of: "\n", with: "\\n") + .replacingOccurrences(of: "\r", with: "\\r") + } + var parts: [String] = [] + if let role = role { parts.append("\"role\":\"\(escape(role))\"") } + if let content = content { + parts.append("\"content\":\"\(escape(content))\"") + } else if includeNullContent { + parts.append("\"content\":null") + } + if let rc = reasoningContent { parts.append("\"reasoning_content\":\"\(escape(rc))\"") } + let deltaJson = "{\(parts.joined(separator: ","))}" + + let fr = finishReason.map { "\"\($0)\"" } ?? "null" + let responseModel = requestModel ?? modelId + let event = "data: {\"id\":\"\(requestId)\",\"object\":\"chat.completion.chunk\",\"created\":\(Int(Date().timeIntervalSince1970)),\"model\":\"\(responseModel)\",\"system_fingerprint\":\"mlx-swift-v1\",\"choices\":[{\"index\":0,\"delta\":\(deltaJson),\"finish_reason\":\(fr)}]}\n\n" + _ = event.withCString { write(fd, $0, Int(strlen($0))) } + } + + func sendResponse(fd: Int32, status: Int, body: String, contentType: String, extraHeaders: String = "", corsOrigin: String = "*") { + let statusText: String + switch status { + case 200: statusText = "OK" + case 204: statusText = "No Content" + case 400: statusText = "Bad Request" + case 413: statusText = "Payload Too Large" + case 404: statusText = "Not Found" + case 500: statusText = "Internal Server Error" + case 503: statusText = "Service Unavailable" + default: statusText = "Unknown" + } + let response = "HTTP/1.1 \(status) \(statusText)\r\nContent-Type: \(contentType)\r\nContent-Length: \(body.utf8.count)\r\nAccess-Control-Allow-Origin: \(corsOrigin)\r\nAccess-Control-Allow-Credentials: true\r\n\(extraHeaders)\r\n\(body)" + _ = response.withCString { write(fd, $0, Int(strlen($0))) } + } + + enum ServerError: Error { + case socketCreation, bind(UInt16), listen + } +} + +// MARK: - Entry Point + +@main +struct MLXServerApp { + @MainActor + static func main() async throws { + // Ignore SIGPIPE — client disconnects during streaming should not crash + signal(SIGPIPE, SIG_IGN) + + let args = CommandLine.arguments + let model = args.firstIndex(of: "--model").flatMap { i in + i + 1 < args.count ? args[i + 1] : nil + } ?? "mlx-community/gemma-4-e2b-it-4bit" + + let port = args.firstIndex(of: "--port").flatMap { i in + i + 1 < args.count ? UInt16(args[i + 1]) : nil + } ?? 8080 + + let slots = args.firstIndex(of: "--slots").flatMap { i in + i + 1 < args.count ? Int(args[i + 1]) : nil + } ?? 4 + + let kvScheme = args.firstIndex(of: "--kv").flatMap { i in + i + 1 < args.count ? args[i + 1] : nil + } + + log("Loading model: \(model)") + let config: ModelConfiguration + if model.hasPrefix("/") || model.hasPrefix("~") || model.hasPrefix(".") { + let expandedPath = NSString(string: model).expandingTildeInPath + config = ModelConfiguration(directory: URL(fileURLWithPath: expandedPath)) + } else { + config = ModelConfiguration(id: model) + } + + // Load model + let downloader: any Downloader = #hubDownloader() + let tokenizerLoader: any TokenizerLoader = #huggingFaceTokenizerLoader() + let container: ModelContainer + do { + container = try await LLMModelFactory.shared.loadContainer( + from: downloader, using: tokenizerLoader, + configuration: config) { p in + if p.fractionCompleted > 0.99 { log("Model loaded (LLM)") } + } + } catch { + log("LLM load failed, trying VLM...") + container = try await VLMModelFactory.shared.loadContainer( + from: downloader, using: tokenizerLoader, + configuration: config) { p in + if p.fractionCompleted > 0.99 { log("Model loaded (VLM)") } + } + } + + let server = SimpleHTTPServer(port: port, container: container, modelId: model, slotCount: slots, kvScheme: kvScheme) + if let kv = kvScheme { log("KV scheme: \(kv)") } + try server.start() + } +} diff --git a/Sources/NativePrefillBridge/generic_prefill.cpp b/Sources/NativePrefillBridge/generic_prefill.cpp new file mode 100644 index 0000000000..1765f55f45 --- /dev/null +++ b/Sources/NativePrefillBridge/generic_prefill.cpp @@ -0,0 +1,1459 @@ +// generic_prefill.cpp — Model-agnostic native prefill bridge +// +// Shared infrastructure for any MLX model. Model-specific layer forward +// passes are dispatched by model_type. Currently supports: +// - gemma4_text (Gemma 4 E2B/A4B with shared KV, PLE, sliding/full attention) +// - minimax_m2 (MiniMax M2.7 with 256-expert SwitchGLU MoE) +// +// Adding a new model: implement a LayerForward function and register it. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/mlx.h" +#include "generic_prefill.h" + +using namespace mlx::core; + +// ============================================================================ +// Reliable observer — NEVER use raw sum(abs(x)) on float16. +// MLX's float16 reduction kernel produces wrong results for large arrays. +// ============================================================================ + +static float safe_abssum(const array& a) { + // Cast to float32 before reducing to avoid float16 reduction bug + auto f32 = astype(a, float32); + auto result = sum(abs(f32)); + eval({result}); + return result.item(); +} + +// CPU-side checksum: read first N float16 elements, hash them +static uint64_t cpu_hash(const array& a, int n = 256) { + auto* raw = static_cast( + const_cast(a.buffer()).raw_ptr()); + uint64_t h = 0; + for (int i = 0; i < std::min(n, (int)a.size()); i++) { + h = h * 31 + raw[i]; + } + return h; +} + +// ============================================================================ +// Shared primitives +// ============================================================================ + +static constexpr float DEFAULT_RMS_EPS = 1e-6f; + +struct QuantizedLinear { + std::optional weight; + std::optional scales; + std::optional biases; // quantization biases + std::optional linear_bias; // linear layer bias (e.g., Qwen2 attention) + int group_size = 64; + int bits = 4; + bool quantized = true; + + array operator()(const array& x) const { + if (quantized) { + auto out = quantized_matmul(x, *weight, *scales, *biases, + true, group_size, bits, "affine"); + if (linear_bias) out = out + *linear_bias; + return out; + } else { + auto out = matmul(x, transpose(*weight)); + if (linear_bias) out = out + *linear_bias; + return out; + } + } +}; + +struct Norm { + std::optional weight; + float eps = 1e-6f; + + array operator()(const array& x) const { + if (weight) return fast::rms_norm(x, *weight, eps); + return fast::rms_norm(x, std::nullopt, eps); + } +}; + +struct Embedding { + std::optional weight; + std::optional scales; + std::optional biases; + int group_size = 64; + int bits = 4; + bool quantized = false; + + array operator()(const array& indices) const { + if (quantized) { + auto w = take(*weight, indices, 0); + auto s = take(*scales, indices, 0); + auto b = take(*biases, indices, 0); + return dequantize(w, s, b, group_size, bits, "affine"); + } + return take(*weight, indices, 0); + } +}; + +// ============================================================================ +// Model config — parsed from JSON +// ============================================================================ + +struct ModelConfig { + std::string model_type; + int hidden_size = 0; + int num_layers = 0; + int num_heads = 0; + int num_kv_heads = 0; + int head_dim = 0; + int intermediate_size = 0; + int vocab_size = 0; + float rms_norm_eps = 1e-6f; + float rope_theta = 10000.0f; + int rotary_dim = 0; // 0 = full head_dim + bool tie_word_embeddings = false; + bool use_qk_norm = false; + + // MoE params + int num_local_experts = 0; + int num_experts_per_tok = 0; + std::string scoring_func = "softmax"; + + // Gemma4 params + int sliding_window = 0; + int sliding_pattern = 0; + int num_kv_shared_layers = 0; + int hidden_per_layer = 0; + int total_layers = 0; + float partial_rotary_factor = 1.0f; + float global_rope_theta = 1000000.0f; + int global_head_dim = 0; + + // YaRN RoPE params + std::string rope_type = ""; // "", "yarn", "linear", "llama3" + float yarn_factor = 1.0f; + float yarn_beta_fast = 32.0f; + float yarn_beta_slow = 1.0f; + int yarn_original_max_pos = 4096; + float yarn_mscale = 1.0f; + float yarn_mscale_all_dim = 0.0f; + + // Quantization + int quant_bits = 4; + int quant_group_size = 64; + + bool is_moe() const { return num_local_experts > 0; } +}; + +// ============================================================================ +// KV Cache (same as decode bridge) +// ============================================================================ + +struct KVCache { + std::optional keys; + std::optional values; + int offset = 0; + + bool has_data() const { return keys.has_value(); } + + void append(const array& k, const array& v, int seq_len) { + if (keys) { + keys = concatenate({*keys, k}, 2); + values = concatenate({*values, v}, 2); + } else { + keys = k; + values = v; + } + offset += seq_len; + } + + void reset() { + keys.reset(); + values.reset(); + offset = 0; + } +}; + +// ============================================================================ +// YaRN RoPE frequency computation +// ============================================================================ + +// Compute YaRN-corrected RoPE frequencies. +// Returns: [dims/2] frequency tensor suitable for fast::rope(..., freqs) +// Also returns the mscale factor to apply to Q/K before RoPE. +static std::pair compute_yarn_freqs( + int dims, float base, float factor, + int original_max_pos, float beta_fast, float beta_slow, + float mscale_val, float mscale_all_dim) { + + // yarnFindCorrectionDim: find the dimension index for a given rotation count + auto find_correction_dim = [&](float num_rotations) -> float { + return (float)dims + * std::log((float)original_max_pos / (num_rotations * 2.0f * M_PI)) + / (2.0f * std::log(base)); + }; + + // yarnFindCorrectionRange + int low = std::max(0, (int)std::floor(find_correction_dim(beta_fast))); + int high = std::min(dims - 1, (int)std::ceil(find_correction_dim(beta_slow))); + + // yarnGetMscale + auto get_mscale = [](float scale, float ms) -> float { + if (scale <= 1.0f) return 1.0f; + return 0.1f * ms * std::log(scale) + 1.0f; + }; + + float mscale = get_mscale(factor, mscale_val) / get_mscale(factor, mscale_all_dim); + + // Compute base frequencies: base^(i / dims) for i in [0, 2, 4, ..., dims-2] + int half = dims / 2; + auto indices = astype(arange(0, dims, 2), float32); + auto base_freqs = power(array(base, float32), indices / (float)dims); + + // freqExtra = base_freqs (unscaled) + // freqInter = factor * base_freqs (interpolated) + auto freq_extra = base_freqs; + auto freq_inter = array(factor, float32) * base_freqs; + + // yarnLinearRampMask: linear interpolation mask between low and high + float max_val = (low == high) ? (float)high + 0.001f : (float)high; + auto ramp = (astype(arange(0, half), float32) - (float)low) / (max_val - (float)low); + ramp = clip(ramp, array(0.0f), array(1.0f)); + auto freq_mask = array(1.0f, float32) - ramp; + + // Final frequency combination (matches Swift exactly): + // freqs = (freqInter * freqExtra) / (freqInter * freqMask + freqExtra * (1 - freqMask)) + auto freqs = (freq_inter * freq_extra) + / (freq_inter * freq_mask + freq_extra * (array(1.0f, float32) - freq_mask)); + + eval({freqs}); + return {freqs, mscale}; +} + +// ============================================================================ +// Generic attention (works for all models) +// ============================================================================ + +static array generic_attention( + const array& x, + const QuantizedLinear& q_proj, + const QuantizedLinear& k_proj, + const QuantizedLinear& v_proj, + const QuantizedLinear& o_proj, + const Norm* q_norm, + const Norm* k_norm, + int num_heads, int num_kv_heads, int head_dim, + bool qk_norm_before_reshape, // MiniMax: true, Gemma4: false + float rope_theta, int rotary_dim, + const array* rope_freqs, // for proportional RoPE (Gemma4 full layers) + KVCache& cache, + int rope_offset = 0, // position offset for chunked prefill + float custom_scale = 0.0f, // 0 = use 1/sqrt(head_dim) + float yarn_mscale = 1.0f, // YaRN mscale for Q/K before RoPE + const std::optional& sinks = {} // attention sinks (GPT-OSS) +) { + int B = x.shape(0); + int S = x.shape(1); + + + auto q = q_proj(x); + auto k = k_proj(x); + auto v = v_proj(x); + + if (q_norm && qk_norm_before_reshape) { + q = (*q_norm)(q); k = (*k_norm)(k); + } + + q = transpose(reshape(q, {B, S, num_heads, head_dim}), {0, 2, 1, 3}); + k = transpose(reshape(k, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + v = transpose(reshape(v, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + + if (q_norm && !qk_norm_before_reshape) { + q = (*q_norm)(q); k = (*k_norm)(k); + } + + if (yarn_mscale != 1.0f) { + q = q * array(yarn_mscale, q.dtype()); + k = k * array(yarn_mscale, k.dtype()); + } + + + int actual_rotary = rotary_dim > 0 ? rotary_dim : head_dim; + if (rope_freqs && rope_freqs->ndim() == 1) { + q = fast::rope(q, head_dim, false, std::nullopt, 1.0f, rope_offset, *rope_freqs); + k = fast::rope(k, head_dim, false, std::nullopt, 1.0f, rope_offset, *rope_freqs); + } else { + q = fast::rope(q, actual_rotary, false, rope_theta, 1.0f, rope_offset); + k = fast::rope(k, actual_rotary, false, rope_theta, 1.0f, rope_offset); + } + + auto kv_dtype = k_proj.scales ? k_proj.scales->dtype() : float16; + k = astype(k, kv_dtype); + v = astype(v, kv_dtype); + + cache.append(k, v, S); + + float scale = custom_scale > 0.0f ? custom_scale + : 1.0f / std::sqrt(static_cast(head_dim)); + + auto attn = fast::scaled_dot_product_attention( + q, *cache.keys, *cache.values, scale, "causal", std::nullopt, sinks); + + attn = reshape(transpose(attn, {0, 2, 1, 3}), {B, S, num_heads * head_dim}); + + auto out = o_proj(attn); + + return out; +} + +// ============================================================================ +// MoE routing (MiniMax: sigmoid + top-k + correction bias) +// ============================================================================ + +static array moe_forward( + const array& x, + const QuantizedLinear& gate, + const array& correction_bias, + // SwitchGLU expert weights: [num_experts, hidden, dim] stacked + const array& gate_proj_w, const array& gate_proj_s, const std::optional& gate_proj_b, + const array& up_proj_w, const array& up_proj_s, const std::optional& up_proj_b, + const array& down_proj_w, const array& down_proj_s, const std::optional& down_proj_b, + int num_experts_per_tok, + int group_size, + int gate_bits, int up_bits, int down_bits, + const std::string& scoring_func +) { + // Route: compute gate scores and select top-k experts + auto gates = gate(astype(x, float32)); + array scores = array(0.0f); + if (scoring_func == "sigmoid") { + scores = sigmoid(gates); + } else { + scores = softmax(gates, -1); + } + + int k = num_experts_per_tok; + // Select top-k experts. Use raw gates for argpartition (monotonic with softmax) + // to match Swift's implementation and avoid unnecessary negative(softmax) copies. + // For sigmoid routing with correction_bias (MiniMax), apply bias before selection. + array sort_keys = array(0.0f); + if (scoring_func == "sigmoid" && correction_bias.size() > 1) { + sort_keys = negative(scores + correction_bias); + } else { + sort_keys = negative(gates); // Match Swift: argPartition(-gates) + } + auto inds = argpartition(sort_keys, k - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), k}); + auto sel_scores = take_along_axis(scores, inds, -1); + + // Normalize + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, x.dtype()); + + // SwitchGLU via gather_qmm with expert-sorted dispatch + // Sorting tokens by expert index improves GPU cache locality (38-48% at T≥1024) + auto B = x.shape(0); + auto S = x.shape(1); + + // Sort by expert for cache-friendly dispatch (matches Swift's SwitchGLU) + bool do_sort = true; // always sort — expert locality is always beneficial + + auto x_exp = expand_dims(x, {-2, -3}); // [B, S, 1, 1, D] + array use_x = x_exp; + array use_inds = inds; + array inv_order = array(0); + + if (do_sort) { + // Flatten indices [B, S, K] → [B*S*K] + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + inv_order = argsort(order); + + // Reorder x: flatten to [B*S, 1, 1, D], gather by order/K + auto x_flat = flatten(x_exp, 0, 1); // [B*S, 1, 1, D] + auto token_idx = astype(order / array(k), uint32); // which token each slot maps to + use_x = take(x_flat, token_idx, 0); // [B*S*K, 1, 1, D] + use_inds = reshape(take(flat_inds, order, 0), {-1, 1}); // [B*S*K, 1] sorted + } + + // Detect quantization mode from biases presence and scales dtype + // affine: has biases (float16/bfloat16 scales) + // mxfp4: no biases (uint8 scales) + auto detect_mode = [](const std::optional& b, const array& s) -> std::string { + if (!b || b->size() <= 1) { + // No biases — check scales dtype for MXFP variants + if (s.dtype() == uint8) return "mxfp4"; + return "affine"; // fallback + } + return "affine"; + }; + + auto gate_out = gather_qmm( + use_x, gate_proj_w, gate_proj_s, gate_proj_b, + std::nullopt, use_inds, + true, group_size, gate_bits, detect_mode(gate_proj_b, gate_proj_s), do_sort); + + auto up_out = gather_qmm( + use_x, up_proj_w, up_proj_s, up_proj_b, + std::nullopt, use_inds, + true, group_size, up_bits, detect_mode(up_proj_b, up_proj_s), do_sort); + + // SiLU activation on gate, multiply with up + auto hidden_act = (gate_out * sigmoid(gate_out)) * up_out; + + auto down_out = gather_qmm( + hidden_act, down_proj_w, down_proj_s, down_proj_b, + std::nullopt, use_inds, + true, group_size, down_bits, detect_mode(down_proj_b, down_proj_s), do_sort); + + // Squeeze extra dim from gather_qmm output + down_out = squeeze(down_out, {-2}); // [N, D] where N=B*S*K (sorted) or [B,S,K,D] + + if (do_sort) { + // Unsort back to original token order and reshape + down_out = take(down_out, inv_order, 0); // [B*S*K, D] + down_out = reshape(down_out, {B, S, k, -1}); // [B, S, K, D] + } + + auto y = sum(down_out * expand_dims(sel_scores, -1), -2); + + return y; +} + +// ============================================================================ +// Standard MLP (GeGLU for Gemma4, SiLU+gate for others) +// ============================================================================ + +static array gelu_approx(const array& x) { + auto dt = x.dtype(); + auto x3 = power(x, array(3, dt)); + auto inner = array(0.7978845608028654f, dt) * (x + array(0.044715f, dt) * x3); + return array(0.5f, dt) * x * (array(1.0f, dt) + tanh(inner)); +} + +static array mlp_forward( + const array& x, + const QuantizedLinear& gate_proj, + const QuantizedLinear& up_proj, + const QuantizedLinear& down_proj, + const std::string& activation = "silu" +) { + auto gate = gate_proj(x); + auto up = up_proj(x); + if (activation == "gelu") { + return down_proj(gelu_approx(gate) * up); + } + return down_proj((gate * sigmoid(gate)) * up); +} + +// ============================================================================ +// Generic layer +// ============================================================================ + +struct MoEWeights { + QuantizedLinear gate; + std::optional correction_bias; + std::optional switch_gate_w, switch_gate_s, switch_gate_b; + std::optional switch_up_w, switch_up_s, switch_up_b; + std::optional switch_down_w, switch_down_s, switch_down_b; + int num_experts_per_tok = 0; + int gate_bits = 4; + int up_bits = 4; + int down_bits = 4; + std::string scoring_func = "softmax"; +}; + +struct PLEWeights { + QuantizedLinear gate, proj; + Norm post_norm; + std::optional layer_scalar; +}; + +struct Layer { + Norm input_norm; + Norm post_attn_norm; + + // Attention + QuantizedLinear q_proj, k_proj, v_proj, o_proj; + Norm q_norm, k_norm; + bool has_qk_norm = false; + bool qk_norm_before_reshape = false; + float rope_theta = 10000.0f; + int rotary_dim = 0; + std::optional rope_freqs; + + // Custom attention scale (Gemma3 uses queryPreAttnScalar^(-0.5)) + float attn_scale = 0.0f; // 0 = use default 1/sqrt(head_dim) + + // YaRN mscale: applied to Q/K before RoPE (1.0 = no scaling) + float yarn_mscale = 1.0f; + + // Attention sinks (GPT-OSS) + std::optional sinks; + + // MLP (standard dense path) + QuantizedLinear gate_proj, up_proj, down_proj; + std::string mlp_activation = "silu"; // "silu" or "gelu" + + // Gemma3 extra norms (pre/post feedforward) + Norm pre_ff_norm, post_ff_norm; + bool has_gemma3_norms = false; + bool is_sliding = false; // sliding window attention layer + + // MoE (only allocated for MoE models) + bool is_moe = false; + std::optional moe; + + // Gemma4 PLE (only allocated for Gemma4) + bool has_ple = false; + std::optional ple; + + int num_heads = 0, num_kv_heads = 0, head_dim = 0; + int group_size = 64, bits = 4; + + KVCache cache; +}; + +// ============================================================================ +// Model +// ============================================================================ + +struct GenericModel { + ModelConfig config; + Embedding embed_tokens; + std::vector layers; + Norm final_norm; + + // Gemma4 PLE + Embedding embed_per_layer; + QuantizedLinear per_layer_projection; + Norm per_layer_projection_norm; + bool has_ple = false; + float embed_scale = 1.0f; + float pl_embed_scale = 1.0f; + float pl_input_scale = 0.707f; + + static constexpr int CHUNK_SIZE = 4096; + + // Eval barrier cadence: every EVAL_CADENCE layers to prevent + // lazy-graph pressure from reclaiming weight Metal buffers. + static constexpr int EVAL_CADENCE = 8; + + + array forward(const array& token_ids) { + int B = token_ids.shape(0); + int S = token_ids.shape(1); + + auto all_h = embed_tokens(token_ids); + if (embed_scale != 1.0f) { + all_h = all_h * array(embed_scale, all_h.dtype()); + } + + // Gemma4 PLE setup (over full sequence) + array combined_per_layer = array(0.0f); + if (has_ple) { + auto pli = embed_per_layer(token_ids) * array(pl_embed_scale, bfloat16); + pli = reshape(pli, {B, S, config.total_layers, config.hidden_per_layer}); + auto plp = per_layer_projection(all_h); + plp = reshape(plp, {B, S, config.total_layers, config.hidden_per_layer}); + plp = per_layer_projection_norm(plp); + combined_per_layer = (plp + pli) * array(pl_input_scale, bfloat16); + } + + int num_chunks = (S + CHUNK_SIZE - 1) / CHUNK_SIZE; + array h = array(0.0f); + + for (int c = 0; c < num_chunks; c++) { + int chunk_start = c * CHUNK_SIZE; + int chunk_end = std::min(chunk_start + CHUNK_SIZE, S); + int chunk_len = chunk_end - chunk_start; + + h = slice(all_h, {0, chunk_start, 0}, {B, chunk_end, config.hidden_size}); + + + for (int i = 0; i < (int)layers.size(); i++) { + auto& layer = layers[i]; + auto residual = h; + + auto normed = layer.input_norm(h); + + auto attn_out = generic_attention( + normed, + layer.q_proj, layer.k_proj, layer.v_proj, layer.o_proj, + layer.has_qk_norm ? &layer.q_norm : nullptr, + layer.has_qk_norm ? &layer.k_norm : nullptr, + layer.num_heads, layer.num_kv_heads, layer.head_dim, + layer.qk_norm_before_reshape, + layer.rope_theta, layer.rotary_dim, + layer.rope_freqs && layer.rope_freqs->ndim() == 1 ? &*layer.rope_freqs : nullptr, + layer.cache, + chunk_start, + layer.attn_scale, + layer.yarn_mscale, + layer.sinks + ); + + if (layer.has_gemma3_norms) { + // Gemma3: post_attn_norm on attention output, then add residual + h = residual + layer.post_attn_norm(attn_out); + } else { + h = residual + attn_out; + } + + + residual = h; + if (layer.is_moe) { + auto normed_ff = layer.post_attn_norm(h); + h = residual + moe_forward( + normed_ff, layer.moe->gate, *layer.moe->correction_bias, + *layer.moe->switch_gate_w, *layer.moe->switch_gate_s, layer.moe->switch_gate_b, + *layer.moe->switch_up_w, *layer.moe->switch_up_s, layer.moe->switch_up_b, + *layer.moe->switch_down_w, *layer.moe->switch_down_s, layer.moe->switch_down_b, + layer.moe->num_experts_per_tok, layer.group_size, + layer.moe->gate_bits, layer.moe->up_bits, layer.moe->down_bits, + layer.moe->scoring_func + ); + } else if (layer.has_gemma3_norms) { + // Gemma3: pre_ff_norm → MLP → post_ff_norm → add residual + auto pre_ff = layer.pre_ff_norm(h); + auto mlp_out = mlp_forward(pre_ff, layer.gate_proj, layer.up_proj, layer.down_proj, layer.mlp_activation); + h = residual + layer.post_ff_norm(mlp_out); + } else { + auto normed_ff = layer.post_attn_norm(h); + h = residual + mlp_forward(normed_ff, layer.gate_proj, layer.up_proj, layer.down_proj, layer.mlp_activation); + } + + // PLE (Gemma4) + if (layer.has_ple) { + residual = h; + auto pli = slice(combined_per_layer, + {0, chunk_start, i, 0}, {B, chunk_end, i + 1, config.hidden_per_layer}); + pli = reshape(pli, {B, chunk_len, config.hidden_per_layer}); + auto gate = layer.ple->gate(h); + gate = gelu_approx(gate) * pli; + gate = layer.ple->proj(gate); + gate = layer.ple->post_norm(gate); + h = residual + gate; + h = h * *layer.ple->layer_scalar; + } + + if (c == 0 && (i == 0 || i == (int)layers.size() - 1)) { + char buf[64]; + snprintf(buf, sizeof(buf), "L%d post_layer", i); + } + + // Periodic eval barrier to prevent lazy-graph pressure + // from reclaiming weight Metal buffers. + // Include embedding weight/scales/biases to keep them pinned. + if ((i + 1) % EVAL_CADENCE == 0 || i == (int)layers.size() - 1) { + std::vector to_sync = {h}; + if (layer.cache.has_data()) { + to_sync.push_back(*layer.cache.keys); + to_sync.push_back(*layer.cache.values); + } + if (embed_tokens.weight) to_sync.push_back(*embed_tokens.weight); + if (embed_tokens.scales) to_sync.push_back(*embed_tokens.scales); + if (embed_tokens.biases) to_sync.push_back(*embed_tokens.biases); + eval(to_sync); + } + } + + // Final chunk eval — sync all KV caches + std::vector to_eval = {h}; + for (auto& layer : layers) { + if (layer.cache.has_data()) { + to_eval.push_back(*layer.cache.keys); + to_eval.push_back(*layer.cache.values); + } + } + eval(to_eval); + + if (num_chunks > 1) { + } + } + + auto out = final_norm(h); + return out; + } +}; + +// ============================================================================ +// Global state +// ============================================================================ + +static std::unique_ptr g_model; +static std::unordered_map g_weights; +static ModelConfig g_config; +static bool g_initialized = false; +static bool g_finalized = false; + +// ============================================================================ +// Weight helpers +// ============================================================================ + +static array extract_array(void* ptr) { + return *static_cast(ptr); +} + +static array get_w(const std::string& key) { + auto it = g_weights.find(key); + if (it == g_weights.end()) throw std::runtime_error("Missing weight: " + key); + return it->second; +} + +static bool has_w(const std::string& key) { + return g_weights.count(key) > 0; +} + +// Split a fused [N, D] quantized weight into two halves along dim 0 +// Used for fused qkv_proj → q_proj + kv_proj, or gate_up_proj → gate + up +// Returns two QuantizedLinears via out params to avoid std::pair construction issues +static void split_fused_qlinear(QuantizedLinear& out1, QuantizedLinear& out2, + const std::string& prefix, int split_at, int gs = 0, int b = 0) { + if (gs == 0) gs = g_config.quant_group_size; + auto w = get_w(prefix + ".weight"); + auto s = get_w(prefix + ".scales"); + // Quantization biases are optional (not present in symmetric/MXFP quant) + bool has_qbiases = has_w(prefix + ".biases"); + array bi = has_qbiases ? get_w(prefix + ".biases") : array(0.0f); + int w_last = w.shape(-1); + int s_last = s.shape(-1); + if (s_last > 0 && b == 0) { + int ratio = w_last / s_last; + b = ratio * 32 / gs; + } + if (b == 0) b = g_config.quant_bits; + + // split_at is in OUTPUT dimension (dim 0 of weight) + // For quantized weights, the packed dim is dim 1, so we split dim 0 + int scale_split = split_at / gs; // scales have output_dim / group_size cols... no + // Actually for quantized: weight=[out, packed_in], scales=[out, groups] + // Split along dim 0 (output dimension) + auto w1 = slice(w, {0, 0}, {split_at, w.shape(1)}); + auto w2 = slice(w, {split_at, 0}, {w.shape(0), w.shape(1)}); + auto s1 = slice(s, {0, 0}, {split_at, s.shape(1)}); + auto s2 = slice(s, {split_at, 0}, {s.shape(0), s.shape(1)}); + + // Split quantization biases if present + std::optional b1_opt, b2_opt; + if (has_qbiases) { + b1_opt = slice(bi, {0, 0}, {split_at, bi.shape(1)}); + b2_opt = slice(bi, {split_at, 0}, {bi.shape(0), bi.shape(1)}); + } + + // Split linear bias if present + std::optional lb1, lb2; + if (has_w(prefix + ".bias")) { + auto lbias = get_w(prefix + ".bias"); + lb1 = slice(lbias, {0}, {split_at}); + lb2 = slice(lbias, {split_at}, {lbias.shape(0)}); + } + + out1.weight = w1; out1.scales = s1; out1.biases = b1_opt.value_or(array(0.0f)); + out1.linear_bias = lb1; out1.group_size = gs; out1.bits = b; out1.quantized = true; + out2.weight = w2; out2.scales = s2; out2.biases = b2_opt.value_or(array(0.0f)); + out2.linear_bias = lb2; out2.group_size = gs; out2.bits = b; out2.quantized = true; +} + +static QuantizedLinear make_qlinear(const std::string& prefix, int gs = 0, int b = 0) { + if (gs == 0) gs = g_config.quant_group_size; + // Check if weight is quantized (has scales) + if (has_w(prefix + ".scales")) { + auto w = get_w(prefix + ".weight"); + auto s = get_w(prefix + ".scales"); + auto bi = get_w(prefix + ".biases"); + // Auto-detect bits from weight/scales shape ratio + // ratio = weight.shape(-1) / scales.shape(-1) = bits * group_size / 32 + int w_last = w.shape(-1); + int s_last = s.shape(-1); + if (s_last > 0 && b == 0) { + int ratio = w_last / s_last; + b = ratio * 32 / gs; // bits = ratio * 32 / group_size + } + if (b == 0) b = g_config.quant_bits; + // Check for linear bias (e.g., Qwen2 attention has bias: true) + std::optional lb; + if (has_w(prefix + ".bias")) { + lb = get_w(prefix + ".bias"); + } + return {w, s, bi, lb, gs, b, true}; + } + // Unquantized linear + if (b == 0) b = g_config.quant_bits; + std::optional lb; + if (has_w(prefix + ".bias")) lb = get_w(prefix + ".bias"); + return {get_w(prefix + ".weight"), array(0.0f), array(0.0f), lb, gs, b, false}; +} + +static int detect_bits(const std::string& weight_key, const std::string& scales_key, int gs = 64) { + if (!has_w(weight_key) || !has_w(scales_key)) return g_config.quant_bits; + auto w = get_w(weight_key); + auto s = get_w(scales_key); + int w_last = w.shape(-1); + int s_last = s.shape(-1); + if (s_last <= 0) return g_config.quant_bits; + return (w_last * 32) / (s_last * gs); +} + +static Norm make_norm(const std::string& prefix) { + return {get_w(prefix + ".weight"), g_config.rms_norm_eps}; +} + +static Embedding make_embedding(const std::string& prefix) { + bool q = has_w(prefix + ".scales"); + Embedding emb; + // Use direct weight reference. Swift already evaluated these arrays, + // so they have pinned GPU buffers. The add-zero copy is unnecessary. + emb.weight = get_w(prefix + ".weight"); + eval({*emb.weight}); + if (q) { + emb.scales = get_w(prefix + ".scales"); + emb.biases = get_w(prefix + ".biases"); + eval({*emb.scales, *emb.biases}); + emb.group_size = g_config.quant_group_size; + emb.bits = detect_bits(prefix + ".weight", prefix + ".scales", g_config.quant_group_size); + emb.quantized = true; + } + return emb; +} + +// ============================================================================ +// Config parsing (minimal JSON — just extract what we need) +// ============================================================================ + +static std::string json_string(const std::string& json, const std::string& key) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return ""; + pos = json.find(":", pos); + auto start = json.find("\"", pos + 1); + auto end = json.find("\"", start + 1); + return json.substr(start + 1, end - start - 1); +} + +static int json_int(const std::string& json, const std::string& key, int def = 0) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return def; + pos = json.find(":", pos); + auto start = json.find_first_of("-0123456789", pos + 1); + auto end = json.find_first_not_of("-0123456789", start); + return std::stoi(json.substr(start, end - start)); +} + +static float json_float(const std::string& json, const std::string& key, float def = 0) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return def; + pos = json.find(":", pos); + auto start = json.find_first_of("-0123456789.", pos + 1); + auto end = json.find_first_not_of("-0123456789.eE+-", start); + return std::stof(json.substr(start, end - start)); +} + +static bool json_bool(const std::string& json, const std::string& key, bool def = false) { + auto pos = json.find("\"" + key + "\""); + if (pos == std::string::npos) return def; + pos = json.find(":", pos); + auto val_start = json.find_first_not_of(" \t\n", pos + 1); + return json.substr(val_start, 4) == "true"; +} + +// ============================================================================ +// Build model from config + weights +// ============================================================================ + +static void build_minimax_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = true; // MiniMax: norm before reshape + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + // Auto-detect per-layer attention bits from weight shapes + layer.bits = layer.q_proj.bits; + + // MoE + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".block_sparse_moe.gate"); + layer.moe->correction_bias = get_w(p + ".block_sparse_moe.e_score_correction_bias"); + layer.moe->switch_gate_w = get_w(p + ".block_sparse_moe.switch_mlp.gate_proj.weight"); + layer.moe->switch_gate_s = get_w(p + ".block_sparse_moe.switch_mlp.gate_proj.scales"); + layer.moe->switch_gate_b = get_w(p + ".block_sparse_moe.switch_mlp.gate_proj.biases"); + layer.moe->switch_up_w = get_w(p + ".block_sparse_moe.switch_mlp.up_proj.weight"); + layer.moe->switch_up_s = get_w(p + ".block_sparse_moe.switch_mlp.up_proj.scales"); + layer.moe->switch_up_b = get_w(p + ".block_sparse_moe.switch_mlp.up_proj.biases"); + layer.moe->switch_down_w = get_w(p + ".block_sparse_moe.switch_mlp.down_proj.weight"); + layer.moe->switch_down_s = get_w(p + ".block_sparse_moe.switch_mlp.down_proj.scales"); + layer.moe->switch_down_b = get_w(p + ".block_sparse_moe.switch_mlp.down_proj.biases"); + // Auto-detect per-layer MoE bits from weight shapes + std::string moe_p = p + ".block_sparse_moe.switch_mlp"; + layer.moe->gate_bits = detect_bits(moe_p + ".gate_proj.weight", moe_p + ".gate_proj.scales"); + layer.moe->up_bits = detect_bits(moe_p + ".up_proj.weight", moe_p + ".up_proj.scales"); + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + layer.moe->scoring_func = g_config.scoring_func; +} + +static void build_qwen3_moe_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = false; // Qwen3: norm AFTER reshape (per-head) + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // MoE -- Qwen3 uses mlp.gate and mlp.switch_mlp (not block_sparse_moe) + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".mlp.gate"); + // Qwen3 uses softmax routing, no correction_bias + layer.moe->correction_bias = array(0.0f); + layer.moe->switch_gate_w = get_w(p + ".mlp.switch_mlp.gate_proj.weight"); + layer.moe->switch_gate_s = get_w(p + ".mlp.switch_mlp.gate_proj.scales"); + layer.moe->switch_gate_b = get_w(p + ".mlp.switch_mlp.gate_proj.biases"); + layer.moe->switch_up_w = get_w(p + ".mlp.switch_mlp.up_proj.weight"); + layer.moe->switch_up_s = get_w(p + ".mlp.switch_mlp.up_proj.scales"); + layer.moe->switch_up_b = get_w(p + ".mlp.switch_mlp.up_proj.biases"); + layer.moe->switch_down_w = get_w(p + ".mlp.switch_mlp.down_proj.weight"); + layer.moe->switch_down_s = get_w(p + ".mlp.switch_mlp.down_proj.scales"); + layer.moe->switch_down_b = get_w(p + ".mlp.switch_mlp.down_proj.biases"); + std::string moe_p = p + ".mlp.switch_mlp"; + layer.moe->gate_bits = detect_bits(moe_p + ".gate_proj.weight", moe_p + ".gate_proj.scales"); + layer.moe->up_bits = detect_bits(moe_p + ".up_proj.weight", moe_p + ".up_proj.scales"); + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + layer.moe->scoring_func = "softmax"; // Qwen3 always uses softmax +} + +// Qwen2/Qwen3 dense layer builder -- handles attention bias, QK norm +static void build_qwen_dense_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = false; // Qwen: norm after reshape + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // Dense MLP (SiLU-gated) + layer.is_moe = false; + layer.gate_proj = make_qlinear(p + ".mlp.gate_proj"); + layer.up_proj = make_qlinear(p + ".mlp.up_proj"); + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + + // Force-eval all layer weights to pin GPU buffers. + // Without this, the Metal allocator reclaims weight buffers when + // subsequent layers are constructed (hundreds of array(0.0f) defaults). + std::vector layer_weights = { + *layer.q_proj.weight, *layer.q_proj.scales, + *layer.k_proj.weight, *layer.k_proj.scales, + *layer.v_proj.weight, *layer.v_proj.scales, + *layer.o_proj.weight, *layer.o_proj.scales, + *layer.gate_proj.weight, *layer.gate_proj.scales, + *layer.up_proj.weight, *layer.up_proj.scales, + *layer.down_proj.weight, *layer.down_proj.scales, + *layer.input_norm.weight, *layer.post_attn_norm.weight + }; + if (layer.q_proj.linear_bias) { + layer_weights.push_back(*layer.q_proj.linear_bias); + layer_weights.push_back(*layer.k_proj.linear_bias); + layer_weights.push_back(*layer.v_proj.linear_bias); + } + eval(layer_weights); +} + +// Phi3 layer builder — handles fused qkv_proj and gate_up_proj +static void build_phi3_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + // Fused QKV: split into Q, K, V + // qkv_proj output dim = (num_heads + 2*num_kv_heads) * head_dim + int q_dim = g_config.num_heads * g_config.head_dim; + int kv_dim = g_config.num_kv_heads * g_config.head_dim; + { + // Split: [q_dim, kv_dim, kv_dim] along output dim 0 + auto qkv_w = get_w(p + ".self_attn.qkv_proj.weight"); + auto qkv_s = get_w(p + ".self_attn.qkv_proj.scales"); + auto qkv_b = get_w(p + ".self_attn.qkv_proj.biases"); + int gs = g_config.quant_group_size; + int w_last = qkv_w.shape(-1); + int s_last = qkv_s.shape(-1); + int bits = (s_last > 0) ? (w_last * 32) / (s_last * gs) : g_config.quant_bits; + + auto make_split = [&](int start, int end) -> QuantizedLinear { + auto w = slice(qkv_w, {start, 0}, {end, qkv_w.shape(1)}); + auto s = slice(qkv_s, {start, 0}, {end, qkv_s.shape(1)}); + auto b = slice(qkv_b, {start, 0}, {end, qkv_b.shape(1)}); + return {w, s, b, std::nullopt, gs, bits, true}; + }; + layer.q_proj = make_split(0, q_dim); + layer.k_proj = make_split(q_dim, q_dim + kv_dim); + layer.v_proj = make_split(q_dim + kv_dim, q_dim + 2 * kv_dim); + } + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // Fused gate_up_proj: split into gate and up (equal halves) + { + auto gu_w = get_w(p + ".mlp.gate_up_proj.weight"); + int half = gu_w.shape(0) / 2; + split_fused_qlinear(layer.gate_proj, layer.up_proj, p + ".mlp.gate_up_proj", half); + } + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + layer.is_moe = false; +} + +// GPT-OSS layer builder — standard attention + MoE with fused gate_up SwitchGLU +static void build_gptoss_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + // Attention sinks + if (has_w(p + ".self_attn.sinks")) { + auto s = get_w(p + ".self_attn.sinks"); + // Only use sinks if they're non-zero + eval({s}); + float smax = max(abs(s)).item(); + if (smax > 0.0f) { + layer.sinks = s; + } + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = 0; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // YaRN RoPE: compute corrected frequencies if configured + if (g_config.rope_type == "yarn" && g_config.yarn_factor > 1.0f) { + auto [freqs, mscale] = compute_yarn_freqs( + g_config.head_dim, g_config.rope_theta, g_config.yarn_factor, + g_config.yarn_original_max_pos, g_config.yarn_beta_fast, g_config.yarn_beta_slow, + g_config.yarn_mscale, g_config.yarn_mscale_all_dim); + layer.rope_freqs = freqs; + layer.yarn_mscale = mscale; + if (idx == 0) { + } + } + + // GPT-OSS MLP uses FusedGateUpSwitchGLU with stacked expert weights [E, out, in] + // The gate_up_proj is fused: first half is gate, second half is up + // Route through MoE path with gather_qmm + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".mlp.router"); + layer.moe->correction_bias = array(0.0f); // GPT-OSS uses softmax routing, no correction + + // Fused gate_up_proj: [E, gate_dim+up_dim, packed_in] + // Need to split into separate gate and up for gather_qmm + auto gu_w = get_w(p + ".mlp.experts.gate_up_proj.weight"); + auto gu_s = get_w(p + ".mlp.experts.gate_up_proj.scales"); + int E = gu_w.shape(0); + int fused_out = gu_w.shape(1); + int half = fused_out / 2; + + // Split along dim 1 (output dim): [E, half, in] each + layer.moe->switch_gate_w = slice(gu_w, {0, 0, 0}, {E, half, gu_w.shape(2)}); + layer.moe->switch_gate_s = slice(gu_s, {0, 0, 0}, {E, half, gu_s.shape(2)}); + layer.moe->switch_up_w = slice(gu_w, {0, half, 0}, {E, fused_out, gu_w.shape(2)}); + layer.moe->switch_up_s = slice(gu_s, {0, half, 0}, {E, fused_out, gu_s.shape(2)}); + + // Quantization biases: optional (MXFP4 doesn't have them) + if (has_w(p + ".mlp.experts.gate_up_proj.biases")) { + auto gu_b = get_w(p + ".mlp.experts.gate_up_proj.biases"); + layer.moe->switch_gate_b = slice(gu_b, {0, 0, 0}, {E, half, gu_b.shape(2)}); + layer.moe->switch_up_b = slice(gu_b, {0, half, 0}, {E, fused_out, gu_b.shape(2)}); + } + // else: leave as std::nullopt — gather_qmm handles absent biases + + // down_proj: [E, out, in] + layer.moe->switch_down_w = get_w(p + ".mlp.experts.down_proj.weight"); + layer.moe->switch_down_s = get_w(p + ".mlp.experts.down_proj.scales"); + if (has_w(p + ".mlp.experts.down_proj.biases")) { + layer.moe->switch_down_b = get_w(p + ".mlp.experts.down_proj.biases"); + } + + // Bits detection: MXFP4 uses uint8 scales, so detect_bits formula doesn't apply + // Use config quant_bits (default 4) for MXFP4 models + std::string moe_p = p + ".mlp.experts"; + auto gs_scales = get_w(moe_p + ".gate_up_proj.scales"); + if (gs_scales.dtype() == uint8) { + // MXFP4: bits=4, group_size derived from weight/scales shapes + // w=[E, out, packed_in] (uint32), s=[E, out, groups] (uint8) + // in_dim = packed_in * 32 / bits, group_size = in_dim / groups + auto w0 = get_w(moe_p + ".gate_up_proj.weight"); + int packed_in = w0.shape(2); + int groups = gs_scales.shape(2); + int in_dim = packed_in * 32 / 4; // uint32 packing: 8 values per uint32 + layer.group_size = in_dim / groups; + layer.moe->gate_bits = 4; + layer.moe->up_bits = 4; + layer.moe->down_bits = 4; + } else { + layer.moe->gate_bits = detect_bits(moe_p + ".gate_up_proj.weight", moe_p + ".gate_up_proj.scales"); + layer.moe->up_bits = layer.moe->gate_bits; + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + } + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + layer.moe->scoring_func = "softmax"; +} + +// Gemma3 clip residual: clamp the updated residual to prevent overflow +static array clip_residual(const array& x, const array& r) { + // Gemma uses soft capping: tanh(residual / 50) * 50 + // But in practice the Swift code just does x + r without explicit clipping + // for the text-only path. Let's match the Swift behavior. + return x + r; +} + +// Gemma3 layer builder — handles 4 norms, QK norm, GELU, sliding/global RoPE +static void build_gemma3_layer(Layer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + layer.pre_ff_norm = make_norm(p + ".pre_feedforward_layernorm"); + layer.post_ff_norm = make_norm(p + ".post_feedforward_layernorm"); + layer.has_gemma3_norms = true; + + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + layer.qk_norm_before_reshape = false; // Gemma3: per-head norm + + // Sliding window pattern: most layers are sliding, every Nth is global + int pattern = g_config.sliding_pattern > 0 ? g_config.sliding_pattern : 6; + layer.is_sliding = ((idx + 1) % pattern != 0); + + // Different RoPE for sliding vs global layers + if (layer.is_sliding) { + // Sliding layers use local base freq (default 10000) + layer.rope_theta = 10000.0f; // TODO: parse rope_local_base_freq from config + } else { + // Global layers use the main rope_theta with scaling + layer.rope_theta = g_config.rope_theta; + } + layer.rotary_dim = 0; // full head_dim + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + layer.bits = layer.q_proj.bits; + + // Custom attention scale: queryPreAttnScalar^(-0.5) + // For gemma3-4b, queryPreAttnScalar = head_dim = 256, so scale = 1/16 + float query_pre_attn_scalar = static_cast(g_config.head_dim); // default + layer.attn_scale = 1.0f / std::sqrt(query_pre_attn_scalar); + + // MLP uses GELU activation + layer.gate_proj = make_qlinear(p + ".mlp.gate_proj"); + layer.up_proj = make_qlinear(p + ".mlp.up_proj"); + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + layer.mlp_activation = "gelu"; + layer.is_moe = false; +} + +static GenericModel build_model() { + GenericModel m; + m.config = g_config; + // NOTE: embedding and final_norm are built AFTER layers. + // layers.resize() creates hundreds of default array(0.0f) objects + // which can cause the Metal allocator to reclaim GPU buffers + // backing previously-assigned arrays (embedding scales, etc.). + + if (g_config.model_type == "gemma4_text" || g_config.model_type == "gemma4" || + g_config.model_type == "gemma3" || g_config.model_type == "gemma3_text") { + m.embed_scale = std::sqrt(static_cast(g_config.hidden_size)); + } + + // Build embedding and norm FIRST (before layer loop). + // Layer default-construction creates many arrays which can trigger + // MLX Metal buffer reclamation. Building embedding first and verifying + // it survives the loop is the key test. + m.embed_tokens = make_embedding("model.embed_tokens"); + m.final_norm = make_norm("model.norm"); + + int num_layers = g_config.num_layers; + m.layers.reserve(num_layers); + + for (int i = 0; i < num_layers; i++) { + m.layers.emplace_back(); + + if (g_config.model_type == "minimax_m2") { + build_minimax_layer(m.layers[i], i); + } else if (g_config.model_type == "qwen3_moe") { + build_qwen3_moe_layer(m.layers[i], i); + } else if (g_config.model_type == "qwen2" || g_config.model_type == "qwen3") { + build_qwen_dense_layer(m.layers[i], i); + } else if (g_config.model_type == "phi3") { + build_phi3_layer(m.layers[i], i); + } else if (g_config.model_type == "gemma3" || g_config.model_type == "gemma3_text") { + build_gemma3_layer(m.layers[i], i); + } else if (g_config.model_type == "gpt_oss") { + build_gptoss_layer(m.layers[i], i); + } else { + // Generic transformer layer + std::string p = "model.layers." + std::to_string(i); + m.layers[i].input_norm = make_norm(p + ".input_layernorm"); + m.layers[i].post_attn_norm = make_norm(p + ".post_attention_layernorm"); + m.layers[i].q_proj = make_qlinear(p + ".self_attn.q_proj"); + m.layers[i].k_proj = make_qlinear(p + ".self_attn.k_proj"); + m.layers[i].v_proj = make_qlinear(p + ".self_attn.v_proj"); + m.layers[i].o_proj = make_qlinear(p + ".self_attn.o_proj"); + m.layers[i].gate_proj = make_qlinear(p + ".mlp.gate_proj"); + m.layers[i].up_proj = make_qlinear(p + ".mlp.up_proj"); + m.layers[i].down_proj = make_qlinear(p + ".mlp.down_proj"); + m.layers[i].num_heads = g_config.num_heads; + m.layers[i].num_kv_heads = g_config.num_kv_heads; + m.layers[i].head_dim = g_config.head_dim; + m.layers[i].rope_theta = g_config.rope_theta; + m.layers[i].rotary_dim = g_config.rotary_dim; + } + } + + return m; +} + +// ============================================================================ +// C ABI +// ============================================================================ + +extern "C" { + +int gp_init(const char* config_json) { + try { + std::string json(config_json); + g_config.model_type = json_string(json, "model_type"); + g_config.hidden_size = json_int(json, "hidden_size", 3072); + g_config.num_layers = json_int(json, "num_hidden_layers", 62); + g_config.num_heads = json_int(json, "num_attention_heads", 48); + g_config.num_kv_heads = json_int(json, "num_key_value_heads", 8); + g_config.head_dim = json_int(json, "head_dim", 128); + g_config.intermediate_size = json_int(json, "intermediate_size", 1536); + g_config.vocab_size = json_int(json, "vocab_size", 200064); + g_config.rms_norm_eps = json_float(json, "rms_norm_eps", 1e-6f); + g_config.rope_theta = json_float(json, "rope_theta", 5000000.0f); + g_config.rotary_dim = json_int(json, "rotary_dim", 64); + g_config.tie_word_embeddings = json_bool(json, "tie_word_embeddings", false); + g_config.use_qk_norm = json_bool(json, "use_qk_norm", true); + g_config.num_local_experts = json_int(json, "num_local_experts", 0); + g_config.num_experts_per_tok = json_int(json, "num_experts_per_tok", 0); + g_config.scoring_func = json_string(json, "scoring_func"); + if (g_config.scoring_func.empty()) g_config.scoring_func = "softmax"; + g_config.sliding_window = json_int(json, "sliding_window", 0); + g_config.sliding_pattern = json_int(json, "sliding_pattern", 0); + + // YaRN RoPE params + g_config.rope_type = json_string(json, "rope_type"); + g_config.yarn_factor = json_float(json, "yarn_factor", 1.0f); + g_config.yarn_beta_fast = json_float(json, "yarn_beta_fast", 32.0f); + g_config.yarn_beta_slow = json_float(json, "yarn_beta_slow", 1.0f); + g_config.yarn_original_max_pos = json_int(json, "yarn_original_max_pos", 4096); + g_config.yarn_mscale = json_float(json, "yarn_mscale", 1.0f); + g_config.yarn_mscale_all_dim = json_float(json, "yarn_mscale_all_dim", 0.0f); + + g_weights.clear(); + g_model.reset(); + g_initialized = true; + g_finalized = false; + + fprintf(stderr, "[gp] Init: model_type=%s layers=%d hidden=%d heads=%d/%d experts=%d rope_theta=%.0f rms_eps=%.1e head_dim=%d\n", + g_config.model_type.c_str(), g_config.num_layers, + g_config.hidden_size, g_config.num_heads, g_config.num_kv_heads, + g_config.num_local_experts, g_config.rope_theta, g_config.rms_norm_eps, + g_config.head_dim); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] init error: %s\n", e.what()); + return -1; + } +} + +int gp_set_weight(const char* key, void* arr_ptr) { + if (!g_initialized || g_finalized) return -1; + try { + auto arr = extract_array(arr_ptr); + std::string k(key); + g_weights.insert_or_assign(k, arr); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] set_weight error for '%s': %s\n", key, e.what()); + return -1; + } +} + +int gp_finalize(void) { + if (!g_initialized || g_finalized) return -1; + try { + + g_model = std::make_unique(build_model()); + g_finalized = true; + g_weights.clear(); + + fprintf(stderr, "[gp] Model built (%d layers)\n", g_config.num_layers); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] finalize error: %s\n", e.what()); + return -1; + } +} + +int gp_run(void* token_array_ptr, double* out_elapsed_ms) { + if (!g_model) return -1; + try { + auto& tokens = *static_cast(token_array_ptr); + auto t0 = std::chrono::high_resolution_clock::now(); + + // Reset KV caches before forward + for (auto& layer : g_model->layers) { + layer.cache.reset(); + } + + auto output = g_model->forward(tokens); + + // Eval all KV caches + std::vector to_eval; + for (auto& layer : g_model->layers) { + if (layer.cache.has_data()) { + to_eval.push_back(*layer.cache.keys); + to_eval.push_back(*layer.cache.values); + } + } + eval(to_eval); + + // Free intermediate activation buffers (critical for MoE with 256 experts) + // DO NOT clear_cache -- reclaims weight buffers + + auto t1 = std::chrono::high_resolution_clock::now(); + if (out_elapsed_ms) { + *out_elapsed_ms = std::chrono::duration(t1 - t0).count(); + } + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[gp] run error: %s\n", e.what()); + return -1; + } +} + +int gp_num_cache_layers(void) { + return g_model ? (int)g_model->layers.size() : 0; +} + +void* gp_get_k_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[layer_idx].cache; + if (!c.keys) return nullptr; + return new mlx::core::array(*c.keys); +} + +void* gp_get_v_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[layer_idx].cache; + if (!c.values) return nullptr; + return new mlx::core::array(*c.values); +} + +int gp_kv_shape(int layer_idx, int* kv_heads, int* seq_len, int* head_dim) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return -1; + auto& c = g_model->layers[layer_idx].cache; + if (!c.has_data()) return -2; + *kv_heads = c.keys->shape(1); + *seq_len = c.keys->shape(2); + *head_dim = c.keys->shape(3); + return 0; +} + +void gp_cleanup(void) { + g_model.reset(); + g_weights.clear(); + g_initialized = false; + g_finalized = false; +} + +} // extern "C" diff --git a/Sources/NativePrefillBridge/generic_prefill.h b/Sources/NativePrefillBridge/generic_prefill.h new file mode 100644 index 0000000000..cddc1b96ff --- /dev/null +++ b/Sources/NativePrefillBridge/generic_prefill.h @@ -0,0 +1,50 @@ +// generic_prefill.h — Model-agnostic native prefill bridge +// +// Supports multiple model architectures via runtime config. +// Same weight-sharing pattern as prefill_bridge_v2: Swift passes +// MLXArray.ctx pointers, bridge copies metadata (shares GPU buffer). +#ifndef GENERIC_PREFILL_H +#define GENERIC_PREFILL_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Initialize with model config JSON string +// Parses model_type, layer count, dimensions, etc. +int gp_init(const char* config_json); + +// Set a weight tensor (pass Swift's MLXArray.ctx pointer) +int gp_set_weight(const char* key, void* arr_ptr); + +// Mark initialization complete — builds model from weights +int gp_finalize(void); + +// Run prefill on token array (pass MLXArray.ctx pointer) +// Returns 0 on success +int gp_run(void* token_array_ptr, double* out_elapsed_ms); + +// Get number of KV cache layers +int gp_num_cache_layers(void); + +// Get K/V array pointers for cache injection into Swift +// Returns heap-allocated mlx::core::array* (caller takes ownership) +void* gp_get_k_ptr(int layer_idx); +void* gp_get_v_ptr(int layer_idx); + +// KV shape info +int gp_kv_shape(int layer_idx, int* kv_heads, int* seq_len, int* head_dim); + +// Cleanup +void gp_cleanup(void); + +// Allocator bug repro (standalone test, no model needed) +int gp_repro_allocator_bug(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Sources/NativePrefillBridge/mlx_allocator_repro.cpp b/Sources/NativePrefillBridge/mlx_allocator_repro.cpp new file mode 100644 index 0000000000..af12334976 --- /dev/null +++ b/Sources/NativePrefillBridge/mlx_allocator_repro.cpp @@ -0,0 +1,129 @@ +// Minimal repro: MLX GPU compute path reads wrong buffer for live arrays +// +// PROVEN: CPU memory is stable. MLX sum(abs()) returns wrong values. +// This test splits the observer to isolate where the GPU path diverges. + +#include +#include +#include +#include "mlx/mlx.h" + +using namespace mlx::core; + +// CPU-side float16 abssum for ground truth +static double cpu_f16_abssum(const array& a) { + auto* raw = static_cast<_Float16*>(const_cast(a.buffer()).raw_ptr()); + double s = 0; + for (int i = 0; i < (int)a.size(); i++) { + s += std::abs(static_cast(raw[i])); + } + return s; +} + +// CPU-side: read first N float16 values and return a checksum +static uint64_t cpu_f16_hash(const array& a, int n = 256) { + auto* raw = static_cast(const_cast(a.buffer()).raw_ptr()); + uint64_t h = 0; + for (int i = 0; i < std::min(n, (int)a.size()); i++) { + h = h * 31 + raw[i]; + } + return h; +} + +extern "C" { + +int gp_repro_allocator_bug(void) { + fprintf(stderr, "\n=== MLX GPU BINDING BUG REPRO ===\n"); + + // 1. Create and eval a persistent array + auto long_lived = random::normal({32768, 64}, float16); + eval({long_lived}); + + double cpu_baseline = cpu_f16_abssum(long_lived); + uint64_t hash_baseline = cpu_f16_hash(long_lived); + void* buf_ptr = long_lived.buffer().raw_ptr(); + fprintf(stderr, "baseline: cpu_abssum=%.2f buf=%p hash=%llx\n", + cpu_baseline, buf_ptr, hash_baseline); + + // 2. Test MLX ops on long_lived BEFORE any pressure + { + auto a = abs(long_lived); + eval({a}); + double cpu_abs = cpu_f16_abssum(a); + float mlx_sum_a = sum(a).item(); + fprintf(stderr, "pre-pressure: abs cpu_abssum=%.2f sum(abs) via mlx=%.6f\n", + cpu_abs, mlx_sum_a); + } + + // 3. One round of pressure + { + int D = 4096; + auto x = random::normal({4, D}, float16); + auto q = matmul(x, transpose(random::normal({D, D}, float16))); + auto k = matmul(x, transpose(random::normal({D, D}, float16))); + auto v = matmul(x, transpose(random::normal({D, D}, float16))); + auto out = matmul(x, transpose(random::normal({D, D}, float16))); + auto gate = matmul(x, transpose(random::normal({14336, D}, float16))); + auto up = matmul(x, transpose(random::normal({14336, D}, float16))); + auto down = matmul(gate * sigmoid(gate) * up, + transpose(random::normal({D, 14336}, float16))); + eval({out, down}); + } + + // 4. Test each op individually AFTER pressure + fprintf(stderr, "\n--- after 1 round of pressure ---\n"); + + // 4a. CPU ground truth + double cpu_after = cpu_f16_abssum(long_lived); + uint64_t hash_after = cpu_f16_hash(long_lived); + void* ptr_after = long_lived.buffer().raw_ptr(); + fprintf(stderr, "cpu: abssum=%.2f hash=%llx ptr=%p %s\n", + cpu_after, hash_after, ptr_after, + (hash_after == hash_baseline) ? "STABLE" : "CHANGED"); + + // 4b. abs() alone — eval it, then check its output on CPU + { + auto a = abs(long_lived); + eval({a}); + void* abs_ptr = const_cast(a.buffer()).raw_ptr(); + double cpu_abs_out = cpu_f16_abssum(a); + fprintf(stderr, "abs(long_lived): output cpu_abssum=%.2f output buf=%p same_as_input=%s\n", + cpu_abs_out, abs_ptr, (abs_ptr == buf_ptr) ? "YES(donated!)" : "no"); + } + + // 4c. sum() on a tiny known-good array + { + auto tiny = array({1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); + eval({tiny}); + float s = sum(tiny).item(); + fprintf(stderr, "sum([1..5]): mlx=%.6f expected=15.0 %s\n", + s, (std::abs(s - 15.0f) < 0.01f) ? "OK" : "WRONG"); + } + + // 4d. Full sum(abs(long_lived)) via MLX + { + float mlx_val = sum(abs(long_lived)).item(); + fprintf(stderr, "sum(abs(long_lived)): mlx=%.6f cpu=%.2f ratio=%.4f %s\n", + mlx_val, cpu_after, mlx_val / cpu_after, + (std::abs(mlx_val - cpu_after) / cpu_after > 0.01) ? "DIVERGED" : "OK"); + } + + // 4e. Force CPU eval path if possible: convert to float32, eval, read back + { + auto f32 = astype(long_lived, float32); + eval({f32}); + auto* f32_raw = static_cast(f32.buffer().raw_ptr()); + double cpu_f32_sum = 0; + for (int i = 0; i < std::min(1000, (int)f32.size()); i++) { + cpu_f32_sum += std::abs(f32_raw[i]); + } + float mlx_f32_sum = sum(abs(f32)).item(); + fprintf(stderr, "astype(f32): cpu_first1000=%.2f mlx_full=%.6f\n", + cpu_f32_sum, mlx_f32_sum); + } + + fprintf(stderr, "=== END REPRO ===\n\n"); + return 0; +} + +} // extern "C" diff --git a/Sources/NativePrefillBridge/prefill_bridge_gemma.cpp b/Sources/NativePrefillBridge/prefill_bridge_gemma.cpp new file mode 100644 index 0000000000..653d8d5657 --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_gemma.cpp @@ -0,0 +1,788 @@ +// prefill_bridge_gemma.cpp — Gemma-family native prefill bridge +// +// Accepts EXTERNAL weight arrays from Swift instead of loading safetensors. +// The arr_ptr passed to gemma_set_weight() is MLXArray.ctx — a raw +// mlx::core::array* owned by Swift. We copy the mlx::core::array (cheap: +// ~100 bytes metadata, shared_ptr to underlying buffer) so the bridge holds +// a reference but does NOT own or free the Swift-side array. +// +// Forward pass is IDENTICAL to prefill_bridge.cpp: +// - 15 non-shared layers (0–14) +// - Sliding attention (head_dim=256) at layers 0-3, 5-8, 10-13 +// - Full attention (head_dim=512) at layers 4, 9, 14 +// - GeGLU MLP (gelu_approx), 4-bit quantized weights +// - Per-layer input gating +// - RMSNorm with direct weight (NOT 1+weight) +// - Proportional RoPE for full layers, standard RoPE for sliding +// - Causal SDPA +// +// Build: +// clang++ -std=c++20 -O3 -shared -fPIC \ +// -I/opt/homebrew/lib/python3.13/site-packages/mlx/include \ +// -I/Users/tom/dev/mlx-swift/Source/Cmlx/mlx-c \ +// -I/tmp \ +// -L/opt/homebrew/lib/python3.13/site-packages/mlx/lib -lmlx \ +// -framework Metal -framework Foundation -framework Accelerate \ +// -Wl,-rpath,/opt/homebrew/lib/python3.13/site-packages/mlx/lib \ +// -o /tmp/libprefill_bridge_v2.dylib /tmp/prefill_bridge_v2.cpp + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "mlx/mlx.h" +#include "prefill_bridge_gemma.h" + +// Private mlx-c header — gives us mlx_array_get_() to extract C++ array +// from the opaque C handle. We only use this to understand the struct layout; +// the actual arr_ptr from Swift is MLXArray.ctx which is already mlx::core::array*. +// Including it anyway for documentation and the inline helpers. +#include "mlx/c/private/array.h" + +using namespace mlx::core; + +// ============================================================================ +// Architecture constants — set by gemma_init() +// ============================================================================ +static int g_num_layers = 0; +static int g_hidden_size = 0; +static int g_num_heads = 0; +static int g_num_kv_heads = 0; +static int g_sliding_window = 0; +static int g_sliding_pattern = 0; // every Nth layer is full attention + +// Derived constants (Gemma 4 E2B defaults — recomputed in gemma_init) +static int g_head_dim_slide = 256; +static int g_head_dim_full = 512; +static int g_intermediate = 0; +static int g_total_layers = 0; +static int g_hidden_per_layer = 256; + +// Quantization params (hardcoded for 4-bit Gemma 4 E2B) +static constexpr int BITS = 4; +static constexpr int GROUP_SIZE = 64; +static constexpr float RMS_EPS = 1e-6f; + +// RoPE params +static constexpr float ROPE_THETA_SLIDING = 10000.0f; +static constexpr float ROPE_THETA_FULL = 1000000.0f; + +static bool is_full_attention(int layer_idx) { + return g_sliding_pattern > 0 && ((layer_idx + 1) % g_sliding_pattern == 0); +} + +// ============================================================================ +// Helper: GELU approximate (tanh approximation) +// ============================================================================ +static array gelu_approx(const array& x) { + // Must match Python's nn.gelu_approx exactly: + // 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x**3))) + // + // Two critical details: + // 1. x**3 = power(x, 3) — single op, one final round. + // x*x*x = two bf16 multiplies with intermediate rounding → different. + // 2. Python float scalars are "universal" type that don't promote bf16. + // C++ array(float, bf16) pre-rounds; array(float) promotes to f32. + // Use bf16 constants (pre-rounded) + power() to get closest match. + auto dt = x.dtype(); + static const float kSqrt2OverPi = 0.7978845608028654f; + auto x3 = power(x, array(3, dt)); + auto inner = array(kSqrt2OverPi, dt) * (x + array(0.044715f, dt) * x3); + return array(0.5f, dt) * x * (array(1.0f, dt) + tanh(inner)); +} + +// ============================================================================ +// Layer components — same structs as v1 but weights stored as array copies +// ============================================================================ + +struct QuantizedLinear { + array weight; // uint32 packed + array scales; // bfloat16 + array biases; // bfloat16 + + array operator()(const array& x) const { + return quantized_matmul( + x, weight, scales, biases, + /*transpose=*/true, + /*group_size=*/GROUP_SIZE, + /*bits=*/BITS, + /*mode=*/"affine"); + } +}; + +struct RMSNorm { + array weight; // learned scale — used directly (NOT 1+weight) + + array operator()(const array& x) const { + return fast::rms_norm(x, weight, RMS_EPS); + } +}; + +static array rms_norm_no_scale(const array& x) { + return fast::rms_norm(x, std::nullopt, RMS_EPS); +} + +struct QuantizedEmbedding { + array weight; // [vocab, packed_cols] uint32 + array scales; // [vocab, num_groups] bfloat16 + array biases; // [vocab, num_groups] bfloat16 + + array operator()(const array& indices) const { + auto w = take(weight, indices, 0); + auto s = take(scales, indices, 0); + auto b = take(biases, indices, 0); + return dequantize(w, s, b, GROUP_SIZE, BITS, "affine"); + } +}; + +struct ScaledLinear { + array weight; // [out, in] bfloat16 + float scalar; + + array operator()(const array& x) const { + auto out = matmul(x, transpose(weight)); + // Python ScaledLinear: (x @ W.T) * scalar, where scalar is Python float + // When W is bf16, x is bf16, matmul output is bf16 + // bf16 * Python float → bf16 (MLX keeps lower dtype) + return out * array(scalar, bfloat16); + } +}; + +struct Attention { + QuantizedLinear q_proj, k_proj; + std::shared_ptr v_proj; // optional: null when k_eq_v + QuantizedLinear o_proj; + RMSNorm q_norm, k_norm; + int head_dim; + int num_heads; + int num_kv_heads; + bool is_sliding; + float rope_theta; + array rope_freqs; // precomputed for full (proportional), empty for sliding + + mutable array last_k = array({}, bfloat16); + mutable array last_v = array({}, bfloat16); + + array operator()(const array& x) const { + int B = x.shape(0); + int S = x.shape(1); + + auto q = q_proj(x); + auto k = k_proj(x); + auto v = v_proj ? (*v_proj)(x) : k; // k_eq_v: V = K when no v_proj + + q = transpose(reshape(q, {B, S, num_heads, head_dim}), {0, 2, 1, 3}); + k = transpose(reshape(k, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + v = transpose(reshape(v, {B, S, num_kv_heads, head_dim}), {0, 2, 1, 3}); + + q = q_norm(q); + k = k_norm(k); + v = rms_norm_no_scale(v); + + // RoPE: sliding = standard, full = proportional (precomputed freqs) + if (is_sliding) { + q = fast::rope(q, head_dim, false, rope_theta, 1.0f, 0); + k = fast::rope(k, head_dim, false, rope_theta, 1.0f, 0); + } else { + q = fast::rope(q, head_dim, false, std::nullopt, 1.0f, 0, rope_freqs); + k = fast::rope(k, head_dim, false, std::nullopt, 1.0f, 0, rope_freqs); + } + + // Store K/V in bfloat16 to match Swift's cache dtype + // Python's cache.update_and_fetch() stores bf16, then SDPA reads bf16 back. + // We must use bf16 K/V for SDPA to match Python exactly. + last_k = astype(k, bfloat16); + last_v = astype(v, bfloat16); + k = last_k; + v = last_v; + + // SDPA (scale=1.0 for Gemma4) + float scale = 1.0f; + auto make_attn = [&]() -> array { + if (is_sliding && S > g_sliding_window) { + auto rinds = arange(S); + auto linds = reshape(arange(S), {S, 1}); + auto mask_arr = (linds >= rinds) & (linds < (rinds + g_sliding_window)); + return fast::scaled_dot_product_attention( + q, k, v, scale, /*mask_mode=*/"", /*mask_arr=*/mask_arr); + } else if (is_sliding) { + return fast::scaled_dot_product_attention( + q, k, v, scale, "causal"); + } else { + return fast::scaled_dot_product_attention( + q, k, v, scale, "causal"); + } + }; + auto attn_out = make_attn(); + + attn_out = reshape( + transpose(attn_out, {0, 2, 1, 3}), + {B, S, num_heads * head_dim}); + + return o_proj(attn_out); + } +}; + +struct MLP { + QuantizedLinear gate_proj, up_proj, down_proj; + + array operator()(const array& x) const { + auto gate = gate_proj(x); + auto up = up_proj(x); + return down_proj(gelu_approx(gate) * up); + } +}; + +struct TransformerLayer { + RMSNorm input_layernorm; + Attention self_attn; + RMSNorm post_attention_layernorm; + RMSNorm pre_feedforward_layernorm; + MLP mlp; + RMSNorm post_feedforward_layernorm; + + // PLE fields — optional for models without PLE + std::shared_ptr per_layer_input_gate; + std::shared_ptr per_layer_projection; + std::shared_ptr post_per_layer_input_norm; + std::shared_ptr layer_scalar; + bool has_ple = false; + + array operator()(const array& x, const array& per_layer_input) const { + // Pre-norm attention with residual + auto residual = x; + auto h = input_layernorm(x); + h = self_attn(h); + h = post_attention_layernorm(h); + h = residual + h; + + // Pre-norm MLP with residual + residual = h; + auto ff = pre_feedforward_layernorm(h); + ff = mlp(ff); + ff = post_feedforward_layernorm(ff); + h = residual + ff; + + // Per-layer input gating (PLE) — only for models with PLE + if (has_ple) { + residual = h; + auto gate = (*per_layer_input_gate)(h); + gate = gelu_approx(gate); + gate = gate * per_layer_input; + gate = (*per_layer_projection)(gate); + gate = (*post_per_layer_input_norm)(gate); + h = residual + gate; + + h = h * (*layer_scalar); + } + + return h; + } +}; + +struct Model { + QuantizedEmbedding embed_tokens; + std::shared_ptr embed_tokens_per_layer; + std::shared_ptr per_layer_model_projection; + std::shared_ptr per_layer_projection_norm; + bool has_ple = false; + std::vector layers; + RMSNorm final_norm; + + // Precomputed scale constants (avoid per-call array creation) + array embed_scale_arr = array(0.0f); + array pl_embed_scale_arr = array(0.0f); + array pl_input_scale_arr = array(0.0f); + + void precompute_scales() { + // Match Python: scalars stored as bf16 (Python float * bf16 → bf16) + embed_scale_arr = array(std::sqrt(static_cast(g_hidden_size)), bfloat16); + pl_embed_scale_arr = array(std::sqrt(static_cast(g_hidden_per_layer)), bfloat16); + pl_input_scale_arr = array(std::pow(2.0f, -0.5f), bfloat16); + } + + array forward(const array& token_ids) const { + int B = token_ids.shape(0); + int S = token_ids.shape(1); + + auto h = embed_tokens(token_ids) * embed_scale_arr; + + // PLE (Per-Layer Embeddings) — optional, only for models with hiddenSizePerLayerInput > 0 + array combined_per_layer = array(0.0f); + if (has_ple) { + auto per_layer_inputs = (*embed_tokens_per_layer)(token_ids) * pl_embed_scale_arr; + per_layer_inputs = reshape(per_layer_inputs, {B, S, g_total_layers, g_hidden_per_layer}); + + auto per_layer_proj = per_layer_model_projection->operator()(h); + per_layer_proj = reshape(per_layer_proj, {B, S, g_total_layers, g_hidden_per_layer}); + per_layer_proj = (*per_layer_projection_norm)(per_layer_proj); + + combined_per_layer = (per_layer_proj + per_layer_inputs) * pl_input_scale_arr; + } + + // Run through non-shared layers + for (int i = 0; i < g_num_layers; i++) { + if (has_ple) { + auto pli = slice(combined_per_layer, + {0, 0, i, 0}, + {B, S, i + 1, g_hidden_per_layer}); + pli = reshape(pli, {B, S, g_hidden_per_layer}); + h = layers[i](h, pli); + } else { + // No PLE: pass zero PLE input + auto pli = zeros({B, S, std::max(g_hidden_per_layer, 1)}, h.dtype()); + h = layers[i](h, pli); + } + } + + // Skip final norm during prefill — K/V eval doesn't need it + return h; + } +}; + +// ============================================================================ +// Global state +// ============================================================================ +static std::shared_ptr g_model = nullptr; +static std::unordered_map g_weight_store; +static bool g_initialized = false; +static bool g_finalized = false; + +// ============================================================================ +// Weight extraction from Swift's MLXArray.ctx +// +// Swift passes MLXArray.ctx which is the void* inside the mlx_array struct. +// That void* points to a heap-allocated mlx::core::array. +// We COPY the mlx::core::array (cheap — shares underlying data buffer via +// shared_ptr) so the bridge holds a reference without owning Swift's object. +// ============================================================================ +static array extract_array(void* arr_ptr) { + if (!arr_ptr) { + throw std::runtime_error("gemma_set_weight: null arr_ptr"); + } + // arr_ptr IS the mlx::core::array* (the ctx field from mlx_array struct) + auto* cpp_array = static_cast(arr_ptr); + // Copy — shares underlying data buffer, just bumps refcount (~100 bytes metadata) + return *cpp_array; +} + +// ============================================================================ +// Build helpers — pull from g_weight_store +// ============================================================================ +static array get_weight(const std::string& key) { + auto it = g_weight_store.find(key); + if (it != g_weight_store.end()) return it->second; + fprintf(stderr, "[pb2] WARNING: weight not found: %s\n", key.c_str()); + throw std::runtime_error("Missing weight: " + key); +} + +static bool has_weight(const std::string& key) { + return g_weight_store.count(key) > 0; +} + +static QuantizedLinear make_quantized_linear(const std::string& prefix) { + return { + get_weight(prefix + ".weight"), + get_weight(prefix + ".scales"), + get_weight(prefix + ".biases"), + }; +} + +static RMSNorm make_rms_norm(const std::string& prefix) { + return {get_weight(prefix + ".weight")}; +} + +static QuantizedEmbedding make_quantized_embedding(const std::string& prefix) { + return { + get_weight(prefix + ".weight"), + get_weight(prefix + ".scales"), + get_weight(prefix + ".biases"), + }; +} + +static Attention make_attention(const std::string& prefix, int layer_idx) { + bool full = is_full_attention(layer_idx); + int hd = full ? g_head_dim_full : g_head_dim_slide; + float theta = full ? ROPE_THETA_FULL : ROPE_THETA_SLIDING; + + // Proportional RoPE freqs for full-attention layers + // partial_rotary_factor=0.25: only first 25% of dims are rotated, + // remaining get inf (identity). Matches Python's ProportionalRoPE. + array freqs({}, float32); + if (full) { + int rotated_dims = hd / 4; // partial_rotary_factor=0.25 + auto exponents = arange(0, rotated_dims, 2, float32); + exponents = exponents / static_cast(hd); + auto rotated_freqs = power(array(theta, float32), exponents); + auto inf_freqs = mlx::core::full( + {(hd - rotated_dims) / 2}, + std::numeric_limits::infinity(), float32); + freqs = concatenate({rotated_freqs, inf_freqs}); + } + + // v_proj: present for sliding layers, absent for full layers with k_eq_v + std::shared_ptr v; + if (has_weight(prefix + ".v_proj.weight")) { + auto _v = make_quantized_linear(prefix + ".v_proj"); + v = std::make_shared(std::move(_v)); + } + + return { + make_quantized_linear(prefix + ".q_proj"), + make_quantized_linear(prefix + ".k_proj"), + std::move(v), + make_quantized_linear(prefix + ".o_proj"), + make_rms_norm(prefix + ".q_norm"), + make_rms_norm(prefix + ".k_norm"), + hd, + g_num_heads, + g_num_kv_heads, + !full, + theta, + freqs, + }; +} + +static MLP make_mlp(const std::string& prefix) { + return { + make_quantized_linear(prefix + ".gate_proj"), + make_quantized_linear(prefix + ".up_proj"), + make_quantized_linear(prefix + ".down_proj"), + }; +} + +static TransformerLayer make_layer(int layer_idx) { + std::string prefix = "layers." + std::to_string(layer_idx); + + // Build core layer components + auto attn = make_attention(prefix + ".self_attn", layer_idx); + auto mlp_block = make_mlp(prefix + ".mlp"); + + // PLE fields — only if weights exist + std::shared_ptr ple_gate, ple_proj; + std::shared_ptr ple_norm; + std::shared_ptr ple_scalar; + bool layer_has_ple = false; + if (has_weight(prefix + ".per_layer_input_gate.weight")) { + auto _g = make_quantized_linear(prefix + ".per_layer_input_gate"); + ple_gate = std::make_shared(std::move(_g)); + auto _p = make_quantized_linear(prefix + ".per_layer_projection"); + ple_proj = std::make_shared(std::move(_p)); + auto _n = make_rms_norm(prefix + ".post_per_layer_input_norm"); + ple_norm = std::make_shared(std::move(_n)); + auto _s = get_weight(prefix + ".layer_scalar"); + ple_scalar = std::make_shared(std::move(_s)); + layer_has_ple = true; + } + + return TransformerLayer{ + make_rms_norm(prefix + ".input_layernorm"), + std::move(attn), + make_rms_norm(prefix + ".post_attention_layernorm"), + make_rms_norm(prefix + ".pre_feedforward_layernorm"), + std::move(mlp_block), + make_rms_norm(prefix + ".post_feedforward_layernorm"), + std::move(ple_gate), std::move(ple_proj), + std::move(ple_norm), std::move(ple_scalar), + layer_has_ple, + }; +} + +static std::shared_ptr build_model() { + auto embed_tokens = make_quantized_embedding("embed_tokens"); + + // PLE: optional + bool ple_active = has_weight("embed_tokens_per_layer.weight"); + std::shared_ptr embed_tokens_per_layer; + std::shared_ptr per_layer_model_projection; + std::shared_ptr per_layer_projection_norm; + if (ple_active) { + auto _e = make_quantized_embedding("embed_tokens_per_layer"); + embed_tokens_per_layer = std::make_shared(std::move(_e)); + float projection_scalar = 1.0f / std::sqrt(static_cast(g_hidden_size)); + auto _sl = ScaledLinear{get_weight("per_layer_model_projection.weight"), projection_scalar}; + per_layer_model_projection = std::make_shared(std::move(_sl)); + auto _rn = make_rms_norm("per_layer_projection_norm"); + per_layer_projection_norm = std::make_shared(std::move(_rn)); + } else { + } + + std::vector layers; + layers.reserve(g_num_layers); + for (int i = 0; i < g_num_layers; i++) { + layers.push_back(make_layer(i)); + } + + auto final_norm = make_rms_norm("norm"); + + return std::shared_ptr(new Model{ + std::move(embed_tokens), + std::move(embed_tokens_per_layer), + std::move(per_layer_model_projection), + std::move(per_layer_projection_norm), + ple_active, + std::move(layers), + std::move(final_norm), + }); +} + +// ============================================================================ +// C ABI +// ============================================================================ +extern "C" { + +int gemma_init(int num_layers, int hidden_size, int num_heads, int num_kv_heads, + int sliding_window, int sliding_window_pattern) { + try { + g_num_layers = num_layers; + g_hidden_size = hidden_size; + g_num_heads = num_heads; + g_num_kv_heads = num_kv_heads; + g_sliding_window = sliding_window; + g_sliding_pattern = sliding_window_pattern; + + // Derived constants for Gemma 4 E2B architecture + // head_dim_slide = hidden_size * 2 / num_heads (256 for 1536/8 * ... — actually from config) + // For Gemma 4 E2B: slide=256, full=512, intermediate=6144 + // TODO: Make these configurable if needed for other models + g_head_dim_slide = 256; + g_head_dim_full = 512; + g_intermediate = hidden_size * 4; // 6144 for hidden=1536 + g_total_layers = 35; // Gemma 4 E2B total + g_hidden_per_layer = 256; // hidden_size_per_layer_input + + g_weight_store.clear(); + g_model.reset(); + g_initialized = true; + g_finalized = false; + + fprintf(stderr, "[pb2] Initialized: %d layers, hidden=%d, heads=%d/%d, pattern=%d\n", + num_layers, hidden_size, num_heads, num_kv_heads, sliding_window_pattern); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] init error: %s\n", e.what()); + return -1; + } +} + +int gemma_set_weight(const char* key, void* arr_ptr) { + if (!g_initialized || g_finalized) { + fprintf(stderr, "[pb2] set_weight called in wrong state (init=%d, final=%d)\n", + g_initialized, g_finalized); + return -1; + } + + try { + array copied = extract_array(arr_ptr); + g_weight_store.insert_or_assign(std::string(key), std::move(copied)); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] set_weight error for '%s': %s\n", key, e.what()); + return -1; + } +} + +int gemma_finalize(void) { + if (!g_initialized || g_finalized) { + fprintf(stderr, "[pb2] finalize called in wrong state\n"); + return -1; + } + + try { + g_model = build_model(); + g_model->precompute_scales(); + g_finalized = true; + + // Clear the weight store — model now holds all the array copies + g_weight_store.clear(); + + fprintf(stderr, "[pb2] Model built successfully (zero-copy weight sharing with Swift)\n"); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] finalize error: %s\n", e.what()); + return -1; + } +} + +// Zero-copy variant: accepts raw mlx::core::array* (avoids GPU→CPU→GPU roundtrip for tokens) +extern "C" +int gemma_run_array(void* token_arr_ptr, + double* out_elapsed_ms, float* out_checksum) { + if (!g_model || !token_arr_ptr) { + fprintf(stderr, "[pb2] run_array called before finalize or with null ptr\n"); + return -1; + } + + try { + // Zero-copy: use the Swift MLXArray's underlying data directly + auto& tokens_1d = *static_cast(token_arr_ptr); + auto tokens = reshape(tokens_1d, {1, static_cast(tokens_1d.size())}); + + auto t0 = std::chrono::high_resolution_clock::now(); + auto output = g_model->forward(tokens); + + std::vector cache_arrays; + for (auto& layer : g_model->layers) { + cache_arrays.push_back(layer.self_attn.last_k); + cache_arrays.push_back(layer.self_attn.last_v); + } + eval(cache_arrays); + auto t1 = std::chrono::high_resolution_clock::now(); + + double elapsed_ms = std::chrono::duration(t1 - t0).count(); + + auto& layer0_k = g_model->layers[0].self_attn.last_k; + eval(layer0_k); + auto checksum_arr = astype(sum(layer0_k), float32); + eval(checksum_arr); + float checksum = checksum_arr.item(); + + if (out_elapsed_ms) *out_elapsed_ms = elapsed_ms; + if (out_checksum) *out_checksum = checksum; + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] run_array error: %s\n", e.what()); + return -1; + } +} + +int gemma_run(const int32_t* token_ids, int token_count, + double* out_elapsed_ms, float* out_checksum) { + if (!g_model) { + fprintf(stderr, "[pb2] run called before finalize\n"); + return -1; + } + + try { + // Create token ID tensor [1, token_count] + auto tokens = array(token_ids, {1, token_count}, int32); + eval(tokens); + + // Timed forward pass + auto t0 = std::chrono::high_resolution_clock::now(); + auto output = g_model->forward(tokens); + + // Eval all layer K AND V tensors + std::vector cache_arrays; + for (auto& layer : g_model->layers) { + cache_arrays.push_back(layer.self_attn.last_k); + cache_arrays.push_back(layer.self_attn.last_v); + } + eval(cache_arrays); + auto t1 = std::chrono::high_resolution_clock::now(); + + double elapsed_ms = std::chrono::duration(t1 - t0).count(); + + // Checksum: sum of layer 0's K + auto& layer0_k = g_model->layers[0].self_attn.last_k; + eval(layer0_k); + auto checksum_arr = astype(sum(layer0_k), float32); + eval(checksum_arr); + float checksum = checksum_arr.item(); + + if (out_elapsed_ms) *out_elapsed_ms = elapsed_ms; + if (out_checksum) *out_checksum = checksum; + + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[pb2] run error: %s\n", e.what()); + return -1; + } +} + +void gemma_cleanup(void) { + g_model.reset(); + g_weight_store.clear(); + g_initialized = false; + g_finalized = false; + fprintf(stderr, "[pb2] Cleaned up\n"); +} + +} // extern "C" + +// ============================================================================ +// K/V export for Swift cache injection +// ============================================================================ + +// Get number of non-shared layers (= number of caches to populate) +extern "C" int gemma_num_layers() { + return g_model ? (int)g_model->layers.size() : 0; +} + +// Get K/V shape for a layer after forward: [1, kv_heads, seq_len, head_dim] +extern "C" int gemma_kv_shape(int layer_idx, int* out_kv_heads, int* out_seq_len, int* out_head_dim) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return -1; + auto& k = g_model->layers[layer_idx].self_attn.last_k; + if (k.size() == 0) return -2; + // Shape: [B, kv_heads, seq_len, head_dim] + *out_kv_heads = k.shape(1); + *out_seq_len = k.shape(2); + *out_head_dim = k.shape(3); + return 0; +} + +// Get byte size of K (or V) for a layer +extern "C" size_t gemma_kv_nbytes(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return 0; + auto& k = g_model->layers[layer_idx].self_attn.last_k; + return k.nbytes(); +} + +// Export K and V as CPU-side bfloat16 data. +// Caller allocates out_k and out_v buffers of gemma_kv_nbytes() each. +extern "C" int gemma_export_kv(int layer_idx, void* out_k, void* out_v) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return -1; + auto& attn = g_model->layers[layer_idx].self_attn; + if (attn.last_k.size() == 0) return -2; + + eval({attn.last_k, attn.last_v}); + + std::memcpy(out_k, attn.last_k.data(), attn.last_k.nbytes()); + std::memcpy(out_v, attn.last_v.data(), attn.last_v.nbytes()); + return 0; +} + +// Checksum of a layer's K: sum(K) as float +extern "C" float gemma_layer_k_checksum(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return 0; + auto& k = g_model->layers[layer_idx].self_attn.last_k; + if (k.size() == 0) return 0; + eval(k); + auto s = astype(sum(k), float32); + eval(s); + return s.item(); +} + +// Zero-copy K/V access: return raw mlx::core::array* pointers +// Swift can pass these to mlx-c functions via the ctx field +extern "C" void* gemma_get_k_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + return &(g_model->layers[layer_idx].self_attn.last_k); +} +extern "C" void* gemma_get_v_ptr(int layer_idx) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) return nullptr; + return &(g_model->layers[layer_idx].self_attn.last_v); +} + +// Create new heap-allocated mlx::core::array copies of K/V for a layer. +// Returns raw pointers via out params. Shares underlying GPU data buffer via shared_ptr. +// Caller takes ownership and must eventually delete (or pass to MLXArray which handles it). +extern "C" void gemma_get_kv_handles(int layer_idx, void** out_k_ptr, void** out_v_ptr) { + if (!g_model || layer_idx < 0 || layer_idx >= (int)g_model->layers.size()) { + if (out_k_ptr) *out_k_ptr = nullptr; + if (out_v_ptr) *out_v_ptr = nullptr; + return; + } + auto& attn = g_model->layers[layer_idx].self_attn; + + // new array(...) creates a lightweight copy that shares the underlying data buffer + if (out_k_ptr) *out_k_ptr = new mlx::core::array(attn.last_k); + if (out_v_ptr) *out_v_ptr = new mlx::core::array(attn.last_v); +} + diff --git a/Sources/NativePrefillBridge/prefill_bridge_gemma.h b/Sources/NativePrefillBridge/prefill_bridge_gemma.h new file mode 100644 index 0000000000..63e758c1dd --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_gemma.h @@ -0,0 +1,43 @@ +// prefill_bridge_gemma.h — Gemma-family native prefill bridge +// +// Dedicated prefill bridge for Gemma-4 E2B architectures. +// Accepts external weight arrays instead of loading its own. +#ifndef PREFILL_BRIDGE_GEMMA_H +#define PREFILL_BRIDGE_GEMMA_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Initialize bridge with model architecture (no weight loading) +int gemma_init(int num_layers, int hidden_size, int num_heads, int num_kv_heads, + int sliding_window, int sliding_window_pattern); + +// Set a weight tensor for the bridge (pass Swift's mlx_array ctx pointer) +// key: weight name like "layers.0.self_attn.q_proj.weight" +// arr_ptr: the mlx_array opaque handle from Swift (MLXArray.ctx) +int gemma_set_weight(const char* key, void* arr_ptr); + +// Mark initialization complete (all weights set) +int gemma_finalize(void); + +// Run prefill +int gemma_run(const int32_t* token_ids, int token_count, + double* out_elapsed_ms, float* out_checksum); + +// Run prefill with MLXArray pointer (zero-copy) +int gemma_run_array(void* token_arr_ptr, double* out_elapsed_ms, float* out_checksum); + +// Get K/V cache handles for a layer +void gemma_get_kv_handles(int layer_idx, void** out_k_ptr, void** out_v_ptr); + +// Cleanup +void gemma_cleanup(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Sources/NativePrefillBridge/prefill_bridge_qwen.cpp b/Sources/NativePrefillBridge/prefill_bridge_qwen.cpp new file mode 100644 index 0000000000..3561307192 --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_qwen.cpp @@ -0,0 +1,1048 @@ +// prefill_bridge_qwen.cpp — Qwen-family native prefill bridge +// +// Dedicated bridge for Qwen2, Qwen3 (dense), and Qwen3 MoE. +// Key differences from generic_prefill.cpp: +// - Qwen-specific eval barrier tuning +// - MoE routing optimized for softmax-only (no sigmoid/correction_bias) +// - Single forward path per architecture variant (no runtime dispatch) +// - Independent from other model families — changes here don't affect +// Mistral, Phi-4, GPT-OSS, etc. +// +// Architecture support: +// - qwen2: dense with optional attention bias, no QK norm +// - qwen3: dense with QK norm (per-head, after reshape) +// - qwen3_moe: MoE with SwitchGLU, softmax routing, QK norm + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlx/mlx.h" +#include "prefill_bridge_qwen.h" + +using namespace mlx::core; + +// ============================================================================ +// Per-stage profiler — enabled by QWEN_PROFILE=1 +// +// Forces eval+sync after each stage to get true GPU wall-clock time. +// This DESTROYS graph fusion, so numbers will be ~2-3x slower than +// production. The point is relative attribution, not absolute speed. +// ============================================================================ + +struct QwenProfiler { + bool enabled = false; + + // Accumulate across all layers + double embed_ms = 0, input_norm_ms = 0; + double qkv_proj_ms = 0, qk_norm_ms = 0, rope_ms = 0; + double kv_append_ms = 0, sdpa_ms = 0, o_proj_ms = 0; + double post_norm_ms = 0; + double moe_routing_ms = 0, moe_sort_ms = 0; + double moe_gqmm_gate_up_ms = 0, moe_silu_ms = 0, moe_gqmm_down_ms = 0; + double moe_combine_ms = 0; + double dense_mlp_ms = 0; + double eval_barrier_ms = 0, final_norm_ms = 0; + double residual_ms = 0; // residual adds + int layer_count = 0; + + using clock = std::chrono::high_resolution_clock; + clock::time_point tp; + + void tick() { if (enabled) tp = clock::now(); } + + double tock_ms() { + if (!enabled) return 0; + auto now = clock::now(); + return std::chrono::duration(now - tp).count(); + } + + // eval + sync + return elapsed since last tick + double sync_tock(const array& a) { + if (!enabled) return 0; + eval({a}); + return tock_ms(); + } + double sync_tock(const std::vector& v) { + if (!enabled) return 0; + eval(v); + return tock_ms(); + } + + void reset() { + embed_ms = input_norm_ms = 0; + qkv_proj_ms = qk_norm_ms = rope_ms = 0; + kv_append_ms = sdpa_ms = o_proj_ms = 0; + post_norm_ms = 0; + moe_routing_ms = moe_sort_ms = 0; + moe_gqmm_gate_up_ms = moe_silu_ms = moe_gqmm_down_ms = 0; + moe_combine_ms = 0; + dense_mlp_ms = 0; + eval_barrier_ms = final_norm_ms = 0; + residual_ms = 0; + layer_count = 0; + } + + void report(int seq_len) { + if (!enabled) return; + double moe_gqmm_ms = moe_gqmm_gate_up_ms + moe_silu_ms + moe_gqmm_down_ms; + double total = embed_ms + input_norm_ms + qkv_proj_ms + qk_norm_ms + + rope_ms + kv_append_ms + sdpa_ms + o_proj_ms + post_norm_ms + + moe_routing_ms + moe_sort_ms + moe_gqmm_ms + moe_combine_ms + + dense_mlp_ms + eval_barrier_ms + final_norm_ms + residual_ms; + + auto pct = [&](double v) { return total > 0 ? 100.0 * v / total : 0; }; + + fprintf(stderr, "\n[qwen-profile] === %d tokens, %d layers ===\n", seq_len, layer_count); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "embedding", embed_ms, pct(embed_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "input_norm", input_norm_ms, pct(input_norm_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "qkv_proj", qkv_proj_ms, pct(qkv_proj_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "qk_norm", qk_norm_ms, pct(qk_norm_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "rope", rope_ms, pct(rope_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "kv_append", kv_append_ms, pct(kv_append_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "sdpa", sdpa_ms, pct(sdpa_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "o_proj", o_proj_ms, pct(o_proj_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "residual_add", residual_ms, pct(residual_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "post_norm", post_norm_ms, pct(post_norm_ms)); + if (moe_routing_ms > 0 || moe_gqmm_ms > 0) { + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_routing", moe_routing_ms, pct(moe_routing_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_sort", moe_sort_ms, pct(moe_sort_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_gqmm_total", moe_gqmm_ms, pct(moe_gqmm_ms)); + fprintf(stderr, "[qwen-profile] %-18s %8.1fms (%5.1f%%)\n", "gate+up", moe_gqmm_gate_up_ms, pct(moe_gqmm_gate_up_ms)); + fprintf(stderr, "[qwen-profile] %-18s %8.1fms (%5.1f%%)\n", "silu*up", moe_silu_ms, pct(moe_silu_ms)); + fprintf(stderr, "[qwen-profile] %-18s %8.1fms (%5.1f%%)\n", "down", moe_gqmm_down_ms, pct(moe_gqmm_down_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "moe_combine", moe_combine_ms, pct(moe_combine_ms)); + } + if (dense_mlp_ms > 0) + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "dense_mlp", dense_mlp_ms, pct(dense_mlp_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "eval_barrier", eval_barrier_ms, pct(eval_barrier_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms (%5.1f%%)\n", "final_norm", final_norm_ms, pct(final_norm_ms)); + fprintf(stderr, "[qwen-profile] %-20s %8.1fms\n", "TOTAL", total); + fprintf(stderr, "[qwen-profile] %-20s %8.0f tok/s (profiled, ~2-3x slower than production)\n", + "throughput", seq_len / (total / 1000.0)); + } +}; + +static QwenProfiler g_prof; + +// ============================================================================ +// Primitives (same as generic but self-contained) +// ============================================================================ + +struct QuantizedLinear { + std::optional weight, scales, biases, linear_bias; + int group_size = 64, bits = 4; + bool quantized = true; + + array operator()(const array& x) const { + if (quantized) { + auto out = quantized_matmul(x, *weight, *scales, *biases, + true, group_size, bits, "affine"); + if (linear_bias) out = out + *linear_bias; + return out; + } + auto out = matmul(x, transpose(*weight)); + if (linear_bias) out = out + *linear_bias; + return out; + } +}; + +struct Norm { + std::optional weight; + float eps = 1e-6f; + array operator()(const array& x) const { + if (weight) return fast::rms_norm(x, *weight, eps); + return fast::rms_norm(x, std::nullopt, eps); + } +}; + +struct Embedding { + std::optional weight, scales, biases; + int group_size = 64, bits = 4; + bool quantized = false; + + array operator()(const array& indices) const { + if (quantized) { + return dequantize( + take(*weight, indices, 0), + take(*scales, indices, 0), + take(*biases, indices, 0), + group_size, bits, "affine"); + } + return take(*weight, indices, 0); + } +}; + +struct KVCache { + std::optional keys, values; + int offset = 0; + bool has_data() const { return keys.has_value(); } + void append(const array& k, const array& v, int S) { + if (keys) { + keys = concatenate({*keys, k}, 2); + values = concatenate({*values, v}, 2); + } else { + keys = k; values = v; + } + offset += S; + } + void reset() { keys.reset(); values.reset(); offset = 0; } +}; + +// ============================================================================ +// Config +// ============================================================================ + +struct QwenConfig { + std::string model_type; // "qwen2", "qwen3", "qwen3_moe" + int hidden_size = 0, num_layers = 0, num_heads = 0, num_kv_heads = 0; + int head_dim = 0, intermediate_size = 0, vocab_size = 0; + float rms_norm_eps = 1e-6f, rope_theta = 1000000.0f; + int rotary_dim = 0; + bool tie_word_embeddings = false, use_qk_norm = false; + int num_local_experts = 0, num_experts_per_tok = 0; + int quant_bits = 4, quant_group_size = 64; + bool is_moe() const { return num_local_experts > 0; } +}; + +// ============================================================================ +// MoE forward (Qwen3 softmax-only, no correction bias) +// ============================================================================ + +static array qwen_moe_forward( + const array& x, + const QuantizedLinear& gate, + const array& gate_w, const array& gate_s, const std::optional& gate_b, + const array& up_w, const array& up_s, const std::optional& up_b, + const array& down_w, const array& down_s, const std::optional& down_b, + int num_experts_per_tok, int group_size, + int gate_bits, int up_bits, int down_bits +) { + // Softmax routing (Qwen3 MoE only uses softmax, no sigmoid/correction) + // Match Swift: no float32 cast on gate input, use precise softmax instead + auto gates = gate(x); + auto scores = softmax(gates, -1, true); // precise=true matches Swift + int k = num_experts_per_tok; + + auto inds = argpartition(negative(gates), k - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), k}); + auto sel_scores = take_along_axis(scores, inds, -1); + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, x.dtype()); + + int B = x.shape(0), S = x.shape(1); + + // Expert-sorted dispatch (matches Swift gatherSort/scatterUnsort pattern) + auto x_exp = expand_dims(x, {-2, -3}); + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + auto inv_order = argsort(order); + auto x_sorted = take(flatten(x_exp, 0, -3), floor_divide(order, array(k)), 0); + auto sorted_inds = take(flat_inds, order, 0); + + auto gate_out = gather_qmm(x_sorted, gate_w, gate_s, gate_b, + std::nullopt, sorted_inds, true, group_size, gate_bits, "affine", true); + auto up_out = gather_qmm(x_sorted, up_w, up_s, up_b, + std::nullopt, sorted_inds, true, group_size, up_bits, "affine", true); + + auto hidden = (gate_out * sigmoid(gate_out)) * up_out; + + auto down_out = gather_qmm(hidden, down_w, down_s, down_b, + std::nullopt, sorted_inds, true, group_size, down_bits, "affine", true); + + down_out = squeeze(down_out, {-2}); + down_out = take(down_out, inv_order, 0); + down_out = reshape(down_out, {inds.shape(0), inds.shape(1), k, -1}); + + return sum(down_out * expand_dims(sel_scores, -1), -2); +} + +// Fused gate+up variant: single gather_qmm for gate+up, then split output +static array qwen_moe_forward_fused( + const array& x, + const QuantizedLinear& gate, + const array& fused_w, const array& fused_s, const std::optional& fused_b, + int gate_up_split, + const array& down_w, const array& down_s, const std::optional& down_b, + int num_experts_per_tok, int group_size, + int fused_bits, int down_bits +) { + auto gates = gate(x); + auto scores = softmax(gates, -1, true); + int k = num_experts_per_tok; + + auto inds = argpartition(negative(gates), k - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), k}); + auto sel_scores = take_along_axis(scores, inds, -1); + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, x.dtype()); + + int B = x.shape(0), S = x.shape(1); + + auto x_exp = expand_dims(x, {-2, -3}); + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + auto inv_order = argsort(order); + auto x_sorted = take(flatten(x_exp, 0, -3), floor_divide(order, array(k)), 0); + auto sorted_inds = take(flat_inds, order, 0); + + // Single gather_qmm for gate+up (fused along output dim) + auto fused_out = gather_qmm(x_sorted, fused_w, fused_s, fused_b, + std::nullopt, sorted_inds, true, group_size, fused_bits, "affine", true); + + auto gate_out = slice(fused_out, {0, 0, 0, 0}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), gate_up_split}); + auto up_out = slice(fused_out, {0, 0, 0, gate_up_split}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), fused_out.shape(3)}); + + auto hidden = (gate_out * sigmoid(gate_out)) * up_out; + + auto down_out = gather_qmm(hidden, down_w, down_s, down_b, + std::nullopt, sorted_inds, true, group_size, down_bits, "affine", true); + + down_out = squeeze(down_out, {-2}); + down_out = take(down_out, inv_order, 0); + down_out = reshape(down_out, {inds.shape(0), inds.shape(1), k, -1}); + + return sum(down_out * expand_dims(sel_scores, -1), -2); +} + +// ============================================================================ +// Dense MLP +// ============================================================================ + +static array qwen_mlp_forward( + const array& x, + const QuantizedLinear& gate_proj, + const QuantizedLinear& up_proj, + const QuantizedLinear& down_proj +) { + auto gate = gate_proj(x); + auto up = up_proj(x); + return down_proj((gate * sigmoid(gate)) * up); +} + +// ============================================================================ +// Attention +// ============================================================================ + +static array qwen_attention( + const array& x, + const QuantizedLinear& q_proj, const QuantizedLinear& k_proj, + const QuantizedLinear& v_proj, const QuantizedLinear& o_proj, + const Norm* q_norm, const Norm* k_norm, + int num_heads, int num_kv_heads, int head_dim, + float rope_theta, int rotary_dim, + KVCache& cache, int rope_offset +) { + int B = x.shape(0), S = x.shape(1); + auto q = q_proj(x), k = k_proj(x), v = v_proj(x); + + q = reshape(q, {B, S, num_heads, head_dim}); + k = reshape(k, {B, S, num_kv_heads, head_dim}); + v = reshape(v, {B, S, num_kv_heads, head_dim}); + + // QK norm applied BEFORE transpose (matches Swift — norm on contiguous layout) + if (q_norm) { q = (*q_norm)(q); k = (*k_norm)(k); } + + q = transpose(q, {0, 2, 1, 3}); + k = transpose(k, {0, 2, 1, 3}); + v = transpose(v, {0, 2, 1, 3}); + + int rot = rotary_dim > 0 ? rotary_dim : head_dim; + q = fast::rope(q, rot, false, rope_theta, 1.0f, rope_offset); + k = fast::rope(k, rot, false, rope_theta, 1.0f, rope_offset); + + // KV dtype matches model's quantization scales + auto kv_dtype = k_proj.scales ? k_proj.scales->dtype() : float16; + k = astype(k, kv_dtype); + v = astype(v, kv_dtype); + cache.append(k, v, S); + + float scale = 1.0f / std::sqrt(static_cast(head_dim)); + auto attn = fast::scaled_dot_product_attention( + q, *cache.keys, *cache.values, scale, "causal"); + + attn = reshape(transpose(attn, {0, 2, 1, 3}), {B, S, num_heads * head_dim}); + return o_proj(attn); +} + +// ============================================================================ +// Layer +// ============================================================================ + +struct MoEWeights { + QuantizedLinear gate; + // Original per-projection weights (kept for reference/fallback) + std::optional gate_w, gate_s, gate_b; + std::optional up_w, up_s, up_b; + std::optional down_w, down_s, down_b; + // Fused gate+up weights (concatenated along output dim for single gather_qmm) + std::optional fused_gate_up_w, fused_gate_up_s, fused_gate_up_b; + int gate_up_split = 0; // output dim to split at (= intermediate_size / pack_factor) + int num_experts_per_tok = 0; + int gate_bits = 4, up_bits = 4, down_bits = 4; + bool use_fused_gate_up = false; +}; + +struct QwenLayer { + Norm input_norm, post_attn_norm; + QuantizedLinear q_proj, k_proj, v_proj, o_proj; + Norm q_norm, k_norm; + bool has_qk_norm = false; + + // Dense MLP (qwen2/qwen3 dense) + QuantizedLinear gate_proj, up_proj, down_proj; + + // MoE (qwen3_moe) + bool is_moe = false; + std::optional moe; + + float rope_theta = 1000000.0f; + int rotary_dim = 0; + int num_heads = 0, num_kv_heads = 0, head_dim = 0; + int group_size = 64; + + KVCache cache; +}; + +// ============================================================================ +// Model +// ============================================================================ + +struct QwenModel { + QwenConfig config; + Embedding embed_tokens; + std::vector layers; + Norm final_norm; + + // Tunable: how many layers per eval barrier. + // Set via QWEN_EVAL_CADENCE env var for experimentation. + int eval_cadence = 8; + + // Production forward — no profiling overhead + array forward(const array& token_ids) { + int B = token_ids.shape(0), S = token_ids.shape(1); + auto h = embed_tokens(token_ids); + + for (int i = 0; i < (int)layers.size(); i++) { + auto& L = layers[i]; + auto residual = h; + + auto normed = L.input_norm(h); + auto attn_out = qwen_attention(normed, + L.q_proj, L.k_proj, L.v_proj, L.o_proj, + L.has_qk_norm ? &L.q_norm : nullptr, + L.has_qk_norm ? &L.k_norm : nullptr, + L.num_heads, L.num_kv_heads, L.head_dim, + L.rope_theta, L.rotary_dim, + L.cache, 0); + h = residual + attn_out; + + residual = h; + if (L.is_moe) { + auto normed_ff = L.post_attn_norm(h); + if (L.moe->use_fused_gate_up) { + h = residual + qwen_moe_forward_fused(normed_ff, + L.moe->gate, + *L.moe->fused_gate_up_w, *L.moe->fused_gate_up_s, L.moe->fused_gate_up_b, + L.moe->gate_up_split, + *L.moe->down_w, *L.moe->down_s, L.moe->down_b, + L.moe->num_experts_per_tok, L.group_size, + L.moe->gate_bits, L.moe->down_bits); + } else { + h = residual + qwen_moe_forward(normed_ff, + L.moe->gate, + *L.moe->gate_w, *L.moe->gate_s, L.moe->gate_b, + *L.moe->up_w, *L.moe->up_s, L.moe->up_b, + *L.moe->down_w, *L.moe->down_s, L.moe->down_b, + L.moe->num_experts_per_tok, L.group_size, + L.moe->gate_bits, L.moe->up_bits, L.moe->down_bits); + } + } else { + auto normed_ff = L.post_attn_norm(h); + h = residual + qwen_mlp_forward(normed_ff, + L.gate_proj, L.up_proj, L.down_proj); + } + + // No intermediate barriers — single eval at the end in qwen_run + // matches Swift's pattern of building one massive lazy graph + } + + return final_norm(h); + } + + // Profiled forward — eval+sync after every stage for accurate attribution. + // ~2-3x slower than production due to killed graph fusion. + array forward_profiled(const array& token_ids) { + auto& P = g_prof; + P.reset(); + int B = token_ids.shape(0), S = token_ids.shape(1); + + // Embedding + P.tick(); + auto h = embed_tokens(token_ids); + P.embed_ms += P.sync_tock(h); + + for (int i = 0; i < (int)layers.size(); i++) { + auto& L = layers[i]; + P.layer_count++; + + // Input norm + P.tick(); + auto normed = L.input_norm(h); + P.input_norm_ms += P.sync_tock(normed); + + // Q/K/V projections + P.tick(); + auto q = L.q_proj(normed), k = L.k_proj(normed), v = L.v_proj(normed); + P.qkv_proj_ms += P.sync_tock({q, k, v}); + + // Reshape (norm before transpose — matches Swift contiguous layout) + q = reshape(q, {B, S, L.num_heads, L.head_dim}); + k = reshape(k, {B, S, L.num_kv_heads, L.head_dim}); + v = reshape(v, {B, S, L.num_kv_heads, L.head_dim}); + + // QK norm (before transpose — on contiguous layout) + if (L.has_qk_norm) { + P.tick(); + q = L.q_norm(q); k = L.k_norm(k); + P.qk_norm_ms += P.sync_tock({q, k}); + } + + q = transpose(q, {0, 2, 1, 3}); + k = transpose(k, {0, 2, 1, 3}); + v = transpose(v, {0, 2, 1, 3}); + + // RoPE + P.tick(); + int rot = L.rotary_dim > 0 ? L.rotary_dim : L.head_dim; + q = fast::rope(q, rot, false, L.rope_theta, 1.0f, 0); + k = fast::rope(k, rot, false, L.rope_theta, 1.0f, 0); + P.rope_ms += P.sync_tock({q, k}); + + // KV cache append + P.tick(); + auto kv_dtype = L.k_proj.scales ? L.k_proj.scales->dtype() : float16; + k = astype(k, kv_dtype); + v = astype(v, kv_dtype); + L.cache.append(k, v, S); + P.kv_append_ms += P.sync_tock({*L.cache.keys, *L.cache.values}); + + // SDPA + P.tick(); + float scale = 1.0f / std::sqrt(static_cast(L.head_dim)); + auto attn = fast::scaled_dot_product_attention( + q, *L.cache.keys, *L.cache.values, scale, "causal"); + P.sdpa_ms += P.sync_tock(attn); + + // O proj + P.tick(); + attn = reshape(transpose(attn, {0, 2, 1, 3}), {B, S, L.num_heads * L.head_dim}); + auto attn_out = L.o_proj(attn); + P.o_proj_ms += P.sync_tock(attn_out); + + // Residual add + P.tick(); + h = h + attn_out; + P.residual_ms += P.sync_tock(h); + + // Post-attention norm + P.tick(); + auto normed_ff = L.post_attn_norm(h); + P.post_norm_ms += P.sync_tock(normed_ff); + + // MoE or dense MLP + if (L.is_moe) { + // MoE routing (gate + softmax + topk + score normalize) + P.tick(); + auto gates = L.moe->gate(normed_ff); + auto scores = softmax(gates, -1, true); + int kk = L.moe->num_experts_per_tok; + auto inds = argpartition(negative(gates), kk - 1, -1); + inds = slice(inds, {0, 0, 0}, {inds.shape(0), inds.shape(1), kk}); + auto sel_scores = take_along_axis(scores, inds, -1); + sel_scores = sel_scores / (sum(sel_scores, -1, true) + 1e-20f); + sel_scores = astype(sel_scores, normed_ff.dtype()); + P.moe_routing_ms += P.sync_tock({inds, sel_scores}); + + // Expert sort + dispatch prep + P.tick(); + auto x_exp = expand_dims(normed_ff, {-2, -3}); + auto flat_inds = flatten(inds); + auto order = argsort(flat_inds); + auto inv_order = argsort(order); + auto x_sorted = take(flatten(x_exp, 0, -3), floor_divide(order, array(kk)), 0); + auto sorted_inds = take(flat_inds, order, 0); + P.moe_sort_ms += P.sync_tock({x_sorted, sorted_inds, inv_order}); + + // gather_qmm: gate + up (fused or separate) + P.tick(); + std::optional gate_out_opt, up_out_opt; + if (L.moe->use_fused_gate_up) { + auto fused_out = gather_qmm(x_sorted, + *L.moe->fused_gate_up_w, *L.moe->fused_gate_up_s, L.moe->fused_gate_up_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->gate_bits, "affine", true); + int sp = L.moe->gate_up_split; + gate_out_opt = slice(fused_out, {0, 0, 0, 0}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), sp}); + up_out_opt = slice(fused_out, {0, 0, 0, sp}, + {fused_out.shape(0), fused_out.shape(1), fused_out.shape(2), fused_out.shape(3)}); + } else { + gate_out_opt = gather_qmm(x_sorted, *L.moe->gate_w, *L.moe->gate_s, L.moe->gate_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->gate_bits, "affine", true); + up_out_opt = gather_qmm(x_sorted, *L.moe->up_w, *L.moe->up_s, L.moe->up_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->up_bits, "affine", true); + } + auto& gate_out = *gate_out_opt; + auto& up_out = *up_out_opt; + P.moe_gqmm_gate_up_ms += P.sync_tock({gate_out, up_out}); + + // SiLU activation + elementwise multiply + P.tick(); + auto hidden = (gate_out * sigmoid(gate_out)) * up_out; + P.moe_silu_ms += P.sync_tock(hidden); + + // gather_qmm: down projection + P.tick(); + auto down_out = gather_qmm(hidden, *L.moe->down_w, *L.moe->down_s, L.moe->down_b, + std::nullopt, sorted_inds, true, L.group_size, L.moe->down_bits, "affine", true); + P.moe_gqmm_down_ms += P.sync_tock(down_out); + + // Combine (unsort + weighted sum + residual) + P.tick(); + down_out = squeeze(down_out, {-2}); + down_out = take(down_out, inv_order, 0); + down_out = reshape(down_out, {inds.shape(0), inds.shape(1), kk, -1}); + auto moe_out = sum(down_out * expand_dims(sel_scores, -1), -2); + h = h + moe_out; + P.moe_combine_ms += P.sync_tock(h); + } else { + P.tick(); + auto mlp_out = qwen_mlp_forward(normed_ff, + L.gate_proj, L.up_proj, L.down_proj); + h = h + mlp_out; + P.dense_mlp_ms += P.sync_tock(h); + } + + // Eval barrier (still needed even in profiled mode for KV correctness) + if ((i + 1) % eval_cadence == 0 || i == (int)layers.size() - 1) { + P.tick(); + std::vector to_sync = {h}; + if (L.cache.has_data()) { + to_sync.push_back(*L.cache.keys); + to_sync.push_back(*L.cache.values); + } + eval(to_sync); + P.eval_barrier_ms += P.tock_ms(); + } + } + + P.tick(); + auto out = final_norm(h); + P.final_norm_ms += P.sync_tock(out); + P.report(S); + + return out; + } +}; + +// ============================================================================ +// Global state +// ============================================================================ + +static std::unique_ptr g_model; +static std::unordered_map g_weights; +static QwenConfig g_config; +static bool g_initialized = false, g_finalized = false; + +// ============================================================================ +// Weight helpers +// ============================================================================ + +static array extract_array(void* ptr) { return *static_cast(ptr); } + +static array get_w(const std::string& key) { + auto it = g_weights.find(key); + if (it == g_weights.end()) throw std::runtime_error("Missing weight: " + key); + return it->second; +} + +static bool has_w(const std::string& key) { return g_weights.count(key) > 0; } + +static QuantizedLinear make_qlinear(const std::string& prefix) { + int gs = g_config.quant_group_size; + if (has_w(prefix + ".scales")) { + auto w = get_w(prefix + ".weight"); + auto s = get_w(prefix + ".scales"); + auto bi = get_w(prefix + ".biases"); + int w_last = w.shape(-1), s_last = s.shape(-1); + int b = (s_last > 0) ? (w_last * 32) / (s_last * gs) : g_config.quant_bits; + if (b == 0) b = g_config.quant_bits; + std::optional lb; + if (has_w(prefix + ".bias")) lb = get_w(prefix + ".bias"); + return {w, s, bi, lb, gs, b, true}; + } + std::optional lb; + if (has_w(prefix + ".bias")) lb = get_w(prefix + ".bias"); + return {get_w(prefix + ".weight"), array(0.0f), array(0.0f), lb, gs, g_config.quant_bits, false}; +} + +static int detect_bits(const std::string& wk, const std::string& sk) { + if (!has_w(wk) || !has_w(sk)) return g_config.quant_bits; + return (get_w(wk).shape(-1) * 32) / (get_w(sk).shape(-1) * g_config.quant_group_size); +} + +static Norm make_norm(const std::string& prefix) { + return {get_w(prefix + ".weight"), g_config.rms_norm_eps}; +} + +static Embedding make_embedding(const std::string& prefix) { + Embedding emb; + emb.weight = get_w(prefix + ".weight"); + eval({*emb.weight}); + if (has_w(prefix + ".scales")) { + emb.scales = get_w(prefix + ".scales"); + emb.biases = get_w(prefix + ".biases"); + eval({*emb.scales, *emb.biases}); + emb.group_size = g_config.quant_group_size; + emb.bits = detect_bits(prefix + ".weight", prefix + ".scales"); + emb.quantized = true; + } + return emb; +} + +// ============================================================================ +// Layer builders +// ============================================================================ + +static void build_dense_layer(QwenLayer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + + layer.gate_proj = make_qlinear(p + ".mlp.gate_proj"); + layer.up_proj = make_qlinear(p + ".mlp.up_proj"); + layer.down_proj = make_qlinear(p + ".mlp.down_proj"); + layer.is_moe = false; + + // Force-eval layer weights to pin GPU buffers + std::vector lw = { + *layer.q_proj.weight, *layer.q_proj.scales, + *layer.k_proj.weight, *layer.k_proj.scales, + *layer.v_proj.weight, *layer.v_proj.scales, + *layer.o_proj.weight, *layer.o_proj.scales, + *layer.gate_proj.weight, *layer.gate_proj.scales, + *layer.up_proj.weight, *layer.up_proj.scales, + *layer.down_proj.weight, *layer.down_proj.scales, + *layer.input_norm.weight, *layer.post_attn_norm.weight + }; + if (layer.q_proj.linear_bias) { + lw.push_back(*layer.q_proj.linear_bias); + lw.push_back(*layer.k_proj.linear_bias); + lw.push_back(*layer.v_proj.linear_bias); + } + eval(lw); +} + +static void build_moe_layer(QwenLayer& layer, int idx) { + std::string p = "model.layers." + std::to_string(idx); + layer.input_norm = make_norm(p + ".input_layernorm"); + layer.post_attn_norm = make_norm(p + ".post_attention_layernorm"); + layer.q_proj = make_qlinear(p + ".self_attn.q_proj"); + layer.k_proj = make_qlinear(p + ".self_attn.k_proj"); + layer.v_proj = make_qlinear(p + ".self_attn.v_proj"); + layer.o_proj = make_qlinear(p + ".self_attn.o_proj"); + + if (g_config.use_qk_norm) { + layer.q_norm = make_norm(p + ".self_attn.q_norm"); + layer.k_norm = make_norm(p + ".self_attn.k_norm"); + layer.has_qk_norm = true; + } + + layer.rope_theta = g_config.rope_theta; + layer.rotary_dim = g_config.rotary_dim; + layer.num_heads = g_config.num_heads; + layer.num_kv_heads = g_config.num_kv_heads; + layer.head_dim = g_config.head_dim; + layer.group_size = g_config.quant_group_size; + + layer.is_moe = true; + layer.moe.emplace(); + layer.moe->gate = make_qlinear(p + ".mlp.gate"); + layer.moe->gate_w = get_w(p + ".mlp.switch_mlp.gate_proj.weight"); + layer.moe->gate_s = get_w(p + ".mlp.switch_mlp.gate_proj.scales"); + layer.moe->gate_b = get_w(p + ".mlp.switch_mlp.gate_proj.biases"); + layer.moe->up_w = get_w(p + ".mlp.switch_mlp.up_proj.weight"); + layer.moe->up_s = get_w(p + ".mlp.switch_mlp.up_proj.scales"); + layer.moe->up_b = get_w(p + ".mlp.switch_mlp.up_proj.biases"); + layer.moe->down_w = get_w(p + ".mlp.switch_mlp.down_proj.weight"); + layer.moe->down_s = get_w(p + ".mlp.switch_mlp.down_proj.scales"); + layer.moe->down_b = get_w(p + ".mlp.switch_mlp.down_proj.biases"); + std::string moe_p = p + ".mlp.switch_mlp"; + layer.moe->gate_bits = detect_bits(moe_p + ".gate_proj.weight", moe_p + ".gate_proj.scales"); + layer.moe->up_bits = detect_bits(moe_p + ".up_proj.weight", moe_p + ".up_proj.scales"); + layer.moe->down_bits = detect_bits(moe_p + ".down_proj.weight", moe_p + ".down_proj.scales"); + layer.moe->num_experts_per_tok = g_config.num_experts_per_tok; + + // Fuse gate+up weights: concatenate along output dim (axis=1) for single gather_qmm. + // Only valid when gate and up have identical quantization config. + // NOTE: measured ~+1% at 1k but -3% at 4k — larger N hurts kernel efficiency. + // Disabled by default. Set QWEN_FUSE_GATE_UP=1 to enable. + const char* fuse_env = std::getenv("QWEN_FUSE_GATE_UP"); + if (fuse_env && std::string(fuse_env) == "1" && layer.moe->gate_bits == layer.moe->up_bits) { + auto& gw = *layer.moe->gate_w; + auto& uw = *layer.moe->up_w; + auto& gs = *layer.moe->gate_s; + auto& us = *layer.moe->up_s; + auto& gb = *layer.moe->gate_b; + auto& ub = *layer.moe->up_b; + layer.moe->fused_gate_up_w = concatenate({gw, uw}, 1); + layer.moe->fused_gate_up_s = concatenate({gs, us}, 1); + layer.moe->fused_gate_up_b = concatenate({gb, ub}, 1); + layer.moe->gate_up_split = gw.shape(1); // split point in output dim + eval({*layer.moe->fused_gate_up_w, *layer.moe->fused_gate_up_s, + *layer.moe->fused_gate_up_b}); + layer.moe->use_fused_gate_up = true; + if (idx == 0) + } +} + +// ============================================================================ +// Model builder +// ============================================================================ + +static QwenModel build_model() { + QwenModel m; + m.config = g_config; + + // Tunable eval cadence from env + const char* cadence_env = std::getenv("QWEN_EVAL_CADENCE"); + m.eval_cadence = cadence_env ? std::atoi(cadence_env) : 8; + + m.embed_tokens = make_embedding("model.embed_tokens"); + m.final_norm = make_norm("model.norm"); + + int N = g_config.num_layers; + m.layers.reserve(N); + for (int i = 0; i < N; i++) { + m.layers.emplace_back(); + if (g_config.is_moe()) { + build_moe_layer(m.layers[i], i); + } else { + build_dense_layer(m.layers[i], i); + } + } + + // Log MoE weight shapes for optimization analysis + if (g_config.is_moe() && N > 0 && m.layers[0].is_moe) { + auto& moe = *m.layers[0].moe; + auto shape_str = [](const array& a) { + std::string s = "["; + for (int d = 0; d < a.ndim(); d++) { + if (d) s += ","; + s += std::to_string(a.shape(d)); + } + return s + "]"; + }; + } + + fprintf(stderr, "[qwen] Model built: %d layers, %s\n", + N, g_config.is_moe() ? "MoE" : "dense"); + return m; +} + +// ============================================================================ +// JSON parsing (minimal) +// ============================================================================ + +static std::string json_str(const std::string& j, const std::string& k) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return ""; + p = j.find(":", p); auto s = j.find("\"", p+1); auto e = j.find("\"", s+1); + return j.substr(s+1, e-s-1); +} +static int json_int(const std::string& j, const std::string& k, int d=0) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return d; + p = j.find(":", p); auto s = j.find_first_of("-0123456789", p+1); + auto e = j.find_first_not_of("-0123456789", s); + return std::stoi(j.substr(s, e-s)); +} +static float json_float(const std::string& j, const std::string& k, float d=0) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return d; + p = j.find(":", p); auto s = j.find_first_of("-0123456789.", p+1); + auto e = j.find_first_not_of("-0123456789.eE+-", s); + return std::stof(j.substr(s, e-s)); +} +static bool json_bool(const std::string& j, const std::string& k, bool d=false) { + auto p = j.find("\"" + k + "\""); + if (p == std::string::npos) return d; + p = j.find(":", p); auto s = j.find_first_not_of(" \t\n", p+1); + return j.substr(s, 4) == "true"; +} + +// ============================================================================ +// C ABI +// ============================================================================ + +extern "C" { + +int qwen_init(const char* config_json) { + try { + std::string j(config_json); + g_config.model_type = json_str(j, "model_type"); + g_config.hidden_size = json_int(j, "hidden_size", 2048); + g_config.num_layers = json_int(j, "num_hidden_layers", 28); + g_config.num_heads = json_int(j, "num_attention_heads", 16); + g_config.num_kv_heads = json_int(j, "num_key_value_heads", 2); + g_config.head_dim = json_int(j, "head_dim", 128); + g_config.intermediate_size = json_int(j, "intermediate_size", 8960); + g_config.vocab_size = json_int(j, "vocab_size", 151936); + g_config.rms_norm_eps = json_float(j, "rms_norm_eps", 1e-6f); + g_config.rope_theta = json_float(j, "rope_theta", 1000000.0f); + g_config.rotary_dim = json_int(j, "rotary_dim", 0); + g_config.tie_word_embeddings = json_bool(j, "tie_word_embeddings", false); + g_config.use_qk_norm = json_bool(j, "use_qk_norm", false); + g_config.num_local_experts = json_int(j, "num_local_experts", 0); + g_config.num_experts_per_tok = json_int(j, "num_experts_per_tok", 0); + + g_weights.clear(); + g_model.reset(); + g_initialized = true; + g_finalized = false; + + // Profiling: QWEN_PROFILE=1 enables per-stage timing + const char* prof_env = std::getenv("QWEN_PROFILE"); + g_prof.enabled = prof_env && std::string(prof_env) == "1"; + if (g_prof.enabled) + fprintf(stderr, "[qwen] PROFILING ENABLED — will eval+sync per stage (slower)\n"); + + fprintf(stderr, "[qwen] Init: type=%s layers=%d hidden=%d heads=%d/%d hd=%d experts=%d\n", + g_config.model_type.c_str(), g_config.num_layers, + g_config.hidden_size, g_config.num_heads, g_config.num_kv_heads, + g_config.head_dim, g_config.num_local_experts); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] init error: %s\n", e.what()); + return -1; + } +} + +int qwen_set_weight(const char* key, void* arr_ptr) { + if (!g_initialized || g_finalized) return -1; + try { + g_weights.insert_or_assign(std::string(key), extract_array(arr_ptr)); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] set_weight error '%s': %s\n", key, e.what()); + return -1; + } +} + +int qwen_finalize(void) { + if (!g_initialized || g_finalized) return -1; + try { + g_model = std::make_unique(build_model()); + g_finalized = true; + g_weights.clear(); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] finalize error: %s\n", e.what()); + return -1; + } +} + +int qwen_run(void* token_array_ptr, double* out_elapsed_ms) { + if (!g_model) return -1; + try { + auto& tokens = *static_cast(token_array_ptr); + auto t0 = std::chrono::high_resolution_clock::now(); + + for (auto& layer : g_model->layers) layer.cache.reset(); + + auto output = g_prof.enabled + ? g_model->forward_profiled(tokens) + : g_model->forward(tokens); + + // Async eval of all KV caches — non-blocking, GPU work overlaps + // with Swift-side KV injection. The arrays will be materialized + // when Swift's cache.update() accesses them. + std::vector to_eval; + for (auto& layer : g_model->layers) { + if (layer.cache.has_data()) { + to_eval.push_back(*layer.cache.keys); + to_eval.push_back(*layer.cache.values); + } + } + async_eval(to_eval); + + auto t1 = std::chrono::high_resolution_clock::now(); + if (out_elapsed_ms) + *out_elapsed_ms = std::chrono::duration(t1 - t0).count(); + return 0; + } catch (const std::exception& e) { + fprintf(stderr, "[qwen] run error: %s\n", e.what()); + return -1; + } +} + +int qwen_num_cache_layers(void) { + return g_model ? (int)g_model->layers.size() : 0; +} + +void* qwen_get_k_ptr(int i) { + if (!g_model || i < 0 || i >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[i].cache; + return c.keys ? new array(*c.keys) : nullptr; +} + +void* qwen_get_v_ptr(int i) { + if (!g_model || i < 0 || i >= (int)g_model->layers.size()) return nullptr; + auto& c = g_model->layers[i].cache; + return c.values ? new array(*c.values) : nullptr; +} + +int qwen_kv_shape(int i, int* kv_heads, int* seq_len, int* head_dim) { + if (!g_model || i < 0 || i >= (int)g_model->layers.size()) return -1; + auto& c = g_model->layers[i].cache; + if (!c.has_data()) return -2; + *kv_heads = c.keys->shape(1); + *seq_len = c.keys->shape(2); + *head_dim = c.keys->shape(3); + return 0; +} + +void qwen_cleanup(void) { + g_model.reset(); + g_weights.clear(); + g_initialized = false; + g_finalized = false; +} + +} // extern "C" diff --git a/Sources/NativePrefillBridge/prefill_bridge_qwen.h b/Sources/NativePrefillBridge/prefill_bridge_qwen.h new file mode 100644 index 0000000000..9b00ee11c9 --- /dev/null +++ b/Sources/NativePrefillBridge/prefill_bridge_qwen.h @@ -0,0 +1,47 @@ +// prefill_bridge_qwen.h — Qwen-family native prefill bridge +// +// Dedicated prefill bridge for Qwen2, Qwen3, and Qwen3-MoE architectures. +// Separated from generic_prefill.cpp to allow Qwen-specific tuning +// (eval barriers, graph structure, MoE dispatch) without risking +// regressions on other model families. +// +// Integration: called from Qwen Swift model prepare() methods. +#ifndef PREFILL_BRIDGE_QWEN_H +#define PREFILL_BRIDGE_QWEN_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// Initialize with Qwen model config JSON +int qwen_init(const char* config_json); + +// Set a weight tensor (pass Swift's MLXArray.ctx pointer) +int qwen_set_weight(const char* key, void* arr_ptr); + +// Mark initialization complete — builds model from weights +int qwen_finalize(void); + +// Run prefill on token array (pass MLXArray.ctx pointer) +int qwen_run(void* token_array_ptr, double* out_elapsed_ms); + +// Get number of KV cache layers +int qwen_num_cache_layers(void); + +// Get K/V array pointers for cache injection +void* qwen_get_k_ptr(int layer_idx); +void* qwen_get_v_ptr(int layer_idx); + +// KV shape info +int qwen_kv_shape(int layer_idx, int* kv_heads, int* seq_len, int* head_dim); + +// Cleanup +void qwen_cleanup(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Tests/Benchmarks/InferenceBenchmark.swift b/Tests/Benchmarks/InferenceBenchmark.swift new file mode 100644 index 0000000000..8b031f6393 --- /dev/null +++ b/Tests/Benchmarks/InferenceBenchmark.swift @@ -0,0 +1,2069 @@ +import Foundation +import Testing +import MLX +import MLXNN +import MLXLMCommon +import MLXLLM +import HuggingFace +import MLXHuggingFace +import Tokenizers + +// MARK: - HuggingFace Integration + +// Macro-generated bridges from MLXHuggingFace: +// - `#hubDownloader()` wraps `HubClient.default` (cache-first; auto-detects +// `~/.cache/huggingface/hub` unless `HF_HUB_CACHE` / `HF_HOME` override it) +// as an `MLXLMCommon.Downloader`. +// - `#huggingFaceTokenizerLoader()` wraps swift-transformers' `AutoTokenizer` +// as an `MLXLMCommon.TokenizerLoader`. +// +// The pattern mirrors `IntegrationTesting/IntegrationTestingTests/ToolCallIntegrationTests.swift`. +private let benchmarkDownloader: any Downloader = #hubDownloader() +private let benchmarkTokenizerLoader: any TokenizerLoader = #huggingFaceTokenizerLoader() + +// MARK: - Thinking Budget Processor + +/// Forces after a token budget to prevent unbounded thinking phases. +/// This keeps benchmarks tractable: models think up to `maxThinkingTokens`, +/// then must emit and generate the actual response. +/// Reference-type box for additive logit-suppression masks, populated lazily +/// on the first `process()` call (vocab size isn't known at processor init). +/// The containing processor is a struct with a non-mutating `process(logits:)` +/// per the `LogitProcessor` protocol, so cacheing through this shared class +/// lets us populate the masks without making `process` mutating. +fileprivate final class SuppressMaskCache { + var thinking: MLXArray? + var postExhaust: MLXArray? +} + +private struct ThinkingBudgetProcessor: LogitProcessor { + let thinkStartTokenId: Int32 + let thinkEndTokenId: Int32 + let maxThinkingTokens: Int + let initialThinkingPhase: Bool + /// EOS token IDs to suppress while in thinking phase, preventing the model from + /// terminating before generating and actual response text. + let eosTokenIds: [Int32] + + var inThinkingPhase: Bool + var thinkingTokenCount: Int = 0 + /// Set when the budget forces . Prevents the model from re-entering + /// thinking mode by suppressing in all subsequent tokens. Without this, + /// models (especially Gemma 4) immediately re-emit <|channel> after the forced + /// , creating a marker-only loop that consumes the generation budget + /// with no actual content — resulting in Gen PPL = nil. + var budgetExhausted: Bool = false + + /// Pre-built additive masks applied to logits via one `+` op, replacing the + /// previous scatter-per-suppressed-token loop. Shape `[V]`, value 0 at all + /// positions except suppressed IDs which hold -inf. Built lazily on the + /// first `process()` call when the vocabulary size is first observed. + /// + /// Stored in a reference-type box because `process(logits:)` is non-mutating + /// on the `LogitProcessor` protocol — we need to populate the cache without + /// marking the method mutating. + let masks = SuppressMaskCache() + + /// Lazy accumulator of sampled tokens awaiting a batched state-machine + /// update. Batching eliminates the per-token GPU→CPU sync that would + /// otherwise block the next forward-pass dispatch on every step — the + /// primary source of `--think` decode overhead on large models. The + /// iterator has already called `asyncEval(token)` on every pending entry, + /// so by the time we flush, evaluation is in flight and a single `eval` + /// call syncs the whole batch. + var pendingTokens: [MLXArray] = [] + + /// Upper bound on pending-token buffer size. The state machine may be up + /// to `flushBatchSize - 1` steps stale between flushes, which can cause + /// the thinking budget to overshoot by the same amount. Chosen small + /// enough that the overshoot is ≤5% of a typical 200-token budget. + private static let flushBatchSize = 10 + + init( + thinkStartTokenId: Int32, thinkEndTokenId: Int32, + maxThinkingTokens: Int, prefilled: Bool = false, + eosTokenIds: [Int32] = [] + ) { + self.thinkStartTokenId = thinkStartTokenId + self.thinkEndTokenId = thinkEndTokenId + self.maxThinkingTokens = maxThinkingTokens + self.initialThinkingPhase = prefilled + self.inThinkingPhase = prefilled + self.eosTokenIds = eosTokenIds + } + + mutating func prompt(_ prompt: MLXArray) { + inThinkingPhase = initialThinkingPhase + thinkingTokenCount = 0 + budgetExhausted = false + pendingTokens.removeAll(keepingCapacity: true) + } + + func process(logits: MLXArray) -> MLXArray { + // Lazy mask construction: vocab size only known once we see the logits. + // Shape [V] broadcasts against both [V] and [1, V] input shapes. + let vocab = logits.shape.last ?? 0 + if masks.thinking == nil && vocab > 0 { + masks.thinking = buildSuppressMask( + suppressedIds: eosTokenIds, vocabSize: vocab) + } + if masks.postExhaust == nil && vocab > 0 { + masks.postExhaust = buildSuppressMask( + suppressedIds: [thinkStartTokenId], vocabSize: vocab) + } + + // After budget exhaustion, suppress think-start to prevent re-entry loops. + if budgetExhausted && !inThinkingPhase { + if let m = masks.postExhaust { + return logits + m + } + return logits + } + + guard inThinkingPhase else { return logits } + + // Single elementwise-add replaces the per-EOS scatter loop. + var modified = logits + if let m = masks.thinking { + modified = modified + m + } + + // Budget exceeded: force by boosting its logit to dominate softmax. + // Use a large FINITE value (not +inf) — softmax(+inf) = exp(+inf)/sum = NaN + // which causes the sampler to return garbage (token 0), never triggering transition. + // With logits typically in [-30, 30], 100.0 gives P() ≈ 1.0 with no NaN. + // + // NB: due to batched state flushing, thinkingTokenCount may lag by up to + // `flushBatchSize` tokens. This means the forced actually triggers + // somewhere in the [budget, budget + flushBatchSize) range. For a typical + // 200-token budget that's ≤5% overshoot — acceptable slack in exchange + // for removing the per-step GPU sync. + if thinkingTokenCount >= maxThinkingTokens { + if logits.ndim == 1 { + modified[Int(thinkEndTokenId)] = MLXArray(Float(100.0)) + modified[Int(thinkStartTokenId)] = MLXArray(-Float.infinity) + } else { + modified[0..., Int(thinkEndTokenId)] = MLXArray(Float(100.0)) + modified[0..., Int(thinkStartTokenId)] = MLXArray(-Float.infinity) + } + } + + return modified + } + + mutating func didSample(token: MLXArray) { + // Defer the item() sync: the iterator has already asyncEval'd the + // token, so by the time we flush a batch the syncs are close to free. + // Synchronously calling .item() here would block the next forward + // pass from dispatching — a per-step stall that dominates on large + // models. + pendingTokens.append(token) + + // Dynamic flush threshold: shrink when approaching the budget so + // forcing triggers within a few tokens of the configured limit. + // thinkingTokenCount=195, budget=200 → headroom=5 → flush every 2. + // thinkingTokenCount=100, budget=200 → headroom=100 → flush every 10. + let headroom = inThinkingPhase + ? max(0, maxThinkingTokens - thinkingTokenCount) + : Int.max + let threshold = max(1, min(Self.flushBatchSize, headroom / 2)) + if pendingTokens.count >= threshold { + flushPending() + } + } + + mutating func flushPending() { + guard !pendingTokens.isEmpty else { return } + // Batch eval — tokens were already async-dispatched by the iterator, + // so one eval() call completes the whole queue in one sync point. + eval(pendingTokens) + let ids = pendingTokens.map { $0.item(Int32.self) } + pendingTokens.removeAll(keepingCapacity: true) + for id in ids { + applyStateUpdate(id: id) + } + } + + private mutating func applyStateUpdate(id: Int32) { + if id == thinkStartTokenId { + inThinkingPhase = true + } else if id == thinkEndTokenId { + inThinkingPhase = false + if thinkingTokenCount >= maxThinkingTokens { + budgetExhausted = true + } + } else if inThinkingPhase { + thinkingTokenCount += 1 + } + } +} + +/// Build a `[V]` additive mask with `-inf` at `suppressedIds` positions and +/// `0` elsewhere. Constructed host-side so the upload to GPU is one kernel — +/// not `N` scatter ops, which is what a naïve +/// `modified[id] = MLXArray(-inf)` loop would emit per call. +fileprivate func buildSuppressMask( + suppressedIds: [Int32], vocabSize: Int +) -> MLXArray { + var mask = [Float](repeating: 0, count: vocabSize) + for id in suppressedIds { + let i = Int(id) + if i >= 0 && i < vocabSize { + mask[i] = -.infinity + } + } + return MLXArray(mask) +} + +/// Harmony-format thinking-budget enforcer. +/// +/// Analogue to ``ThinkingBudgetProcessor`` for models whose reasoning is +/// delimited by channel transitions rather than a `…` +/// bracket pair. Counts tokens emitted inside the analysis channel; once +/// `maxThinkingTokens` are produced, pins the next `forcedTransitionSequence.count` +/// sampling steps to force-emit the multi-token sequence that closes the +/// analysis message and opens the final-channel visible answer. +/// +/// For GPT-OSS / harmony the transition is +/// `<|end|> <|start|> assistant <|channel|> final <|message|>` (6 tokens). +/// +/// After the forced transition completes, the model is free to generate +/// final-channel content normally — but the analysis channel is +/// suppressed to prevent bouncing back into reasoning. +/// +/// Caveat: the 6 forced tokens land in ``GenerateCompletionInfo.perTokenLogProbs`` +/// with logprob ≈ 0 (we pinned the sampler). They slightly bias per-phase +/// PPL toward 1.0 — bounded contribution (6 tokens out of hundreds) and +/// not material to the signal we care about (reasoning-phase PPL/KLD +/// comparisons across KV configs). +private struct HarmonyThinkingBudgetProcessor: LogitProcessor { + let channelMarkerTokenId: Int32 + let thinkingChannelTokenIds: Set + let generationChannelTokenIds: Set + let forcedTransitionSequence: [Int32] + let maxThinkingTokens: Int + let eosTokenIds: [Int32] + + var inThinking: Bool = false + var awaitingChannelName: Bool = false + var thinkingTokenCount: Int = 0 + /// When ≥ 0, we're actively forcing the transition sequence; + /// indexes the next token to force. When the sequence completes, reset to -1. + var forceIndex: Int = -1 + var budgetExhausted: Bool = false + + /// Pre-built additive masks — one per cacheable set of suppressed IDs. + /// Replaces the scatter-per-suppressed-token loops with one elementwise + /// add. `thinking` suppresses EOS during reasoning so the model emits a + /// channel transition; `postExhaust` suppresses analysis-channel re-entry + /// after the budget has forced a transition. See ``SuppressMaskCache``. + let masks = SuppressMaskCache() + + /// Lazy accumulator of sampled content tokens awaiting a batched + /// state-machine update. See ``ThinkingBudgetProcessor`` for the + /// rationale; the win on GPT-OSS is larger because per-step GPU→CPU + /// syncs block dispatch of the next forward pass on a 20B MoE. + /// + /// Tokens sampled while `forceIndex >= 0` are NOT queued — during an + /// active force-emit we know each sampled ID deterministically (we + /// pinned the sampler), so state can advance without any sync. + var pendingTokens: [MLXArray] = [] + + private static let flushBatchSize = 10 + + init( + channelMarkerTokenId: Int32, + thinkingChannelTokenIds: Set, + generationChannelTokenIds: Set, + forcedTransitionSequence: [Int32], + maxThinkingTokens: Int, + eosTokenIds: [Int32] = [] + ) { + self.channelMarkerTokenId = channelMarkerTokenId + self.thinkingChannelTokenIds = thinkingChannelTokenIds + self.generationChannelTokenIds = generationChannelTokenIds + self.forcedTransitionSequence = forcedTransitionSequence + self.maxThinkingTokens = maxThinkingTokens + self.eosTokenIds = eosTokenIds + } + + mutating func prompt(_ prompt: MLXArray) { + inThinking = false + awaitingChannelName = false + thinkingTokenCount = 0 + forceIndex = -1 + budgetExhausted = false + pendingTokens.removeAll(keepingCapacity: true) + } + + func process(logits: MLXArray) -> MLXArray { + // Lazy mask construction on first use. + let vocab = logits.shape.last ?? 0 + if masks.thinking == nil && vocab > 0 { + masks.thinking = buildSuppressMask( + suppressedIds: eosTokenIds, vocabSize: vocab) + } + if masks.postExhaust == nil && vocab > 0 { + masks.postExhaust = buildSuppressMask( + suppressedIds: Array(thinkingChannelTokenIds), vocabSize: vocab) + } + + // Active force-emit: pin the next sequence token. + if forceIndex >= 0 && forceIndex < forcedTransitionSequence.count { + var modified = logits + let targetId = Int(forcedTransitionSequence[forceIndex]) + // Use a large finite value (100) — softmax(+inf) → NaN which the + // sampler would misroute. 100 gives P(target) ≈ 1.0 with no NaN. + if logits.ndim == 1 { + modified[targetId] = MLXArray(Float(100.0)) + } else { + modified[0..., targetId] = MLXArray(Float(100.0)) + } + return modified + } + + // After completing the forced transition, suppress analysis-channel + // entry so the model can't oscillate back into reasoning. + if budgetExhausted && !inThinking { + if let m = masks.postExhaust { + return logits + m + } + return logits + } + + // During reasoning, suppress EOS so the model is forced to emit a + // channel transition before terminating. + guard inThinking else { return logits } + if let m = masks.thinking { + return logits + m + } + return logits + } + + mutating func didSample(token: MLXArray) { + // During active force-emit we know each sampled token deterministically + // (we pinned its logit to +100). Advance state without any sync — no + // need to queue the lazy MLXArray. + if forceIndex >= 0 { + forceIndex += 1 + if forceIndex >= forcedTransitionSequence.count { + forceIndex = -1 + inThinking = false + awaitingChannelName = false + budgetExhausted = true + } + return + } + + // Otherwise defer the sync: queue lazily and flush in batches. See + // `ThinkingBudgetProcessor.didSample` for the full rationale. + pendingTokens.append(token) + + let headroom = inThinking + ? max(0, maxThinkingTokens - thinkingTokenCount) + : Int.max + let threshold = max(1, min(Self.flushBatchSize, headroom / 2)) + if pendingTokens.count >= threshold { + flushPending() + } + } + + mutating func flushPending() { + guard !pendingTokens.isEmpty else { return } + eval(pendingTokens) + let ids = pendingTokens.map { $0.item(Int32.self) } + pendingTokens.removeAll(keepingCapacity: true) + for id in ids { + applyStateUpdate(id: id) + // If the state machine armed force-emit mid-batch, stop draining + // here — the remaining pending tokens (if any) were sampled + // BEFORE the armed point, and the next `process()` call needs to + // see `forceIndex >= 0` to start pinning the transition. + // + // Note: pendingTokens is already empty by the time we get here + // (removeAll above), so there's nothing to preserve — the break + // is defensive in case the loop is refactored. + if forceIndex >= 0 { break } + } + } + + private mutating func applyStateUpdate(id: Int32) { + if id == channelMarkerTokenId { + awaitingChannelName = true + return + } + if awaitingChannelName { + awaitingChannelName = false + if thinkingChannelTokenIds.contains(id) { + inThinking = true + thinkingTokenCount = 0 + } else if generationChannelTokenIds.contains(id) { + inThinking = false + } + return + } + if inThinking { + thinkingTokenCount += 1 + if thinkingTokenCount >= maxThinkingTokens { + forceIndex = 0 + } + } + } +} + +// MARK: - KV Cache Configuration + +/// KV cache quantization configuration for benchmarks. +enum KVCacheConfig: CustomStringConvertible { + case none // No KV quantization + case affine(bits: Int) // MLX affine quantization (kvBits) + case turbo(bits: Int) // TurboQuant symmetric (kvScheme="turbo4") + case turboAsym(keyBits: Int, valueBits: Int) // Asymmetric ("turbo4v2") + + var description: String { + switch self { + case .none: return "no-quant" + case .affine(let b): return "affine-\(b)" + case .turbo(let b): return "turbo\(b)" + case .turboAsym(let kb, let vb): return "turbo\(kb)v\(vb)" + } + } + + var kvBits: Int? { + if case .affine(let b) = self { return b } + return nil + } + + var kvScheme: String? { + switch self { + case .turbo(let b): + return "turbo\(b)" + case .turboAsym(let kb, let vb): + return "turbo\(kb)v\(vb)" + default: return nil + } + } + + var quantizedKVStart: Int { + switch self { + case .none: return 0 + case .affine: return 512 + case .turbo, .turboAsym: return 0 + } + } + + /// Compute KV cache size in bytes from token count and model config. + /// Deterministic and comparable across runs — independent of MLX memory pool. + func cacheBytes(tokens: Int, kvHeads: Int, headDim: Int, layers: Int) -> Int { + let perTokenPerHead: Int // bytes for K+V per token per head + switch self { + case .none: + // FP16: 2 bytes per element, K+V + perTokenPerHead = headDim * 2 * 2 // K + V, FP16 + + case .affine(let bits): + // wq: headDim * bits / 8 bytes, scales: (headDim/64) * 4, biases: (headDim/64) * 4 + let groupSize = 64 + let groups = headDim / groupSize + let wqBytes = headDim * bits / 8 + let metaBytes = groups * 4 * 2 // scale + bias per group, FP32 + perTokenPerHead = (wqBytes + metaBytes) * 2 // K + V + + case .turbo(let bits): + // packed: packedWidth * 4 bytes, norm: 4 bytes + let pw = (headDim * bits + 31) / 32 + perTokenPerHead = (pw * 4 + 4) * 2 // K + V + + case .turboAsym(let keyBits, let valueBits): + let kpw = (headDim * keyBits + 31) / 32 + let vpw = (headDim * valueBits + 31) / 32 + perTokenPerHead = (kpw * 4 + 4) + (vpw * 4 + 4) // K + V + } + + return tokens * kvHeads * perTokenPerHead * layers + } +} + +// MARK: - Mock Tools + +/// Minimal mock tool spec for tool-call benchmarking (no external dependencies). +enum MockTools { + static func shellToolSpec() -> MLXLMCommon.ToolSpec { + [ + "type": "function", + "function": [ + "name": "execute_shell", + "description": "Run a command. Use for system tasks, file operations, data analysis, and all available CLI tools.", + "parameters": [ + "type": "object", + "properties": [ + "command": [ + "type": "string", + "description": "The command to execute" + ] as [String: any Sendable] + ] as [String: any Sendable], + "required": ["command"] + ] as [String: any Sendable], + ] as [String: any Sendable], + ] as MLXLMCommon.ToolSpec + } +} + +// MARK: - Environment + +/// Centralized environment variable access for benchmarks. +/// All configuration comes from env vars set by benchmark.sh (or manually). +private enum BenchEnv { + /// Model to benchmark — registry short name (e.g., "qwen35-0.8b"), alias (e.g., "nemotron-cascade-2"), or HF repo ID. + static var model: String? { + ProcessInfo.processInfo.environment["MLX_BENCH_MODEL"] + } + /// Benchmark method: simple, summarization, wikitext2, niah, multi-turn, tool-calling + static var method: String { + ProcessInfo.processInfo.environment["MLX_BENCH_METHOD"] ?? "simple" + } + /// Weight quantization: bf16, 8bit, 4bit (default: 4bit) + static var quantization: String { + ProcessInfo.processInfo.environment["MLX_BENCH_QUANT"] ?? "4bit" + } + /// KV cache configuration. + static var kvConfig: KVCacheConfig { + switch ProcessInfo.processInfo.environment["MLX_BENCH_KV"] { + case "affine8": return .affine(bits: 8) + case "affine4": return .affine(bits: 4) + case "turbo8": return .turbo(bits: 8) + case "turbo8v4": return .turboAsym(keyBits: 8, valueBits: 4) + case "turbo8v2": return .turboAsym(keyBits: 8, valueBits: 2) + case "turbo4": return .turbo(bits: 4) + case "turbo3": return .turbo(bits: 3) + case "turbo4v2": return .turboAsym(keyBits: 4, valueBits: 2) + case "turbo4v3": return .turboAsym(keyBits: 4, valueBits: 3) + case "turbo3v2": return .turboAsym(keyBits: 3, valueBits: 2) + default: return .none + } + } + /// Context sizes to evaluate (comma-separated). Nil = use all default sizes. + static var contexts: [Int]? { + guard let filter = ProcessInfo.processInfo.environment["MLX_BENCH_CONTEXT"], !filter.isEmpty else { + return nil + } + return filter.split(separator: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) } + } + /// Auto-select highest-fidelity variant that fits in memory. + static var baselineMode: Bool { + ProcessInfo.processInfo.environment["MLX_BENCH_BASELINE"] == "1" + } + /// Enable KL divergence computation vs bf16/8bit baseline. + static var kldEnabled: Bool { + ProcessInfo.processInfo.environment["MLX_BENCH_KLD"] == "1" + } + /// Number of concurrent generations to run (default: 1). + static var batch: Int { + Int(ProcessInfo.processInfo.environment["MLX_BENCH_BATCH"] ?? "1") ?? 1 + } + /// Enable thinking mode for thinking-capable models (default: off for max speed). + static var thinkEnabled: Bool { + ProcessInfo.processInfo.environment["MLX_BENCH_THINK"] == "1" + } + /// Reasoning effort override for models that honour it (e.g. GPT-OSS). + /// When nil, the family's default is used. Accepted values: "low", + /// "medium", "high" — or any string the underlying chat template + /// understands. Value validation is deliberately loose so future + /// models' vocabularies pass through without a harness change. + static var reasoningEffort: String? { + guard let raw = ProcessInfo.processInfo.environment["MLX_BENCH_REASONING"] else { + return nil + } + let v = raw.trimmingCharacters(in: .whitespacesAndNewlines) + return v.isEmpty ? nil : v + } + /// N-gram speculative-decoding size for the benchmark run. Default is 0 + /// (disabled) so benchmarks measure pure autoregressive decode rather + /// than a composite with variable accept-rate overhead. Set via + /// `--ngram N` → `MLX_BENCH_NGRAM=N`. + /// + /// This differs from the library's `GenerateParameters.ngramSize` + /// default (3) — the library picks a typical usable value; benchmarks + /// prefer a clean baseline and let the user opt in to measure the + /// speculative path explicitly. + static var ngramSize: Int { + guard let raw = ProcessInfo.processInfo.environment["MLX_BENCH_NGRAM"], + let v = Int(raw.trimmingCharacters(in: .whitespacesAndNewlines)), + v >= 0 + else { return 0 } + return v + } +} + +// MARK: - Baseline Token Data + +/// Per-token data collected from baseline generation, used for in-memory KLD computation. +private struct BaselineTokenData { + let tokenIds: [Int] + let logProbs: [Double] + let phases: [String] // "think", "gen", or "marker" +} + +// MARK: - Model Cache + +/// Cache loaded models across test runs to avoid reloading per context size. +/// Safe because InferenceBenchmarks uses .serialized (sequential execution). +private final class ModelCache: @unchecked Sendable { + static let shared = ModelCache() + private var cache: [String: ModelContainer] = [:] + private let lock = NSLock() + + func get(_ id: String) -> ModelContainer? { + lock.lock() + defer { lock.unlock() } + return cache[id] + } + + func set(_ id: String, _ container: ModelContainer) { + lock.lock() + defer { lock.unlock() } + cache[id] = container + } +} + +// MARK: - Test Suite + +/// Inference benchmarks for production models. +/// +/// Single entry point driven by environment variables. +/// Usage: ./scripts/benchmark.sh --method --model [options] +/// See benchmarks/README.md for full documentation. +@Suite("Inference Benchmarks", .serialized) +struct InferenceBenchmarks { + + // MARK: - Constants + + static let contextSizes = [128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072] + static let toolQuery = "What is the current date and time?" + static let multiTurnContext: [MLXLMCommon.Message] = [ + ["role": "user", "content": "Hello, what is your name?"], + ["role": "assistant", "content": "Hello! I'm an AI assistant. How can I help you today?"], + ["role": "user", "content": "My name is Bob and my partner's name is Alice."], + ["role": "assistant", "content": "Nice to meet you! What can I help you with?"], + ] + static let multiTurnRecallTests: [(question: String, expected: String)] = [ + ("What is my name?", "Bob"), + ("What is my partner's name?", "Alice"), + ] + static let minimalSystemPrompt = "You are a helpful assistant. Keep responses concise." + static let simpleQuery = ProcessInfo.processInfo.environment["MLX_BENCH_PROMPT"] ?? "Hello! What is your name and what can you help me with?" + /// Default context limit for non-scaling methods. + /// Enforced via maxKVSize (RotatingKVCache) to simulate a realistic chat deployment. + static let defaultContextLimit = 4096 + static let niahNeedle = "The special magic verification code is BLUE TIGER 42." + static let niahAnswer = "BLUE TIGER 42" + static let niahQuestion = "What is the special magic verification code mentioned in the text above? Reply with only the code, nothing else." + static let niahDepths: [Double] = [0.1, 0.25, 0.5, 0.75, 0.9] + + // MARK: - Entry Point + + /// Single benchmark entry point. All configuration comes from env vars. + /// Print build environment for debugging — confirms NAX and model template. + /// If prefill < 10K tok/s on Gemma E2B, something is wrong. + static func printBuildEnvironment() { + // NAX check: if Cmlx was compiled with NAX, the .o files exist + let naxObj = FileManager.default.fileExists( + atPath: ".build/arm64-apple-macosx/release/Cmlx.build/mlx-generated/steel_attention_nax.cpp.o") + print("[ENV] NAX: \(naxObj ? "ENABLED ✓" : "DISABLED ✗ — merge ekryski/mlx-swift#2, swift package clean, rebuild")") + + // Gemma 4 template check + if let modelPath = ProcessInfo.processInfo.environment["MLX_BENCH_MODEL"], + modelPath.lowercased().contains("gemma") { + let tcPath = (modelPath as NSString).expandingTildeInPath + "/tokenizer_config.json" + if let data = try? Data(contentsOf: URL(fileURLWithPath: tcPath)), + let tc = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { + if let tmpl = tc["chat_template"] as? String, tmpl.count > 100 { + print("[ENV] Gemma template: OK (\(tmpl.count) chars)") + } else { + print("[ENV] Gemma template: MISSING ✗ — run: python3 scripts/fix-gemma4-template.py \(modelPath)") + } + } + } + } + + @Test @MainActor func benchmark() async throws { + // Force line-buffered stdout so progress lines appear immediately when piped + setlinebuf(stdout) + + Self.printBuildEnvironment() + + let family = try resolveFamily() + let kv = BenchEnv.kvConfig + let (variant, repoId) = try await resolveVariant(family: family) + let method = BenchEnv.method + + switch method { + case "simple": + try await runGenerationBenchmark( + family: family, variant: variant, repoId: repoId, kv: kv, + label: "\(family.name) [\(variant.quantization)] — simple [\(kv)]", + contextSize: Self.defaultContextLimit, + messages: [["role": "user", "content": Self.simpleQuery]], + systemPrompt: Self.minimalSystemPrompt, maxTokens: 200 + ) + + case "summarization": + let contexts = BenchEnv.contexts ?? Self.contextSizes + let batch = BenchEnv.batch + // Without thinking: match total decode cap of thinking runs (200 think + 200 answer). + let summarizationMaxNewTokens = BenchEnv.thinkEnabled ? 200 : 400 + + // ── Warmup pass: JIT Metal shaders and warm caches before timed runs ── + // Without this, the first context size eats a cold-start penalty (shader + // compilation, buffer allocation, Metal pipeline setup) that inflates TTFT + // and deflates prefill tok/s. Run a short 64-token generation, sync GPU, + // then discard. This matches llama.cpp's llama-bench warmup behavior. + do { + // Warmup with 2048+ tokens to warm ALL Metal pipeline specializations + // including the SDPA kernels that only dispatch at longer sequences. + print("[WARMUP] Running warmup pass (2048 tokens)...") + let warmupPrompt = try loadPrompt(tokenCount: 2048) + try await runGenerationBenchmark( + family: family, variant: variant, repoId: repoId, kv: kv, + label: "warmup", + contextSize: 2048, + messages: [["role": "user", "content": warmupPrompt]], + systemPrompt: nil, maxTokens: 16, + warmup: true + ) + Stream.defaultStream(.gpu).synchronize() + MLX.Memory.clearCache() + print("[WARMUP] Done — Metal pipeline hot\n") + } + + for (idx, ctx) in contexts.enumerated() { + print("[PROGRESS] Context \(idx + 1)/\(contexts.count): \(ctx) tokens") + let prompt = try loadPrompt(tokenCount: ctx) + if batch > 1 { + try await runBatchedBenchmark( + batchSize: batch, + family: family, variant: variant, repoId: repoId, kv: kv, + label: "\(family.name) [\(variant.quantization)] — summarization \(ctx) [\(kv)] batch=\(batch)", + contextSize: ctx, + messages: [["role": "user", "content": prompt]], + systemPrompt: nil, maxTokens: summarizationMaxNewTokens + ) + } else { + try await runGenerationBenchmark( + family: family, variant: variant, repoId: repoId, kv: kv, + label: "\(family.name) [\(variant.quantization)] — summarization \(ctx) [\(kv)]", + contextSize: ctx, + messages: [["role": "user", "content": prompt]], + systemPrompt: nil, maxTokens: summarizationMaxNewTokens + ) + } + // Release GPU buffers between contexts to prevent Invalid Resource + // errors from Metal buffer reuse on large models (18+ GB). + Stream.defaultStream(.gpu).synchronize() + MLX.Memory.clearCache() + } + + case "wikitext2": + let contexts = BenchEnv.contexts ?? Self.contextSizes + for (idx, ctx) in contexts.enumerated() { + print("[PROGRESS] Context \(idx + 1)/\(contexts.count): \(ctx) tokens") + try await runWikitext2Benchmark(family: family, kv: kv, contextSize: ctx) + } + + case "niah": + let contexts = BenchEnv.contexts ?? Self.contextSizes + for (idx, ctx) in contexts.enumerated() { + print("[PROGRESS] Context \(idx + 1)/\(contexts.count): \(ctx) tokens") + try await runNIAHBenchmark(family: family, kv: kv, contextSize: ctx) + } + + case "multi-turn": + for (question, expected) in Self.multiTurnRecallTests { + var messages = Self.multiTurnContext + messages.append(["role": "user", "content": question]) + try await runGenerationBenchmark( + family: family, variant: variant, repoId: repoId, kv: kv, + label: "\(family.name) [\(variant.quantization)] — multi-turn(\(expected)) [\(kv)]", + contextSize: Self.defaultContextLimit, + messages: messages, + systemPrompt: Self.minimalSystemPrompt, maxTokens: 200, + validation: { output, _ in + output.lowercased().contains(expected.lowercased()) + ? "PASS(\(expected)): " : "FAIL(missing \(expected)): " + } + ) + } + + case "tool-calling": + try await runGenerationBenchmark( + family: family, variant: variant, repoId: repoId, kv: kv, + label: "\(family.name) [\(variant.quantization)] — tool [\(kv)]", + contextSize: Self.defaultContextLimit, + messages: [["role": "user", "content": Self.toolQuery]], + systemPrompt: Self.minimalSystemPrompt, maxTokens: 200, + includeTools: true, + validation: { _, toolCalls in + guard let tc = toolCalls.first else { + return "FAIL(no tool call): " + } + guard tc.function.name == "execute_shell" else { + return "FAIL(wrong tool: \(tc.function.name)): " + } + let cmdArg = tc.function.arguments["command"] + let cmdStr = cmdArg.flatMap { "\($0)" } ?? "" + guard cmdStr.lowercased().contains("date") else { + return "FAIL(wrong command: \(cmdStr)): " + } + return "PASS: " + } + ) + + case "raw-prefill": + let contexts = BenchEnv.contexts ?? Self.contextSizes + for (idx, ctx) in contexts.enumerated() { + print("[PROGRESS] Context \(idx + 1)/\(contexts.count): \(ctx) tokens") + try await runRawPrefillBenchmark(family: family, kv: kv, contextSize: ctx) + } + + default: + print("[BENCH] Unknown method: \(method)") + } + } + + // MARK: - Family Resolution + + /// Resolve model family from MLX_BENCH_MODEL env var (short name, alias, or HF repo id). + private func resolveFamily() throws -> ModelFamily { + guard let name = BenchEnv.model else { + throw BenchmarkError("MLX_BENCH_MODEL not set — use --model flag") + } + if let family = ModelRegistry.family(named: name) { + return family + } + // If it doesn't contain '/' it's not a HF repo ID — the user likely mistyped a short name + if !name.contains("/") { + let available = ModelRegistry.allFamilies.map(\.shortName) + let close = available.filter { $0.hasPrefix(name) || name.hasPrefix($0) } + var msg = "Unknown model '\(name)'." + if !close.isEmpty { + msg += " Did you mean: \(close.joined(separator: ", "))?" + } + msg += "\nAvailable models: \(available.joined(separator: ", "))" + throw BenchmarkError(msg) + } + // Treat as HuggingFace repo ID (custom model) + return ModelRegistry.customFamily(repoId: name) + } + + // MARK: - Variant Resolution + + /// Resolve which model variant to use based on env vars (baseline mode, quant selection). + /// Pre-checks estimated model size against GPU memory and warns if it may not fit. + private func resolveVariant(family: ModelFamily) async throws -> (ModelVariant, String) { + if BenchEnv.baselineMode { + let hw = SystemInfo.hardware() + let variant = try await family.selectBaseline(hardware: hw) + return (variant, variant.repoId) + } + + let quant = BenchEnv.quantization + guard let variant = family.variant(for: quant) else { + let fallback = family.variants[0] + print("[BENCH] No \(quant) variant for \(family.name), using \(fallback.quantization)") + return (fallback, fallback.repoId) + } + + // Pre-check: estimate if the model fits in GPU memory + let hw = SystemInfo.hardware() + do { + let size = try await SystemInfo.estimateModelSize(repo: variant.repoId) + if !SystemInfo.fitsInMemory(modelSizeBytes: size, hardware: hw) { + throw BenchmarkError( + "\(family.name) \(quant) (~\(SystemInfo.formatGB(size))) exceeds GPU memory limit " + + "(\(String(format: "%.0f", hw.gpuMemoryLimitGB))GB). " + + "Use --baseline to auto-select a smaller variant, or specify --quant 8bit/4bit." + ) + } + } catch let error as BenchmarkError { + throw error // re-throw our own errors + } catch { + print("[BENCH] Could not estimate model size for \(variant.repoId): \(error)") + } + + return (variant, variant.repoId) + } + + // MARK: - Core Benchmark Runner + + /// Validation closure: receives (outputText, toolCalls) → returns status prefix for output column. + /// Return nil for no validation, or e.g. "PASS: " / "FAIL: ". + typealias ValidationCheck = @Sendable (_ output: String, _ toolCalls: [ToolCall]) -> String? + + private func runGenerationBenchmark( + family: ModelFamily, + variant: ModelVariant, + repoId: String, + kv: KVCacheConfig, + label: String, + contextSize: Int, + messages: [MLXLMCommon.Message], + systemPrompt: String?, + maxTokens: Int = Int(ProcessInfo.processInfo.environment["MLX_BENCH_MAX_TOKENS"].flatMap { Int($0) } ?? 200), + includeTools: Bool = false, + validation: ValidationCheck? = nil, + warmup: Bool = false + ) async throws { + let hr = String(repeating: "=", count: 80) + print("\n\(hr)") + print("[BENCH] \(label)") + print("[BENCH] Model: \(repoId)") + print("[BENCH] Quantization: \(variant.quantization)") + print("[BENCH] KV: \(kv)") + print(hr) + + // Thinking is only active when BOTH the model supports it AND --think flag is set + let useThinking = family.supportsThinking && BenchEnv.thinkEnabled + + let thinkingBudget = 200 // max thinking tokens before forcing + + // ── 1. Build user input (no container needed yet) ───────────────────── + var allMessages: [MLXLMCommon.Message] = [] + if let sys = systemPrompt { + allMessages.append(["role": "system", "content": sys]) + } + allMessages.append(contentsOf: messages) + // Force thinking mode via assistant prefill (Qwen-style: prefill with \n) + if useThinking && !family.thinkingConfig.assistantPrefill.isEmpty { + allMessages.append(["role": "assistant", "content": family.thinkingConfig.assistantPrefill]) + } + let tools: [MLXLMCommon.ToolSpec]? = includeTools ? [MockTools.shellToolSpec()] : nil + // Pass enable_thinking to the chat template for models that support it (Qwen, Gemma 4) + let additionalContext: [String: any Sendable]? = useThinking + ? ["enable_thinking": true] : nil + let userInput = UserInput( + prompt: .messages(allMessages), tools: tools, + additionalContext: additionalContext) + + // ── 2. Load target model (cached across context sizes) ────────────────── + let container = try await loadOrCacheModel(family: family, repoId: repoId) + + // ── 4. Discover thinking tokens with target container ───────────────── + // + // Two styles per ThinkingConfig: + // • bracket — resolve a single start + end token pair (Qwen, Gemma 4). + // • harmonyChannel — resolve the channel marker plus each channel-name + // token so phase labeling can run the harmony SM + // (GPT-OSS analysis vs final/commentary). + let thinkingConfig = family.thinkingConfig + struct ThinkingTokens { + var thinkStartId: Int32? + var thinkEndId: Int32? + var harmonyMarkerId: Int32? + var harmonyThinkingIds: [Int32] = [] + var harmonyGenerationIds: [Int32] = [] + var harmonyTransitionIds: [Int32] = [] + var eosTokenIds: [Int32] = [] + } + let thinkingTokenIds: ThinkingTokens = useThinking + ? await container.perform { ctx in + var result = ThinkingTokens() + // Collect all EOS token IDs so we can suppress them during thinking phase + var eosIds = ctx.configuration.eosTokenIds.map { Int32($0) } + if let tokEos = ctx.tokenizer.eosTokenId { eosIds.append(Int32(tokEos)) } + for token in ctx.configuration.extraEOSTokens { + if let id = ctx.tokenizer.convertTokenToId(token) { eosIds.append(Int32(id)) } + } + result.eosTokenIds = Array(Set(eosIds)) + + switch thinkingConfig.style { + case .bracket(let start, let end): + result.thinkStartId = ctx.tokenizer.convertTokenToId(start).map { Int32($0) } + result.thinkEndId = ctx.tokenizer.convertTokenToId(end).map { Int32($0) } + case .harmonyChannel(let marker, let thinkingChans, let genChans, let transitionSeq): + result.harmonyMarkerId = ctx.tokenizer.convertTokenToId(marker).map { Int32($0) } + result.harmonyThinkingIds = thinkingChans.compactMap { + ctx.tokenizer.convertTokenToId($0).map { Int32($0) } + } + result.harmonyGenerationIds = genChans.compactMap { + ctx.tokenizer.convertTokenToId($0).map { Int32($0) } + } + // The forced-transition sequence is only useful if every + // token resolves; a missing ID would derail the force SM. + let resolved = transitionSeq.compactMap { + ctx.tokenizer.convertTokenToId($0).map { Int32($0) } + } + result.harmonyTransitionIds = resolved.count == transitionSeq.count ? resolved : [] + } + return result + } + : ThinkingTokens() + + let thinkStartId = thinkingTokenIds.thinkStartId + let thinkEndId = thinkingTokenIds.thinkEndId + let harmonyMarkerId = thinkingTokenIds.harmonyMarkerId + let harmonyThinkingIds = thinkingTokenIds.harmonyThinkingIds + let harmonyGenerationIds = thinkingTokenIds.harmonyGenerationIds + let harmonyTransitionIds = thinkingTokenIds.harmonyTransitionIds + let eosTokenIds = thinkingTokenIds.eosTokenIds + + if let s = thinkStartId, let e = thinkEndId { + if case .bracket(let startStr, let endStr) = thinkingConfig.style { + print("[BENCH] Thinking tokens: \(startStr)=\(s), \(endStr)=\(e), budget=\(thinkingBudget), eos=\(eosTokenIds)") + } + } else if let m = harmonyMarkerId { + print("[BENCH] Harmony channel marker=\(m), thinking=\(harmonyThinkingIds), generation=\(harmonyGenerationIds), transition=\(harmonyTransitionIds), eos=\(eosTokenIds)") + } + let thinkingPrefilled = !family.thinkingConfig.assistantPrefill.isEmpty + let bracketBudgetProcessor: ThinkingBudgetProcessor? = thinkStartId.flatMap { startId in + thinkEndId.map { endId in + ThinkingBudgetProcessor( + thinkStartTokenId: startId, + thinkEndTokenId: endId, + maxThinkingTokens: thinkingBudget, + prefilled: thinkingPrefilled, + eosTokenIds: eosTokenIds + ) + } + } + // Harmony equivalent: enforce the thinking budget by force-emitting + // the channel-transition sequence after N analysis-message tokens. + // Only constructed when every transition-sequence token resolved. + let harmonyBudgetProcessor: HarmonyThinkingBudgetProcessor? = { + guard let markerId = harmonyMarkerId, + !harmonyTransitionIds.isEmpty, + !harmonyGenerationIds.isEmpty + else { return nil } + return HarmonyThinkingBudgetProcessor( + channelMarkerTokenId: markerId, + thinkingChannelTokenIds: Set(harmonyThinkingIds), + generationChannelTokenIds: Set(harmonyGenerationIds), + forcedTransitionSequence: harmonyTransitionIds, + maxThinkingTokens: thinkingBudget, + eosTokenIds: eosTokenIds + ) + }() + + // ── 5. Prepare input ────────────────────────────────────────────────── + let prepareStart = Date() + var lmInput: LMInput + do { + lmInput = try await container.prepare(input: userInput) + } catch { + // Some models (e.g. Mistral) don't support system messages or tools. + // Retry with just the user messages, no system prompt, no tools. + let userOnly = allMessages.filter { ($0["role"] as? String) != "system" } + print("[BENCH] Template error: \(error). Retrying without system/tools...") + let fallbackInput = UserInput(prompt: .messages(userOnly)) + lmInput = try await container.prepare(input: fallbackInput) + } + var promptTokens = lmInput.text.tokens.dim(lmInput.text.tokens.ndim - 1) + + // Trim prompt to fit context limit. Pre-built prompt files are sized with a + // reference tokenizer; the target model's tokenizer + chat template overhead + // can push the actual token count above contextSize, causing the rotating KV + // cache to silently drop the first tokens. Fix: trim the raw user content + // from the end (preserving the instruction prefix) and re-prepare. + if contextSize > 0 && promptTokens > contextSize { + let overshoot = promptTokens - contextSize + let messagesToTrim = allMessages + let trimmedMessages: [MLXLMCommon.Message] = await container.perform { ctx in + var result = messagesToTrim + if let lastUserIdx = result.lastIndex(where: { $0["role"] as? String == "user" }), + let content = result[lastUserIdx]["content"] as? String + { + let tokens = ctx.tokenizer.encode(text: content) + if tokens.count > overshoot { + let trimmedTokens = Array(tokens.prefix(tokens.count - overshoot)) + let trimmedContent = ctx.tokenizer.decode(tokenIds: trimmedTokens) + result[lastUserIdx] = ["role": "user", "content": trimmedContent] + } + } + return result + } + let trimmedInput = UserInput( + prompt: .messages(trimmedMessages), tools: tools, + additionalContext: additionalContext) + lmInput = try await container.prepare(input: trimmedInput) + promptTokens = lmInput.text.tokens.dim(lmInput.text.tokens.ndim - 1) + print("[BENCH] Trimmed prompt to \(promptTokens) tokens (context limit: \(contextSize))") + } + + print("[BENCH] Prepared \(promptTokens) tokens in \(String(format: "%.0f", Date().timeIntervalSince(prepareStart) * 1000))ms") + + // ── 6. Generate ─────────────────────────────────────────────────────── + // effectiveMaxTokens = thinking budget + response budget for thinking models. + // Bracket mode (Qwen, Gemma 4) keys off thinkStartId; harmony mode + // (GPT-OSS) keys off harmonyMarkerId. Either path reserves the same + // thinkingBudget tokens for reasoning before the response budget. + let hasThinkingBudget = thinkStartId != nil || harmonyMarkerId != nil + let effectiveMaxTokens = hasThinkingBudget ? thinkingBudget + maxTokens : maxTokens + // Exactly one budget enforcer applies per run: bracket XOR harmony. + // Both nil → model runs unconstrained. + var additionalProcessors: [any LogitProcessor] = [] + if let p = bracketBudgetProcessor { additionalProcessors.append(p) } + if let p = harmonyBudgetProcessor { additionalProcessors.append(p) } + + // When KLD is enabled, collect per-token data during generation so we can + // compare against the bf16/8bit baseline (no KV quant) via forced decode. + // Only skip for bf16 + no KV quant (that IS the baseline). + let isKVQuantized: Bool + if case .none = kv { isKVQuantized = false } else { isKVQuantized = true } + let needsKLD = BenchEnv.kldEnabled && (variant.quantization != "bf16" || isKVQuantized) + + let params = GenerateParameters( + maxTokens: effectiveMaxTokens, + maxKVSize: contextSize > 0 ? contextSize : nil, + kvBits: kv.kvBits, + kvGroupSize: 64, + quantizedKVStart: kv.quantizedKVStart, + temperature: family.temperature, + topP: family.topP, + topK: family.topK, + minP: family.minP, + repetitionPenalty: family.repetitionPenalty, + presencePenalty: family.presencePenalty, + prefillStepSize: 2048, + kvScheme: kv.kvScheme, + additionalProcessors: additionalProcessors, + reasoningEffort: BenchEnv.reasoningEffort ?? family.reasoningEffort, + ngramSize: BenchEnv.ngramSize, + maxNgramDraftTokens: BenchEnv.ngramSize, + thinkStartTokenId: thinkStartId, + thinkEndTokenId: thinkEndId, + thinkingPhasePrefilled: thinkStartId != nil && !family.thinkingConfig.assistantPrefill.isEmpty, + harmonyChannelMarkerTokenId: harmonyMarkerId, + harmonyThinkingChannelTokenIds: harmonyThinkingIds, + harmonyGenerationChannelTokenIds: harmonyGenerationIds, + collectPerTokenData: needsKLD, + trackPerplexity: ProcessInfo.processInfo.environment["MLX_BENCH_PPL"] == "1" + ) + + // Model-aware memory pinning: compute budget from actual model dimensions. + // Falls back to 20GB fixed ticket if MLX_SMART_MEMORY=0. + let ticket: WiredMemoryTicket + if ProcessInfo.processInfo.environment["MLX_SMART_MEMORY"] != "0" { + let maxTokens = contextSize > 0 ? contextSize + effectiveMaxTokens : 4096 + let estimatedTicket = try await container.perform { model, _ in + WiredMemoryUtils.estimatedTicket( + model: model, + maxTokens: maxTokens, + parameters: params + ) + } + ticket = estimatedTicket + print("[BENCH] Smart memory: \(ticket.size / 1_048_576)MB ticket for \(maxTokens) max tokens") + } else { + ticket = WiredMemoryTicket( + size: 20 * 1024 * 1024 * 1024, + policy: MLX.WiredSumPolicy() + ) + } + + // Sync GPU before timing to flush any pending lazy eval from setup + Stream.defaultStream(.gpu).synchronize() + + // Memory breakdown before generation + let preGenActive = MLX.Memory.activeMemory + let preGenCache = MLX.Memory.cacheMemory + print("[MEM] Pre-generation: active=\(preGenActive / 1_048_576)MB cache=\(preGenCache / 1_048_576)MB") + + MLX.GPU.resetPeakMemory() + let baselineGPU = MLX.Memory.activeMemory + + let genStart = Date() + var tokenCount = 0 + var firstTokenTime: TimeInterval? = nil + var outputText = "" + var completionInfo: GenerateCompletionInfo? = nil + var toolCalls: [ToolCall] = [] + + let stream = try await container.generate(input: lmInput, parameters: params, wiredMemoryTicket: ticket) + for try await generation in stream { + if case .info(let info) = generation { + completionInfo = info + continue + } + if case .toolCall(let tc) = generation { + toolCalls.append(tc) + print("[BENCH] Tool call: \(tc.function.name)(\(tc.function.arguments))") + continue + } + guard let chunk = generation.chunk else { continue } + + tokenCount += 1 + outputText += chunk + + if firstTokenTime == nil { + firstTokenTime = Date().timeIntervalSince(genStart) + } + } + + let totalTime = Date().timeIntervalSince(genStart) + let ttft = firstTokenTime ?? totalTime + + // Warmup: we only needed to push through the Metal pipeline. Skip reporting. + if warmup { + MLX.Memory.clearCache() + return + } + + let generationTime = totalTime - ttft + let genTokPerSec = generationTime > 0 ? Double(tokenCount - 1) / generationTime : 0 + + let prefillTime = completionInfo?.promptTime ?? ttft + let prefillTokens = completionInfo?.promptTokenCount ?? promptTokens + let prefillTokPerSec = prefillTime > 0 ? Double(prefillTokens) / prefillTime : 0 + + let peakGPU = MLX.Memory.peakMemory + let activeGPU = MLX.Memory.activeMemory + let kvDelta = activeGPU > baselineGPU ? activeGPU - baselineGPU : 0 + + // Memory breakdown + let postGenCache = MLX.Memory.cacheMemory + print("[MEM] Post-generation: active=\(activeGPU / 1_048_576)MB cache=\(postGenCache / 1_048_576)MB peak=\(peakGPU / 1_048_576)MB") + // Sync GPU before clearing buffer pool — prevents Invalid Resource errors + // when buffers are freed while command buffers still reference them. + Stream.defaultStream(.gpu).synchronize() + MLX.Memory.clearCache() + let postClearActive = MLX.Memory.activeMemory + print("[MEM] After clearCache: active=\(postClearActive / 1_048_576)MB (KV+weights delta: \((Int(postClearActive) - Int(preGenActive)) / 1_048_576)MB)") + + // KV cache size computed from token count and quantization config. + // Deterministic and comparable across runs (unlike MLX activeMemory delta). + let totalTokens = prefillTokens + tokenCount + let kvCacheBytes = kv.cacheBytes( + tokens: totalTokens, kvHeads: 16, headDim: 128, layers: 28) + + let thinkingPerplexity = completionInfo?.thinkingPerplexity.map { Double($0) } + let generationPerplexity = completionInfo?.generationPerplexity.map { Double($0) } + + // ── 7. [KLD] Forced decode through bf16/8bit baseline to get baseline logprobs ── + // The normal generation (step 6) ran with the target model (weight quant + KV quant) + // and collected per-token logprobs. Now we feed the SAME tokens through the highest- + // fidelity baseline model (bf16 → 8bit fallback) WITHOUT KV quantization. KLD measures + // the total quality cost of the deployment config vs the gold standard. + var thinkKLD: Double? = nil + var genKLD: Double? = nil + if needsKLD, + let quantizedIds = completionInfo?.perTokenIds, + let quantizedLogProbs = completionInfo?.perTokenLogProbs, + let quantizedPhases = completionInfo?.perTokenPhases, + !quantizedIds.isEmpty + { + let quantizedData = BaselineTokenData( + tokenIds: quantizedIds, + logProbs: quantizedLogProbs.map { Double($0) }, + phases: quantizedPhases + ) + + // Select and load the highest-fidelity baseline variant (bf16 → 8bit → 4bit) + let hw = SystemInfo.hardware() + if let baselineVariant = try? await family.selectBaseline(hardware: hw), + // Skip if the baseline would be the same model+config as the target + // (e.g., 8bit fallback baseline vs 8bit target with no KV quant) + !(baselineVariant.quantization == variant.quantization && !isKVQuantized) + { + print("[KLD] Loading baseline \(baselineVariant.quantization): \(baselineVariant.repoId)") + let baselineConfig = family.extraEOSTokens.isEmpty + ? ModelConfiguration(id: baselineVariant.repoId) + : ModelConfiguration(id: baselineVariant.repoId, extraEOSTokens: Set(family.extraEOSTokens)) + + let baselineContainer = try await LLMModelFactory.shared.loadContainer( + from: benchmarkDownloader, + using: benchmarkTokenizerLoader, + configuration: baselineConfig, + progressHandler: { p in + if p.fractionCompleted < 0.01 || p.fractionCompleted > 0.99 { + print("[KLD] Loading baseline: \(String(format: "%.0f", p.fractionCompleted * 100))%") + } + } + ) + + // Prepare input with the baseline model's tokenizer + let kldInput = try await baselineContainer.prepare( + input: UserInput(prompt: .messages(allMessages), tools: tools)) + + (thinkKLD, genKLD) = try await forcedDecodeKLD( + container: baselineContainer, + input: kldInput, + family: family, + quantizedData: quantizedData, + thinkStartId: thinkStartId, + thinkEndId: thinkEndId, + thinkingBudget: thinkingBudget, + maxTokens: maxTokens + ) + + // baselineContainer goes out of scope → freed + MLX.Memory.clearCache() + } else { + print("[KLD] Could not select baseline variant, skipping KLD") + } + } + + // ── 8. Validation ────────────────────────────────────────────────────── + let validationPrefix = validation?(outputText, toolCalls) + let reportOutput = (validationPrefix ?? "") + outputText + if let prefix = validationPrefix { + print("[BENCH] Validation: \(prefix.trimmingCharacters(in: .whitespaces))") + } + + // ── 9. Report ───────────────────────────────────────────────────────── + let scenario = BenchEnv.method + + print("\n[BENCH] === RESULTS: \(label) ===") + print("[BENCH] Method: \(scenario)") + print("[BENCH] Context: \(contextSize) tokens, Prompt Tokens: \(prefillTokens) (after template)") + print("[BENCH] Prefill: \(String(format: "%.1f", prefillTokPerSec)) tok/s") + print("[BENCH] Generation: \(String(format: "%.1f", genTokPerSec)) tok/s (\(tokenCount) tokens)") + print("[BENCH] TTFT: \(String(format: "%.0f", ttft * 1000))ms") + print("[BENCH] Total: \(String(format: "%.1f", totalTime))s") + if let ppl = thinkingPerplexity { + print("[BENCH] Think PPL: \(String(format: "%.4f", ppl))") + } + if let ppl = generationPerplexity { + print("[BENCH] Gen PPL: \(String(format: "%.4f", ppl))") + } + if let k = thinkKLD { print("[KLD] Think KLD: \(String(format: "%.6f", k))") } + if let k = genKLD { print("[KLD] Gen KLD: \(String(format: "%.6f", k))") } + print("[BENCH] GPU Baseline: \(formatBytes(baselineGPU))") + print("[BENCH] GPU Peak: \(formatBytes(peakGPU))") + print("[BENCH] KV Delta: \(formatBytes(kvDelta))") + if kvCacheBytes > 0 { + print("[BENCH] KV Cache: \(formatBytes(kvCacheBytes))") + } + print("[BENCH] Output: \(String(outputText.prefix(150)))") + + print(hr + "\n") + + // ── 9. Write to markdown file ───────────────────────────────────────── + BenchmarkWriter.append( + model: family.name, + repoId: variant.repoId, + quantization: variant.quantization, + kvConfig: kv.description, + scenario: scenario, + configKeyExtras: BenchEnv.ngramSize > 0 ? [("ngram", "\(BenchEnv.ngramSize)")] : [], + contextSize: contextSize, + promptTokens: prefillTokens, + prefillTokPerSec: prefillTokPerSec, + genTokPerSec: genTokPerSec, + genTokens: tokenCount, + ttftMs: ttft * 1000, + thinkingPerplexity: thinkingPerplexity, + generationPerplexity: generationPerplexity, + thinkingKLD: thinkKLD, + generationKLD: genKLD, + baselineGPU: baselineGPU, + peakGPU: Int(peakGPU), + kvDelta: kvDelta, + kvCacheBytes: kvCacheBytes, + outputPreview: reportOutput, + parameters: .init( + generate: params, + thinkingEnabled: useThinking, + thinkingTokenBudget: hasThinkingBudget ? thinkingBudget : nil, + kldSummary: kldParameterSummary(needsKLD: needsKLD, isWikitext2: false), + maxOpsPerBuffer: BenchmarkWriter.resolvedMaxOpsPerBufferReport(), + batchSize: BenchEnv.batch, + speculativeDecoding: speculativeDecodingLabel( + ngramSize: params.ngramSize, + maxNgramDraftTokens: params.maxNgramDraftTokens, + draftModelId: draftModelIdForReport() + ), + systemPromptSummary: systemPromptSummary(for: systemPrompt, scenario: scenario) + ) + ) + + MLX.Memory.clearCache() + #expect(tokenCount > 0, "[\(label)] Should generate at least 1 token") + } + + // MARK: - Batched Benchmark + + /// Run N concurrent generations to measure multi-user throughput. + /// Each generation runs independently through the ModelContainer's actor, + /// which serializes access. This simulates N users sharing one model instance. + private func runBatchedBenchmark( + batchSize: Int, + family: ModelFamily, + variant: ModelVariant, + repoId: String, + kv: KVCacheConfig, + label: String, + contextSize: Int, + messages: [MLXLMCommon.Message], + systemPrompt: String?, + maxTokens: Int = 200 + ) async throws { + let hr = String(repeating: "=", count: 80) + print("\n\(hr)") + print("[BENCH] \(label)") + print("[BENCH] Batch size: \(batchSize)") + print(hr) + + let container = try await loadOrCacheModel(family: family, repoId: repoId) + + // Build input once (same prompt for all batch elements) + var allMessages: [MLXLMCommon.Message] = [] + if let sys = systemPrompt { + allMessages.append(["role": "system", "content": sys]) + } + allMessages.append(contentsOf: messages) + if family.supportsThinking && BenchEnv.thinkEnabled + && !family.thinkingConfig.assistantPrefill.isEmpty { + allMessages.append(["role": "assistant", "content": family.thinkingConfig.assistantPrefill]) + } + let additionalContext: [String: any Sendable]? = + (family.supportsThinking && BenchEnv.thinkEnabled) ? ["enable_thinking": true] : nil + nonisolated(unsafe) let userInput = UserInput(prompt: .messages(allMessages), additionalContext: additionalContext) + let lmInput = try await container.prepare(input: copy userInput) + let promptTokens = lmInput.text.tokens.dim(lmInput.text.tokens.ndim - 1) + print("[BENCH] Prepared \(promptTokens) tokens") + + let params = GenerateParameters( + maxTokens: maxTokens, + maxKVSize: contextSize > 0 ? contextSize : nil, + kvBits: kv.kvBits, + kvGroupSize: 64, + quantizedKVStart: kv.quantizedKVStart, + temperature: family.temperature, + topP: family.topP, + topK: family.topK, + minP: family.minP, + repetitionPenalty: family.repetitionPenalty, + presencePenalty: family.presencePenalty, + prefillStepSize: 2048, + kvScheme: kv.kvScheme, + ngramSize: BenchEnv.ngramSize, + maxNgramDraftTokens: BenchEnv.ngramSize, + trackPerplexity: false + ) + + MLX.GPU.resetPeakMemory() + let baselineGPU = MLX.Memory.activeMemory + + struct BatchResult: Sendable { + let tokenCount: Int + let ttft: TimeInterval + let totalTime: TimeInterval + } + + let batchStart = Date() + + // Sendable capture for the task group: UserInput itself isn't Sendable, but + // its constructor inputs (`[Message]` + optional `[String: any Sendable]`) + // are. Rebuild a fresh UserInput inside each task from these primitives. + let taskMessages = allMessages + let taskAdditionalContext = additionalContext + + let results: [BatchResult] = try await withThrowingTaskGroup(of: BatchResult.self) { group in + for _ in 0.. Double in + let genTime = r.totalTime - r.ttft + return genTime > 0 ? Double(r.tokenCount - 1) / genTime : 0 + }.reduce(0, +) / Double(results.count) + let aggregateTokPerSec = batchWallTime > 0 ? Double(totalTokens) / batchWallTime : 0 + + let peakGPU = MLX.Memory.peakMemory + + // ── Results ────────────────────────────────────────────────────── + print("[BENCH] === RESULTS: \(label) ===") + print("[BENCH] Method: summarization (batched)") + print("[BENCH] Context: \(contextSize) tokens, Prompt Tokens: \(promptTokens) (after template)") + print("[BENCH] Batch size: \(batchSize)") + print("[BENCH] Aggregate throughput: \(String(format: "%.1f", aggregateTokPerSec)) tok/s (\(totalTokens) tokens in \(String(format: "%.1f", batchWallTime))s)") + print("[BENCH] Avg per-sequence decode: \(String(format: "%.1f", avgPerSeqTokPerSec)) tok/s") + print("[BENCH] Avg TTFT: \(String(format: "%.0f", avgTTFT * 1000))ms") + print("[BENCH] GPU Baseline: \(String(format: "%.2f", Double(baselineGPU) / 1e9))GB") + print("[BENCH] GPU Peak: \(String(format: "%.2f", Double(peakGPU) / 1e9))GB") + } + + // MARK: - WikiText-2 Perplexity + + /// Standard LM perplexity evaluation via forced decode on WikiText-2 text. + /// Tokenizes the text, feeds it through the model in chunks computing log-prob of + /// each next token. No generation — pure evaluation of the model's predictive ability. + /// PPL = exp(mean negative log-probability) over all predicted positions. + private func runWikitext2Benchmark( + family: ModelFamily, + kv: KVCacheConfig, + contextSize: Int + ) async throws { + let (variant, repoId) = try await resolveVariant(family: family) + let label = "\(family.name) [\(variant.quantization)] — wikitext2 \(contextSize) [\(kv)]" + + let hr = String(repeating: "=", count: 80) + print("\n\(hr)") + print("[BENCH] \(label)") + print(hr) + + // Load model + let container = try await loadOrCacheModel(family: family, repoId: repoId) + + // Load and tokenize WikiText-2 text. + // We tokenize the full text, take the first `contextSize` tokens, then decode + // back to count whitespace-delimited words for word-level PPL normalization + // (the standard metric per EleutherAI, comparable across tokenizers). + let wikitext = try loadWikitext2() + let (tokenIds, wordCount): ([Int32], Int) = await container.perform { ctx in + let allTokens = ctx.tokenizer.encode(text: wikitext) + let sliced = Array(allTokens.prefix(contextSize)) + // Decode the evaluated tokens back to text to count words + let decodedText = ctx.tokenizer.decode(tokenIds: sliced) + let words = decodedText.split(whereSeparator: { $0.isWhitespace }).count + return (sliced.map { Int32($0) }, words) + } + + guard tokenIds.count >= 2 else { + print("[BENCH] Not enough tokens for wikitext2 evaluation at context \(contextSize)") + return + } + + print("[BENCH] WikiText-2: \(tokenIds.count) tokens, \(wordCount) words (target: \(contextSize))") + + let chunkSize = 2048 // Process in chunks to avoid OOM on the computation graph + + let params = GenerateParameters( + maxKVSize: contextSize > 0 ? contextSize : nil, + kvBits: kv.kvBits, + kvGroupSize: 64, + quantizedKVStart: kv.quantizedKVStart, + prefillStepSize: chunkSize, + kvScheme: kv.kvScheme + ) + + MLX.GPU.resetPeakMemory() + let baselineGPU = MLX.Memory.activeMemory + let startTime = Date() + + // Process the ENTIRE sequence in chunks, capturing logits from every position. + // Unlike model.prepare() which discards logits from early chunks, we manually + // feed each chunk and extract per-position log-probs before moving on. + let ppl: (wordPPL: Double, tokenPPL: Double, totalNLL: Double) = try await container.perform { ctx in + var cache = ctx.model.newCache(parameters: params) + var state: LMOutput.State? = nil + var negLogProbSum: Double = 0 + var evalCount = 0 + + // Process tokens in chunks, accumulating NLL + let seqLen = tokenIds.count + var offset = 0 + while offset < seqLen - 1 { + let end = min(offset + chunkSize, seqLen - 1) + let chunkTokens = MLXArray(Array(tokenIds[offset.. baselineGPU ? activeGPU - baselineGPU : 0 + + print("[BENCH] WikiText-2 Word PPL: \(String(format: "%.4f", ppl.wordPPL)) (token PPL: \(String(format: "%.4f", ppl.tokenPPL)))") + print("[BENCH] Throughput: \(String(format: "%.1f", tokPerSec)) tok/s") + print("[BENCH] Time: \(String(format: "%.1f", elapsed))s") + print(hr) + + BenchmarkWriter.append( + model: family.name, + repoId: variant.repoId, + quantization: variant.quantization, + kvConfig: kv.description, + scenario: "wikitext2", + contextSize: contextSize, + promptTokens: tokenIds.count, + prefillTokPerSec: tokPerSec, + genTokPerSec: 0, + genTokens: 0, + ttftMs: elapsed * 1000, + thinkingPerplexity: nil, + generationPerplexity: ppl.wordPPL, + thinkingKLD: nil, + generationKLD: nil, + baselineGPU: baselineGPU, + peakGPU: Int(peakGPU), + kvDelta: kvDelta, + outputPreview: "WikiText-2 forced-decode perplexity evaluation", + parameters: .init( + generate: params, + thinkingEnabled: false, + thinkingTokenBudget: nil, + kldSummary: kldParameterSummary(needsKLD: false, isWikitext2: true), + maxOpsPerBuffer: BenchmarkWriter.resolvedMaxOpsPerBufferReport(), + batchSize: BenchEnv.batch, + speculativeDecoding: speculativeDecodingLabel( + ngramSize: params.ngramSize, + maxNgramDraftTokens: params.maxNgramDraftTokens, + draftModelId: draftModelIdForReport() + ), + systemPromptSummary: systemPromptSummary(for: nil, scenario: "wikitext2") + ) + ) + + MLX.Memory.clearCache() + } + + // MARK: - Needle-in-a-Haystack + + /// Needle-in-a-haystack benchmark: insert a known fact at multiple depth positions + /// in filler text and test whether the model can retrieve it. Runs one test per depth. + private func runNIAHBenchmark( + family: ModelFamily, + kv: KVCacheConfig, + contextSize: Int + ) async throws { + let (variant, repoId) = try await resolveVariant(family: family) + let filler = try loadPrompt(tokenCount: contextSize) + + for depth in Self.niahDepths { + let depthPct = Int(depth * 100) + let insertAt = filler.index( + filler.startIndex, + offsetBy: max(0, min(Int(Double(filler.count) * depth), filler.count - 1)) + ) + let prompt = String(filler[.. ModelContainer { + if let cached = ModelCache.shared.get(repoId) { + return cached + } + // Support local paths: if repoId starts with / or ~, treat as directory + let isLocal = repoId.hasPrefix("/") || repoId.hasPrefix("~") || repoId.hasPrefix(".") + let modelConfig: ModelConfiguration + if isLocal { + let expanded = NSString(string: repoId).expandingTildeInPath + modelConfig = family.extraEOSTokens.isEmpty + ? ModelConfiguration(directory: URL(fileURLWithPath: expanded)) + : ModelConfiguration(directory: URL(fileURLWithPath: expanded), extraEOSTokens: Set(family.extraEOSTokens)) + } else { + modelConfig = family.extraEOSTokens.isEmpty + ? ModelConfiguration(id: repoId) + : ModelConfiguration(id: repoId, extraEOSTokens: Set(family.extraEOSTokens)) + } + let container = try await LLMModelFactory.shared.loadContainer( + from: benchmarkDownloader, + using: benchmarkTokenizerLoader, + configuration: modelConfig, + progressHandler: { p in + if p.fractionCompleted < 0.01 || p.fractionCompleted > 0.99 { + print("[BENCH] Loading: \(String(format: "%.0f", p.fractionCompleted * 100))%") + } + } + ) + ModelCache.shared.set(repoId, container) + return container + } + + // MARK: - KLD Forced Decode + + /// Forced decode: feed tokens from the target generation through the baseline model + /// (bf16/8bit, no KV quantization), computing the baseline log prob of each token. + /// KLD = mean(quantized_logprob - baseline_logprob) per phase (≥ 0). + private func forcedDecodeKLD( + container: ModelContainer, + input: LMInput, + family: ModelFamily, + quantizedData: BaselineTokenData, + thinkStartId: Int32?, + thinkEndId: Int32?, + thinkingBudget: Int, + maxTokens: Int + ) async throws -> (thinkKLD: Double?, genKLD: Double?) { + // effectiveMaxTokens keys off whichever thinking style is active, matching + // the hasThinkingBudget computation at the main call site. + let hasThinkingBudget = thinkStartId != nil // bracket-only here; harmony path + // populates quantizedData directly and we + // just process everything captured. + let effectiveMaxTokens = hasThinkingBudget ? thinkingBudget + maxTokens : maxTokens + + // Params WITHOUT KV quantization — the baseline model runs unquantized + let params = GenerateParameters( + maxTokens: effectiveMaxTokens, + temperature: family.temperature, + topP: family.topP, + topK: family.topK, + minP: family.minP, + repetitionPenalty: family.repetitionPenalty, + presencePenalty: family.presencePenalty, + prefillStepSize: 2048, + reasoningEffort: family.reasoningEffort, + thinkStartTokenId: thinkStartId, + thinkEndTokenId: thinkEndId, + thinkingPhasePrefilled: thinkStartId != nil + ) + + print("[KLD] Running forced decode (no KV quant) for \(quantizedData.tokenIds.count) tokens...") + + // Manual prefill + forced decode (bypasses TokenIterator to avoid off-by-one: + // TokenIterator.init does prefill AND samples the first token, consuming position-0 + // logits. We need those logits to compute KLD for token[0].) + nonisolated(unsafe) let sendableInput = input + return try await container.perform { ctx in + // 1. Create cache and prefill — NO KV quantization + var cache = ctx.model.newCache(parameters: params) + var state: LMOutput.State? = nil + var logits: MLXArray + + switch try ctx.model.prepare(sendableInput, cache: cache, windowSize: params.prefillStepSize) { + case .tokens(let remaining): + let result = ctx.model( + remaining[text: .newAxis], + cache: cache.isEmpty ? nil : cache, + state: nil + ) + state = result.state + logits = result.logits + case .logits(let result): + logits = result.logits + state = result.state + } + + // 2. Forced decode: compute baseline (unquantized) log prob for each token. + // Process the full captured sequence — the target's generation loop already + // bounded it via its own maxTokens, so capping again here would drop data. + let tokenIds = quantizedData.tokenIds + let quantizedLogProbs = quantizedData.logProbs + let phases = quantizedData.phases + let tokenCount = tokenIds.count + _ = effectiveMaxTokens // retained for the Parameters summary only + + var thinkKLDSum: Double = 0 + var thinkCount = 0 + var genKLDSum: Double = 0 + var genCount = 0 + var inThinkPhase = thinkStartId != nil // prefilled + + for i in 0.. 0 ? thinkKLDSum / Double(thinkCount) : nil + let genKLD = genCount > 0 ? genKLDSum / Double(genCount) : nil + + print("[KLD] Forced decode: \(tokenCount) tokens, think=\(thinkCount) gen=\(genCount)") + if let k = thinkKLD { print("[KLD] Think KLD: \(String(format: "%.6f", k))") } + if let k = genKLD { print("[KLD] Gen KLD: \(String(format: "%.6f", k))") } + + return (thinkKLD, genKLD) + } + } + + // MARK: - Utilities + + private func formatBytes(_ bytes: Int) -> String { + BenchmarkWriter.formatBytes(bytes) + } + + /// Short text for benchmark `## System prompt` (no user prompt bodies). + private func systemPromptSummary(for systemPrompt: String?, scenario: String) -> String { + if scenario == "wikitext2" { + return "Not applicable (WikiText-2 LM evaluation; no chat system role)." + } + guard let sp = systemPrompt else { + return "No system role message; user-only messages per methodology (no full user prompt in this report)." + } + if sp == Self.minimalSystemPrompt { + return "Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts)." + } + return "Custom system prompt (not repeated in this report)." + } + + /// When set, reported as `draft (id)` in benchmark markdown (draft-model speculative runs). + private func draftModelIdForReport() -> String? { + let s = ProcessInfo.processInfo.environment["MLX_BENCH_DRAFT_MODEL"]? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return s.isEmpty ? nil : s + } + + private func kldParameterSummary(needsKLD: Bool, isWikitext2: Bool) -> String { + guard BenchEnv.kldEnabled else { return "No" } + if isWikitext2 { + return "Yes (not evaluated — wikitext2 method)" + } + if needsKLD { + return "Yes" + } + return "Yes (not evaluated — baseline configuration)" + } + + private func speculativeDecodingLabel( + ngramSize: Int, + maxNgramDraftTokens: Int, + draftModelId: String? = nil + ) -> String { + if let id = draftModelId?.trimmingCharacters(in: .whitespacesAndNewlines), !id.isEmpty { + return "draft (\(id))" + } + if ngramSize > 0 { + return "ngram (size=\(ngramSize), maxDraft=\(maxNgramDraftTokens))" + } + return "none" + } + + /// Resolve a resource file relative to the Tests/Benchmarks/Resources directory. + /// Uses #filePath since Bundle.module is unavailable (no resource processing in this target). + private static func resourceURL(name: String, ext: String, filePath: String = #filePath) -> URL? { + let thisFile = URL(fileURLWithPath: filePath) + let benchDir = thisFile.deletingLastPathComponent() + let resourceURL = benchDir.appendingPathComponent("Resources") + .appendingPathComponent("llm-test-prompts") + .appendingPathComponent(name) + .appendingPathExtension(ext) + return FileManager.default.fileExists(atPath: resourceURL.path) ? resourceURL : nil + } + + private func loadPrompt(tokenCount: Int) throws -> String { + let filename = "prompt_\(tokenCount)" + guard let url = Self.resourceURL(name: filename, ext: "txt") else { + throw BenchmarkError("Missing test resource: \(filename).txt") + } + return try String(contentsOf: url, encoding: .utf8) + } + + private func loadWikitext2() throws -> String { + guard let url = Self.resourceURL(name: "wikitext2_test", ext: "txt") else { + throw BenchmarkError("Missing test resource: wikitext2_test.txt") + } + return try String(contentsOf: url, encoding: .utf8) + } +} diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_1024.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_1024.txt new file mode 100644 index 0000000000..382853b230 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_1024.txt @@ -0,0 +1,102 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_128.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_128.txt new file mode 100644 index 0000000000..b7d9aa7cc2 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_128.txt @@ -0,0 +1,30 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_131072.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_131072.txt new file mode 100644 index 0000000000..9a428e311e --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_131072.txt @@ -0,0 +1,11504 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I decided to go East and learn the bond +business. Everybody I knew was in the bond business, so I supposed it +could support one more single man. All my aunts and uncles talked it +over as if they were choosing a prep school for me, and finally said, +“Why—ye-es,” with very grave, hesitant faces. Father agreed to finance +me for a year, and after various delays I came East, permanently, I +thought, in the spring of twenty-two. + +The practical thing was to find rooms in the city, but it was a warm +season, and I had just left a country of wide lawns and friendly +trees, so when a young man at the office suggested that we take a +house together in a commuting town, it sounded like a great idea. He +found the house, a weather-beaten cardboard bungalow at eighty a +month, but at the last minute the firm ordered him to Washington, and +I went out to the country alone. I had a dog—at least I had him for a +few days until he ran away—and an old Dodge and a Finnish woman, who +made my bed and cooked breakfast and muttered Finnish wisdom to +herself over the electric stove. + +It was lonely for a day or so until one morning some man, more +recently arrived than I, stopped me on the road. + +“How do you get to West Egg village?” he asked helplessly. + +I told him. And as I walked on I was lonely no longer. I was a guide, +a pathfinder, an original settler. He had casually conferred on me the +freedom of the neighbourhood. + +And so with the sunshine and the great bursts of leaves growing on the +trees, just as things grow in fast movies, I had that familiar +conviction that life was beginning over again with the summer. + +There was so much to read, for one thing, and so much fine health to +be pulled down out of the young breath-giving air. I bought a dozen +volumes on banking and credit and investment securities, and they +stood on my shelf in red and gold like new money from the mint, +promising to unfold the shining secrets that only Midas and Morgan and +Maecenas knew. And I had the high intention of reading many other +books besides. I was rather literary in college—one year I wrote a +series of very solemn and obvious editorials for the Yale News—and now +I was going to bring back all such things into my life and become +again that most limited of all specialists, the “well-rounded man.” +This isn’t just an epigram—life is much more successfully looked at +from a single window, after all. + +It was a matter of chance that I should have rented a house in one of +the strangest communities in North America. It was on that slender +riotous island which extends itself due east of New York—and where +there are, among other natural curiosities, two unusual formations of +land. Twenty miles from the city a pair of enormous eggs, identical in +contour and separated only by a courtesy bay, jut out into the most +domesticated body of salt water in the Western hemisphere, the great +wet barnyard of Long Island Sound. They are not perfect ovals—like the +egg in the Columbus story, they are both crushed flat at the contact +end—but their physical resemblance must be a source of perpetual +wonder to the gulls that fly overhead. To the wingless a more +interesting phenomenon is their dissimilarity in every particular +except shape and size. + +I lived at West Egg, the—well, the less fashionable of the two, though +this is a most superficial tag to express the bizarre and not a little +sinister contrast between them. My house was at the very tip of the +egg, only fifty yards from the Sound, and squeezed between two huge +places that rented for twelve or fifteen thousand a season. The one on +my right was a colossal affair by any standard—it was a factual +imitation of some Hôtel de Ville in Normandy, with a tower on one +side, spanking new under a thin beard of raw ivy, and a marble +swimming pool, and more than forty acres of lawn and garden. It was +Gatsby’s mansion. Or, rather, as I didn’t know Mr. Gatsby, it was a +mansion inhabited by a gentleman of that name. My own house was an +eyesore, but it was a small eyesore, and it had been overlooked, so I +had a view of the water, a partial view of my neighbour’s lawn, and +the consoling proximity of millionaires—all for eighty dollars a +month. + +Across the courtesy bay the white palaces of fashionable East Egg +glittered along the water, and the history of the summer really begins +on the evening I drove over there to have dinner with the Tom +Buchanans. Daisy was my second cousin once removed, and I’d known Tom +in college. And just after the war I spent two days with them in +Chicago. + +Her husband, among various physical accomplishments, had been one of +the most powerful ends that ever played football at New Haven—a +national figure in a way, one of those men who reach such an acute +limited excellence at twenty-one that everything afterward savours of +anticlimax. His family were enormously wealthy—even in college his +freedom with money was a matter for reproach—but now he’d left Chicago +and come East in a fashion that rather took your breath away: for +instance, he’d brought down a string of polo ponies from Lake +Forest. It was hard to realize that a man in my own generation was +wealthy enough to do that. + +Why they came East I don’t know. They had spent a year in France for +no particular reason, and then drifted here and there unrestfully +wherever people played polo and were rich together. This was a +permanent move, said Daisy over the telephone, but I didn’t believe +it—I had no sight into Daisy’s heart, but I felt that Tom would drift +on forever seeking, a little wistfully, for the dramatic turbulence of +some irrecoverable football game. + +And so it happened that on a warm windy evening I drove over to East +Egg to see two old friends whom I scarcely knew at all. Their house +was even more elaborate than I expected, a cheerful red-and-white +Georgian Colonial mansion, overlooking the bay. The lawn started at +the beach and ran towards the front door for a quarter of a mile, +jumping over sundials and brick walks and burning gardens—finally when +it reached the house drifting up the side in bright vines as though +from the momentum of its run. The front was broken by a line of French +windows, glowing now with reflected gold and wide open to the warm +windy afternoon, and Tom Buchanan in riding clothes was standing with +his legs apart on the front porch. + +He had changed since his New Haven years. Now he was a sturdy +straw-haired man of thirty, with a rather hard mouth and a +supercilious manner. Two shining arrogant eyes had established +dominance over his face and gave him the appearance of always leaning +aggressively forward. Not even the effeminate swank of his riding +clothes could hide the enormous power of that body—he seemed to fill +those glistening boots until he strained the top lacing, and you could +see a great pack of muscle shifting when his shoulder moved under his +thin coat. It was a body capable of enormous leverage—a cruel body. + +His speaking voice, a gruff husky tenor, added to the impression of +fractiousness he conveyed. There was a touch of paternal contempt in +it, even toward people he liked—and there were men at New Haven who +had hated his guts. + +“Now, don’t think my opinion on these matters is final,” he seemed to +say, “just because I’m stronger and more of a man than you are.” We +were in the same senior society, and while we were never intimate I +always had the impression that he approved of me and wanted me to like +him with some harsh, defiant wistfulness of his own. + +We talked for a few minutes on the sunny porch. + +“I’ve got a nice place here,” he said, his eyes flashing about +restlessly. + +Turning me around by one arm, he moved a broad flat hand along the +front vista, including in its sweep a sunken Italian garden, a half +acre of deep, pungent roses, and a snub-nosed motorboat that bumped +the tide offshore. + +“It belonged to Demaine, the oil man.” He turned me around again, +politely and abruptly. “We’ll go inside.” + +We walked through a high hallway into a bright rosy-coloured space, +fragilely bound into the house by French windows at either end. The +windows were ajar and gleaming white against the fresh grass outside +that seemed to grow a little way into the house. A breeze blew through +the room, blew curtains in at one end and out the other like pale +flags, twisting them up toward the frosted wedding-cake of the +ceiling, and then rippled over the wine-coloured rug, making a shadow +on it as wind does on the sea. + +The only completely stationary object in the room was an enormous +couch on which two young women were buoyed up as though upon an +anchored balloon. They were both in white, and their dresses were +rippling and fluttering as if they had just been blown back in after a +short flight around the house. I must have stood for a few moments +listening to the whip and snap of the curtains and the groan of a +picture on the wall. Then there was a boom as Tom Buchanan shut the +rear windows and the caught wind died out about the room, and the +curtains and the rugs and the two young women ballooned slowly to the +floor. + +The younger of the two was a stranger to me. She was extended full +length at her end of the divan, completely motionless, and with her +chin raised a little, as if she were balancing something on it which +was quite likely to fall. If she saw me out of the corner of her eyes +she gave no hint of it—indeed, I was almost surprised into murmuring +an apology for having disturbed her by coming in. + +The other girl, Daisy, made an attempt to rise—she leaned slightly +forward with a conscientious expression—then she laughed, an absurd, +charming little laugh, and I laughed too and came forward into the +room. + +“I’m p-paralysed with happiness.” + +She laughed again, as if she said something very witty, and held my +hand for a moment, looking up into my face, promising that there was +no one in the world she so much wanted to see. That was a way she +had. She hinted in a murmur that the surname of the balancing girl was +Baker. (I’ve heard it said that Daisy’s murmur was only to make people +lean toward her; an irrelevant criticism that made it no less +charming.) + +At any rate, Miss Baker’s lips fluttered, she nodded at me almost +imperceptibly, and then quickly tipped her head back again—the object +she was balancing had obviously tottered a little and given her +something of a fright. Again a sort of apology arose to my lips. +Almost any exhibition of complete self-sufficiency draws a stunned +tribute from me. + +I looked back at my cousin, who began to ask me questions in her low, +thrilling voice. It was the kind of voice that the ear follows up and +down, as if each speech is an arrangement of notes that will never be +played again. Her face was sad and lovely with bright things in it, +bright eyes and a bright passionate mouth, but there was an excitement +in her voice that men who had cared for her found difficult to forget: +a singing compulsion, a whispered “Listen,” a promise that she had +done gay, exciting things just a while since and that there were gay, +exciting things hovering in the next hour. + +I told her how I had stopped off in Chicago for a day on my way East, +and how a dozen people had sent their love through me. + +“Do they miss me?” she cried ecstatically. + +“The whole town is desolate. All the cars have the left rear wheel +painted black as a mourning wreath, and there’s a persistent wail all +night along the north shore.” + +“How gorgeous! Let’s go back, Tom. Tomorrow!” Then she added +irrelevantly: “You ought to see the baby.” + +“I’d like to.” + +“She’s asleep. She’s three years old. Haven’t you ever seen her?” + +“Never.” + +“Well, you ought to see her. She’s—” + +Tom Buchanan, who had been hovering restlessly about the room, stopped +and rested his hand on my shoulder. + +“What you doing, Nick?” + +“I’m a bond man.” + +“Who with?” + +I told him. + +“Never heard of them,” he remarked decisively. + +This annoyed me. + +“You will,” I answered shortly. “You will if you stay in the East.” + +“Oh, I’ll stay in the East, don’t you worry,” he said, glancing at +Daisy and then back at me, as if he were alert for something +more. “I’d be a God damned fool to live anywhere else.” + +At this point Miss Baker said: “Absolutely!” with such suddenness that +I started—it was the first word she had uttered since I came into the +room. Evidently it surprised her as much as it did me, for she yawned +and with a series of rapid, deft movements stood up into the room. + +“I’m stiff,” she complained, “I’ve been lying on that sofa for as long +as I can remember.” + +“Don’t look at me,” Daisy retorted, “I’ve been trying to get you to +New York all afternoon.” + +“No, thanks,” said Miss Baker to the four cocktails just in from the +pantry. “I’m absolutely in training.” + +Her host looked at her incredulously. + +“You are!” He took down his drink as if it were a drop in the bottom +of a glass. “How you ever get anything done is beyond me.” + +I looked at Miss Baker, wondering what it was she “got done.” I +enjoyed looking at her. She was a slender, small-breasted girl, with +an erect carriage, which she accentuated by throwing her body backward +at the shoulders like a young cadet. Her grey sun-strained eyes looked +back at me with polite reciprocal curiosity out of a wan, charming, +discontented face. It occurred to me now that I had seen her, or a +picture of her, somewhere before. + +“You live in West Egg,” she remarked contemptuously. “I know somebody +there.” + +“I don’t know a single—” + +“You must know Gatsby.” + +“Gatsby?” demanded Daisy. “What Gatsby?” + +Before I could reply that he was my neighbour dinner was announced; +wedging his tense arm imperatively under mine, Tom Buchanan compelled +me from the room as though he were moving a checker to another square. + +Slenderly, languidly, their hands set lightly on their hips, the two +young women preceded us out on to a rosy-coloured porch, open toward +the sunset, where four candles flickered on the table in the +diminished wind. + +“Why candles?” objected Daisy, frowning. She snapped them out with her +fingers. “In two weeks it’ll be the longest day in the year.” She +looked at us all radiantly. “Do you always watch for the longest day +of the year and then miss it? I always watch for the longest day in +the year and then miss it.” + +“We ought to plan something,” yawned Miss Baker, sitting down at the +table as if she were getting into bed. + +“All right,” said Daisy. “What’ll we plan?” She turned to me +helplessly: “What do people plan?” + +Before I could answer her eyes fastened with an awed expression on her +little finger. + +“Look!” she complained; “I hurt it.” + +We all looked—the knuckle was black and blue. + +“You did it, Tom,” she said accusingly. “I know you didn’t mean to, +but you did do it. That’s what I get for marrying a brute of a man, a +great, big, hulking physical specimen of a—” + +“I hate that word ‘hulking,’ ” objected Tom crossly, “even in +kidding.” + +“Hulking,” insisted Daisy. + +Sometimes she and Miss Baker talked at once, unobtrusively and with a +bantering inconsequence that was never quite chatter, that was as cool +as their white dresses and their impersonal eyes in the absence of all +desire. They were here, and they accepted Tom and me, making only a +polite pleasant effort to entertain or to be entertained. They knew +that presently dinner would be over and a little later the evening too +would be over and casually put away. It was sharply different from the +West, where an evening was hurried from phase to phase towards its +close, in a continually disappointed anticipation or else in sheer +nervous dread of the moment itself. + +“You make me feel uncivilized, Daisy,” I confessed on my second glass +of corky but rather impressive claret. “Can’t you talk about crops or +something?” + +I meant nothing in particular by this remark, but it was taken up in +an unexpected way. + +“Civilization’s going to pieces,” broke out Tom violently. “I’ve +gotten to be a terrible pessimist about things. Have you read The Rise +of the Coloured Empires by this man Goddard?” + +“Why, no,” I answered, rather surprised by his tone. + +“Well, it’s a fine book, and everybody ought to read it. The idea is +if we don’t look out the white race will be—will be utterly +submerged. It’s all scientific stuff; it’s been proved.” + +“Tom’s getting very profound,” said Daisy, with an expression of +unthoughtful sadness. “He reads deep books with long words in +them. What was that word we—” + +“Well, these books are all scientific,” insisted Tom, glancing at her +impatiently. “This fellow has worked out the whole thing. It’s up to +us, who are the dominant race, to watch out or these other races will +have control of things.” + +“We’ve got to beat them down,” whispered Daisy, winking ferociously +toward the fervent sun. + +“You ought to live in California—” began Miss Baker, but Tom +interrupted her by shifting heavily in his chair. + +“This idea is that we’re Nordics. I am, and you are, and you are, +and—” After an infinitesimal hesitation he included Daisy with a +slight nod, and she winked at me again. “—And we’ve produced all the +things that go to make civilization—oh, science and art, and all +that. Do you see?” + +There was something pathetic in his concentration, as if his +complacency, more acute than of old, was not enough to him any more. +When, almost immediately, the telephone rang inside and the butler +left the porch Daisy seized upon the momentary interruption and leaned +towards me. + +“I’ll tell you a family secret,” she whispered enthusiastically. +“It’s about the butler’s nose. Do you want to hear about the butler’s +nose?” + +“That’s why I came over tonight.” + +“Well, he wasn’t always a butler; he used to be the silver polisher +for some people in New York that had a silver service for two hundred +people. He had to polish it from morning till night, until finally it +began to affect his nose—” + +“Things went from bad to worse,” suggested Miss Baker. + +“Yes. Things went from bad to worse, until finally he had to give up +his position.” + +For a moment the last sunshine fell with romantic affection upon her +glowing face; her voice compelled me forward breathlessly as I +listened—then the glow faded, each light deserting her with lingering +regret, like children leaving a pleasant street at dusk. + +The butler came back and murmured something close to Tom’s ear, +whereupon Tom frowned, pushed back his chair, and without a word went +inside. As if his absence quickened something within her, Daisy leaned +forward again, her voice glowing and singing. + +“I love to see you at my table, Nick. You remind me of a—of a rose, an +absolute rose. Doesn’t he?” She turned to Miss Baker for confirmation: +“An absolute rose?” + +This was untrue. I am not even faintly like a rose. She was only +extemporizing, but a stirring warmth flowed from her, as if her heart +was trying to come out to you concealed in one of those breathless, +thrilling words. Then suddenly she threw her napkin on the table and +excused herself and went into the house. + +Miss Baker and I exchanged a short glance consciously devoid of +meaning. I was about to speak when she sat up alertly and said “Sh!” +in a warning voice. A subdued impassioned murmur was audible in the +room beyond, and Miss Baker leaned forward unashamed, trying to +hear. The murmur trembled on the verge of coherence, sank down, +mounted excitedly, and then ceased altogether. + +“This Mr. Gatsby you spoke of is my neighbour—” I began. + +“Don’t talk. I want to hear what happens.” + +“Is something happening?” I inquired innocently. + +“You mean to say you don’t know?” said Miss Baker, honestly surprised. +“I thought everybody knew.” + +“I don’t.” + +“Why—” she said hesitantly. “Tom’s got some woman in New York.” + +“Got some woman?” I repeated blankly. + +Miss Baker nodded. + +“She might have the decency not to telephone him at dinner time. +Don’t you think?” + +Almost before I had grasped her meaning there was the flutter of a +dress and the crunch of leather boots, and Tom and Daisy were back at +the table. + +“It couldn’t be helped!” cried Daisy with tense gaiety. + +She sat down, glanced searchingly at Miss Baker and then at me, and +continued: “I looked outdoors for a minute, and it’s very romantic +outdoors. There’s a bird on the lawn that I think must be a +nightingale come over on the Cunard or White Star Line. He’s singing +away—” Her voice sang: “It’s romantic, isn’t it, Tom?” + +“Very romantic,” he said, and then miserably to me: “If it’s light +enough after dinner, I want to take you down to the stables.” + +The telephone rang inside, startlingly, and as Daisy shook her head +decisively at Tom the subject of the stables, in fact all subjects, +vanished into air. Among the broken fragments of the last five minutes +at table I remember the candles being lit again, pointlessly, and I +was conscious of wanting to look squarely at everyone, and yet to +avoid all eyes. I couldn’t guess what Daisy and Tom were thinking, but +I doubt if even Miss Baker, who seemed to have mastered a certain +hardy scepticism, was able utterly to put this fifth guest’s shrill +metallic urgency out of mind. To a certain temperament the situation +might have seemed intriguing—my own instinct was to telephone +immediately for the police. + +The horses, needless to say, were not mentioned again. Tom and Miss +Baker, with several feet of twilight between them, strolled back into +the library, as if to a vigil beside a perfectly tangible body, while, +trying to look pleasantly interested and a little deaf, I followed +Daisy around a chain of connecting verandas to the porch in front. In +its deep gloom we sat down side by side on a wicker settee. + +Daisy took her face in her hands as if feeling its lovely shape, and +her eyes moved gradually out into the velvet dusk. I saw that +turbulent emotions possessed her, so I asked what I thought would be +some sedative questions about her little girl. + +“We don’t know each other very well, Nick,” she said suddenly. “Even +if we are cousins. You didn’t come to my wedding.” + +“I wasn’t back from the war.” + +“That’s true.” She hesitated. “Well, I’ve had a very bad time, Nick, +and I’m pretty cynical about everything.” + +Evidently she had reason to be. I waited but she didn’t say any more, +and after a moment I returned rather feebly to the subject of her +daughter. + +“I suppose she talks, and—eats, and everything.” + +“Oh, yes.” She looked at me absently. “Listen, Nick; let me tell you +what I said when she was born. Would you like to hear?” + +“Very much.” + +“It’ll show you how I’ve gotten to feel about—things. Well, she was +less than an hour old and Tom was God knows where. I woke up out of +the ether with an utterly abandoned feeling, and asked the nurse right +away if it was a boy or a girl. She told me it was a girl, and so I +turned my head away and wept. ‘All right,’ I said, ‘I’m glad it’s a +girl. And I hope she’ll be a fool—that’s the best thing a girl can be +in this world, a beautiful little fool.’ + +“You see I think everything’s terrible anyhow,” she went on in a +convinced way. “Everybody thinks so—the most advanced people. And I +know. I’ve been everywhere and seen everything and done everything.” +Her eyes flashed around her in a defiant way, rather like Tom’s, and +she laughed with thrilling scorn. “Sophisticated—God, I’m +sophisticated!” + +The instant her voice broke off, ceasing to compel my attention, my +belief, I felt the basic insincerity of what she had said. It made me +uneasy, as though the whole evening had been a trick of some sort to +exact a contributory emotion from me. I waited, and sure enough, in a +moment she looked at me with an absolute smirk on her lovely face, as +if she had asserted her membership in a rather distinguished secret +society to which she and Tom belonged. + +------------------------------------------------------------------------ + +Inside, the crimson room bloomed with light. Tom and Miss Baker sat at +either end of the long couch and she read aloud to him from the +Saturday Evening Post—the words, murmurous and uninflected, running +together in a soothing tune. The lamplight, bright on his boots and +dull on the autumn-leaf yellow of her hair, glinted along the paper as +she turned a page with a flutter of slender muscles in her arms. + +When we came in she held us silent for a moment with a lifted hand. + +“To be continued,” she said, tossing the magazine on the table, “in +our very next issue.” + +Her body asserted itself with a restless movement of her knee, and she +stood up. + +“Ten o’clock,” she remarked, apparently finding the time on the +ceiling. “Time for this good girl to go to bed.” + +“Jordan’s going to play in the tournament tomorrow,” explained Daisy, +“over at Westchester.” + +“Oh—you’re Jordan Baker.” + +I knew now why her face was familiar—its pleasing contemptuous +expression had looked out at me from many rotogravure pictures of the +sporting life at Asheville and Hot Springs and Palm Beach. I had heard +some story of her too, a critical, unpleasant story, but what it was I +had forgotten long ago. + +“Good night,” she said softly. “Wake me at eight, won’t you.” + +“If you’ll get up.” + +“I will. Good night, Mr. Carraway. See you anon.” + +“Of course you will,” confirmed Daisy. “In fact I think I’ll arrange a +marriage. Come over often, Nick, and I’ll sort of—oh—fling you +together. You know—lock you up accidentally in linen closets and push +you out to sea in a boat, and all that sort of thing—” + +“Good night,” called Miss Baker from the stairs. “I haven’t heard a +word.” + +“She’s a nice girl,” said Tom after a moment. “They oughtn’t to let +her run around the country this way.” + +“Who oughtn’t to?” inquired Daisy coldly. + +“Her family.” + +“Her family is one aunt about a thousand years old. Besides, Nick’s +going to look after her, aren’t you, Nick? She’s going to spend lots +of weekends out here this summer. I think the home influence will be +very good for her.” + +Daisy and Tom looked at each other for a moment in silence. + +“Is she from New York?” I asked quickly. + +“From Louisville. Our white girlhood was passed together there. Our +beautiful white—” + +“Did you give Nick a little heart to heart talk on the veranda?” +demanded Tom suddenly. + +“Did I?” She looked at me. “I can’t seem to remember, but I think we +talked about the Nordic race. Yes, I’m sure we did. It sort of crept +up on us and first thing you know—” + +“Don’t believe everything you hear, Nick,” he advised me. + +I said lightly that I had heard nothing at all, and a few minutes +later I got up to go home. They came to the door with me and stood +side by side in a cheerful square of light. As I started my motor +Daisy peremptorily called: “Wait! + +“I forgot to ask you something, and it’s important. We heard you were +engaged to a girl out West.” + +“That’s right,” corroborated Tom kindly. “We heard that you were +engaged.” + +“It’s a libel. I’m too poor.” + +“But we heard it,” insisted Daisy, surprising me by opening up again +in a flower-like way. “We heard it from three people, so it must be +true.” + +Of course I knew what they were referring to, but I wasn’t even +vaguely engaged. The fact that gossip had published the banns was one +of the reasons I had come East. You can’t stop going with an old +friend on account of rumours, and on the other hand I had no intention +of being rumoured into marriage. + +Their interest rather touched me and made them less remotely +rich—nevertheless, I was confused and a little disgusted as I drove +away. It seemed to me that the thing for Daisy to do was to rush out +of the house, child in arms—but apparently there were no such +intentions in her head. As for Tom, the fact that he “had some woman +in New York” was really less surprising than that he had been +depressed by a book. Something was making him nibble at the edge of +stale ideas as if his sturdy physical egotism no longer nourished his +peremptory heart. + +Already it was deep summer on roadhouse roofs and in front of wayside +garages, where new red petrol-pumps sat out in pools of light, and +when I reached my estate at West Egg I ran the car under its shed and +sat for a while on an abandoned grass roller in the yard. The wind had +blown off, leaving a loud, bright night, with wings beating in the +trees and a persistent organ sound as the full bellows of the earth +blew the frogs full of life. The silhouette of a moving cat wavered +across the moonlight, and, turning my head to watch it, I saw that I +was not alone—fifty feet away a figure had emerged from the shadow of +my neighbour’s mansion and was standing with his hands in his pockets +regarding the silver pepper of the stars. Something in his leisurely +movements and the secure position of his feet upon the lawn suggested +that it was Mr. Gatsby himself, come out to determine what share was +his of our local heavens. + +I decided to call to him. Miss Baker had mentioned him at dinner, and +that would do for an introduction. But I didn’t call to him, for he +gave a sudden intimation that he was content to be alone—he stretched +out his arms toward the dark water in a curious way, and, far as I was +from him, I could have sworn he was trembling. Involuntarily I glanced +seaward—and distinguished nothing except a single green light, minute +and far away, that might have been the end of a dock. When I looked +once more for Gatsby he had vanished, and I was alone again in the +unquiet darkness. + + + II + +About halfway between West Egg and New York the motor road hastily +joins the railroad and runs beside it for a quarter of a mile, so as +to shrink away from a certain desolate area of land. This is a valley +of ashes—a fantastic farm where ashes grow like wheat into ridges and +hills and grotesque gardens; where ashes take the forms of houses and +chimneys and rising smoke and, finally, with a transcendent effort, of +ash-grey men, who move dimly and already crumbling through the powdery +air. Occasionally a line of grey cars crawls along an invisible track, +gives out a ghastly creak, and comes to rest, and immediately the +ash-grey men swarm up with leaden spades and stir up an impenetrable +cloud, which screens their obscure operations from your sight. + +But above the grey land and the spasms of bleak dust which drift +endlessly over it, you perceive, after a moment, the eyes of Doctor T. +J. Eckleburg. The eyes of Doctor T. J. Eckleburg are blue and +gigantic—their retinas are one yard high. They look out of no face, +but, instead, from a pair of enormous yellow spectacles which pass +over a nonexistent nose. Evidently some wild wag of an oculist set +them there to fatten his practice in the borough of Queens, and then +sank down himself into eternal blindness, or forgot them and moved +away. But his eyes, dimmed a little by many paintless days, under sun +and rain, brood on over the solemn dumping ground. + +The valley of ashes is bounded on one side by a small foul river, and, +when the drawbridge is up to let barges through, the passengers on +waiting trains can stare at the dismal scene for as long as half an +hour. There is always a halt there of at least a minute, and it was +because of this that I first met Tom Buchanan’s mistress. + +The fact that he had one was insisted upon wherever he was known. His +acquaintances resented the fact that he turned up in popular cafés +with her and, leaving her at a table, sauntered about, chatting with +whomsoever he knew. Though I was curious to see her, I had no desire +to meet her—but I did. I went up to New York with Tom on the train one +afternoon, and when we stopped by the ash-heaps he jumped to his feet +and, taking hold of my elbow, literally forced me from the car. + +“We’re getting off,” he insisted. “I want you to meet my girl.” + +I think he’d tanked up a good deal at luncheon, and his determination +to have my company bordered on violence. The supercilious assumption +was that on Sunday afternoon I had nothing better to do. + +I followed him over a low whitewashed railroad fence, and we walked +back a hundred yards along the road under Doctor Eckleburg’s +persistent stare. The only building in sight was a small block of +yellow brick sitting on the edge of the waste land, a sort of compact +Main Street ministering to it, and contiguous to absolutely nothing. +One of the three shops it contained was for rent and another was an +all-night restaurant, approached by a trail of ashes; the third was a +garage—Repairs. George B. Wilson. Cars bought and sold.—and I followed +Tom inside. + +The interior was unprosperous and bare; the only car visible was the +dust-covered wreck of a Ford which crouched in a dim corner. It had +occurred to me that this shadow of a garage must be a blind, and that +sumptuous and romantic apartments were concealed overhead, when the +proprietor himself appeared in the door of an office, wiping his hands +on a piece of waste. He was a blond, spiritless man, anaemic, and +faintly handsome. When he saw us a damp gleam of hope sprang into his +light blue eyes. + +“Hello, Wilson, old man,” said Tom, slapping him jovially on the +shoulder. “How’s business?” + +“I can’t complain,” answered Wilson unconvincingly. “When are you +going to sell me that car?” + +“Next week; I’ve got my man working on it now.” + +“Works pretty slow, don’t he?” + +“No, he doesn’t,” said Tom coldly. “And if you feel that way about it, +maybe I’d better sell it somewhere else after all.” + +“I don’t mean that,” explained Wilson quickly. “I just meant—” + +His voice faded off and Tom glanced impatiently around the garage. +Then I heard footsteps on a stairs, and in a moment the thickish +figure of a woman blocked out the light from the office door. She was +in the middle thirties, and faintly stout, but she carried her flesh +sensuously as some women can. Her face, above a spotted dress of dark +blue crêpe-de-chine, contained no facet or gleam of beauty, but there +was an immediately perceptible vitality about her as if the nerves of +her body were continually smouldering. She smiled slowly and, walking +through her husband as if he were a ghost, shook hands with Tom, +looking him flush in the eye. Then she wet her lips, and without +turning around spoke to her husband in a soft, coarse voice: + +“Get some chairs, why don’t you, so somebody can sit down.” + +“Oh, sure,” agreed Wilson hurriedly, and went toward the little +office, mingling immediately with the cement colour of the walls. A +white ashen dust veiled his dark suit and his pale hair as it veiled +everything in the vicinity—except his wife, who moved close to Tom. + +“I want to see you,” said Tom intently. “Get on the next train.” + +“All right.” + +“I’ll meet you by the newsstand on the lower level.” + +She nodded and moved away from him just as George Wilson emerged with +two chairs from his office door. + +We waited for her down the road and out of sight. It was a few days +before the Fourth of July, and a grey, scrawny Italian child was +setting torpedoes in a row along the railroad track. + +“Terrible place, isn’t it,” said Tom, exchanging a frown with Doctor +Eckleburg. + +“Awful.” + +“It does her good to get away.” + +“Doesn’t her husband object?” + +“Wilson? He thinks she goes to see her sister in New York. He’s so +dumb he doesn’t know he’s alive.” + +So Tom Buchanan and his girl and I went up together to New York—or not +quite together, for Mrs. Wilson sat discreetly in another car. Tom +deferred that much to the sensibilities of those East Eggers who might +be on the train. + +She had changed her dress to a brown figured muslin, which stretched +tight over her rather wide hips as Tom helped her to the platform in +New York. At the newsstand she bought a copy of Town Tattle and a +moving-picture magazine, and in the station drugstore some cold cream +and a small flask of perfume. Upstairs, in the solemn echoing drive +she let four taxicabs drive away before she selected a new one, +lavender-coloured with grey upholstery, and in this we slid out from +the mass of the station into the glowing sunshine. But immediately she +turned sharply from the window and, leaning forward, tapped on the +front glass. + +“I want to get one of those dogs,” she said earnestly. “I want to get +one for the apartment. They’re nice to have—a dog.” + +We backed up to a grey old man who bore an absurd resemblance to John +D. Rockefeller. In a basket swung from his neck cowered a dozen very +recent puppies of an indeterminate breed. + +“What kind are they?” asked Mrs. Wilson eagerly, as he came to the +taxi-window. + +“All kinds. What kind do you want, lady?” + +“I’d like to get one of those police dogs; I don’t suppose you got +that kind?” + +The man peered doubtfully into the basket, plunged in his hand and +drew one up, wriggling, by the back of the neck. + +“That’s no police dog,” said Tom. + +“No, it’s not exactly a police dog,” said the man with disappointment +in his voice. “It’s more of an Airedale.” He passed his hand over the +brown washrag of a back. “Look at that coat. Some coat. That’s a dog +that’ll never bother you with catching cold.” + +“I think it’s cute,” said Mrs. Wilson enthusiastically. “How much is +it?” + +“That dog?” He looked at it admiringly. “That dog will cost you ten +dollars.” + +The Airedale—undoubtedly there was an Airedale concerned in it +somewhere, though its feet were startlingly white—changed hands and +settled down into Mrs. Wilson’s lap, where she fondled the +weatherproof coat with rapture. + +“Is it a boy or a girl?” she asked delicately. + +“That dog? That dog’s a boy.” + +“It’s a bitch,” said Tom decisively. “Here’s your money. Go and buy +ten more dogs with it.” + +We drove over to Fifth Avenue, warm and soft, almost pastoral, on the +summer Sunday afternoon. I wouldn’t have been surprised to see a great +flock of white sheep turn the corner. + +“Hold on,” I said, “I have to leave you here.” + +“No you don’t,” interposed Tom quickly. “Myrtle’ll be hurt if you +don’t come up to the apartment. Won’t you, Myrtle?” + +“Come on,” she urged. “I’ll telephone my sister Catherine. She’s said +to be very beautiful by people who ought to know.” + +“Well, I’d like to, but—” + +We went on, cutting back again over the Park toward the West Hundreds. +At 158th Street the cab stopped at one slice in a long white cake of +apartment-houses. Throwing a regal homecoming glance around the +neighbourhood, Mrs. Wilson gathered up her dog and her other +purchases, and went haughtily in. + +“I’m going to have the McKees come up,” she announced as we rose in +the elevator. “And, of course, I got to call up my sister, too.” + +The apartment was on the top floor—a small living-room, a small +dining-room, a small bedroom, and a bath. The living-room was crowded +to the doors with a set of tapestried furniture entirely too large for +it, so that to move about was to stumble continually over scenes of +ladies swinging in the gardens of Versailles. The only picture was an +over-enlarged photograph, apparently a hen sitting on a blurred rock. +Looked at from a distance, however, the hen resolved itself into a +bonnet, and the countenance of a stout old lady beamed down into the +room. Several old copies of Town Tattle lay on the table together with +a copy of Simon Called Peter, and some of the small scandal magazines +of Broadway. Mrs. Wilson was first concerned with the dog. A reluctant +elevator boy went for a box full of straw and some milk, to which he +added on his own initiative a tin of large, hard dog biscuits—one of +which decomposed apathetically in the saucer of milk all +afternoon. Meanwhile Tom brought out a bottle of whisky from a locked +bureau door. + +I have been drunk just twice in my life, and the second time was that +afternoon; so everything that happened has a dim, hazy cast over it, +although until after eight o’clock the apartment was full of cheerful +sun. Sitting on Tom’s lap Mrs. Wilson called up several people on the +telephone; then there were no cigarettes, and I went out to buy some +at the drugstore on the corner. When I came back they had both +disappeared, so I sat down discreetly in the living-room and read a +chapter of Simon Called Peter—either it was terrible stuff or the +whisky distorted things, because it didn’t make any sense to me. + +Just as Tom and Myrtle (after the first drink Mrs. Wilson and I called +each other by our first names) reappeared, company commenced to arrive +at the apartment door. + +The sister, Catherine, was a slender, worldly girl of about thirty, +with a solid, sticky bob of red hair, and a complexion powdered milky +white. Her eyebrows had been plucked and then drawn on again at a more +rakish angle, but the efforts of nature toward the restoration of the +old alignment gave a blurred air to her face. When she moved about +there was an incessant clicking as innumerable pottery bracelets +jingled up and down upon her arms. She came in with such a proprietary +haste, and looked around so possessively at the furniture that I +wondered if she lived here. But when I asked her she laughed +immoderately, repeated my question aloud, and told me she lived with a +girl friend at a hotel. + +Mr. McKee was a pale, feminine man from the flat below. He had just +shaved, for there was a white spot of lather on his cheekbone, and he +was most respectful in his greeting to everyone in the room. He +informed me that he was in the “artistic game,” and I gathered later +that he was a photographer and had made the dim enlargement of +Mrs. Wilson’s mother which hovered like an ectoplasm on the wall. His +wife was shrill, languid, handsome, and horrible. She told me with +pride that her husband had photographed her a hundred and twenty-seven +times since they had been married. + +Mrs. Wilson had changed her costume some time before, and was now +attired in an elaborate afternoon dress of cream-coloured chiffon, +which gave out a continual rustle as she swept about the room. With +the influence of the dress her personality had also undergone a +change. The intense vitality that had been so remarkable in the garage +was converted into impressive hauteur. Her laughter, her gestures, her +assertions became more violently affected moment by moment, and as she +expanded the room grew smaller around her, until she seemed to be +revolving on a noisy, creaking pivot through the smoky air. + +“My dear,” she told her sister in a high, mincing shout, “most of +these fellas will cheat you every time. All they think of is money. I +had a woman up here last week to look at my feet, and when she gave me +the bill you’d of thought she had my appendicitis out.” + +“What was the name of the woman?” asked Mrs. McKee. + +“Mrs. Eberhardt. She goes around looking at people’s feet in their own +homes.” + +“I like your dress,” remarked Mrs. McKee, “I think it’s adorable.” + +Mrs. Wilson rejected the compliment by raising her eyebrow in disdain. + +“It’s just a crazy old thing,” she said. “I just slip it on sometimes +when I don’t care what I look like.” + +“But it looks wonderful on you, if you know what I mean,” pursued Mrs. +McKee. “If Chester could only get you in that pose I think he could +make something of it.” + +We all looked in silence at Mrs. Wilson, who removed a strand of hair +from over her eyes and looked back at us with a brilliant smile. Mr. +McKee regarded her intently with his head on one side, and then moved +his hand back and forth slowly in front of his face. + +“I should change the light,” he said after a moment. “I’d like to +bring out the modelling of the features. And I’d try to get hold of +all the back hair.” + +“I wouldn’t think of changing the light,” cried Mrs. McKee. “I think +it’s—” + +Her husband said “Sh!” and we all looked at the subject again, +whereupon Tom Buchanan yawned audibly and got to his feet. + +“You McKees have something to drink,” he said. “Get some more ice and +mineral water, Myrtle, before everybody goes to sleep.” + +“I told that boy about the ice.” Myrtle raised her eyebrows in despair +at the shiftlessness of the lower orders. “These people! You have to +keep after them all the time.” + +She looked at me and laughed pointlessly. Then she flounced over to +the dog, kissed it with ecstasy, and swept into the kitchen, implying +that a dozen chefs awaited her orders there. + +“I’ve done some nice things out on Long Island,” asserted Mr. McKee. + +Tom looked at him blankly. + +“Two of them we have framed downstairs.” + +“Two what?” demanded Tom. + +“Two studies. One of them I call Montauk Point—The Gulls, and the +other I call Montauk Point—The Sea.” + +The sister Catherine sat down beside me on the couch. + +“Do you live down on Long Island, too?” she inquired. + +“I live at West Egg.” + +“Really? I was down there at a party about a month ago. At a man named +Gatsby’s. Do you know him?” + +“I live next door to him.” + +“Well, they say he’s a nephew or a cousin of Kaiser Wilhelm’s. That’s +where all his money comes from.” + +“Really?” + +She nodded. + +“I’m scared of him. I’d hate to have him get anything on me.” + +This absorbing information about my neighbour was interrupted by Mrs. +McKee’s pointing suddenly at Catherine: + +“Chester, I think you could do something with her,” she broke out, but +Mr. McKee only nodded in a bored way, and turned his attention to Tom. + +“I’d like to do more work on Long Island, if I could get the entry. +All I ask is that they should give me a start.” + +“Ask Myrtle,” said Tom, breaking into a short shout of laughter as +Mrs. Wilson entered with a tray. “She’ll give you a letter of +introduction, won’t you, Myrtle?” + +“Do what?” she asked, startled. + +“You’ll give McKee a letter of introduction to your husband, so he can +do some studies of him.” His lips moved silently for a moment as he +invented, “ ‘George B. Wilson at the Gasoline Pump,’ or something like +that.” + +Catherine leaned close to me and whispered in my ear: + +“Neither of them can stand the person they’re married to.” + +“Can’t they?” + +“Can’t stand them.” She looked at Myrtle and then at Tom. “What I say +is, why go on living with them if they can’t stand them? If I was them +I’d get a divorce and get married to each other right away.” + +“Doesn’t she like Wilson either?” + +The answer to this was unexpected. It came from Myrtle, who had +overheard the question, and it was violent and obscene. + +“You see,” cried Catherine triumphantly. She lowered her voice again. +“It’s really his wife that’s keeping them apart. She’s a Catholic, and +they don’t believe in divorce.” + +Daisy was not a Catholic, and I was a little shocked at the +elaborateness of the lie. + +“When they do get married,” continued Catherine, “they’re going West +to live for a while until it blows over.” + +“It’d be more discreet to go to Europe.” + +“Oh, do you like Europe?” she exclaimed surprisingly. “I just got back +from Monte Carlo.” + +“Really.” + +“Just last year. I went over there with another girl.” + +“Stay long?” + +“No, we just went to Monte Carlo and back. We went by way of +Marseilles. We had over twelve hundred dollars when we started, but we +got gyped out of it all in two days in the private rooms. We had an +awful time getting back, I can tell you. God, how I hated that town!” + +The late afternoon sky bloomed in the window for a moment like the +blue honey of the Mediterranean—then the shrill voice of Mrs. McKee +called me back into the room. + +“I almost made a mistake, too,” she declared vigorously. “I almost +married a little kike who’d been after me for years. I knew he was +below me. Everybody kept saying to me: ‘Lucille, that man’s way below +you!’ But if I hadn’t met Chester, he’d of got me sure.” + +“Yes, but listen,” said Myrtle Wilson, nodding her head up and down, +“at least you didn’t marry him.” + +“I know I didn’t.” + +“Well, I married him,” said Myrtle, ambiguously. “And that’s the +difference between your case and mine.” + +“Why did you, Myrtle?” demanded Catherine. “Nobody forced you to.” + +Myrtle considered. + +“I married him because I thought he was a gentleman,” she said +finally. “I thought he knew something about breeding, but he wasn’t +fit to lick my shoe.” + +“You were crazy about him for a while,” said Catherine. + +“Crazy about him!” cried Myrtle incredulously. “Who said I was crazy +about him? I never was any more crazy about him than I was about that +man there.” + +She pointed suddenly at me, and everyone looked at me accusingly. I +tried to show by my expression that I expected no affection. + +“The only crazy I was was when I married him. I knew right away I made +a mistake. He borrowed somebody’s best suit to get married in, and +never even told me about it, and the man came after it one day when he +was out: ‘Oh, is that your suit?’ I said. ‘This is the first I ever +heard about it.’ But I gave it to him and then I lay down and cried to +beat the band all afternoon.” + +“She really ought to get away from him,” resumed Catherine to me. +“They’ve been living over that garage for eleven years. And Tom’s the +first sweetie she ever had.” + +The bottle of whisky—a second one—was now in constant demand by all +present, excepting Catherine, who “felt just as good on nothing at +all.” Tom rang for the janitor and sent him for some celebrated +sandwiches, which were a complete supper in themselves. I wanted to +get out and walk eastward toward the park through the soft twilight, +but each time I tried to go I became entangled in some wild, strident +argument which pulled me back, as if with ropes, into my chair. Yet +high over the city our line of yellow windows must have contributed +their share of human secrecy to the casual watcher in the darkening +streets, and I saw him too, looking up and wondering. I was within and +without, simultaneously enchanted and repelled by the inexhaustible +variety of life. + +Myrtle pulled her chair close to mine, and suddenly her warm breath +poured over me the story of her first meeting with Tom. + +“It was on the two little seats facing each other that are always the +last ones left on the train. I was going up to New York to see my +sister and spend the night. He had on a dress suit and patent leather +shoes, and I couldn’t keep my eyes off him, but every time he looked +at me I had to pretend to be looking at the advertisement over his +head. When we came into the station he was next to me, and his white +shirtfront pressed against my arm, and so I told him I’d have to call +a policeman, but he knew I lied. I was so excited that when I got into +a taxi with him I didn’t hardly know I wasn’t getting into a subway +train. All I kept thinking about, over and over, was ‘You can’t live +forever; you can’t live forever.’ ” + +She turned to Mrs. McKee and the room rang full of her artificial +laughter. + +“My dear,” she cried, “I’m going to give you this dress as soon as I’m +through with it. I’ve got to get another one tomorrow. I’m going to +make a list of all the things I’ve got to get. A massage and a wave, +and a collar for the dog, and one of those cute little ashtrays where +you touch a spring, and a wreath with a black silk bow for mother’s +grave that’ll last all summer. I got to write down a list so I won’t +forget all the things I got to do.” + +It was nine o’clock—almost immediately afterward I looked at my watch +and found it was ten. Mr. McKee was asleep on a chair with his fists +clenched in his lap, like a photograph of a man of action. Taking out +my handkerchief I wiped from his cheek the spot of dried lather that +had worried me all the afternoon. + +The little dog was sitting on the table looking with blind eyes +through the smoke, and from time to time groaning faintly. People +disappeared, reappeared, made plans to go somewhere, and then lost +each other, searched for each other, found each other a few feet +away. Some time toward midnight Tom Buchanan and Mrs. Wilson stood +face to face discussing, in impassioned voices, whether Mrs. Wilson +had any right to mention Daisy’s name. + +“Daisy! Daisy! Daisy!” shouted Mrs. Wilson. “I’ll say it whenever I +want to! Daisy! Dai—” + +Making a short deft movement, Tom Buchanan broke her nose with his +open hand. + +Then there were bloody towels upon the bathroom floor, and women’s +voices scolding, and high over the confusion a long broken wail of +pain. Mr. McKee awoke from his doze and started in a daze toward the +door. When he had gone halfway he turned around and stared at the +scene—his wife and Catherine scolding and consoling as they stumbled +here and there among the crowded furniture with articles of aid, and +the despairing figure on the couch, bleeding fluently, and trying to +spread a copy of Town Tattle over the tapestry scenes of +Versailles. Then Mr. McKee turned and continued on out the door. +Taking my hat from the chandelier, I followed. + +“Come to lunch some day,” he suggested, as we groaned down in the +elevator. + +“Where?” + +“Anywhere.” + +“Keep your hands off the lever,” snapped the elevator boy. + +“I beg your pardon,” said Mr. McKee with dignity, “I didn’t know I was +touching it.” + +“All right,” I agreed, “I’ll be glad to.” + +… I was standing beside his bed and he was sitting up between the +sheets, clad in his underwear, with a great portfolio in his hands. + +“Beauty and the Beast … Loneliness … Old Grocery Horse … Brook’n +Bridge …” + +Then I was lying half asleep in the cold lower level of the +Pennsylvania Station, staring at the morning Tribune, and waiting for +the four o’clock train. + + + III + +There was music from my neighbour’s house through the summer nights. +In his blue gardens men and girls came and went like moths among the +whisperings and the champagne and the stars. At high tide in the +afternoon I watched his guests diving from the tower of his raft, or +taking the sun on the hot sand of his beach while his two motorboats +slit the waters of the Sound, drawing aquaplanes over cataracts of +foam. On weekends his Rolls-Royce became an omnibus, bearing parties +to and from the city between nine in the morning and long past +midnight, while his station wagon scampered like a brisk yellow bug to +meet all trains. And on Mondays eight servants, including an extra +gardener, toiled all day with mops and scrubbing-brushes and hammers +and garden-shears, repairing the ravages of the night before. + +Every Friday five crates of oranges and lemons arrived from a +fruiterer in New York—every Monday these same oranges and lemons left +his back door in a pyramid of pulpless halves. There was a machine in +the kitchen which could extract the juice of two hundred oranges in +half an hour if a little button was pressed two hundred times by a +butler’s thumb. + +At least once a fortnight a corps of caterers came down with several +hundred feet of canvas and enough coloured lights to make a Christmas +tree of Gatsby’s enormous garden. On buffet tables, garnished with +glistening hors-d’oeuvre, spiced baked hams crowded against salads of +harlequin designs and pastry pigs and turkeys bewitched to a dark +gold. In the main hall a bar with a real brass rail was set up, and +stocked with gins and liquors and with cordials so long forgotten that +most of his female guests were too young to know one from another. + +By seven o’clock the orchestra has arrived, no thin five-piece affair, +but a whole pitful of oboes and trombones and saxophones and viols and +cornets and piccolos, and low and high drums. The last swimmers have +come in from the beach now and are dressing upstairs; the cars from +New York are parked five deep in the drive, and already the halls and +salons and verandas are gaudy with primary colours, and hair bobbed in +strange new ways, and shawls beyond the dreams of Castile. The bar is +in full swing, and floating rounds of cocktails permeate the garden +outside, until the air is alive with chatter and laughter, and casual +innuendo and introductions forgotten on the spot, and enthusiastic +meetings between women who never knew each other’s names. + +The lights grow brighter as the earth lurches away from the sun, and +now the orchestra is playing yellow cocktail music, and the opera of +voices pitches a key higher. Laughter is easier minute by minute, +spilled with prodigality, tipped out at a cheerful word. The groups +change more swiftly, swell with new arrivals, dissolve and form in the +same breath; already there are wanderers, confident girls who weave +here and there among the stouter and more stable, become for a sharp, +joyous moment the centre of a group, and then, excited with triumph, +glide on through the sea-change of faces and voices and colour under +the constantly changing light. + +Suddenly one of these gypsies, in trembling opal, seizes a cocktail +out of the air, dumps it down for courage and, moving her hands like +Frisco, dances out alone on the canvas platform. A momentary hush; the +orchestra leader varies his rhythm obligingly for her, and there is a +burst of chatter as the erroneous news goes around that she is Gilda +Gray’s understudy from the Follies. The party has begun. + +I believe that on the first night I went to Gatsby’s house I was one +of the few guests who had actually been invited. People were not +invited—they went there. They got into automobiles which bore them out +to Long Island, and somehow they ended up at Gatsby’s door. Once there +they were introduced by somebody who knew Gatsby, and after that they +conducted themselves according to the rules of behaviour associated +with an amusement park. Sometimes they came and went without having +met Gatsby at all, came for the party with a simplicity of heart that +was its own ticket of admission. + +I had been actually invited. A chauffeur in a uniform of robin’s-egg +blue crossed my lawn early that Saturday morning with a surprisingly +formal note from his employer: the honour would be entirely Gatsby’s, +it said, if I would attend his “little party” that night. He had seen +me several times, and had intended to call on me long before, but a +peculiar combination of circumstances had prevented it—signed Jay +Gatsby, in a majestic hand. + +Dressed up in white flannels I went over to his lawn a little after +seven, and wandered around rather ill at ease among swirls and eddies +of people I didn’t know—though here and there was a face I had noticed +on the commuting train. I was immediately struck by the number of +young Englishmen dotted about; all well dressed, all looking a little +hungry, and all talking in low, earnest voices to solid and prosperous +Americans. I was sure that they were selling something: bonds or +insurance or automobiles. They were at least agonizingly aware of the +easy money in the vicinity and convinced that it was theirs for a few +words in the right key. + +As soon as I arrived I made an attempt to find my host, but the two or +three people of whom I asked his whereabouts stared at me in such an +amazed way, and denied so vehemently any knowledge of his movements, +that I slunk off in the direction of the cocktail table—the only place +in the garden where a single man could linger without looking +purposeless and alone. + +I was on my way to get roaring drunk from sheer embarrassment when +Jordan Baker came out of the house and stood at the head of the marble +steps, leaning a little backward and looking with contemptuous +interest down into the garden. + +Welcome or not, I found it necessary to attach myself to someone +before I should begin to address cordial remarks to the passersby. + +“Hello!” I roared, advancing toward her. My voice seemed unnaturally +loud across the garden. + +“I thought you might be here,” she responded absently as I came up. +“I remembered you lived next door to—” + +She held my hand impersonally, as a promise that she’d take care of me +in a minute, and gave ear to two girls in twin yellow dresses, who +stopped at the foot of the steps. + +“Hello!” they cried together. “Sorry you didn’t win.” + +That was for the golf tournament. She had lost in the finals the week +before. + +“You don’t know who we are,” said one of the girls in yellow, “but we +met you here about a month ago.” + +“You’ve dyed your hair since then,” remarked Jordan, and I started, +but the girls had moved casually on and her remark was addressed to +the premature moon, produced like the supper, no doubt, out of a +caterer’s basket. With Jordan’s slender golden arm resting in mine, we +descended the steps and sauntered about the garden. A tray of +cocktails floated at us through the twilight, and we sat down at a +table with the two girls in yellow and three men, each one introduced +to us as Mr. Mumble. + +“Do you come to these parties often?” inquired Jordan of the girl +beside her. + +“The last one was the one I met you at,” answered the girl, in an +alert confident voice. She turned to her companion: “Wasn’t it for +you, Lucille?” + +It was for Lucille, too. + +“I like to come,” Lucille said. “I never care what I do, so I always +have a good time. When I was here last I tore my gown on a chair, and +he asked me my name and address—inside of a week I got a package from +Croirier’s with a new evening gown in it.” + +“Did you keep it?” asked Jordan. + +“Sure I did. I was going to wear it tonight, but it was too big in the +bust and had to be altered. It was gas blue with lavender beads. Two +hundred and sixty-five dollars.” + +“There’s something funny about a fellow that’ll do a thing like that,” +said the other girl eagerly. “He doesn’t want any trouble with +anybody.” + +“Who doesn’t?” I inquired. + +“Gatsby. Somebody told me—” + +The two girls and Jordan leaned together confidentially. + +“Somebody told me they thought he killed a man once.” + +A thrill passed over all of us. The three Mr. Mumbles bent forward and +listened eagerly. + +“I don’t think it’s so much that,” argued Lucille sceptically; “It’s +more that he was a German spy during the war.” + +One of the men nodded in confirmation. + +“I heard that from a man who knew all about him, grew up with him in +Germany,” he assured us positively. + +“Oh, no,” said the first girl, “it couldn’t be that, because he was in +the American army during the war.” As our credulity switched back to +her she leaned forward with enthusiasm. “You look at him sometimes +when he thinks nobody’s looking at him. I’ll bet he killed a man.” + +She narrowed her eyes and shivered. Lucille shivered. We all turned +and looked around for Gatsby. It was testimony to the romantic +speculation he inspired that there were whispers about him from those +who had found little that it was necessary to whisper about in this +world. + +The first supper—there would be another one after midnight—was now +being served, and Jordan invited me to join her own party, who were +spread around a table on the other side of the garden. There were +three married couples and Jordan’s escort, a persistent undergraduate +given to violent innuendo, and obviously under the impression that +sooner or later Jordan was going to yield him up her person to a +greater or lesser degree. Instead of rambling, this party had +preserved a dignified homogeneity, and assumed to itself the function +of representing the staid nobility of the countryside—East Egg +condescending to West Egg and carefully on guard against its +spectroscopic gaiety. + +“Let’s get out,” whispered Jordan, after a somehow wasteful and +inappropriate half-hour; “this is much too polite for me.” + +We got up, and she explained that we were going to find the host: I +had never met him, she said, and it was making me uneasy. The +undergraduate nodded in a cynical, melancholy way. + +The bar, where we glanced first, was crowded, but Gatsby was not +there. She couldn’t find him from the top of the steps, and he wasn’t +on the veranda. On a chance we tried an important-looking door, and +walked into a high Gothic library, panelled with carved English oak, +and probably transported complete from some ruin overseas. + +A stout, middle-aged man, with enormous owl-eyed spectacles, was +sitting somewhat drunk on the edge of a great table, staring with +unsteady concentration at the shelves of books. As we entered he +wheeled excitedly around and examined Jordan from head to foot. + +“What do you think?” he demanded impetuously. + +“About what?” + +He waved his hand toward the bookshelves. + +“About that. As a matter of fact you needn’t bother to ascertain. I +ascertained. They’re real.” + +“The books?” + +He nodded. + +“Absolutely real—have pages and everything. I thought they’d be a nice +durable cardboard. Matter of fact, they’re absolutely real. Pages +and—Here! Lemme show you.” + +Taking our scepticism for granted, he rushed to the bookcases and +returned with Volume One of the Stoddard Lectures. + +“See!” he cried triumphantly. “It’s a bona-fide piece of printed +matter. It fooled me. This fella’s a regular Belasco. It’s a +triumph. What thoroughness! What realism! Knew when to stop, +too—didn’t cut the pages. But what do you want? What do you expect?” + +He snatched the book from me and replaced it hastily on its shelf, +muttering that if one brick was removed the whole library was liable +to collapse. + +“Who brought you?” he demanded. “Or did you just come? I was brought. +Most people were brought.” + +Jordan looked at him alertly, cheerfully, without answering. + +“I was brought by a woman named Roosevelt,” he continued. “Mrs. Claud +Roosevelt. Do you know her? I met her somewhere last night. I’ve been +drunk for about a week now, and I thought it might sober me up to sit +in a library.” + +“Has it?” + +“A little bit, I think. I can’t tell yet. I’ve only been here an hour. +Did I tell you about the books? They’re real. They’re—” + +“You told us.” + +We shook hands with him gravely and went back outdoors. + +There was dancing now on the canvas in the garden; old men pushing +young girls backward in eternal graceless circles, superior couples +holding each other tortuously, fashionably, and keeping in the +corners—and a great number of single girls dancing individually or +relieving the orchestra for a moment of the burden of the banjo or the +traps. By midnight the hilarity had increased. A celebrated tenor had +sung in Italian, and a notorious contralto had sung in jazz, and +between the numbers people were doing “stunts” all over the garden, +while happy, vacuous bursts of laughter rose toward the summer sky. A +pair of stage twins, who turned out to be the girls in yellow, did a +baby act in costume, and champagne was served in glasses bigger than +finger-bowls. The moon had risen higher, and floating in the Sound was +a triangle of silver scales, trembling a little to the stiff, tinny +drip of the banjoes on the lawn. + +I was still with Jordan Baker. We were sitting at a table with a man +of about my age and a rowdy little girl, who gave way upon the +slightest provocation to uncontrollable laughter. I was enjoying +myself now. I had taken two finger-bowls of champagne, and the scene +had changed before my eyes into something significant, elemental, and +profound. + +At a lull in the entertainment the man looked at me and smiled. + +“Your face is familiar,” he said politely. “Weren’t you in the First +Division during the war?” + +“Why yes. I was in the Twenty-eighth Infantry.” + +“I was in the Sixteenth until June nineteen-eighteen. I knew I’d seen +you somewhere before.” + +We talked for a moment about some wet, grey little villages in France. +Evidently he lived in this vicinity, for he told me that he had just +bought a hydroplane, and was going to try it out in the morning. + +“Want to go with me, old sport? Just near the shore along the Sound.” + +“What time?” + +“Any time that suits you best.” + +It was on the tip of my tongue to ask his name when Jordan looked +around and smiled. + +“Having a gay time now?” she inquired. + +“Much better.” I turned again to my new acquaintance. “This is an +unusual party for me. I haven’t even seen the host. I live over +there—” I waved my hand at the invisible hedge in the distance, “and +this man Gatsby sent over his chauffeur with an invitation.” + +For a moment he looked at me as if he failed to understand. + +“I’m Gatsby,” he said suddenly. + +“What!” I exclaimed. “Oh, I beg your pardon.” + +“I thought you knew, old sport. I’m afraid I’m not a very good host.” + +He smiled understandingly—much more than understandingly. It was one +of those rare smiles with a quality of eternal reassurance in it, that +you may come across four or five times in life. It faced—or seemed to +face—the whole eternal world for an instant, and then concentrated on +you with an irresistible prejudice in your favour. It understood you +just so far as you wanted to be understood, believed in you as you +would like to believe in yourself, and assured you that it had +precisely the impression of you that, at your best, you hoped to +convey. Precisely at that point it vanished—and I was looking at an +elegant young roughneck, a year or two over thirty, whose elaborate +formality of speech just missed being absurd. Some time before he +introduced himself I’d got a strong impression that he was picking his +words with care. + +Almost at the moment when Mr. Gatsby identified himself a butler +hurried toward him with the information that Chicago was calling him +on the wire. He excused himself with a small bow that included each of +us in turn. + +“If you want anything just ask for it, old sport,” he urged me. +“Excuse me. I will rejoin you later.” + +When he was gone I turned immediately to Jordan—constrained to assure +her of my surprise. I had expected that Mr. Gatsby would be a florid +and corpulent person in his middle years. + +“Who is he?” I demanded. “Do you know?” + +“He’s just a man named Gatsby.” + +“Where is he from, I mean? And what does he do?” + +“Now you’re started on the subject,” she answered with a wan smile. +“Well, he told me once he was an Oxford man.” + +A dim background started to take shape behind him, but at her next +remark it faded away. + +“However, I don’t believe it.” + +“Why not?” + +“I don’t know,” she insisted, “I just don’t think he went there.” + +Something in her tone reminded me of the other girl’s “I think he +killed a man,” and had the effect of stimulating my curiosity. I would +have accepted without question the information that Gatsby sprang from +the swamps of Louisiana or from the lower East Side of New York. That +was comprehensible. But young men didn’t—at least in my provincial +inexperience I believed they didn’t—drift coolly out of nowhere and +buy a palace on Long Island Sound. + +“Anyhow, he gives large parties,” said Jordan, changing the subject +with an urban distaste for the concrete. “And I like large parties. +They’re so intimate. At small parties there isn’t any privacy.” + +There was the boom of a bass drum, and the voice of the orchestra +leader rang out suddenly above the echolalia of the garden. + +“Ladies and gentlemen,” he cried. “At the request of Mr. Gatsby we are +going to play for you Mr. Vladmir Tostoff’s latest work, which +attracted so much attention at Carnegie Hall last May. If you read the +papers you know there was a big sensation.” He smiled with jovial +condescension, and added: “Some sensation!” Whereupon everybody +laughed. + +“The piece is known,” he concluded lustily, “as ‘Vladmir Tostoff’s +Jazz History of the World!’ ” + +The nature of Mr. Tostoff’s composition eluded me, because just as it +began my eyes fell on Gatsby, standing alone on the marble steps and +looking from one group to another with approving eyes. His tanned skin +was drawn attractively tight on his face and his short hair looked as +though it were trimmed every day. I could see nothing sinister about +him. I wondered if the fact that he was not drinking helped to set him +off from his guests, for it seemed to me that he grew more correct as +the fraternal hilarity increased. When the “Jazz History of the World” +was over, girls were putting their heads on men’s shoulders in a +puppyish, convivial way, girls were swooning backward playfully into +men’s arms, even into groups, knowing that someone would arrest their +falls—but no one swooned backward on Gatsby, and no French bob touched +Gatsby’s shoulder, and no singing quartets were formed with Gatsby’s +head for one link. + +“I beg your pardon.” + +Gatsby’s butler was suddenly standing beside us. + +“Miss Baker?” he inquired. “I beg your pardon, but Mr. Gatsby would +like to speak to you alone.” + +“With me?” she exclaimed in surprise. + +“Yes, madame.” + +She got up slowly, raising her eyebrows at me in astonishment, and +followed the butler toward the house. I noticed that she wore her +evening-dress, all her dresses, like sports clothes—there was a +jauntiness about her movements as if she had first learned to walk +upon golf courses on clean, crisp mornings. + +I was alone and it was almost two. For some time confused and +intriguing sounds had issued from a long, many-windowed room which +overhung the terrace. Eluding Jordan’s undergraduate, who was now +engaged in an obstetrical conversation with two chorus girls, and who +implored me to join him, I went inside. + +The large room was full of people. One of the girls in yellow was +playing the piano, and beside her stood a tall, red-haired young lady +from a famous chorus, engaged in song. She had drunk a quantity of +champagne, and during the course of her song she had decided, ineptly, +that everything was very, very sad—she was not only singing, she was +weeping too. Whenever there was a pause in the song she filled it with +gasping, broken sobs, and then took up the lyric again in a quavering +soprano. The tears coursed down her cheeks—not freely, however, for +when they came into contact with her heavily beaded eyelashes they +assumed an inky colour, and pursued the rest of their way in slow +black rivulets. A humorous suggestion was made that she sing the notes +on her face, whereupon she threw up her hands, sank into a chair, and +went off into a deep vinous sleep. + +“She had a fight with a man who says he’s her husband,” explained a +girl at my elbow. + +I looked around. Most of the remaining women were now having fights +with men said to be their husbands. Even Jordan’s party, the quartet +from East Egg, were rent asunder by dissension. One of the men was +talking with curious intensity to a young actress, and his wife, after +attempting to laugh at the situation in a dignified and indifferent +way, broke down entirely and resorted to flank attacks—at intervals +she appeared suddenly at his side like an angry diamond, and hissed: +“You promised!” into his ear. + +The reluctance to go home was not confined to wayward men. The hall +was at present occupied by two deplorably sober men and their highly +indignant wives. The wives were sympathizing with each other in +slightly raised voices. + +“Whenever he sees I’m having a good time he wants to go home.” + +“Never heard anything so selfish in my life.” + +“We’re always the first ones to leave.” + +“So are we.” + +“Well, we’re almost the last tonight,” said one of the men sheepishly. +“The orchestra left half an hour ago.” + +In spite of the wives’ agreement that such malevolence was beyond +credibility, the dispute ended in a short struggle, and both wives +were lifted, kicking, into the night. + +As I waited for my hat in the hall the door of the library opened and +Jordan Baker and Gatsby came out together. He was saying some last +word to her, but the eagerness in his manner tightened abruptly into +formality as several people approached him to say goodbye. + +Jordan’s party were calling impatiently to her from the porch, but she +lingered for a moment to shake hands. + +“I’ve just heard the most amazing thing,” she whispered. “How long +were we in there?” + +“Why, about an hour.” + +“It was … simply amazing,” she repeated abstractedly. “But I swore I +wouldn’t tell it and here I am tantalizing you.” She yawned gracefully +in my face. “Please come and see me … Phone book … Under the name of +Mrs. Sigourney Howard … My aunt …” She was hurrying off as she +talked—her brown hand waved a jaunty salute as she melted into her +party at the door. + +Rather ashamed that on my first appearance I had stayed so late, I +joined the last of Gatsby’s guests, who were clustered around him. I +wanted to explain that I’d hunted for him early in the evening and to +apologize for not having known him in the garden. + +“Don’t mention it,” he enjoined me eagerly. “Don’t give it another +thought, old sport.” The familiar expression held no more familiarity +than the hand which reassuringly brushed my shoulder. “And don’t +forget we’re going up in the hydroplane tomorrow morning, at nine +o’clock.” + +Then the butler, behind his shoulder: + +“Philadelphia wants you on the phone, sir.” + +“All right, in a minute. Tell them I’ll be right there … Good night.” + +“Good night.” + +“Good night.” He smiled—and suddenly there seemed to be a pleasant +significance in having been among the last to go, as if he had desired +it all the time. “Good night, old sport … Good night.” + +But as I walked down the steps I saw that the evening was not quite +over. Fifty feet from the door a dozen headlights illuminated a +bizarre and tumultuous scene. In the ditch beside the road, right side +up, but violently shorn of one wheel, rested a new coupé which had +left Gatsby’s drive not two minutes before. The sharp jut of a wall +accounted for the detachment of the wheel, which was now getting +considerable attention from half a dozen curious chauffeurs. However, +as they had left their cars blocking the road, a harsh, discordant din +from those in the rear had been audible for some time, and added to +the already violent confusion of the scene. + +A man in a long duster had dismounted from the wreck and now stood in +the middle of the road, looking from the car to the tyre and from the +tyre to the observers in a pleasant, puzzled way. + +“See!” he explained. “It went in the ditch.” + +The fact was infinitely astonishing to him, and I recognized first the +unusual quality of wonder, and then the man—it was the late patron of +Gatsby’s library. + +“How’d it happen?” + +He shrugged his shoulders. + +“I know nothing whatever about mechanics,” he said decisively. + +“But how did it happen? Did you run into the wall?” + +“Don’t ask me,” said Owl Eyes, washing his hands of the whole +matter. “I know very little about driving—next to nothing. It +happened, and that’s all I know.” + +“Well, if you’re a poor driver you oughtn’t to try driving at night.” + +“But I wasn’t even trying,” he explained indignantly, “I wasn’t even +trying.” + +An awed hush fell upon the bystanders. + +“Do you want to commit suicide?” + +“You’re lucky it was just a wheel! A bad driver and not even trying!” + +“You don’t understand,” explained the criminal. “I wasn’t driving. +There’s another man in the car.” + +The shock that followed this declaration found voice in a sustained +“Ah-h-h!” as the door of the coupé swung slowly open. The crowd—it was +now a crowd—stepped back involuntarily, and when the door had opened +wide there was a ghostly pause. Then, very gradually, part by part, a +pale, dangling individual stepped out of the wreck, pawing tentatively +at the ground with a large uncertain dancing shoe. + +Blinded by the glare of the headlights and confused by the incessant +groaning of the horns, the apparition stood swaying for a moment +before he perceived the man in the duster. + +“Wha’s matter?” he inquired calmly. “Did we run outa gas?” + +“Look!” + +Half a dozen fingers pointed at the amputated wheel—he stared at it +for a moment, and then looked upward as though he suspected that it +had dropped from the sky. + +“It came off,” someone explained. + +He nodded. + +“At first I din’ notice we’d stopped.” + +A pause. Then, taking a long breath and straightening his shoulders, +he remarked in a determined voice: + +“Wonder’ff tell me where there’s a gas’line station?” + +At least a dozen men, some of them a little better off than he was, +explained to him that wheel and car were no longer joined by any +physical bond. + +“Back out,” he suggested after a moment. “Put her in reverse.” + +“But the wheel’s off!” + +He hesitated. + +“No harm in trying,” he said. + +The caterwauling horns had reached a crescendo and I turned away and +cut across the lawn toward home. I glanced back once. A wafer of a +moon was shining over Gatsby’s house, making the night fine as before, +and surviving the laughter and the sound of his still glowing garden. +A sudden emptiness seemed to flow now from the windows and the great +doors, endowing with complete isolation the figure of the host, who +stood on the porch, his hand up in a formal gesture of farewell. + +------------------------------------------------------------------------ + +Reading over what I have written so far, I see I have given the +impression that the events of three nights several weeks apart were +all that absorbed me. On the contrary, they were merely casual events +in a crowded summer, and, until much later, they absorbed me +infinitely less than my personal affairs. + +Most of the time I worked. In the early morning the sun threw my +shadow westward as I hurried down the white chasms of lower New York +to the Probity Trust. I knew the other clerks and young bond-salesmen +by their first names, and lunched with them in dark, crowded +restaurants on little pig sausages and mashed potatoes and coffee. I +even had a short affair with a girl who lived in Jersey City and +worked in the accounting department, but her brother began throwing +mean looks in my direction, so when she went on her vacation in July I +let it blow quietly away. + +I took dinner usually at the Yale Club—for some reason it was the +gloomiest event of my day—and then I went upstairs to the library and +studied investments and securities for a conscientious hour. There +were generally a few rioters around, but they never came into the +library, so it was a good place to work. After that, if the night was +mellow, I strolled down Madison Avenue past the old Murray Hill Hotel, +and over 33rd Street to the Pennsylvania Station. + +I began to like New York, the racy, adventurous feel of it at night, +and the satisfaction that the constant flicker of men and women and +machines gives to the restless eye. I liked to walk up Fifth Avenue +and pick out romantic women from the crowd and imagine that in a few +minutes I was going to enter into their lives, and no one would ever +know or disapprove. Sometimes, in my mind, I followed them to their +apartments on the corners of hidden streets, and they turned and +smiled back at me before they faded through a door into warm +darkness. At the enchanted metropolitan twilight I felt a haunting +loneliness sometimes, and felt it in others—poor young clerks who +loitered in front of windows waiting until it was time for a solitary +restaurant dinner—young clerks in the dusk, wasting the most poignant +moments of night and life. + +Again at eight o’clock, when the dark lanes of the Forties were lined +five deep with throbbing taxicabs, bound for the theatre district, I +felt a sinking in my heart. Forms leaned together in the taxis as they +waited, and voices sang, and there was laughter from unheard jokes, +and lighted cigarettes made unintelligible circles inside. Imagining +that I, too, was hurrying towards gaiety and sharing their intimate +excitement, I wished them well. + +For a while I lost sight of Jordan Baker, and then in midsummer I +found her again. At first I was flattered to go places with her, +because she was a golf champion, and everyone knew her name. Then it +was something more. I wasn’t actually in love, but I felt a sort of +tender curiosity. The bored haughty face that she turned to the world +concealed something—most affectations conceal something eventually, +even though they don’t in the beginning—and one day I found what it +was. When we were on a house-party together up in Warwick, she left a +borrowed car out in the rain with the top down, and then lied about +it—and suddenly I remembered the story about her that had eluded me +that night at Daisy’s. At her first big golf tournament there was a +row that nearly reached the newspapers—a suggestion that she had moved +her ball from a bad lie in the semifinal round. The thing approached +the proportions of a scandal—then died away. A caddy retracted his +statement, and the only other witness admitted that he might have been +mistaken. The incident and the name had remained together in my mind. + +Jordan Baker instinctively avoided clever, shrewd men, and now I saw +that this was because she felt safer on a plane where any divergence +from a code would be thought impossible. She was incurably dishonest. +She wasn’t able to endure being at a disadvantage and, given this +unwillingness, I suppose she had begun dealing in subterfuges when she +was very young in order to keep that cool, insolent smile turned to +the world and yet satisfy the demands of her hard, jaunty body. + +It made no difference to me. Dishonesty in a woman is a thing you +never blame deeply—I was casually sorry, and then I forgot. It was on +that same house-party that we had a curious conversation about driving +a car. It started because she passed so close to some workmen that our +fender flicked a button on one man’s coat. + +“You’re a rotten driver,” I protested. “Either you ought to be more +careful, or you oughtn’t to drive at all.” + +“I am careful.” + +“No, you’re not.” + +“Well, other people are,” she said lightly. + +“What’s that got to do with it?” + +“They’ll keep out of my way,” she insisted. “It takes two to make an +accident.” + +“Suppose you met somebody just as careless as yourself.” + +“I hope I never will,” she answered. “I hate careless people. That’s +why I like you.” + +Her grey, sun-strained eyes stared straight ahead, but she had +deliberately shifted our relations, and for a moment I thought I loved +her. But I am slow-thinking and full of interior rules that act as +brakes on my desires, and I knew that first I had to get myself +definitely out of that tangle back home. I’d been writing letters once +a week and signing them: “Love, Nick,” and all I could think of was +how, when that certain girl played tennis, a faint moustache of +perspiration appeared on her upper lip. Nevertheless there was a vague +understanding that had to be tactfully broken off before I was free. + +Everyone suspects himself of at least one of the cardinal virtues, and +this is mine: I am one of the few honest people that I have ever +known. + + + IV + +On Sunday morning while church bells rang in the villages alongshore, +the world and its mistress returned to Gatsby’s house and twinkled +hilariously on his lawn. + +“He’s a bootlegger,” said the young ladies, moving somewhere between +his cocktails and his flowers. “One time he killed a man who had found +out that he was nephew to Von Hindenburg and second cousin to the +devil. Reach me a rose, honey, and pour me a last drop into that there +crystal glass.” + +Once I wrote down on the empty spaces of a timetable the names of +those who came to Gatsby’s house that summer. It is an old timetable +now, disintegrating at its folds, and headed “This schedule in effect +July 5th, 1922.” But I can still read the grey names, and they will +give you a better impression than my generalities of those who +accepted Gatsby’s hospitality and paid him the subtle tribute of +knowing nothing whatever about him. + +From East Egg, then, came the Chester Beckers and the Leeches, and a +man named Bunsen, whom I knew at Yale, and Doctor Webster Civet, who +was drowned last summer up in Maine. And the Hornbeams and the Willie +Voltaires, and a whole clan named Blackbuck, who always gathered in a +corner and flipped up their noses like goats at whosoever came +near. And the Ismays and the Chrysties (or rather Hubert Auerbach and +Mr. Chrystie’s wife), and Edgar Beaver, whose hair, they say, turned +cotton-white one winter afternoon for no good reason at all. + +Clarence Endive was from East Egg, as I remember. He came only once, +in white knickerbockers, and had a fight with a bum named Etty in the +garden. From farther out on the Island came the Cheadles and the O. +R. P. Schraeders, and the Stonewall Jackson Abrams of Georgia, and the +Fishguards and the Ripley Snells. Snell was there three days before he +went to the penitentiary, so drunk out on the gravel drive that +Mrs. Ulysses Swett’s automobile ran over his right hand. The Dancies +came, too, and S. B. Whitebait, who was well over sixty, and Maurice +A. Flink, and the Hammerheads, and Beluga the tobacco importer, and +Beluga’s girls. + +From West Egg came the Poles and the Mulreadys and Cecil Roebuck and +Cecil Schoen and Gulick the State senator and Newton Orchid, who +controlled Films Par Excellence, and Eckhaust and Clyde Cohen and Don +S. Schwartz (the son) and Arthur McCarty, all connected with the +movies in one way or another. And the Catlips and the Bembergs and G. +Earl Muldoon, brother to that Muldoon who afterward strangled his +wife. Da Fontano the promoter came there, and Ed Legros and James B. +(“Rot-Gut”) Ferret and the De Jongs and Ernest Lilly—they came to +gamble, and when Ferret wandered into the garden it meant he was +cleaned out and Associated Traction would have to fluctuate profitably +next day. + +A man named Klipspringer was there so often that he became known as +“the boarder”—I doubt if he had any other home. Of theatrical people +there were Gus Waize and Horace O’Donavan and Lester Myer and George +Duckweed and Francis Bull. Also from New York were the Chromes and the +Backhyssons and the Dennickers and Russel Betty and the Corrigans and +the Kellehers and the Dewars and the Scullys and S. W. Belcher and the +Smirkes and the young Quinns, divorced now, and Henry L. Palmetto, who +killed himself by jumping in front of a subway train in Times Square. + +Benny McClenahan arrived always with four girls. They were never quite +the same ones in physical person, but they were so identical one with +another that it inevitably seemed they had been there before. I have +forgotten their names—Jaqueline, I think, or else Consuela, or Gloria +or Judy or June, and their last names were either the melodious names +of flowers and months or the sterner ones of the great American +capitalists whose cousins, if pressed, they would confess themselves +to be. + +In addition to all these I can remember that Faustina O’Brien came +there at least once and the Baedeker girls and young Brewer, who had +his nose shot off in the war, and Mr. Albrucksburger and Miss Haag, +his fiancée, and Ardita Fitz-Peters and Mr. P. Jewett, once head of +the American Legion, and Miss Claudia Hip, with a man reputed to be +her chauffeur, and a prince of something, whom we called Duke, and +whose name, if I ever knew it, I have forgotten. + +All these people came to Gatsby’s house in the summer. + +------------------------------------------------------------------------ + +At nine o’clock, one morning late in July, Gatsby’s gorgeous car +lurched up the rocky drive to my door and gave out a burst of melody +from its three-noted horn. + +It was the first time he had called on me, though I had gone to two of +his parties, mounted in his hydroplane, and, at his urgent invitation, +made frequent use of his beach. + +“Good morning, old sport. You’re having lunch with me today and I +thought we’d ride up together.” + +He was balancing himself on the dashboard of his car with that +resourcefulness of movement that is so peculiarly American—that comes, +I suppose, with the absence of lifting work in youth and, even more, +with the formless grace of our nervous, sporadic games. This quality +was continually breaking through his punctilious manner in the shape +of restlessness. He was never quite still; there was always a tapping +foot somewhere or the impatient opening and closing of a hand. + +He saw me looking with admiration at his car. + +“It’s pretty, isn’t it, old sport?” He jumped off to give me a better +view. “Haven’t you ever seen it before?” + +I’d seen it. Everybody had seen it. It was a rich cream colour, bright +with nickel, swollen here and there in its monstrous length with +triumphant hatboxes and supper-boxes and toolboxes, and terraced with +a labyrinth of windshields that mirrored a dozen suns. Sitting down +behind many layers of glass in a sort of green leather conservatory, +we started to town. + +I had talked with him perhaps half a dozen times in the past month and +found, to my disappointment, that he had little to say. So my first +impression, that he was a person of some undefined consequence, had +gradually faded and he had become simply the proprietor of an +elaborate roadhouse next door. + +And then came that disconcerting ride. We hadn’t reached West Egg +village before Gatsby began leaving his elegant sentences unfinished +and slapping himself indecisively on the knee of his caramel-coloured +suit. + +“Look here, old sport,” he broke out surprisingly, “what’s your +opinion of me, anyhow?” + +A little overwhelmed, I began the generalized evasions which that +question deserves. + +“Well, I’m going to tell you something about my life,” he interrupted. +“I don’t want you to get a wrong idea of me from all these stories you +hear.” + +So he was aware of the bizarre accusations that flavoured conversation +in his halls. + +“I’ll tell you God’s truth.” His right hand suddenly ordered divine +retribution to stand by. “I am the son of some wealthy people in the +Middle West—all dead now. I was brought up in America but educated at +Oxford, because all my ancestors have been educated there for many +years. It is a family tradition.” + +He looked at me sideways—and I knew why Jordan Baker had believed he +was lying. He hurried the phrase “educated at Oxford,” or swallowed +it, or choked on it, as though it had bothered him before. And with +this doubt, his whole statement fell to pieces, and I wondered if +there wasn’t something a little sinister about him, after all. + +“What part of the Middle West?” I inquired casually. + +“San Francisco.” + +“I see.” + +“My family all died and I came into a good deal of money.” + +His voice was solemn, as if the memory of that sudden extinction of a +clan still haunted him. For a moment I suspected that he was pulling +my leg, but a glance at him convinced me otherwise. + +“After that I lived like a young rajah in all the capitals of +Europe—Paris, Venice, Rome—collecting jewels, chiefly rubies, hunting +big game, painting a little, things for myself only, and trying to +forget something very sad that had happened to me long ago.” + +With an effort I managed to restrain my incredulous laughter. The very +phrases were worn so threadbare that they evoked no image except that +of a turbaned “character” leaking sawdust at every pore as he pursued +a tiger through the Bois de Boulogne. + +“Then came the war, old sport. It was a great relief, and I tried very +hard to die, but I seemed to bear an enchanted life. I accepted a +commission as first lieutenant when it began. In the Argonne Forest I +took the remains of my machine-gun battalion so far forward that there +was a half mile gap on either side of us where the infantry couldn’t +advance. We stayed there two days and two nights, a hundred and thirty +men with sixteen Lewis guns, and when the infantry came up at last +they found the insignia of three German divisions among the piles of +dead. I was promoted to be a major, and every Allied government gave +me a decoration—even Montenegro, little Montenegro down on the +Adriatic Sea!” + +Little Montenegro! He lifted up the words and nodded at them—with his +smile. The smile comprehended Montenegro’s troubled history and +sympathized with the brave struggles of the Montenegrin people. It +appreciated fully the chain of national circumstances which had +elicited this tribute from Montenegro’s warm little heart. My +incredulity was submerged in fascination now; it was like skimming +hastily through a dozen magazines. + +He reached in his pocket, and a piece of metal, slung on a ribbon, +fell into my palm. + +“That’s the one from Montenegro.” + +To my astonishment, the thing had an authentic look. “Orderi di +Danilo,” ran the circular legend, “Montenegro, Nicolas Rex.” + +“Turn it.” + +“Major Jay Gatsby,” I read, “For Valour Extraordinary.” + +“Here’s another thing I always carry. A souvenir of Oxford days. It +was taken in Trinity Quad—the man on my left is now the Earl of +Doncaster.” + +It was a photograph of half a dozen young men in blazers loafing in an +archway through which were visible a host of spires. There was Gatsby, +looking a little, not much, younger—with a cricket bat in his hand. + +Then it was all true. I saw the skins of tigers flaming in his palace +on the Grand Canal; I saw him opening a chest of rubies to ease, with +their crimson-lighted depths, the gnawings of his broken heart. + +“I’m going to make a big request of you today,” he said, pocketing his +souvenirs with satisfaction, “so I thought you ought to know something +about me. I didn’t want you to think I was just some nobody. You see, +I usually find myself among strangers because I drift here and there +trying to forget the sad things that happened to me.” He hesitated. +“You’ll hear about it this afternoon.” + +“At lunch?” + +“No, this afternoon. I happened to find out that you’re taking Miss +Baker to tea.” + +“Do you mean you’re in love with Miss Baker?” + +“No, old sport, I’m not. But Miss Baker has kindly consented to speak +to you about this matter.” + +I hadn’t the faintest idea what “this matter” was, but I was more +annoyed than interested. I hadn’t asked Jordan to tea in order to +discuss Mr. Jay Gatsby. I was sure the request would be something +utterly fantastic, and for a moment I was sorry I’d ever set foot upon +his overpopulated lawn. + +He wouldn’t say another word. His correctness grew on him as we neared +the city. We passed Port Roosevelt, where there was a glimpse of +red-belted oceangoing ships, and sped along a cobbled slum lined with +the dark, undeserted saloons of the faded-gilt nineteen-hundreds. +Then the valley of ashes opened out on both sides of us, and I had a +glimpse of Mrs. Wilson straining at the garage pump with panting +vitality as we went by. + +With fenders spread like wings we scattered light through half +Astoria—only half, for as we twisted among the pillars of the elevated +I heard the familiar “jug-jug-spat!” of a motorcycle, and a frantic +policeman rode alongside. + +“All right, old sport,” called Gatsby. We slowed down. Taking a white +card from his wallet, he waved it before the man’s eyes. + +“Right you are,” agreed the policeman, tipping his cap. “Know you next +time, Mr. Gatsby. Excuse me!” + +“What was that?” I inquired. “The picture of Oxford?” + +“I was able to do the commissioner a favour once, and he sends me a +Christmas card every year.” + +Over the great bridge, with the sunlight through the girders making a +constant flicker upon the moving cars, with the city rising up across +the river in white heaps and sugar lumps all built with a wish out of +nonolfactory money. The city seen from the Queensboro Bridge is always +the city seen for the first time, in its first wild promise of all the +mystery and the beauty in the world. + +A dead man passed us in a hearse heaped with blooms, followed by two +carriages with drawn blinds, and by more cheerful carriages for +friends. The friends looked out at us with the tragic eyes and short +upper lips of southeastern Europe, and I was glad that the sight of +Gatsby’s splendid car was included in their sombre holiday. As we +crossed Blackwell’s Island a limousine passed us, driven by a white +chauffeur, in which sat three modish negroes, two bucks and a girl. I +laughed aloud as the yolks of their eyeballs rolled toward us in +haughty rivalry. + +“Anything can happen now that we’ve slid over this bridge,” I thought; +“anything at all …” + +Even Gatsby could happen, without any particular wonder. + +------------------------------------------------------------------------ + +Roaring noon. In a well-fanned Forty-second Street cellar I met Gatsby +for lunch. Blinking away the brightness of the street outside, my eyes +picked him out obscurely in the anteroom, talking to another man. + +“Mr. Carraway, this is my friend Mr. Wolfshiem.” + +A small, flat-nosed Jew raised his large head and regarded me with two +fine growths of hair which luxuriated in either nostril. After a +moment I discovered his tiny eyes in the half-darkness. + +“—So I took one look at him,” said Mr. Wolfshiem, shaking my hand +earnestly, “and what do you think I did?” + +“What?” I inquired politely. + +But evidently he was not addressing me, for he dropped my hand and +covered Gatsby with his expressive nose. + +“I handed the money to Katspaugh and I said: ‘All right, Katspaugh, +don’t pay him a penny till he shuts his mouth.’ He shut it then and +there.” + +Gatsby took an arm of each of us and moved forward into the +restaurant, whereupon Mr. Wolfshiem swallowed a new sentence he was +starting and lapsed into a somnambulatory abstraction. + +“Highballs?” asked the head waiter. + +“This is a nice restaurant here,” said Mr. Wolfshiem, looking at the +presbyterian nymphs on the ceiling. “But I like across the street +better!” + +“Yes, highballs,” agreed Gatsby, and then to Mr. Wolfshiem: “It’s too +hot over there.” + +“Hot and small—yes,” said Mr. Wolfshiem, “but full of memories.” + +“What place is that?” I asked. + +“The old Metropole.” + +“The old Metropole,” brooded Mr. Wolfshiem gloomily. “Filled with +faces dead and gone. Filled with friends gone now forever. I can’t +forget so long as I live the night they shot Rosy Rosenthal there. It +was six of us at the table, and Rosy had eat and drunk a lot all +evening. When it was almost morning the waiter came up to him with a +funny look and says somebody wants to speak to him outside. ‘All +right,’ says Rosy, and begins to get up, and I pulled him down in his +chair. + +“ ‘Let the bastards come in here if they want you, Rosy, but don’t +you, so help me, move outside this room.’ + +“It was four o’clock in the morning then, and if we’d of raised the +blinds we’d of seen daylight.” + +“Did he go?” I asked innocently. + +“Sure he went.” Mr. Wolfshiem’s nose flashed at me indignantly. “He +turned around in the door and says: ‘Don’t let that waiter take away +my coffee!’ Then he went out on the sidewalk, and they shot him three +times in his full belly and drove away.” + +“Four of them were electrocuted,” I said, remembering. + +“Five, with Becker.” His nostrils turned to me in an interested way. +“I understand you’re looking for a business gonnegtion.” + +The juxtaposition of these two remarks was startling. Gatsby answered +for me: + +“Oh, no,” he exclaimed, “this isn’t the man.” + +“No?” Mr. Wolfshiem seemed disappointed. + +“This is just a friend. I told you we’d talk about that some other +time.” + +“I beg your pardon,” said Mr. Wolfshiem, “I had a wrong man.” + +A succulent hash arrived, and Mr. Wolfshiem, forgetting the more +sentimental atmosphere of the old Metropole, began to eat with +ferocious delicacy. His eyes, meanwhile, roved very slowly all around +the room—he completed the arc by turning to inspect the people +directly behind. I think that, except for my presence, he would have +taken one short glance beneath our own table. + +“Look here, old sport,” said Gatsby, leaning toward me, “I’m afraid I +made you a little angry this morning in the car.” + +There was the smile again, but this time I held out against it. + +“I don’t like mysteries,” I answered, “and I don’t understand why you +won’t come out frankly and tell me what you want. Why has it all got +to come through Miss Baker?” + +“Oh, it’s nothing underhand,” he assured me. “Miss Baker’s a great +sportswoman, you know, and she’d never do anything that wasn’t all +right.” + +Suddenly he looked at his watch, jumped up, and hurried from the room, +leaving me with Mr. Wolfshiem at the table. + +“He has to telephone,” said Mr. Wolfshiem, following him with his +eyes. “Fine fellow, isn’t he? Handsome to look at and a perfect +gentleman.” + +“Yes.” + +“He’s an Oggsford man.” + +“Oh!” + +“He went to Oggsford College in England. You know Oggsford College?” + +“I’ve heard of it.” + +“It’s one of the most famous colleges in the world.” + +“Have you known Gatsby for a long time?” I inquired. + +“Several years,” he answered in a gratified way. “I made the pleasure +of his acquaintance just after the war. But I knew I had discovered a +man of fine breeding after I talked with him an hour. I said to +myself: ‘There’s the kind of man you’d like to take home and introduce +to your mother and sister.’ ” He paused. “I see you’re looking at my +cuff buttons.” + +I hadn’t been looking at them, but I did now. They were composed of +oddly familiar pieces of ivory. + +“Finest specimens of human molars,” he informed me. + +“Well!” I inspected them. “That’s a very interesting idea.” + +“Yeah.” He flipped his sleeves up under his coat. “Yeah, Gatsby’s very +careful about women. He would never so much as look at a friend’s +wife.” + +When the subject of this instinctive trust returned to the table and +sat down Mr. Wolfshiem drank his coffee with a jerk and got to his +feet. + +“I have enjoyed my lunch,” he said, “and I’m going to run off from you +two young men before I outstay my welcome.” + +“Don’t hurry Meyer,” said Gatsby, without enthusiasm. Mr. Wolfshiem +raised his hand in a sort of benediction. + +“You’re very polite, but I belong to another generation,” he announced +solemnly. “You sit here and discuss your sports and your young ladies +and your—” He supplied an imaginary noun with another wave of his +hand. “As for me, I am fifty years old, and I won’t impose myself on +you any longer.” + +As he shook hands and turned away his tragic nose was trembling. I +wondered if I had said anything to offend him. + +“He becomes very sentimental sometimes,” explained Gatsby. “This is +one of his sentimental days. He’s quite a character around New York—a +denizen of Broadway.” + +“Who is he, anyhow, an actor?” + +“No.” + +“A dentist?” + +“Meyer Wolfshiem? No, he’s a gambler.” Gatsby hesitated, then added, +coolly: “He’s the man who fixed the World’s Series back in 1919.” + +“Fixed the World’s Series?” I repeated. + +The idea staggered me. I remembered, of course, that the World’s +Series had been fixed in 1919, but if I had thought of it at all I +would have thought of it as a thing that merely happened, the end of +some inevitable chain. It never occurred to me that one man could +start to play with the faith of fifty million people—with the +single-mindedness of a burglar blowing a safe. + +“How did he happen to do that?” I asked after a minute. + +“He just saw the opportunity.” + +“Why isn’t he in jail?” + +“They can’t get him, old sport. He’s a smart man.” + +I insisted on paying the check. As the waiter brought my change I +caught sight of Tom Buchanan across the crowded room. + +“Come along with me for a minute,” I said; “I’ve got to say hello to +someone.” + +When he saw us Tom jumped up and took half a dozen steps in our +direction. + +“Where’ve you been?” he demanded eagerly. “Daisy’s furious because you +haven’t called up.” + +“This is Mr. Gatsby, Mr. Buchanan.” + +They shook hands briefly, and a strained, unfamiliar look of +embarrassment came over Gatsby’s face. + +“How’ve you been, anyhow?” demanded Tom of me. “How’d you happen to +come up this far to eat?” + +“I’ve been having lunch with Mr. Gatsby.” + +I turned toward Mr. Gatsby, but he was no longer there. + +------------------------------------------------------------------------ + +One October day in nineteen-seventeen— + +(said Jordan Baker that afternoon, sitting up very straight on a +straight chair in the tea-garden at the Plaza Hotel) + +—I was walking along from one place to another, half on the sidewalks +and half on the lawns. I was happier on the lawns because I had on +shoes from England with rubber knobs on the soles that bit into the +soft ground. I had on a new plaid skirt also that blew a little in the +wind, and whenever this happened the red, white, and blue banners in +front of all the houses stretched out stiff and said tut-tut-tut-tut, +in a disapproving way. + +The largest of the banners and the largest of the lawns belonged to +Daisy Fay’s house. She was just eighteen, two years older than me, and +by far the most popular of all the young girls in Louisville. She +dressed in white, and had a little white roadster, and all day long +the telephone rang in her house and excited young officers from Camp +Taylor demanded the privilege of monopolizing her that +night. “Anyways, for an hour!” + +When I came opposite her house that morning her white roadster was +beside the kerb, and she was sitting in it with a lieutenant I had +never seen before. They were so engrossed in each other that she +didn’t see me until I was five feet away. + +“Hello, Jordan,” she called unexpectedly. “Please come here.” + +I was flattered that she wanted to speak to me, because of all the +older girls I admired her most. She asked me if I was going to the Red +Cross to make bandages. I was. Well, then, would I tell them that she +couldn’t come that day? The officer looked at Daisy while she was +speaking, in a way that every young girl wants to be looked at +sometime, and because it seemed romantic to me I have remembered the +incident ever since. His name was Jay Gatsby, and I didn’t lay eyes on +him again for over four years—even after I’d met him on Long Island I +didn’t realize it was the same man. + +That was nineteen-seventeen. By the next year I had a few beaux +myself, and I began to play in tournaments, so I didn’t see Daisy very +often. She went with a slightly older crowd—when she went with anyone +at all. Wild rumours were circulating about her—how her mother had +found her packing her bag one winter night to go to New York and say +goodbye to a soldier who was going overseas. She was effectually +prevented, but she wasn’t on speaking terms with her family for +several weeks. After that she didn’t play around with the soldiers any +more, but only with a few flat-footed, shortsighted young men in town, +who couldn’t get into the army at all. + +By the next autumn she was gay again, gay as ever. She had a début +after the armistice, and in February she was presumably engaged to a +man from New Orleans. In June she married Tom Buchanan of Chicago, +with more pomp and circumstance than Louisville ever knew before. He +came down with a hundred people in four private cars, and hired a +whole floor of the Muhlbach Hotel, and the day before the wedding he +gave her a string of pearls valued at three hundred and fifty thousand +dollars. + +I was a bridesmaid. I came into her room half an hour before the +bridal dinner, and found her lying on her bed as lovely as the June +night in her flowered dress—and as drunk as a monkey. She had a bottle +of Sauterne in one hand and a letter in the other. + +“ ’Gratulate me,” she muttered. “Never had a drink before, but oh how +I do enjoy it.” + +“What’s the matter, Daisy?” + +I was scared, I can tell you; I’d never seen a girl like that before. + +“Here, dearies.” She groped around in a wastebasket she had with her +on the bed and pulled out the string of pearls. “Take ’em downstairs +and give ’em back to whoever they belong to. Tell ’em all Daisy’s +change’ her mine. Say: ‘Daisy’s change’ her mine!’ ” + +She began to cry—she cried and cried. I rushed out and found her +mother’s maid, and we locked the door and got her into a cold bath. +She wouldn’t let go of the letter. She took it into the tub with her +and squeezed it up in a wet ball, and only let me leave it in the +soap-dish when she saw that it was coming to pieces like snow. + +But she didn’t say another word. We gave her spirits of ammonia and +put ice on her forehead and hooked her back into her dress, and half +an hour later, when we walked out of the room, the pearls were around +her neck and the incident was over. Next day at five o’clock she +married Tom Buchanan without so much as a shiver, and started off on a +three months’ trip to the South Seas. + +I saw them in Santa Barbara when they came back, and I thought I’d +never seen a girl so mad about her husband. If he left the room for a +minute she’d look around uneasily, and say: “Where’s Tom gone?” and +wear the most abstracted expression until she saw him coming in the +door. She used to sit on the sand with his head in her lap by the +hour, rubbing her fingers over his eyes and looking at him with +unfathomable delight. It was touching to see them together—it made you +laugh in a hushed, fascinated way. That was in August. A week after I +left Santa Barbara Tom ran into a wagon on the Ventura road one night, +and ripped a front wheel off his car. The girl who was with him got +into the papers, too, because her arm was broken—she was one of the +chambermaids in the Santa Barbara Hotel. + +The next April Daisy had her little girl, and they went to France for +a year. I saw them one spring in Cannes, and later in Deauville, and +then they came back to Chicago to settle down. Daisy was popular in +Chicago, as you know. They moved with a fast crowd, all of them young +and rich and wild, but she came out with an absolutely perfect +reputation. Perhaps because she doesn’t drink. It’s a great advantage +not to drink among hard-drinking people. You can hold your tongue and, +moreover, you can time any little irregularity of your own so that +everybody else is so blind that they don’t see or care. Perhaps Daisy +never went in for amour at all—and yet there’s something in that voice +of hers … + +Well, about six weeks ago, she heard the name Gatsby for the first +time in years. It was when I asked you—do you remember?—if you knew +Gatsby in West Egg. After you had gone home she came into my room and +woke me up, and said: “What Gatsby?” and when I described him—I was +half asleep—she said in the strangest voice that it must be the man +she used to know. It wasn’t until then that I connected this Gatsby +with the officer in her white car. + +------------------------------------------------------------------------ + +When Jordan Baker had finished telling all this we had left the Plaza +for half an hour and were driving in a victoria through Central Park. +The sun had gone down behind the tall apartments of the movie stars in +the West Fifties, and the clear voices of children, already gathered +like crickets on the grass, rose through the hot twilight: + + “I’m the Sheik of Araby. Your love belongs to me. At night when + you’re asleep Into your tent I’ll creep—” + +“It was a strange coincidence,” I said. + +“But it wasn’t a coincidence at all.” + +“Why not?” + +“Gatsby bought that house so that Daisy would be just across the bay.” + +Then it had not been merely the stars to which he had aspired on that +June night. He came alive to me, delivered suddenly from the womb of +his purposeless splendour. + +“He wants to know,” continued Jordan, “if you’ll invite Daisy to your +house some afternoon and then let him come over.” + +The modesty of the demand shook me. He had waited five years and +bought a mansion where he dispensed starlight to casual moths—so that +he could “come over” some afternoon to a stranger’s garden. + +“Did I have to know all this before he could ask such a little thing?” + +“He’s afraid, he’s waited so long. He thought you might be +offended. You see, he’s regular tough underneath it all.” + +Something worried me. + +“Why didn’t he ask you to arrange a meeting?” + +“He wants her to see his house,” she explained. “And your house is +right next door.” + +“Oh!” + +“I think he half expected her to wander into one of his parties, some +night,” went on Jordan, “but she never did. Then he began asking +people casually if they knew her, and I was the first one he found. It +was that night he sent for me at his dance, and you should have heard +the elaborate way he worked up to it. Of course, I immediately +suggested a luncheon in New York—and I thought he’d go mad: + +“ ‘I don’t want to do anything out of the way!’ he kept saying. ‘I +want to see her right next door.’ + +“When I said you were a particular friend of Tom’s, he started to +abandon the whole idea. He doesn’t know very much about Tom, though he +says he’s read a Chicago paper for years just on the chance of +catching a glimpse of Daisy’s name.” + +It was dark now, and as we dipped under a little bridge I put my arm +around Jordan’s golden shoulder and drew her toward me and asked her +to dinner. Suddenly I wasn’t thinking of Daisy and Gatsby any more, +but of this clean, hard, limited person, who dealt in universal +scepticism, and who leaned back jauntily just within the circle of my +arm. A phrase began to beat in my ears with a sort of heady +excitement: “There are only the pursued, the pursuing, the busy, and +the tired.” + +“And Daisy ought to have something in her life,” murmured Jordan to +me. + +“Does she want to see Gatsby?” + +“She’s not to know about it. Gatsby doesn’t want her to know. You’re +just supposed to invite her to tea.” + +We passed a barrier of dark trees, and then the façade of Fifty-Ninth +Street, a block of delicate pale light, beamed down into the park. +Unlike Gatsby and Tom Buchanan, I had no girl whose disembodied face +floated along the dark cornices and blinding signs, and so I drew up +the girl beside me, tightening my arms. Her wan, scornful mouth +smiled, and so I drew her up again closer, this time to my face. + + + V + +When I came home to West Egg that night I was afraid for a moment that +my house was on fire. Two o’clock and the whole corner of the +peninsula was blazing with light, which fell unreal on the shrubbery +and made thin elongating glints upon the roadside wires. Turning a +corner, I saw that it was Gatsby’s house, lit from tower to cellar. + +At first I thought it was another party, a wild rout that had resolved +itself into “hide-and-go-seek” or “sardines-in-the-box” with all the +house thrown open to the game. But there wasn’t a sound. Only wind in +the trees, which blew the wires and made the lights go off and on +again as if the house had winked into the darkness. As my taxi groaned +away I saw Gatsby walking toward me across his lawn. + +“Your place looks like the World’s Fair,” I said. + +“Does it?” He turned his eyes toward it absently. “I have been +glancing into some of the rooms. Let’s go to Coney Island, old +sport. In my car.” + +“It’s too late.” + +“Well, suppose we take a plunge in the swimming pool? I haven’t made +use of it all summer.” + +“I’ve got to go to bed.” + +“All right.” + +He waited, looking at me with suppressed eagerness. + +“I talked with Miss Baker,” I said after a moment. “I’m going to call +up Daisy tomorrow and invite her over here to tea.” + +“Oh, that’s all right,” he said carelessly. “I don’t want to put you +to any trouble.” + +“What day would suit you?” + +“What day would suit you?” he corrected me quickly. “I don’t want to +put you to any trouble, you see.” + +“How about the day after tomorrow?” + +He considered for a moment. Then, with reluctance: “I want to get the +grass cut,” he said. + +We both looked down at the grass—there was a sharp line where my +ragged lawn ended and the darker, well-kept expanse of his began. I +suspected that he meant my grass. + +“There’s another little thing,” he said uncertainly, and hesitated. + +“Would you rather put it off for a few days?” I asked. + +“Oh, it isn’t about that. At least—” He fumbled with a series of +beginnings. “Why, I thought—why, look here, old sport, you don’t make +much money, do you?” + +“Not very much.” + +This seemed to reassure him and he continued more confidently. + +“I thought you didn’t, if you’ll pardon my—you see, I carry on a +little business on the side, a sort of side line, you understand. And +I thought that if you don’t make very much—You’re selling bonds, +aren’t you, old sport?” + +“Trying to.” + +“Well, this would interest you. It wouldn’t take up much of your time +and you might pick up a nice bit of money. It happens to be a rather +confidential sort of thing.” + +I realize now that under different circumstances that conversation +might have been one of the crises of my life. But, because the offer +was obviously and tactlessly for a service to be rendered, I had no +choice except to cut him off there. + +“I’ve got my hands full,” I said. “I’m much obliged but I couldn’t +take on any more work.” + +“You wouldn’t have to do any business with Wolfshiem.” Evidently he +thought that I was shying away from the “gonnegtion” mentioned at +lunch, but I assured him he was wrong. He waited a moment longer, +hoping I’d begin a conversation, but I was too absorbed to be +responsive, so he went unwillingly home. + +The evening had made me lightheaded and happy; I think I walked into a +deep sleep as I entered my front door. So I don’t know whether or not +Gatsby went to Coney Island, or for how many hours he “glanced into +rooms” while his house blazed gaudily on. I called up Daisy from the +office next morning, and invited her to come to tea. + +“Don’t bring Tom,” I warned her. + +“What?” + +“Don’t bring Tom.” + +“Who is ‘Tom’?” she asked innocently. + +The day agreed upon was pouring rain. At eleven o’clock a man in a +raincoat, dragging a lawn-mower, tapped at my front door and said that +Mr. Gatsby had sent him over to cut my grass. This reminded me that I +had forgotten to tell my Finn to come back, so I drove into West Egg +Village to search for her among soggy whitewashed alleys and to buy +some cups and lemons and flowers. + +The flowers were unnecessary, for at two o’clock a greenhouse arrived +from Gatsby’s, with innumerable receptacles to contain it. An hour +later the front door opened nervously, and Gatsby in a white flannel +suit, silver shirt, and gold-coloured tie, hurried in. He was pale, +and there were dark signs of sleeplessness beneath his eyes. + +“Is everything all right?” he asked immediately. + +“The grass looks fine, if that’s what you mean.” + +“What grass?” he inquired blankly. “Oh, the grass in the yard.” He +looked out the window at it, but, judging from his expression, I don’t +believe he saw a thing. + +“Looks very good,” he remarked vaguely. “One of the papers said they +thought the rain would stop about four. I think it was The +Journal. Have you got everything you need in the shape of—of tea?” + +I took him into the pantry, where he looked a little reproachfully at +the Finn. Together we scrutinized the twelve lemon cakes from the +delicatessen shop. + +“Will they do?” I asked. + +“Of course, of course! They’re fine!” and he added hollowly, “… old +sport.” + +The rain cooled about half-past three to a damp mist, through which +occasional thin drops swam like dew. Gatsby looked with vacant eyes +through a copy of Clay’s Economics, starting at the Finnish tread that +shook the kitchen floor, and peering towards the bleared windows from +time to time as if a series of invisible but alarming happenings were +taking place outside. Finally he got up and informed me, in an +uncertain voice, that he was going home. + +“Why’s that?” + +“Nobody’s coming to tea. It’s too late!” He looked at his watch as if +there was some pressing demand on his time elsewhere. “I can’t wait +all day.” + +“Don’t be silly; it’s just two minutes to four.” + +He sat down miserably, as if I had pushed him, and simultaneously +there was the sound of a motor turning into my lane. We both jumped +up, and, a little harrowed myself, I went out into the yard. + +Under the dripping bare lilac-trees a large open car was coming up the +drive. It stopped. Daisy’s face, tipped sideways beneath a +three-cornered lavender hat, looked out at me with a bright ecstatic +smile. + +“Is this absolutely where you live, my dearest one?” + +The exhilarating ripple of her voice was a wild tonic in the rain. I +had to follow the sound of it for a moment, up and down, with my ear +alone, before any words came through. A damp streak of hair lay like a +dash of blue paint across her cheek, and her hand was wet with +glistening drops as I took it to help her from the car. + +“Are you in love with me,” she said low in my ear, “or why did I have +to come alone?” + +“That’s the secret of Castle Rackrent. Tell your chauffeur to go far +away and spend an hour.” + +“Come back in an hour, Ferdie.” Then in a grave murmur: “His name is +Ferdie.” + +“Does the gasoline affect his nose?” + +“I don’t think so,” she said innocently. “Why?” + +We went in. To my overwhelming surprise the living-room was deserted. + +“Well, that’s funny,” I exclaimed. + +“What’s funny?” + +She turned her head as there was a light dignified knocking at the +front door. I went out and opened it. Gatsby, pale as death, with his +hands plunged like weights in his coat pockets, was standing in a +puddle of water glaring tragically into my eyes. + +With his hands still in his coat pockets he stalked by me into the +hall, turned sharply as if he were on a wire, and disappeared into the +living-room. It wasn’t a bit funny. Aware of the loud beating of my +own heart I pulled the door to against the increasing rain. + +For half a minute there wasn’t a sound. Then from the living-room I +heard a sort of choking murmur and part of a laugh, followed by +Daisy’s voice on a clear artificial note: + +“I certainly am awfully glad to see you again.” + +A pause; it endured horribly. I had nothing to do in the hall, so I +went into the room. + +Gatsby, his hands still in his pockets, was reclining against the +mantelpiece in a strained counterfeit of perfect ease, even of +boredom. His head leaned back so far that it rested against the face +of a defunct mantelpiece clock, and from this position his distraught +eyes stared down at Daisy, who was sitting, frightened but graceful, +on the edge of a stiff chair. + +“We’ve met before,” muttered Gatsby. His eyes glanced momentarily at +me, and his lips parted with an abortive attempt at a laugh. Luckily +the clock took this moment to tilt dangerously at the pressure of his +head, whereupon he turned and caught it with trembling fingers, and +set it back in place. Then he sat down, rigidly, his elbow on the arm +of the sofa and his chin in his hand. + +“I’m sorry about the clock,” he said. + +My own face had now assumed a deep tropical burn. I couldn’t muster up +a single commonplace out of the thousand in my head. + +“It’s an old clock,” I told them idiotically. + +I think we all believed for a moment that it had smashed in pieces on +the floor. + +“We haven’t met for many years,” said Daisy, her voice as +matter-of-fact as it could ever be. + +“Five years next November.” + +The automatic quality of Gatsby’s answer set us all back at least +another minute. I had them both on their feet with the desperate +suggestion that they help me make tea in the kitchen when the demoniac +Finn brought it in on a tray. + +Amid the welcome confusion of cups and cakes a certain physical +decency established itself. Gatsby got himself into a shadow and, +while Daisy and I talked, looked conscientiously from one to the other +of us with tense, unhappy eyes. However, as calmness wasn’t an end in +itself, I made an excuse at the first possible moment, and got to my +feet. + +“Where are you going?” demanded Gatsby in immediate alarm. + +“I’ll be back.” + +“I’ve got to speak to you about something before you go.” + +He followed me wildly into the kitchen, closed the door, and +whispered: “Oh, God!” in a miserable way. + +“What’s the matter?” + +“This is a terrible mistake,” he said, shaking his head from side to +side, “a terrible, terrible mistake.” + +“You’re just embarrassed, that’s all,” and luckily I added: “Daisy’s +embarrassed too.” + +“She’s embarrassed?” he repeated incredulously. + +“Just as much as you are.” + +“Don’t talk so loud.” + +“You’re acting like a little boy,” I broke out impatiently. “Not only +that, but you’re rude. Daisy’s sitting in there all alone.” + +He raised his hand to stop my words, looked at me with unforgettable +reproach, and, opening the door cautiously, went back into the other +room. + +I walked out the back way—just as Gatsby had when he had made his +nervous circuit of the house half an hour before—and ran for a huge +black knotted tree, whose massed leaves made a fabric against the +rain. Once more it was pouring, and my irregular lawn, well-shaved by +Gatsby’s gardener, abounded in small muddy swamps and prehistoric +marshes. There was nothing to look at from under the tree except +Gatsby’s enormous house, so I stared at it, like Kant at his church +steeple, for half an hour. A brewer had built it early in the “period” +craze, a decade before, and there was a story that he’d agreed to pay +five years’ taxes on all the neighbouring cottages if the owners would +have their roofs thatched with straw. Perhaps their refusal took the +heart out of his plan to Found a Family—he went into an immediate +decline. His children sold his house with the black wreath still on +the door. Americans, while willing, even eager, to be serfs, have +always been obstinate about being peasantry. + +After half an hour, the sun shone again, and the grocer’s automobile +rounded Gatsby’s drive with the raw material for his servants’ +dinner—I felt sure he wouldn’t eat a spoonful. A maid began opening +the upper windows of his house, appeared momentarily in each, and, +leaning from the large central bay, spat meditatively into the +garden. It was time I went back. While the rain continued it had +seemed like the murmur of their voices, rising and swelling a little +now and then with gusts of emotion. But in the new silence I felt that +silence had fallen within the house too. + +I went in—after making every possible noise in the kitchen, short of +pushing over the stove—but I don’t believe they heard a sound. They +were sitting at either end of the couch, looking at each other as if +some question had been asked, or was in the air, and every vestige of +embarrassment was gone. Daisy’s face was smeared with tears, and when +I came in she jumped up and began wiping at it with her handkerchief +before a mirror. But there was a change in Gatsby that was simply +confounding. He literally glowed; without a word or a gesture of +exultation a new well-being radiated from him and filled the little +room. + +“Oh, hello, old sport,” he said, as if he hadn’t seen me for years. I +thought for a moment he was going to shake hands. + +“It’s stopped raining.” + +“Has it?” When he realized what I was talking about, that there were +twinkle-bells of sunshine in the room, he smiled like a weather man, +like an ecstatic patron of recurrent light, and repeated the news to +Daisy. “What do you think of that? It’s stopped raining.” + +“I’m glad, Jay.” Her throat, full of aching, grieving beauty, told +only of her unexpected joy. + +“I want you and Daisy to come over to my house,” he said, “I’d like to +show her around.” + +“You’re sure you want me to come?” + +“Absolutely, old sport.” + +Daisy went upstairs to wash her face—too late I thought with +humiliation of my towels—while Gatsby and I waited on the lawn. + +“My house looks well, doesn’t it?” he demanded. “See how the whole +front of it catches the light.” + +I agreed that it was splendid. + +“Yes.” His eyes went over it, every arched door and square tower. “It +took me just three years to earn the money that bought it.” + +“I thought you inherited your money.” + +“I did, old sport,” he said automatically, “but I lost most of it in +the big panic—the panic of the war.” + +I think he hardly knew what he was saying, for when I asked him what +business he was in he answered: “That’s my affair,” before he realized +that it wasn’t an appropriate reply. + +“Oh, I’ve been in several things,” he corrected himself. “I was in the +drug business and then I was in the oil business. But I’m not in +either one now.” He looked at me with more attention. “Do you mean +you’ve been thinking over what I proposed the other night?” + +Before I could answer, Daisy came out of the house and two rows of +brass buttons on her dress gleamed in the sunlight. + +“That huge place there?” she cried pointing. + +“Do you like it?” + +“I love it, but I don’t see how you live there all alone.” + +“I keep it always full of interesting people, night and day. People +who do interesting things. Celebrated people.” + +Instead of taking the shortcut along the Sound we went down to the +road and entered by the big postern. With enchanting murmurs Daisy +admired this aspect or that of the feudal silhouette against the sky, +admired the gardens, the sparkling odour of jonquils and the frothy +odour of hawthorn and plum blossoms and the pale gold odour of +kiss-me-at-the-gate. It was strange to reach the marble steps and find +no stir of bright dresses in and out the door, and hear no sound but +bird voices in the trees. + +And inside, as we wandered through Marie Antoinette music-rooms and +Restoration Salons, I felt that there were guests concealed behind +every couch and table, under orders to be breathlessly silent until we +had passed through. As Gatsby closed the door of “the Merton College +Library” I could have sworn I heard the owl-eyed man break into +ghostly laughter. + +We went upstairs, through period bedrooms swathed in rose and lavender +silk and vivid with new flowers, through dressing-rooms and poolrooms, +and bathrooms with sunken baths—intruding into one chamber where a +dishevelled man in pyjamas was doing liver exercises on the floor. It +was Mr. Klipspringer, the “boarder.” I had seen him wandering hungrily +about the beach that morning. Finally we came to Gatsby’s own +apartment, a bedroom and a bath, and an Adam’s study, where we sat +down and drank a glass of some Chartreuse he took from a cupboard in +the wall. + +He hadn’t once ceased looking at Daisy, and I think he revalued +everything in his house according to the measure of response it drew +from her well-loved eyes. Sometimes too, he stared around at his +possessions in a dazed way, as though in her actual and astounding +presence none of it was any longer real. Once he nearly toppled down a +flight of stairs. + +His bedroom was the simplest room of all—except where the dresser was +garnished with a toilet set of pure dull gold. Daisy took the brush +with delight, and smoothed her hair, whereupon Gatsby sat down and +shaded his eyes and began to laugh. + +“It’s the funniest thing, old sport,” he said hilariously. “I +can’t—When I try to—” + +He had passed visibly through two states and was entering upon a +third. After his embarrassment and his unreasoning joy he was consumed +with wonder at her presence. He had been full of the idea so long, +dreamed it right through to the end, waited with his teeth set, so to +speak, at an inconceivable pitch of intensity. Now, in the reaction, +he was running down like an over-wound clock. + +Recovering himself in a minute he opened for us two hulking patent +cabinets which held his massed suits and dressing-gowns and ties, and +his shirts, piled like bricks in stacks a dozen high. + +“I’ve got a man in England who buys me clothes. He sends over a +selection of things at the beginning of each season, spring and fall.” + +He took out a pile of shirts and began throwing them, one by one, +before us, shirts of sheer linen and thick silk and fine flannel, +which lost their folds as they fell and covered the table in +many-coloured disarray. While we admired he brought more and the soft +rich heap mounted higher—shirts with stripes and scrolls and plaids in +coral and apple-green and lavender and faint orange, with monograms of +indian blue. Suddenly, with a strained sound, Daisy bent her head into +the shirts and began to cry stormily. + +“They’re such beautiful shirts,” she sobbed, her voice muffled in the +thick folds. “It makes me sad because I’ve never seen such—such +beautiful shirts before.” + +------------------------------------------------------------------------ + +After the house, we were to see the grounds and the swimming pool, and +the hydroplane, and the midsummer flowers—but outside Gatsby’s window +it began to rain again, so we stood in a row looking at the corrugated +surface of the Sound. + +“If it wasn’t for the mist we could see your home across the bay,” +said Gatsby. “You always have a green light that burns all night at +the end of your dock.” + +Daisy put her arm through his abruptly, but he seemed absorbed in what +he had just said. Possibly it had occurred to him that the colossal +significance of that light had now vanished forever. Compared to the +great distance that had separated him from Daisy it had seemed very +near to her, almost touching her. It had seemed as close as a star to +the moon. Now it was again a green light on a dock. His count of +enchanted objects had diminished by one. + +I began to walk about the room, examining various indefinite objects +in the half darkness. A large photograph of an elderly man in yachting +costume attracted me, hung on the wall over his desk. + +“Who’s this?” + +“That? That’s Mr. Dan Cody, old sport.” + +The name sounded faintly familiar. + +“He’s dead now. He used to be my best friend years ago.” + +There was a small picture of Gatsby, also in yachting costume, on the +bureau—Gatsby with his head thrown back defiantly—taken apparently +when he was about eighteen. + +“I adore it,” exclaimed Daisy. “The pompadour! You never told me you +had a pompadour—or a yacht.” + +“Look at this,” said Gatsby quickly. “Here’s a lot of clippings—about +you.” + +They stood side by side examining it. I was going to ask to see the +rubies when the phone rang, and Gatsby took up the receiver. + +“Yes … Well, I can’t talk now … I can’t talk now, old sport … I said a +small town … He must know what a small town is … Well, he’s no use to +us if Detroit is his idea of a small town …” + +He rang off. + +“Come here quick!” cried Daisy at the window. + +The rain was still falling, but the darkness had parted in the west, +and there was a pink and golden billow of foamy clouds above the sea. + +“Look at that,” she whispered, and then after a moment: “I’d like to +just get one of those pink clouds and put you in it and push you +around.” + +I tried to go then, but they wouldn’t hear of it; perhaps my presence +made them feel more satisfactorily alone. + +“I know what we’ll do,” said Gatsby, “we’ll have Klipspringer play the +piano.” + +He went out of the room calling “Ewing!” and returned in a few minutes +accompanied by an embarrassed, slightly worn young man, with +shell-rimmed glasses and scanty blond hair. He was now decently +clothed in a “sport shirt,” open at the neck, sneakers, and duck +trousers of a nebulous hue. + +“Did we interrupt your exercise?” inquired Daisy politely. + +“I was asleep,” cried Mr. Klipspringer, in a spasm of embarrassment. +“That is, I’d been asleep. Then I got up …” + +“Klipspringer plays the piano,” said Gatsby, cutting him off. “Don’t +you, Ewing, old sport?” + +“I don’t play well. I don’t—hardly play at all. I’m all out of prac—” + +“We’ll go downstairs,” interrupted Gatsby. He flipped a switch. The +grey windows disappeared as the house glowed full of light. + +In the music-room Gatsby turned on a solitary lamp beside the piano. +He lit Daisy’s cigarette from a trembling match, and sat down with her +on a couch far across the room, where there was no light save what the +gleaming floor bounced in from the hall. + +When Klipspringer had played “The Love Nest” he turned around on the +bench and searched unhappily for Gatsby in the gloom. + +“I’m all out of practice, you see. I told you I couldn’t play. I’m all +out of prac—” + +“Don’t talk so much, old sport,” commanded Gatsby. “Play!” + + “In the morning, In the evening, Ain’t we got fun—” + +Outside the wind was loud and there was a faint flow of thunder along +the Sound. All the lights were going on in West Egg now; the electric +trains, men-carrying, were plunging home through the rain from New +York. It was the hour of a profound human change, and excitement was +generating on the air. + + “One thing’s sure and nothing’s surer The rich get richer and the + poor get—children. In the meantime, In between time—” + +As I went over to say goodbye I saw that the expression of +bewilderment had come back into Gatsby’s face, as though a faint doubt +had occurred to him as to the quality of his present happiness. Almost +five years! There must have been moments even that afternoon when +Daisy tumbled short of his dreams—not through her own fault, but +because of the colossal vitality of his illusion. It had gone beyond +her, beyond everything. He had thrown himself into it with a creative +passion, adding to it all the time, decking it out with every bright +feather that drifted his way. No amount of fire or freshness can +challenge what a man can store up in his ghostly heart. + +As I watched him he adjusted himself a little, visibly. His hand took +hold of hers, and as she said something low in his ear he turned +toward her with a rush of emotion. I think that voice held him most, +with its fluctuating, feverish warmth, because it couldn’t be +over-dreamed—that voice was a deathless song. + +They had forgotten me, but Daisy glanced up and held out her hand; +Gatsby didn’t know me now at all. I looked once more at them and they +looked back at me, remotely, possessed by intense life. Then I went +out of the room and down the marble steps into the rain, leaving them +there together. + + + VI + +About this time an ambitious young reporter from New York arrived one +morning at Gatsby’s door and asked him if he had anything to say. + +“Anything to say about what?” inquired Gatsby politely. + +“Why—any statement to give out.” + +It transpired after a confused five minutes that the man had heard +Gatsby’s name around his office in a connection which he either +wouldn’t reveal or didn’t fully understand. This was his day off and +with laudable initiative he had hurried out “to see.” + +It was a random shot, and yet the reporter’s instinct was right. +Gatsby’s notoriety, spread about by the hundreds who had accepted his +hospitality and so become authorities upon his past, had increased all +summer until he fell just short of being news. Contemporary legends +such as the “underground pipeline to Canada” attached themselves to +him, and there was one persistent story that he didn’t live in a house +at all, but in a boat that looked like a house and was moved secretly +up and down the Long Island shore. Just why these inventions were a +source of satisfaction to James Gatz of North Dakota, isn’t easy to +say. + +James Gatz—that was really, or at least legally, his name. He had +changed it at the age of seventeen and at the specific moment that +witnessed the beginning of his career—when he saw Dan Cody’s yacht +drop anchor over the most insidious flat on Lake Superior. It was +James Gatz who had been loafing along the beach that afternoon in a +torn green jersey and a pair of canvas pants, but it was already Jay +Gatsby who borrowed a rowboat, pulled out to the Tuolomee, and +informed Cody that a wind might catch him and break him up in half an +hour. + +I suppose he’d had the name ready for a long time, even then. His +parents were shiftless and unsuccessful farm people—his imagination +had never really accepted them as his parents at all. The truth was +that Jay Gatsby of West Egg, Long Island, sprang from his Platonic +conception of himself. He was a son of God—a phrase which, if it means +anything, means just that—and he must be about His Father’s business, +the service of a vast, vulgar, and meretricious beauty. So he invented +just the sort of Jay Gatsby that a seventeen-year-old boy would be +likely to invent, and to this conception he was faithful to the end. + +For over a year he had been beating his way along the south shore of +Lake Superior as a clam-digger and a salmon-fisher or in any other +capacity that brought him food and bed. His brown, hardening body +lived naturally through the half-fierce, half-lazy work of the bracing +days. He knew women early, and since they spoiled him he became +contemptuous of them, of young virgins because they were ignorant, of +the others because they were hysterical about things which in his +overwhelming self-absorption he took for granted. + +But his heart was in a constant, turbulent riot. The most grotesque +and fantastic conceits haunted him in his bed at night. A universe of +ineffable gaudiness spun itself out in his brain while the clock +ticked on the washstand and the moon soaked with wet light his tangled +clothes upon the floor. Each night he added to the pattern of his +fancies until drowsiness closed down upon some vivid scene with an +oblivious embrace. For a while these reveries provided an outlet for +his imagination; they were a satisfactory hint of the unreality of +reality, a promise that the rock of the world was founded securely on +a fairy’s wing. + +An instinct toward his future glory had led him, some months before, +to the small Lutheran College of St. Olaf’s in southern Minnesota. He +stayed there two weeks, dismayed at its ferocious indifference to the +drums of his destiny, to destiny itself, and despising the janitor’s +work with which he was to pay his way through. Then he drifted back to +Lake Superior, and he was still searching for something to do on the +day that Dan Cody’s yacht dropped anchor in the shallows alongshore. + +Cody was fifty years old then, a product of the Nevada silver fields, +of the Yukon, of every rush for metal since seventy-five. The +transactions in Montana copper that made him many times a millionaire +found him physically robust but on the verge of soft-mindedness, and, +suspecting this, an infinite number of women tried to separate him +from his money. The none too savoury ramifications by which Ella Kaye, +the newspaper woman, played Madame de Maintenon to his weakness and +sent him to sea in a yacht, were common property of the turgid +journalism in 1902. He had been coasting along all too hospitable +shores for five years when he turned up as James Gatz’s destiny in +Little Girl Bay. + +To young Gatz, resting on his oars and looking up at the railed deck, +that yacht represented all the beauty and glamour in the world. I +suppose he smiled at Cody—he had probably discovered that people liked +him when he smiled. At any rate Cody asked him a few questions (one of +them elicited the brand new name) and found that he was quick and +extravagantly ambitious. A few days later he took him to Duluth and +bought him a blue coat, six pairs of white duck trousers, and a +yachting cap. And when the Tuolomee left for the West Indies and the +Barbary Coast, Gatsby left too. + +He was employed in a vague personal capacity—while he remained with +Cody he was in turn steward, mate, skipper, secretary, and even +jailor, for Dan Cody sober knew what lavish doings Dan Cody drunk +might soon be about, and he provided for such contingencies by +reposing more and more trust in Gatsby. The arrangement lasted five +years, during which the boat went three times around the Continent. +It might have lasted indefinitely except for the fact that Ella Kaye +came on board one night in Boston and a week later Dan Cody +inhospitably died. + +I remember the portrait of him up in Gatsby’s bedroom, a grey, florid +man with a hard, empty face—the pioneer debauchee, who during one +phase of American life brought back to the Eastern seaboard the savage +violence of the frontier brothel and saloon. It was indirectly due to +Cody that Gatsby drank so little. Sometimes in the course of gay +parties women used to rub champagne into his hair; for himself he +formed the habit of letting liquor alone. + +And it was from Cody that he inherited money—a legacy of twenty-five +thousand dollars. He didn’t get it. He never understood the legal +device that was used against him, but what remained of the millions +went intact to Ella Kaye. He was left with his singularly appropriate +education; the vague contour of Jay Gatsby had filled out to the +substantiality of a man. + +------------------------------------------------------------------------ + +He told me all this very much later, but I’ve put it down here with +the idea of exploding those first wild rumours about his antecedents, +which weren’t even faintly true. Moreover he told it to me at a time +of confusion, when I had reached the point of believing everything and +nothing about him. So I take advantage of this short halt, while +Gatsby, so to speak, caught his breath, to clear this set of +misconceptions away. + +It was a halt, too, in my association with his affairs. For several +weeks I didn’t see him or hear his voice on the phone—mostly I was in +New York, trotting around with Jordan and trying to ingratiate myself +with her senile aunt—but finally I went over to his house one Sunday +afternoon. I hadn’t been there two minutes when somebody brought Tom +Buchanan in for a drink. I was startled, naturally, but the really +surprising thing was that it hadn’t happened before. + +They were a party of three on horseback—Tom and a man named Sloane and +a pretty woman in a brown riding-habit, who had been there previously. + +“I’m delighted to see you,” said Gatsby, standing on his porch. “I’m +delighted that you dropped in.” + +As though they cared! + +“Sit right down. Have a cigarette or a cigar.” He walked around the +room quickly, ringing bells. “I’ll have something to drink for you in +just a minute.” + +He was profoundly affected by the fact that Tom was there. But he +would be uneasy anyhow until he had given them something, realizing in +a vague way that that was all they came for. Mr. Sloane wanted +nothing. A lemonade? No, thanks. A little champagne? Nothing at all, +thanks … I’m sorry— + +“Did you have a nice ride?” + +“Very good roads around here.” + +“I suppose the automobiles—” + +“Yeah.” + +Moved by an irresistible impulse, Gatsby turned to Tom, who had +accepted the introduction as a stranger. + +“I believe we’ve met somewhere before, Mr. Buchanan.” + +“Oh, yes,” said Tom, gruffly polite, but obviously not remembering. +“So we did. I remember very well.” + +“About two weeks ago.” + +“That’s right. You were with Nick here.” + +“I know your wife,” continued Gatsby, almost aggressively. + +“That so?” + +Tom turned to me. + +“You live near here, Nick?” + +“Next door.” + +“That so?” + +Mr. Sloane didn’t enter into the conversation, but lounged back +haughtily in his chair; the woman said nothing either—until +unexpectedly, after two highballs, she became cordial. + +“We’ll all come over to your next party, Mr. Gatsby,” she suggested. +“What do you say?” + +“Certainly; I’d be delighted to have you.” + +“Be ver’ nice,” said Mr. Sloane, without gratitude. “Well—think ought +to be starting home.” + +“Please don’t hurry,” Gatsby urged them. He had control of himself +now, and he wanted to see more of Tom. “Why don’t you—why don’t you +stay for supper? I wouldn’t be surprised if some other people dropped +in from New York.” + +“You come to supper with me,” said the lady enthusiastically. “Both of +you.” + +This included me. Mr. Sloane got to his feet. + +“Come along,” he said—but to her only. + +“I mean it,” she insisted. “I’d love to have you. Lots of room.” + +Gatsby looked at me questioningly. He wanted to go and he didn’t see +that Mr. Sloane had determined he shouldn’t. + +“I’m afraid I won’t be able to,” I said. + +“Well, you come,” she urged, concentrating on Gatsby. + +Mr. Sloane murmured something close to her ear. + +“We won’t be late if we start now,” she insisted aloud. + +“I haven’t got a horse,” said Gatsby. “I used to ride in the army, but +I’ve never bought a horse. I’ll have to follow you in my car. Excuse +me for just a minute.” + +The rest of us walked out on the porch, where Sloane and the lady +began an impassioned conversation aside. + +“My God, I believe the man’s coming,” said Tom. “Doesn’t he know she +doesn’t want him?” + +“She says she does want him.” + +“She has a big dinner party and he won’t know a soul there.” He +frowned. “I wonder where in the devil he met Daisy. By God, I may be +old-fashioned in my ideas, but women run around too much these days to +suit me. They meet all kinds of crazy fish.” + +Suddenly Mr. Sloane and the lady walked down the steps and mounted +their horses. + +“Come on,” said Mr. Sloane to Tom, “we’re late. We’ve got to go.” And +then to me: “Tell him we couldn’t wait, will you?” + +Tom and I shook hands, the rest of us exchanged a cool nod, and they +trotted quickly down the drive, disappearing under the August foliage +just as Gatsby, with hat and light overcoat in hand, came out the +front door. + +Tom was evidently perturbed at Daisy’s running around alone, for on +the following Saturday night he came with her to Gatsby’s +party. Perhaps his presence gave the evening its peculiar quality of +oppressiveness—it stands out in my memory from Gatsby’s other parties +that summer. There were the same people, or at least the same sort of +people, the same profusion of champagne, the same many-coloured, +many-keyed commotion, but I felt an unpleasantness in the air, a +pervading harshness that hadn’t been there before. Or perhaps I had +merely grown used to it, grown to accept West Egg as a world complete +in itself, with its own standards and its own great figures, second to +nothing because it had no consciousness of being so, and now I was +looking at it again, through Daisy’s eyes. It is invariably saddening +to look through new eyes at things upon which you have expended your +own powers of adjustment. + +They arrived at twilight, and, as we strolled out among the sparkling +hundreds, Daisy’s voice was playing murmurous tricks in her throat. + +“These things excite me so,” she whispered. “If you want to kiss me +any time during the evening, Nick, just let me know and I’ll be glad +to arrange it for you. Just mention my name. Or present a green card. +I’m giving out green—” + +“Look around,” suggested Gatsby. + +“I’m looking around. I’m having a marvellous—” + +“You must see the faces of many people you’ve heard about.” + +Tom’s arrogant eyes roamed the crowd. + +“We don’t go around very much,” he said; “in fact, I was just thinking +I don’t know a soul here.” + +“Perhaps you know that lady.” Gatsby indicated a gorgeous, scarcely +human orchid of a woman who sat in state under a white-plum tree. Tom +and Daisy stared, with that peculiarly unreal feeling that accompanies +the recognition of a hitherto ghostly celebrity of the movies. + +“She’s lovely,” said Daisy. + +“The man bending over her is her director.” + +He took them ceremoniously from group to group: + +“Mrs. Buchanan … and Mr. Buchanan—” After an instant’s hesitation he +added: “the polo player.” + +“Oh no,” objected Tom quickly, “not me.” + +But evidently the sound of it pleased Gatsby for Tom remained “the +polo player” for the rest of the evening. + +“I’ve never met so many celebrities,” Daisy exclaimed. “I liked that +man—what was his name?—with the sort of blue nose.” + +Gatsby identified him, adding that he was a small producer. + +“Well, I liked him anyhow.” + +“I’d a little rather not be the polo player,” said Tom pleasantly, +“I’d rather look at all these famous people in—in oblivion.” + +Daisy and Gatsby danced. I remember being surprised by his graceful, +conservative foxtrot—I had never seen him dance before. Then they +sauntered over to my house and sat on the steps for half an hour, +while at her request I remained watchfully in the garden. “In case +there’s a fire or a flood,” she explained, “or any act of God.” + +Tom appeared from his oblivion as we were sitting down to supper +together. “Do you mind if I eat with some people over here?” he +said. “A fellow’s getting off some funny stuff.” + +“Go ahead,” answered Daisy genially, “and if you want to take down any +addresses here’s my little gold pencil.” … She looked around after a +moment and told me the girl was “common but pretty,” and I knew that +except for the half-hour she’d been alone with Gatsby she wasn’t +having a good time. + +We were at a particularly tipsy table. That was my fault—Gatsby had +been called to the phone, and I’d enjoyed these same people only two +weeks before. But what had amused me then turned septic on the air +now. + +“How do you feel, Miss Baedeker?” + +The girl addressed was trying, unsuccessfully, to slump against my +shoulder. At this inquiry she sat up and opened her eyes. + +“Wha’?” + +A massive and lethargic woman, who had been urging Daisy to play golf +with her at the local club tomorrow, spoke in Miss Baedeker’s defence: + +“Oh, she’s all right now. When she’s had five or six cocktails she +always starts screaming like that. I tell her she ought to leave it +alone.” + +“I do leave it alone,” affirmed the accused hollowly. + +“We heard you yelling, so I said to Doc Civet here: ‘There’s somebody +that needs your help, Doc.’ ” + +“She’s much obliged, I’m sure,” said another friend, without +gratitude, “but you got her dress all wet when you stuck her head in +the pool.” + +“Anything I hate is to get my head stuck in a pool,” mumbled Miss +Baedeker. “They almost drowned me once over in New Jersey.” + +“Then you ought to leave it alone,” countered Doctor Civet. + +“Speak for yourself!” cried Miss Baedeker violently. “Your hand +shakes. I wouldn’t let you operate on me!” + +It was like that. Almost the last thing I remember was standing with +Daisy and watching the moving-picture director and his Star. They were +still under the white-plum tree and their faces were touching except +for a pale, thin ray of moonlight between. It occurred to me that he +had been very slowly bending toward her all evening to attain this +proximity, and even while I watched I saw him stoop one ultimate +degree and kiss at her cheek. + +“I like her,” said Daisy, “I think she’s lovely.” + +But the rest offended her—and inarguably because it wasn’t a gesture +but an emotion. She was appalled by West Egg, this unprecedented +“place” that Broadway had begotten upon a Long Island fishing +village—appalled by its raw vigour that chafed under the old +euphemisms and by the too obtrusive fate that herded its inhabitants +along a shortcut from nothing to nothing. She saw something awful in +the very simplicity she failed to understand. + +I sat on the front steps with them while they waited for their car. +It was dark here in front; only the bright door sent ten square feet +of light volleying out into the soft black morning. Sometimes a shadow +moved against a dressing-room blind above, gave way to another shadow, +an indefinite procession of shadows, who rouged and powdered in an +invisible glass. + +“Who is this Gatsby anyhow?” demanded Tom suddenly. “Some big +bootlegger?” + +“Where’d you hear that?” I inquired. + +“I didn’t hear it. I imagined it. A lot of these newly rich people are +just big bootleggers, you know.” + +“Not Gatsby,” I said shortly. + +He was silent for a moment. The pebbles of the drive crunched under +his feet. + +“Well, he certainly must have strained himself to get this menagerie +together.” + +A breeze stirred the grey haze of Daisy’s fur collar. + +“At least they are more interesting than the people we know,” she said +with an effort. + +“You didn’t look so interested.” + +“Well, I was.” + +Tom laughed and turned to me. + +“Did you notice Daisy’s face when that girl asked her to put her under +a cold shower?” + +Daisy began to sing with the music in a husky, rhythmic whisper, +bringing out a meaning in each word that it had never had before and +would never have again. When the melody rose her voice broke up +sweetly, following it, in a way contralto voices have, and each change +tipped out a little of her warm human magic upon the air. + +“Lots of people come who haven’t been invited,” she said +suddenly. “That girl hadn’t been invited. They simply force their way +in and he’s too polite to object.” + +“I’d like to know who he is and what he does,” insisted Tom. “And I +think I’ll make a point of finding out.” + +“I can tell you right now,” she answered. “He owned some drugstores, a +lot of drugstores. He built them up himself.” + +The dilatory limousine came rolling up the drive. + +“Good night, Nick,” said Daisy. + +Her glance left me and sought the lighted top of the steps, where +“Three O’Clock in the Morning,” a neat, sad little waltz of that year, +was drifting out the open door. After all, in the very casualness of +Gatsby’s party there were romantic possibilities totally absent from +her world. What was it up there in the song that seemed to be calling +her back inside? What would happen now in the dim, incalculable hours? +Perhaps some unbelievable guest would arrive, a person infinitely rare +and to be marvelled at, some authentically radiant young girl who with +one fresh glance at Gatsby, one moment of magical encounter, would +blot out those five years of unwavering devotion. + +I stayed late that night. Gatsby asked me to wait until he was free, +and I lingered in the garden until the inevitable swimming party had +run up, chilled and exalted, from the black beach, until the lights +were extinguished in the guestrooms overhead. When he came down the +steps at last the tanned skin was drawn unusually tight on his face, +and his eyes were bright and tired. + +“She didn’t like it,” he said immediately. + +“Of course she did.” + +“She didn’t like it,” he insisted. “She didn’t have a good time.” + +He was silent, and I guessed at his unutterable depression. + +“I feel far away from her,” he said. “It’s hard to make her +understand.” + +“You mean about the dance?” + +“The dance?” He dismissed all the dances he had given with a snap of +his fingers. “Old sport, the dance is unimportant.” + +He wanted nothing less of Daisy than that she should go to Tom and +say: “I never loved you.” After she had obliterated four years with +that sentence they could decide upon the more practical measures to be +taken. One of them was that, after she was free, they were to go back +to Louisville and be married from her house—just as if it were five +years ago. + +“And she doesn’t understand,” he said. “She used to be able to +understand. We’d sit for hours—” + +He broke off and began to walk up and down a desolate path of fruit +rinds and discarded favours and crushed flowers. + +“I wouldn’t ask too much of her,” I ventured. “You can’t repeat the +past.” + +“Can’t repeat the past?” he cried incredulously. “Why of course you +can!” + +He looked around him wildly, as if the past were lurking here in the +shadow of his house, just out of reach of his hand. + +“I’m going to fix everything just the way it was before,” he said, +nodding determinedly. “She’ll see.” + +He talked a lot about the past, and I gathered that he wanted to +recover something, some idea of himself perhaps, that had gone into +loving Daisy. His life had been confused and disordered since then, +but if he could once return to a certain starting place and go over it +all slowly, he could find out what that thing was … + +… One autumn night, five years before, they had been walking down the +street when the leaves were falling, and they came to a place where +there were no trees and the sidewalk was white with moonlight. They +stopped here and turned toward each other. Now it was a cool night +with that mysterious excitement in it which comes at the two changes +of the year. The quiet lights in the houses were humming out into the +darkness and there was a stir and bustle among the stars. Out of the +corner of his eye Gatsby saw that the blocks of the sidewalks really +formed a ladder and mounted to a secret place above the trees—he could +climb to it, if he climbed alone, and once there he could suck on the +pap of life, gulp down the incomparable milk of wonder. + +His heart beat faster as Daisy’s white face came up to his own. He +knew that when he kissed this girl, and forever wed his unutterable +visions to her perishable breath, his mind would never romp again like +the mind of God. So he waited, listening for a moment longer to the +tuning-fork that had been struck upon a star. Then he kissed her. At +his lips’ touch she blossomed for him like a flower and the +incarnation was complete. + +Through all he said, even through his appalling sentimentality, I was +reminded of something—an elusive rhythm, a fragment of lost words, +that I had heard somewhere a long time ago. For a moment a phrase +tried to take shape in my mouth and my lips parted like a dumb man’s, +as though there was more struggling upon them than a wisp of startled +air. But they made no sound, and what I had almost remembered was +uncommunicable forever. + + + VII + +It was when curiosity about Gatsby was at its highest that the lights +in his house failed to go on one Saturday night—and, as obscurely as +it had begun, his career as Trimalchio was over. Only gradually did I +become aware that the automobiles which turned expectantly into his +drive stayed for just a minute and then drove sulkily away. Wondering +if he were sick I went over to find out—an unfamiliar butler with a +villainous face squinted at me suspiciously from the door. + +“Is Mr. Gatsby sick?” + +“Nope.” After a pause he added “sir” in a dilatory, grudging way. + +“I hadn’t seen him around, and I was rather worried. Tell him Mr. +Carraway came over.” + +“Who?” he demanded rudely. + +“Carraway.” + +“Carraway. All right, I’ll tell him.” + +Abruptly he slammed the door. + +My Finn informed me that Gatsby had dismissed every servant in his +house a week ago and replaced them with half a dozen others, who never +went into West Egg village to be bribed by the tradesmen, but ordered +moderate supplies over the telephone. The grocery boy reported that +the kitchen looked like a pigsty, and the general opinion in the +village was that the new people weren’t servants at all. + +Next day Gatsby called me on the phone. + +“Going away?” I inquired. + +“No, old sport.” + +“I hear you fired all your servants.” + +“I wanted somebody who wouldn’t gossip. Daisy comes over quite +often—in the afternoons.” + +So the whole caravansary had fallen in like a card house at the +disapproval in her eyes. + +“They’re some people Wolfshiem wanted to do something for. They’re all +brothers and sisters. They used to run a small hotel.” + +“I see.” + +He was calling up at Daisy’s request—would I come to lunch at her +house tomorrow? Miss Baker would be there. Half an hour later Daisy +herself telephoned and seemed relieved to find that I was +coming. Something was up. And yet I couldn’t believe that they would +choose this occasion for a scene—especially for the rather harrowing +scene that Gatsby had outlined in the garden. + +The next day was broiling, almost the last, certainly the warmest, of +the summer. As my train emerged from the tunnel into sunlight, only +the hot whistles of the National Biscuit Company broke the simmering +hush at noon. The straw seats of the car hovered on the edge of +combustion; the woman next to me perspired delicately for a while into +her white shirtwaist, and then, as her newspaper dampened under her +fingers, lapsed despairingly into deep heat with a desolate cry. Her +pocketbook slapped to the floor. + +“Oh, my!” she gasped. + +I picked it up with a weary bend and handed it back to her, holding it +at arm’s length and by the extreme tip of the corners to indicate that +I had no designs upon it—but everyone near by, including the woman, +suspected me just the same. + +“Hot!” said the conductor to familiar faces. “Some weather! … Hot! … +Hot! … Hot! … Is it hot enough for you? Is it hot? Is it … ?” + +My commutation ticket came back to me with a dark stain from his hand. +That anyone should care in this heat whose flushed lips he kissed, +whose head made damp the pyjama pocket over his heart! + +… Through the hall of the Buchanans’ house blew a faint wind, carrying +the sound of the telephone bell out to Gatsby and me as we waited at +the door. + +“The master’s body?” roared the butler into the mouthpiece. “I’m +sorry, madame, but we can’t furnish it—it’s far too hot to touch this +noon!” + +What he really said was: “Yes … Yes … I’ll see.” + +He set down the receiver and came toward us, glistening slightly, to +take our stiff straw hats. + +“Madame expects you in the salon!” he cried, needlessly indicating the +direction. In this heat every extra gesture was an affront to the +common store of life. + +The room, shadowed well with awnings, was dark and cool. Daisy and +Jordan lay upon an enormous couch, like silver idols weighing down +their own white dresses against the singing breeze of the fans. + +“We can’t move,” they said together. + +Jordan’s fingers, powdered white over their tan, rested for a moment +in mine. + +“And Mr. Thomas Buchanan, the athlete?” I inquired. + +Simultaneously I heard his voice, gruff, muffled, husky, at the hall +telephone. + +Gatsby stood in the centre of the crimson carpet and gazed around with +fascinated eyes. Daisy watched him and laughed, her sweet, exciting +laugh; a tiny gust of powder rose from her bosom into the air. + +“The rumour is,” whispered Jordan, “that that’s Tom’s girl on the +telephone.” + +We were silent. The voice in the hall rose high with annoyance: “Very +well, then, I won’t sell you the car at all … I’m under no obligations +to you at all … and as for your bothering me about it at lunch time, I +won’t stand that at all!” + +“Holding down the receiver,” said Daisy cynically. + +“No, he’s not,” I assured her. “It’s a bona-fide deal. I happen to +know about it.” + +Tom flung open the door, blocked out its space for a moment with his +thick body, and hurried into the room. + +“Mr. Gatsby!” He put out his broad, flat hand with well-concealed +dislike. “I’m glad to see you, sir … Nick …” + +“Make us a cold drink,” cried Daisy. + +As he left the room again she got up and went over to Gatsby and +pulled his face down, kissing him on the mouth. + +“You know I love you,” she murmured. + +“You forget there’s a lady present,” said Jordan. + +Daisy looked around doubtfully. + +“You kiss Nick too.” + +“What a low, vulgar girl!” + +“I don’t care!” cried Daisy, and began to clog on the brick fireplace. +Then she remembered the heat and sat down guiltily on the couch just +as a freshly laundered nurse leading a little girl came into the room. + +“Bles-sed pre-cious,” she crooned, holding out her arms. “Come to your +own mother that loves you.” + +The child, relinquished by the nurse, rushed across the room and +rooted shyly into her mother’s dress. + +“The bles-sed pre-cious! Did mother get powder on your old yellowy +hair? Stand up now, and say—How-de-do.” + +Gatsby and I in turn leaned down and took the small reluctant hand. +Afterward he kept looking at the child with surprise. I don’t think he +had ever really believed in its existence before. + +“I got dressed before luncheon,” said the child, turning eagerly to +Daisy. + +“That’s because your mother wanted to show you off.” Her face bent +into the single wrinkle of the small white neck. “You dream, you. You +absolute little dream.” + +“Yes,” admitted the child calmly. “Aunt Jordan’s got on a white dress +too.” + +“How do you like mother’s friends?” Daisy turned her around so that +she faced Gatsby. “Do you think they’re pretty?” + +“Where’s Daddy?” + +“She doesn’t look like her father,” explained Daisy. “She looks like +me. She’s got my hair and shape of the face.” + +Daisy sat back upon the couch. The nurse took a step forward and held +out her hand. + +“Come, Pammy.” + +“Goodbye, sweetheart!” + +With a reluctant backward glance the well-disciplined child held to +her nurse’s hand and was pulled out the door, just as Tom came back, +preceding four gin rickeys that clicked full of ice. + +Gatsby took up his drink. + +“They certainly look cool,” he said, with visible tension. + +We drank in long, greedy swallows. + +“I read somewhere that the sun’s getting hotter every year,” said Tom +genially. “It seems that pretty soon the earth’s going to fall into +the sun—or wait a minute—it’s just the opposite—the sun’s getting +colder every year. + +“Come outside,” he suggested to Gatsby, “I’d like you to have a look +at the place.” + +I went with them out to the veranda. On the green Sound, stagnant in +the heat, one small sail crawled slowly toward the fresher sea. +Gatsby’s eyes followed it momentarily; he raised his hand and pointed +across the bay. + +“I’m right across from you.” + +“So you are.” + +Our eyes lifted over the rose-beds and the hot lawn and the weedy +refuse of the dog-days alongshore. Slowly the white wings of the boat +moved against the blue cool limit of the sky. Ahead lay the scalloped +ocean and the abounding blessed isles. + +“There’s sport for you,” said Tom, nodding. “I’d like to be out there +with him for about an hour.” + +We had luncheon in the dining-room, darkened too against the heat, and +drank down nervous gaiety with the cold ale. + +“What’ll we do with ourselves this afternoon?” cried Daisy, “and the +day after that, and the next thirty years?” + +“Don’t be morbid,” Jordan said. “Life starts all over again when it +gets crisp in the fall.” + +“But it’s so hot,” insisted Daisy, on the verge of tears, “and +everything’s so confused. Let’s all go to town!” + +Her voice struggled on through the heat, beating against it, moulding +its senselessness into forms. + +“I’ve heard of making a garage out of a stable,” Tom was saying to +Gatsby, “but I’m the first man who ever made a stable out of a +garage.” + +“Who wants to go to town?” demanded Daisy insistently. Gatsby’s eyes +floated toward her. “Ah,” she cried, “you look so cool.” + +Their eyes met, and they stared together at each other, alone in +space. With an effort she glanced down at the table. + +“You always look so cool,” she repeated. + +She had told him that she loved him, and Tom Buchanan saw. He was +astounded. His mouth opened a little, and he looked at Gatsby, and +then back at Daisy as if he had just recognized her as someone he knew +a long time ago. + +“You resemble the advertisement of the man,” she went on innocently. +“You know the advertisement of the man—” + +“All right,” broke in Tom quickly, “I’m perfectly willing to go to +town. Come on—we’re all going to town.” + +He got up, his eyes still flashing between Gatsby and his wife. No one +moved. + +“Come on!” His temper cracked a little. “What’s the matter, anyhow? +If we’re going to town, let’s start.” + +His hand, trembling with his effort at self-control, bore to his lips +the last of his glass of ale. Daisy’s voice got us to our feet and out +on to the blazing gravel drive. + +“Are we just going to go?” she objected. “Like this? Aren’t we going +to let anyone smoke a cigarette first?” + +“Everybody smoked all through lunch.” + +“Oh, let’s have fun,” she begged him. “It’s too hot to fuss.” + +He didn’t answer. + +“Have it your own way,” she said. “Come on, Jordan.” + +They went upstairs to get ready while we three men stood there +shuffling the hot pebbles with our feet. A silver curve of the moon +hovered already in the western sky. Gatsby started to speak, changed +his mind, but not before Tom wheeled and faced him expectantly. + +“Have you got your stables here?” asked Gatsby with an effort. + +“About a quarter of a mile down the road.” + +“Oh.” + +A pause. + +“I don’t see the idea of going to town,” broke out Tom savagely. +“Women get these notions in their heads—” + +“Shall we take anything to drink?” called Daisy from an upper window. + +“I’ll get some whisky,” answered Tom. He went inside. + +Gatsby turned to me rigidly: + +“I can’t say anything in his house, old sport.” + +“She’s got an indiscreet voice,” I remarked. “It’s full of—” I +hesitated. + +“Her voice is full of money,” he said suddenly. + +That was it. I’d never understood before. It was full of money—that +was the inexhaustible charm that rose and fell in it, the jingle of +it, the cymbals’ song of it … High in a white palace the king’s +daughter, the golden girl … + +Tom came out of the house wrapping a quart bottle in a towel, followed +by Daisy and Jordan wearing small tight hats of metallic cloth and +carrying light capes over their arms. + +“Shall we all go in my car?” suggested Gatsby. He felt the hot, green +leather of the seat. “I ought to have left it in the shade.” + +“Is it standard shift?” demanded Tom. + +“Yes.” + +“Well, you take my coupé and let me drive your car to town.” + +The suggestion was distasteful to Gatsby. + +“I don’t think there’s much gas,” he objected. + +“Plenty of gas,” said Tom boisterously. He looked at the gauge. “And +if it runs out I can stop at a drugstore. You can buy anything at a +drugstore nowadays.” + +A pause followed this apparently pointless remark. Daisy looked at Tom +frowning, and an indefinable expression, at once definitely unfamiliar +and vaguely recognizable, as if I had only heard it described in +words, passed over Gatsby’s face. + +“Come on, Daisy,” said Tom, pressing her with his hand toward Gatsby’s +car. “I’ll take you in this circus wagon.” + +He opened the door, but she moved out from the circle of his arm. + +“You take Nick and Jordan. We’ll follow you in the coupé.” + +She walked close to Gatsby, touching his coat with her hand. Jordan +and Tom and I got into the front seat of Gatsby’s car, Tom pushed the +unfamiliar gears tentatively, and we shot off into the oppressive +heat, leaving them out of sight behind. + +“Did you see that?” demanded Tom. + +“See what?” + +He looked at me keenly, realizing that Jordan and I must have known +all along. + +“You think I’m pretty dumb, don’t you?” he suggested. “Perhaps I am, +but I have a—almost a second sight, sometimes, that tells me what to +do. Maybe you don’t believe that, but science—” + +He paused. The immediate contingency overtook him, pulled him back +from the edge of theoretical abyss. + +“I’ve made a small investigation of this fellow,” he continued. “I +could have gone deeper if I’d known—” + +“Do you mean you’ve been to a medium?” inquired Jordan humorously. + +“What?” Confused, he stared at us as we laughed. “A medium?” + +“About Gatsby.” + +“About Gatsby! No, I haven’t. I said I’d been making a small +investigation of his past.” + +“And you found he was an Oxford man,” said Jordan helpfully. + +“An Oxford man!” He was incredulous. “Like hell he is! He wears a pink +suit.” + +“Nevertheless he’s an Oxford man.” + +“Oxford, New Mexico,” snorted Tom contemptuously, “or something like +that.” + +“Listen, Tom. If you’re such a snob, why did you invite him to lunch?” +demanded Jordan crossly. + +“Daisy invited him; she knew him before we were married—God knows +where!” + +We were all irritable now with the fading ale, and aware of it we +drove for a while in silence. Then as Doctor T. J. Eckleburg’s faded +eyes came into sight down the road, I remembered Gatsby’s caution +about gasoline. + +“We’ve got enough to get us to town,” said Tom. + +“But there’s a garage right here,” objected Jordan. “I don’t want to +get stalled in this baking heat.” + +Tom threw on both brakes impatiently, and we slid to an abrupt dusty +stop under Wilson’s sign. After a moment the proprietor emerged from +the interior of his establishment and gazed hollow-eyed at the car. + +“Let’s have some gas!” cried Tom roughly. “What do you think we +stopped for—to admire the view?” + +“I’m sick,” said Wilson without moving. “Been sick all day.” + +“What’s the matter?” + +“I’m all run down.” + +“Well, shall I help myself?” Tom demanded. “You sounded well enough on +the phone.” + +With an effort Wilson left the shade and support of the doorway and, +breathing hard, unscrewed the cap of the tank. In the sunlight his +face was green. + +“I didn’t mean to interrupt your lunch,” he said. “But I need money +pretty bad, and I was wondering what you were going to do with your +old car.” + +“How do you like this one?” inquired Tom. “I bought it last week.” + +“It’s a nice yellow one,” said Wilson, as he strained at the handle. + +“Like to buy it?” + +“Big chance,” Wilson smiled faintly. “No, but I could make some money +on the other.” + +“What do you want money for, all of a sudden?” + +“I’ve been here too long. I want to get away. My wife and I want to go +West.” + +“Your wife does,” exclaimed Tom, startled. + +“She’s been talking about it for ten years.” He rested for a moment +against the pump, shading his eyes. “And now she’s going whether she +wants to or not. I’m going to get her away.” + +The coupé flashed by us with a flurry of dust and the flash of a +waving hand. + +“What do I owe you?” demanded Tom harshly. + +“I just got wised up to something funny the last two days,” remarked +Wilson. “That’s why I want to get away. That’s why I been bothering +you about the car.” + +“What do I owe you?” + +“Dollar twenty.” + +The relentless beating heat was beginning to confuse me and I had a +bad moment there before I realized that so far his suspicions hadn’t +alighted on Tom. He had discovered that Myrtle had some sort of life +apart from him in another world, and the shock had made him physically +sick. I stared at him and then at Tom, who had made a parallel +discovery less than an hour before—and it occurred to me that there +was no difference between men, in intelligence or race, so profound as +the difference between the sick and the well. Wilson was so sick that +he looked guilty, unforgivably guilty—as if he had just got some poor +girl with child. + +“I’ll let you have that car,” said Tom. “I’ll send it over tomorrow +afternoon.” + +That locality was always vaguely disquieting, even in the broad glare +of afternoon, and now I turned my head as though I had been warned of +something behind. Over the ash-heaps the giant eyes of Doctor T. J. +Eckleburg kept their vigil, but I perceived, after a moment, that +other eyes were regarding us with peculiar intensity from less than +twenty feet away. + +In one of the windows over the garage the curtains had been moved +aside a little, and Myrtle Wilson was peering down at the car. So +engrossed was she that she had no consciousness of being observed, and +one emotion after another crept into her face like objects into a +slowly developing picture. Her expression was curiously familiar—it +was an expression I had often seen on women’s faces, but on Myrtle +Wilson’s face it seemed purposeless and inexplicable until I realized +that her eyes, wide with jealous terror, were fixed not on Tom, but on +Jordan Baker, whom she took to be his wife. + +------------------------------------------------------------------------ + +There is no confusion like the confusion of a simple mind, and as we +drove away Tom was feeling the hot whips of panic. His wife and his +mistress, until an hour ago secure and inviolate, were slipping +precipitately from his control. Instinct made him step on the +accelerator with the double purpose of overtaking Daisy and leaving +Wilson behind, and we sped along toward Astoria at fifty miles an +hour, until, among the spidery girders of the elevated, we came in +sight of the easygoing blue coupé. + +“Those big movies around Fiftieth Street are cool,” suggested +Jordan. “I love New York on summer afternoons when everyone’s away. +There’s something very sensuous about it—overripe, as if all sorts of +funny fruits were going to fall into your hands.” + +The word “sensuous” had the effect of further disquieting Tom, but +before he could invent a protest the coupé came to a stop, and Daisy +signalled us to draw up alongside. + +“Where are we going?” she cried. + +“How about the movies?” + +“It’s so hot,” she complained. “You go. We’ll ride around and meet you +after.” With an effort her wit rose faintly. “We’ll meet you on some +corner. I’ll be the man smoking two cigarettes.” + +“We can’t argue about it here,” Tom said impatiently, as a truck gave +out a cursing whistle behind us. “You follow me to the south side of +Central Park, in front of the Plaza.” + +Several times he turned his head and looked back for their car, and if +the traffic delayed them he slowed up until they came into sight. I +think he was afraid they would dart down a side-street and out of his +life forever. + +But they didn’t. And we all took the less explicable step of engaging +the parlour of a suite in the Plaza Hotel. + +The prolonged and tumultuous argument that ended by herding us into +that room eludes me, though I have a sharp physical memory that, in +the course of it, my underwear kept climbing like a damp snake around +my legs and intermittent beads of sweat raced cool across my back. +The notion originated with Daisy’s suggestion that we hire five +bathrooms and take cold baths, and then assumed more tangible form as +“a place to have a mint julep.” Each of us said over and over that it +was a “crazy idea”—we all talked at once to a baffled clerk and +thought, or pretended to think, that we were being very funny … + +The room was large and stifling, and, though it was already four +o’clock, opening the windows admitted only a gust of hot shrubbery +from the Park. Daisy went to the mirror and stood with her back to us, +fixing her hair. + +“It’s a swell suite,” whispered Jordan respectfully, and everyone +laughed. + +“Open another window,” commanded Daisy, without turning around. + +“There aren’t any more.” + +“Well, we’d better telephone for an axe—” + +“The thing to do is to forget about the heat,” said Tom impatiently. +“You make it ten times worse by crabbing about it.” + +He unrolled the bottle of whisky from the towel and put it on the +table. + +“Why not let her alone, old sport?” remarked Gatsby. “You’re the one +that wanted to come to town.” + +There was a moment of silence. The telephone book slipped from its +nail and splashed to the floor, whereupon Jordan whispered, “Excuse +me”—but this time no one laughed. + +“I’ll pick it up,” I offered. + +“I’ve got it.” Gatsby examined the parted string, muttered “Hum!” in +an interested way, and tossed the book on a chair. + +“That’s a great expression of yours, isn’t it?” said Tom sharply. + +“What is?” + +“All this ‘old sport’ business. Where’d you pick that up?” + +“Now see here, Tom,” said Daisy, turning around from the mirror, “if +you’re going to make personal remarks I won’t stay here a minute. +Call up and order some ice for the mint julep.” + +As Tom took up the receiver the compressed heat exploded into sound +and we were listening to the portentous chords of Mendelssohn’s +Wedding March from the ballroom below. + +“Imagine marrying anybody in this heat!” cried Jordan dismally. + +“Still—I was married in the middle of June,” Daisy remembered. +“Louisville in June! Somebody fainted. Who was it fainted, Tom?” + +“Biloxi,” he answered shortly. + +“A man named Biloxi. ‘Blocks’ Biloxi, and he made boxes—that’s a +fact—and he was from Biloxi, Tennessee.” + +“They carried him into my house,” appended Jordan, “because we lived +just two doors from the church. And he stayed three weeks, until Daddy +told him he had to get out. The day after he left Daddy died.” After +a moment she added as if she might have sounded irreverent, “There +wasn’t any connection.” + +“I used to know a Bill Biloxi from Memphis,” I remarked. + +“That was his cousin. I knew his whole family history before he +left. He gave me an aluminium putter that I use today.” + +The music had died down as the ceremony began and now a long cheer +floated in at the window, followed by intermittent cries of +“Yea—ea—ea!” and finally by a burst of jazz as the dancing began. + +“We’re getting old,” said Daisy. “If we were young we’d rise and +dance.” + +“Remember Biloxi,” Jordan warned her. “Where’d you know him, Tom?” + +“Biloxi?” He concentrated with an effort. “I didn’t know him. He was a +friend of Daisy’s.” + +“He was not,” she denied. “I’d never seen him before. He came down in +the private car.” + +“Well, he said he knew you. He said he was raised in Louisville. Asa +Bird brought him around at the last minute and asked if we had room +for him.” + +Jordan smiled. + +“He was probably bumming his way home. He told me he was president of +your class at Yale.” + +Tom and I looked at each other blankly. + +“Biloxi?” + +“First place, we didn’t have any president—” + +Gatsby’s foot beat a short, restless tattoo and Tom eyed him suddenly. + +“By the way, Mr. Gatsby, I understand you’re an Oxford man.” + +“Not exactly.” + +“Oh, yes, I understand you went to Oxford.” + +“Yes—I went there.” + +A pause. Then Tom’s voice, incredulous and insulting: + +“You must have gone there about the time Biloxi went to New Haven.” + +Another pause. A waiter knocked and came in with crushed mint and ice +but the silence was unbroken by his “thank you” and the soft closing +of the door. This tremendous detail was to be cleared up at last. + +“I told you I went there,” said Gatsby. + +“I heard you, but I’d like to know when.” + +“It was in nineteen-nineteen, I only stayed five months. That’s why I +can’t really call myself an Oxford man.” + +Tom glanced around to see if we mirrored his unbelief. But we were all +looking at Gatsby. + +“It was an opportunity they gave to some of the officers after the +armistice,” he continued. “We could go to any of the universities in +England or France.” + +I wanted to get up and slap him on the back. I had one of those +renewals of complete faith in him that I’d experienced before. + +Daisy rose, smiling faintly, and went to the table. + +“Open the whisky, Tom,” she ordered, “and I’ll make you a mint julep. +Then you won’t seem so stupid to yourself … Look at the mint!” + +“Wait a minute,” snapped Tom, “I want to ask Mr. Gatsby one more +question.” + +“Go on,” Gatsby said politely. + +“What kind of a row are you trying to cause in my house anyhow?” + +They were out in the open at last and Gatsby was content. + +“He isn’t causing a row,” Daisy looked desperately from one to the +other. “You’re causing a row. Please have a little self-control.” + +“Self-control!” repeated Tom incredulously. “I suppose the latest +thing is to sit back and let Mr. Nobody from Nowhere make love to your +wife. Well, if that’s the idea you can count me out … Nowadays people +begin by sneering at family life and family institutions, and next +they’ll throw everything overboard and have intermarriage between +black and white.” + +Flushed with his impassioned gibberish, he saw himself standing alone +on the last barrier of civilization. + +“We’re all white here,” murmured Jordan. + +“I know I’m not very popular. I don’t give big parties. I suppose +you’ve got to make your house into a pigsty in order to have any +friends—in the modern world.” + +Angry as I was, as we all were, I was tempted to laugh whenever he +opened his mouth. The transition from libertine to prig was so +complete. + +“I’ve got something to tell you, old sport—” began Gatsby. But Daisy +guessed at his intention. + +“Please don’t!” she interrupted helplessly. “Please let’s all go +home. Why don’t we all go home?” + +“That’s a good idea,” I got up. “Come on, Tom. Nobody wants a drink.” + +“I want to know what Mr. Gatsby has to tell me.” + +“Your wife doesn’t love you,” said Gatsby. “She’s never loved you. +She loves me.” + +“You must be crazy!” exclaimed Tom automatically. + +Gatsby sprang to his feet, vivid with excitement. + +“She never loved you, do you hear?” he cried. “She only married you +because I was poor and she was tired of waiting for me. It was a +terrible mistake, but in her heart she never loved anyone except me!” + +At this point Jordan and I tried to go, but Tom and Gatsby insisted +with competitive firmness that we remain—as though neither of them had +anything to conceal and it would be a privilege to partake vicariously +of their emotions. + +“Sit down, Daisy,” Tom’s voice groped unsuccessfully for the paternal +note. “What’s been going on? I want to hear all about it.” + +“I told you what’s been going on,” said Gatsby. “Going on for five +years—and you didn’t know.” + +Tom turned to Daisy sharply. + +“You’ve been seeing this fellow for five years?” + +“Not seeing,” said Gatsby. “No, we couldn’t meet. But both of us loved +each other all that time, old sport, and you didn’t know. I used to +laugh sometimes”—but there was no laughter in his eyes—“to think that +you didn’t know.” + +“Oh—that’s all.” Tom tapped his thick fingers together like a +clergyman and leaned back in his chair. + +“You’re crazy!” he exploded. “I can’t speak about what happened five +years ago, because I didn’t know Daisy then—and I’ll be damned if I +see how you got within a mile of her unless you brought the groceries +to the back door. But all the rest of that’s a God damned lie. Daisy +loved me when she married me and she loves me now.” + +“No,” said Gatsby, shaking his head. + +“She does, though. The trouble is that sometimes she gets foolish +ideas in her head and doesn’t know what she’s doing.” He nodded +sagely. “And what’s more, I love Daisy too. Once in a while I go off +on a spree and make a fool of myself, but I always come back, and in +my heart I love her all the time.” + +“You’re revolting,” said Daisy. She turned to me, and her voice, +dropping an octave lower, filled the room with thrilling scorn: “Do +you know why we left Chicago? I’m surprised that they didn’t treat you +to the story of that little spree.” + +Gatsby walked over and stood beside her. + +“Daisy, that’s all over now,” he said earnestly. “It doesn’t matter +any more. Just tell him the truth—that you never loved him—and it’s +all wiped out forever.” + +She looked at him blindly. “Why—how could I love him—possibly?” + +“You never loved him.” + +She hesitated. Her eyes fell on Jordan and me with a sort of appeal, +as though she realized at last what she was doing—and as though she +had never, all along, intended doing anything at all. But it was done +now. It was too late. + +“I never loved him,” she said, with perceptible reluctance. + +“Not at Kapiolani?” demanded Tom suddenly. + +“No.” + +From the ballroom beneath, muffled and suffocating chords were +drifting up on hot waves of air. + +“Not that day I carried you down from the Punch Bowl to keep your +shoes dry?” There was a husky tenderness in his tone … “Daisy?” + +“Please don’t.” Her voice was cold, but the rancour was gone from it. +She looked at Gatsby. “There, Jay,” she said—but her hand as she tried +to light a cigarette was trembling. Suddenly she threw the cigarette +and the burning match on the carpet. + +“Oh, you want too much!” she cried to Gatsby. “I love you now—isn’t +that enough? I can’t help what’s past.” She began to sob +helplessly. “I did love him once—but I loved you too.” + +Gatsby’s eyes opened and closed. + +“You loved me too?” he repeated. + +“Even that’s a lie,” said Tom savagely. “She didn’t know you were +alive. Why—there’s things between Daisy and me that you’ll never know, +things that neither of us can ever forget.” + +The words seemed to bite physically into Gatsby. + +“I want to speak to Daisy alone,” he insisted. “She’s all excited +now—” + +“Even alone I can’t say I never loved Tom,” she admitted in a pitiful +voice. “It wouldn’t be true.” + +“Of course it wouldn’t,” agreed Tom. + +She turned to her husband. + +“As if it mattered to you,” she said. + +“Of course it matters. I’m going to take better care of you from now +on.” + +“You don’t understand,” said Gatsby, with a touch of panic. “You’re +not going to take care of her any more.” + +“I’m not?” Tom opened his eyes wide and laughed. He could afford to +control himself now. “Why’s that?” + +“Daisy’s leaving you.” + +“Nonsense.” + +“I am, though,” she said with a visible effort. + +“She’s not leaving me!” Tom’s words suddenly leaned down over Gatsby. +“Certainly not for a common swindler who’d have to steal the ring he +put on her finger.” + +“I won’t stand this!” cried Daisy. “Oh, please let’s get out.” + +“Who are you, anyhow?” broke out Tom. “You’re one of that bunch that +hangs around with Meyer Wolfshiem—that much I happen to know. I’ve +made a little investigation into your affairs—and I’ll carry it +further tomorrow.” + +“You can suit yourself about that, old sport,” said Gatsby steadily. + +“I found out what your ‘drugstores’ were.” He turned to us and spoke +rapidly. “He and this Wolfshiem bought up a lot of side-street +drugstores here and in Chicago and sold grain alcohol over the +counter. That’s one of his little stunts. I picked him for a +bootlegger the first time I saw him, and I wasn’t far wrong.” + +“What about it?” said Gatsby politely. “I guess your friend Walter +Chase wasn’t too proud to come in on it.” + +“And you left him in the lurch, didn’t you? You let him go to jail for +a month over in New Jersey. God! You ought to hear Walter on the +subject of you.” + +“He came to us dead broke. He was very glad to pick up some money, old +sport.” + +“Don’t you call me ‘old sport’!” cried Tom. Gatsby said +nothing. “Walter could have you up on the betting laws too, but +Wolfshiem scared him into shutting his mouth.” + +That unfamiliar yet recognizable look was back again in Gatsby’s face. + +“That drugstore business was just small change,” continued Tom slowly, +“but you’ve got something on now that Walter’s afraid to tell me +about.” + +I glanced at Daisy, who was staring terrified between Gatsby and her +husband, and at Jordan, who had begun to balance an invisible but +absorbing object on the tip of her chin. Then I turned back to +Gatsby—and was startled at his expression. He looked—and this is said +in all contempt for the babbled slander of his garden—as if he had +“killed a man.” For a moment the set of his face could be described in +just that fantastic way. + +It passed, and he began to talk excitedly to Daisy, denying +everything, defending his name against accusations that had not been +made. But with every word she was drawing further and further into +herself, so he gave that up, and only the dead dream fought on as the +afternoon slipped away, trying to touch what was no longer tangible, +struggling unhappily, undespairingly, toward that lost voice across +the room. + +The voice begged again to go. + +“Please, Tom! I can’t stand this any more.” + +Her frightened eyes told that whatever intentions, whatever courage +she had had, were definitely gone. + +“You two start on home, Daisy,” said Tom. “In Mr. Gatsby’s car.” + +She looked at Tom, alarmed now, but he insisted with magnanimous +scorn. + +“Go on. He won’t annoy you. I think he realizes that his presumptuous +little flirtation is over.” + +They were gone, without a word, snapped out, made accidental, +isolated, like ghosts, even from our pity. + +After a moment Tom got up and began wrapping the unopened bottle of +whisky in the towel. + +“Want any of this stuff? Jordan? … Nick?” + +I didn’t answer. + +“Nick?” He asked again. + +“What?” + +“Want any?” + +“No … I just remembered that today’s my birthday.” + +I was thirty. Before me stretched the portentous, menacing road of a +new decade. + +It was seven o’clock when we got into the coupé with him and started +for Long Island. Tom talked incessantly, exulting and laughing, but +his voice was as remote from Jordan and me as the foreign clamour on +the sidewalk or the tumult of the elevated overhead. Human sympathy +has its limits, and we were content to let all their tragic arguments +fade with the city lights behind. Thirty—the promise of a decade of +loneliness, a thinning list of single men to know, a thinning +briefcase of enthusiasm, thinning hair. But there was Jordan beside +me, who, unlike Daisy, was too wise ever to carry well-forgotten +dreams from age to age. As we passed over the dark bridge her wan face +fell lazily against my coat’s shoulder and the formidable stroke of +thirty died away with the reassuring pressure of her hand. + +So we drove on toward death through the cooling twilight. + +------------------------------------------------------------------------ + +The young Greek, Michaelis, who ran the coffee joint beside the +ash-heaps was the principal witness at the inquest. He had slept +through the heat until after five, when he strolled over to the +garage, and found George Wilson sick in his office—really sick, pale +as his own pale hair and shaking all over. Michaelis advised him to go +to bed, but Wilson refused, saying that he’d miss a lot of business if +he did. While his neighbour was trying to persuade him a violent +racket broke out overhead. + +“I’ve got my wife locked in up there,” explained Wilson calmly. +“She’s going to stay there till the day after tomorrow, and then we’re +going to move away.” + +Michaelis was astonished; they had been neighbours for four years, and +Wilson had never seemed faintly capable of such a statement. +Generally he was one of these worn-out men: when he wasn’t working, he +sat on a chair in the doorway and stared at the people and the cars +that passed along the road. When anyone spoke to him he invariably +laughed in an agreeable, colourless way. He was his wife’s man and not +his own. + +So naturally Michaelis tried to find out what had happened, but Wilson +wouldn’t say a word—instead he began to throw curious, suspicious +glances at his visitor and ask him what he’d been doing at certain +times on certain days. Just as the latter was getting uneasy, some +workmen came past the door bound for his restaurant, and Michaelis +took the opportunity to get away, intending to come back later. But he +didn’t. He supposed he forgot to, that’s all. When he came outside +again, a little after seven, he was reminded of the conversation +because he heard Mrs. Wilson’s voice, loud and scolding, downstairs in +the garage. + +“Beat me!” he heard her cry. “Throw me down and beat me, you dirty +little coward!” + +A moment later she rushed out into the dusk, waving her hands and +shouting—before he could move from his door the business was over. + +The “death car” as the newspapers called it, didn’t stop; it came out +of the gathering darkness, wavered tragically for a moment, and then +disappeared around the next bend. Mavro Michaelis wasn’t even sure of +its colour—he told the first policeman that it was light green. The +other car, the one going toward New York, came to rest a hundred yards +beyond, and its driver hurried back to where Myrtle Wilson, her life +violently extinguished, knelt in the road and mingled her thick dark +blood with the dust. + +Michaelis and this man reached her first, but when they had torn open +her shirtwaist, still damp with perspiration, they saw that her left +breast was swinging loose like a flap, and there was no need to listen +for the heart beneath. The mouth was wide open and ripped a little at +the corners, as though she had choked a little in giving up the +tremendous vitality she had stored so long. + +------------------------------------------------------------------------ + +We saw the three or four automobiles and the crowd when we were still +some distance away. + +“Wreck!” said Tom. “That’s good. Wilson’ll have a little business at +last.” + +He slowed down, but still without any intention of stopping, until, as +we came nearer, the hushed, intent faces of the people at the garage +door made him automatically put on the brakes. + +“We’ll take a look,” he said doubtfully, “just a look.” + +I became aware now of a hollow, wailing sound which issued incessantly +from the garage, a sound which as we got out of the coupé and walked +toward the door resolved itself into the words “Oh, my God!” uttered +over and over in a gasping moan. + +“There’s some bad trouble here,” said Tom excitedly. + +He reached up on tiptoes and peered over a circle of heads into the +garage, which was lit only by a yellow light in a swinging metal +basket overhead. Then he made a harsh sound in his throat, and with a +violent thrusting movement of his powerful arms pushed his way +through. + +The circle closed up again with a running murmur of expostulation; it +was a minute before I could see anything at all. Then new arrivals +deranged the line, and Jordan and I were pushed suddenly inside. + +Myrtle Wilson’s body, wrapped in a blanket, and then in another +blanket, as though she suffered from a chill in the hot night, lay on +a worktable by the wall, and Tom, with his back to us, was bending +over it, motionless. Next to him stood a motorcycle policeman taking +down names with much sweat and correction in a little book. At first I +couldn’t find the source of the high, groaning words that echoed +clamorously through the bare garage—then I saw Wilson standing on the +raised threshold of his office, swaying back and forth and holding to +the doorposts with both hands. Some man was talking to him in a low +voice and attempting, from time to time, to lay a hand on his +shoulder, but Wilson neither heard nor saw. His eyes would drop slowly +from the swinging light to the laden table by the wall, and then jerk +back to the light again, and he gave out incessantly his high, +horrible call: + +“Oh, my Ga-od! Oh, my Ga-od! Oh, Ga-od! Oh, my Ga-od!” + +Presently Tom lifted his head with a jerk and, after staring around +the garage with glazed eyes, addressed a mumbled incoherent remark to +the policeman. + +“M-a-v—” the policeman was saying, “—o—” + +“No, r—” corrected the man, “M-a-v-r-o—” + +“Listen to me!” muttered Tom fiercely. + +“r—” said the policeman, “o—” + +“g—” + +“g—” He looked up as Tom’s broad hand fell sharply on his shoulder. +“What you want, fella?” + +“What happened?—that’s what I want to know.” + +“Auto hit her. Ins’antly killed.” + +“Instantly killed,” repeated Tom, staring. + +“She ran out ina road. Son-of-a-bitch didn’t even stopus car.” + +“There was two cars,” said Michaelis, “one comin’, one goin’, see?” + +“Going where?” asked the policeman keenly. + +“One goin’ each way. Well, she”—his hand rose toward the blankets but +stopped halfway and fell to his side—“she ran out there an’ the one +comin’ from N’York knock right into her, goin’ thirty or forty miles +an hour.” + +“What’s the name of this place here?” demanded the officer. + +“Hasn’t got any name.” + +A pale well-dressed negro stepped near. + +“It was a yellow car,” he said, “big yellow car. New.” + +“See the accident?” asked the policeman. + +“No, but the car passed me down the road, going faster’n forty. Going +fifty, sixty.” + +“Come here and let’s have your name. Look out now. I want to get his +name.” + +Some words of this conversation must have reached Wilson, swaying in +the office door, for suddenly a new theme found voice among his +grasping cries: + +“You don’t have to tell me what kind of car it was! I know what kind +of car it was!” + +Watching Tom, I saw the wad of muscle back of his shoulder tighten +under his coat. He walked quickly over to Wilson and, standing in +front of him, seized him firmly by the upper arms. + +“You’ve got to pull yourself together,” he said with soothing +gruffness. + +Wilson’s eyes fell upon Tom; he started up on his tiptoes and then +would have collapsed to his knees had not Tom held him upright. + +“Listen,” said Tom, shaking him a little. “I just got here a minute +ago, from New York. I was bringing you that coupé we’ve been talking +about. That yellow car I was driving this afternoon wasn’t mine—do you +hear? I haven’t seen it all afternoon.” + +Only the negro and I were near enough to hear what he said, but the +policeman caught something in the tone and looked over with truculent +eyes. + +“What’s all that?” he demanded. + +“I’m a friend of his.” Tom turned his head but kept his hands firm on +Wilson’s body. “He says he knows the car that did it … It was a yellow +car.” + +Some dim impulse moved the policeman to look suspiciously at Tom. + +“And what colour’s your car?” + +“It’s a blue car, a coupé.” + +“We’ve come straight from New York,” I said. + +Someone who had been driving a little behind us confirmed this, and +the policeman turned away. + +“Now, if you’ll let me have that name again correct—” + +Picking up Wilson like a doll, Tom carried him into the office, set +him down in a chair, and came back. + +“If somebody’ll come here and sit with him,” he snapped +authoritatively. He watched while the two men standing closest glanced +at each other and went unwillingly into the room. Then Tom shut the +door on them and came down the single step, his eyes avoiding the +table. As he passed close to me he whispered: “Let’s get out.” + +Self-consciously, with his authoritative arms breaking the way, we +pushed through the still gathering crowd, passing a hurried doctor, +case in hand, who had been sent for in wild hope half an hour ago. + +Tom drove slowly until we were beyond the bend—then his foot came down +hard, and the coupé raced along through the night. In a little while I +heard a low husky sob, and saw that the tears were overflowing down +his face. + +“The God damned coward!” he whimpered. “He didn’t even stop his car.” + +------------------------------------------------------------------------ + +The Buchanans’ house floated suddenly toward us through the dark +rustling trees. Tom stopped beside the porch and looked up at the +second floor, where two windows bloomed with light among the vines. + +“Daisy’s home,” he said. As we got out of the car he glanced at me and +frowned slightly. + +“I ought to have dropped you in West Egg, Nick. There’s nothing we can +do tonight.” + +A change had come over him, and he spoke gravely, and with decision. +As we walked across the moonlight gravel to the porch he disposed of +the situation in a few brisk phrases. + +“I’ll telephone for a taxi to take you home, and while you’re waiting +you and Jordan better go in the kitchen and have them get you some +supper—if you want any.” He opened the door. “Come in.” + +“No, thanks. But I’d be glad if you’d order me the taxi. I’ll wait +outside.” + +Jordan put her hand on my arm. + +“Won’t you come in, Nick?” + +“No, thanks.” + +I was feeling a little sick and I wanted to be alone. But Jordan +lingered for a moment more. + +“It’s only half-past nine,” she said. + +I’d be damned if I’d go in; I’d had enough of all of them for one day, +and suddenly that included Jordan too. She must have seen something of +this in my expression, for she turned abruptly away and ran up the +porch steps into the house. I sat down for a few minutes with my head +in my hands, until I heard the phone taken up inside and the butler’s +voice calling a taxi. Then I walked slowly down the drive away from +the house, intending to wait by the gate. + +I hadn’t gone twenty yards when I heard my name and Gatsby stepped +from between two bushes into the path. I must have felt pretty weird +by that time, because I could think of nothing except the luminosity +of his pink suit under the moon. + +“What are you doing?” I inquired. + +“Just standing here, old sport.” + +Somehow, that seemed a despicable occupation. For all I knew he was +going to rob the house in a moment; I wouldn’t have been surprised to +see sinister faces, the faces of “Wolfshiem’s people,” behind him in +the dark shrubbery. + +“Did you see any trouble on the road?” he asked after a minute. + +“Yes.” + +He hesitated. + +“Was she killed?” + +“Yes.” + +“I thought so; I told Daisy I thought so. It’s better that the shock +should all come at once. She stood it pretty well.” + +He spoke as if Daisy’s reaction was the only thing that mattered. + +“I got to West Egg by a side road,” he went on, “and left the car in +my garage. I don’t think anybody saw us, but of course I can’t be +sure.” + +I disliked him so much by this time that I didn’t find it necessary to +tell him he was wrong. + +“Who was the woman?” he inquired. + +“Her name was Wilson. Her husband owns the garage. How the devil did +it happen?” + +“Well, I tried to swing the wheel—” He broke off, and suddenly I +guessed at the truth. + +“Was Daisy driving?” + +“Yes,” he said after a moment, “but of course I’ll say I was. You see, +when we left New York she was very nervous and she thought it would +steady her to drive—and this woman rushed out at us just as we were +passing a car coming the other way. It all happened in a minute, but +it seemed to me that she wanted to speak to us, thought we were +somebody she knew. Well, first Daisy turned away from the woman toward +the other car, and then she lost her nerve and turned back. The second +my hand reached the wheel I felt the shock—it must have killed her +instantly.” + +“It ripped her open—” + +“Don’t tell me, old sport.” He winced. “Anyhow—Daisy stepped on it. I +tried to make her stop, but she couldn’t, so I pulled on the emergency +brake. Then she fell over into my lap and I drove on. + +“She’ll be all right tomorrow,” he said presently. “I’m just going to +wait here and see if he tries to bother her about that unpleasantness +this afternoon. She’s locked herself into her room, and if he tries +any brutality she’s going to turn the light out and on again.” + +“He won’t touch her,” I said. “He’s not thinking about her.” + +“I don’t trust him, old sport.” + +“How long are you going to wait?” + +“All night, if necessary. Anyhow, till they all go to bed.” + +A new point of view occurred to me. Suppose Tom found out that Daisy +had been driving. He might think he saw a connection in it—he might +think anything. I looked at the house; there were two or three bright +windows downstairs and the pink glow from Daisy’s room on the ground +floor. + +“You wait here,” I said. “I’ll see if there’s any sign of a +commotion.” + +I walked back along the border of the lawn, traversed the gravel +softly, and tiptoed up the veranda steps. The drawing-room curtains +were open, and I saw that the room was empty. Crossing the porch where +we had dined that June night three months before, I came to a small +rectangle of light which I guessed was the pantry window. The blind +was drawn, but I found a rift at the sill. + +Daisy and Tom were sitting opposite each other at the kitchen table, +with a plate of cold fried chicken between them, and two bottles of +ale. He was talking intently across the table at her, and in his +earnestness his hand had fallen upon and covered her own. Once in a +while she looked up at him and nodded in agreement. + +They weren’t happy, and neither of them had touched the chicken or the +ale—and yet they weren’t unhappy either. There was an unmistakable air +of natural intimacy about the picture, and anybody would have said +that they were conspiring together. + +As I tiptoed from the porch I heard my taxi feeling its way along the +dark road toward the house. Gatsby was waiting where I had left him in +the drive. + +“Is it all quiet up there?” he asked anxiously. + +“Yes, it’s all quiet.” I hesitated. “You’d better come home and get +some sleep.” + +He shook his head. + +“I want to wait here till Daisy goes to bed. Good night, old sport.” + +He put his hands in his coat pockets and turned back eagerly to his +scrutiny of the house, as though my presence marred the sacredness of +the vigil. So I walked away and left him standing there in the +moonlight—watching over nothing. + + + VIII + +I couldn’t sleep all night; a foghorn was groaning incessantly on the +Sound, and I tossed half-sick between grotesque reality and savage, +frightening dreams. Toward dawn I heard a taxi go up Gatsby’s drive, +and immediately I jumped out of bed and began to dress—I felt that I +had something to tell him, something to warn him about, and morning +would be too late. + +Crossing his lawn, I saw that his front door was still open and he was +leaning against a table in the hall, heavy with dejection or sleep. + +“Nothing happened,” he said wanly. “I waited, and about four o’clock +she came to the window and stood there for a minute and then turned +out the light.” + +His house had never seemed so enormous to me as it did that night when +we hunted through the great rooms for cigarettes. We pushed aside +curtains that were like pavilions, and felt over innumerable feet of +dark wall for electric light switches—once I tumbled with a sort of +splash upon the keys of a ghostly piano. There was an inexplicable +amount of dust everywhere, and the rooms were musty, as though they +hadn’t been aired for many days. I found the humidor on an unfamiliar +table, with two stale, dry cigarettes inside. Throwing open the French +windows of the drawing-room, we sat smoking out into the darkness. + +“You ought to go away,” I said. “It’s pretty certain they’ll trace +your car.” + +“Go away now, old sport?” + +“Go to Atlantic City for a week, or up to Montreal.” + +He wouldn’t consider it. He couldn’t possibly leave Daisy until he +knew what she was going to do. He was clutching at some last hope and +I couldn’t bear to shake him free. + +It was this night that he told me the strange story of his youth with +Dan Cody—told it to me because “Jay Gatsby” had broken up like glass +against Tom’s hard malice, and the long secret extravaganza was played +out. I think that he would have acknowledged anything now, without +reserve, but he wanted to talk about Daisy. + +She was the first “nice” girl he had ever known. In various unrevealed +capacities he had come in contact with such people, but always with +indiscernible barbed wire between. He found her excitingly +desirable. He went to her house, at first with other officers from +Camp Taylor, then alone. It amazed him—he had never been in such a +beautiful house before. But what gave it an air of breathless +intensity, was that Daisy lived there—it was as casual a thing to her +as his tent out at camp was to him. There was a ripe mystery about it, +a hint of bedrooms upstairs more beautiful and cool than other +bedrooms, of gay and radiant activities taking place through its +corridors, and of romances that were not musty and laid away already +in lavender but fresh and breathing and redolent of this year’s +shining motorcars and of dances whose flowers were scarcely +withered. It excited him, too, that many men had already loved +Daisy—it increased her value in his eyes. He felt their presence all +about the house, pervading the air with the shades and echoes of still +vibrant emotions. + +But he knew that he was in Daisy’s house by a colossal +accident. However glorious might be his future as Jay Gatsby, he was +at present a penniless young man without a past, and at any moment the +invisible cloak of his uniform might slip from his shoulders. So he +made the most of his time. He took what he could get, ravenously and +unscrupulously—eventually he took Daisy one still October night, took +her because he had no real right to touch her hand. + +He might have despised himself, for he had certainly taken her under +false pretences. I don’t mean that he had traded on his phantom +millions, but he had deliberately given Daisy a sense of security; he +let her believe that he was a person from much the same strata as +herself—that he was fully able to take care of her. As a matter of +fact, he had no such facilities—he had no comfortable family standing +behind him, and he was liable at the whim of an impersonal government +to be blown anywhere about the world. + +But he didn’t despise himself and it didn’t turn out as he had +imagined. He had intended, probably, to take what he could and go—but +now he found that he had committed himself to the following of a +grail. He knew that Daisy was extraordinary, but he didn’t realize +just how extraordinary a “nice” girl could be. She vanished into her +rich house, into her rich, full life, leaving Gatsby—nothing. He felt +married to her, that was all. + +When they met again, two days later, it was Gatsby who was breathless, +who was, somehow, betrayed. Her porch was bright with the bought +luxury of star-shine; the wicker of the settee squeaked fashionably as +she turned toward him and he kissed her curious and lovely mouth. She +had caught a cold, and it made her voice huskier and more charming +than ever, and Gatsby was overwhelmingly aware of the youth and +mystery that wealth imprisons and preserves, of the freshness of many +clothes, and of Daisy, gleaming like silver, safe and proud above the +hot struggles of the poor. + +------------------------------------------------------------------------ + +“I can’t describe to you how surprised I was to find out I loved her, +old sport. I even hoped for a while that she’d throw me over, but she +didn’t, because she was in love with me too. She thought I knew a lot +because I knew different things from her … Well, there I was, way off +my ambitions, getting deeper in love every minute, and all of a sudden +I didn’t care. What was the use of doing great things if I could have +a better time telling her what I was going to do?” + +On the last afternoon before he went abroad, he sat with Daisy in his +arms for a long, silent time. It was a cold fall day, with fire in the +room and her cheeks flushed. Now and then she moved and he changed his +arm a little, and once he kissed her dark shining hair. The afternoon +had made them tranquil for a while, as if to give them a deep memory +for the long parting the next day promised. They had never been closer +in their month of love, nor communicated more profoundly one with +another, than when she brushed silent lips against his coat’s shoulder +or when he touched the end of her fingers, gently, as though she were +asleep. + +------------------------------------------------------------------------ + +He did extraordinarily well in the war. He was a captain before he +went to the front, and following the Argonne battles he got his +majority and the command of the divisional machine-guns. After the +armistice he tried frantically to get home, but some complication or +misunderstanding sent him to Oxford instead. He was worried now—there +was a quality of nervous despair in Daisy’s letters. She didn’t see +why he couldn’t come. She was feeling the pressure of the world +outside, and she wanted to see him and feel his presence beside her +and be reassured that she was doing the right thing after all. + +For Daisy was young and her artificial world was redolent of orchids +and pleasant, cheerful snobbery and orchestras which set the rhythm of +the year, summing up the sadness and suggestiveness of life in new +tunes. All night the saxophones wailed the hopeless comment of the +“Beale Street Blues” while a hundred pairs of golden and silver +slippers shuffled the shining dust. At the grey tea hour there were +always rooms that throbbed incessantly with this low, sweet fever, +while fresh faces drifted here and there like rose petals blown by the +sad horns around the floor. + +Through this twilight universe Daisy began to move again with the +season; suddenly she was again keeping half a dozen dates a day with +half a dozen men, and drowsing asleep at dawn with the beads and +chiffon of an evening-dress tangled among dying orchids on the floor +beside her bed. And all the time something within her was crying for a +decision. She wanted her life shaped now, immediately—and the decision +must be made by some force—of love, of money, of unquestionable +practicality—that was close at hand. + +That force took shape in the middle of spring with the arrival of Tom +Buchanan. There was a wholesome bulkiness about his person and his +position, and Daisy was flattered. Doubtless there was a certain +struggle and a certain relief. The letter reached Gatsby while he was +still at Oxford. + +------------------------------------------------------------------------ + +It was dawn now on Long Island and we went about opening the rest of +the windows downstairs, filling the house with grey-turning, +gold-turning light. The shadow of a tree fell abruptly across the dew +and ghostly birds began to sing among the blue leaves. There was a +slow, pleasant movement in the air, scarcely a wind, promising a cool, +lovely day. + +“I don’t think she ever loved him.” Gatsby turned around from a window +and looked at me challengingly. “You must remember, old sport, she was +very excited this afternoon. He told her those things in a way that +frightened her—that made it look as if I was some kind of cheap +sharper. And the result was she hardly knew what she was saying.” + +He sat down gloomily. + +“Of course she might have loved him just for a minute, when they were +first married—and loved me more even then, do you see?” + +Suddenly he came out with a curious remark. + +“In any case,” he said, “it was just personal.” + +What could you make of that, except to suspect some intensity in his +conception of the affair that couldn’t be measured? + +He came back from France when Tom and Daisy were still on their +wedding trip, and made a miserable but irresistible journey to +Louisville on the last of his army pay. He stayed there a week, +walking the streets where their footsteps had clicked together through +the November night and revisiting the out-of-the-way places to which +they had driven in her white car. Just as Daisy’s house had always +seemed to him more mysterious and gay than other houses, so his idea +of the city itself, even though she was gone from it, was pervaded +with a melancholy beauty. + +He left feeling that if he had searched harder, he might have found +her—that he was leaving her behind. The day-coach—he was penniless +now—was hot. He went out to the open vestibule and sat down on a +folding-chair, and the station slid away and the backs of unfamiliar +buildings moved by. Then out into the spring fields, where a yellow +trolley raced them for a minute with people in it who might once have +seen the pale magic of her face along the casual street. + +The track curved and now it was going away from the sun, which, as it +sank lower, seemed to spread itself in benediction over the vanishing +city where she had drawn her breath. He stretched out his hand +desperately as if to snatch only a wisp of air, to save a fragment of +the spot that she had made lovely for him. But it was all going by too +fast now for his blurred eyes and he knew that he had lost that part +of it, the freshest and the best, forever. + +It was nine o’clock when we finished breakfast and went out on the +porch. The night had made a sharp difference in the weather and there +was an autumn flavour in the air. The gardener, the last one of +Gatsby’s former servants, came to the foot of the steps. + +“I’m going to drain the pool today, Mr. Gatsby. Leaves’ll start +falling pretty soon, and then there’s always trouble with the pipes.” + +“Don’t do it today,” Gatsby answered. He turned to me apologetically. +“You know, old sport, I’ve never used that pool all summer?” + +I looked at my watch and stood up. + +“Twelve minutes to my train.” + +I didn’t want to go to the city. I wasn’t worth a decent stroke of +work, but it was more than that—I didn’t want to leave Gatsby. I +missed that train, and then another, before I could get myself away. + +“I’ll call you up,” I said finally. + +“Do, old sport.” + +“I’ll call you about noon.” + +We walked slowly down the steps. + +“I suppose Daisy’ll call too.” He looked at me anxiously, as if he +hoped I’d corroborate this. + +“I suppose so.” + +“Well, goodbye.” + +We shook hands and I started away. Just before I reached the hedge I +remembered something and turned around. + +“They’re a rotten crowd,” I shouted across the lawn. “You’re worth the +whole damn bunch put together.” + +I’ve always been glad I said that. It was the only compliment I ever +gave him, because I disapproved of him from beginning to end. First he +nodded politely, and then his face broke into that radiant and +understanding smile, as if we’d been in ecstatic cahoots on that fact +all the time. His gorgeous pink rag of a suit made a bright spot of +colour against the white steps, and I thought of the night when I +first came to his ancestral home, three months before. The lawn and +drive had been crowded with the faces of those who guessed at his +corruption—and he had stood on those steps, concealing his +incorruptible dream, as he waved them goodbye. + +I thanked him for his hospitality. We were always thanking him for +that—I and the others. + +“Goodbye,” I called. “I enjoyed breakfast, Gatsby.” + +------------------------------------------------------------------------ + +Up in the city, I tried for a while to list the quotations on an +interminable amount of stock, then I fell asleep in my swivel-chair. +Just before noon the phone woke me, and I started up with sweat +breaking out on my forehead. It was Jordan Baker; she often called me +up at this hour because the uncertainty of her own movements between +hotels and clubs and private houses made her hard to find in any other +way. Usually her voice came over the wire as something fresh and cool, +as if a divot from a green golf-links had come sailing in at the +office window, but this morning it seemed harsh and dry. + +“I’ve left Daisy’s house,” she said. “I’m at Hempstead, and I’m going +down to Southampton this afternoon.” + +Probably it had been tactful to leave Daisy’s house, but the act +annoyed me, and her next remark made me rigid. + +“You weren’t so nice to me last night.” + +“How could it have mattered then?” + +Silence for a moment. Then: + +“However—I want to see you.” + +“I want to see you, too.” + +“Suppose I don’t go to Southampton, and come into town this +afternoon?” + +“No—I don’t think this afternoon.” + +“Very well.” + +“It’s impossible this afternoon. Various—” + +We talked like that for a while, and then abruptly we weren’t talking +any longer. I don’t know which of us hung up with a sharp click, but I +know I didn’t care. I couldn’t have talked to her across a tea-table +that day if I never talked to her again in this world. + +I called Gatsby’s house a few minutes later, but the line was busy. I +tried four times; finally an exasperated central told me the wire was +being kept open for long distance from Detroit. Taking out my +timetable, I drew a small circle around the three-fifty train. Then I +leaned back in my chair and tried to think. It was just noon. + +------------------------------------------------------------------------ + +When I passed the ash-heaps on the train that morning I had crossed +deliberately to the other side of the car. I supposed there’d be a +curious crowd around there all day with little boys searching for dark +spots in the dust, and some garrulous man telling over and over what +had happened, until it became less and less real even to him and he +could tell it no longer, and Myrtle Wilson’s tragic achievement was +forgotten. Now I want to go back a little and tell what happened at +the garage after we left there the night before. + +They had difficulty in locating the sister, Catherine. She must have +broken her rule against drinking that night, for when she arrived she +was stupid with liquor and unable to understand that the ambulance had +already gone to Flushing. When they convinced her of this, she +immediately fainted, as if that was the intolerable part of the +affair. Someone, kind or curious, took her in his car and drove her in +the wake of her sister’s body. + +Until long after midnight a changing crowd lapped up against the front +of the garage, while George Wilson rocked himself back and forth on +the couch inside. For a while the door of the office was open, and +everyone who came into the garage glanced irresistibly through it. +Finally someone said it was a shame, and closed the door. Michaelis +and several other men were with him; first, four or five men, later +two or three men. Still later Michaelis had to ask the last stranger +to wait there fifteen minutes longer, while he went back to his own +place and made a pot of coffee. After that, he stayed there alone with +Wilson until dawn. + +About three o’clock the quality of Wilson’s incoherent muttering +changed—he grew quieter and began to talk about the yellow car. He +announced that he had a way of finding out whom the yellow car +belonged to, and then he blurted out that a couple of months ago his +wife had come from the city with her face bruised and her nose +swollen. + +But when he heard himself say this, he flinched and began to cry “Oh, +my God!” again in his groaning voice. Michaelis made a clumsy attempt +to distract him. + +“How long have you been married, George? Come on there, try and sit +still a minute, and answer my question. How long have you been +married?” + +“Twelve years.” + +“Ever had any children? Come on, George, sit still—I asked you a +question. Did you ever have any children?” + +The hard brown beetles kept thudding against the dull light, and +whenever Michaelis heard a car go tearing along the road outside it +sounded to him like the car that hadn’t stopped a few hours before. +He didn’t like to go into the garage, because the work bench was +stained where the body had been lying, so he moved uncomfortably +around the office—he knew every object in it before morning—and from +time to time sat down beside Wilson trying to keep him more quiet. + +“Have you got a church you go to sometimes, George? Maybe even if you +haven’t been there for a long time? Maybe I could call up the church +and get a priest to come over and he could talk to you, see?” + +“Don’t belong to any.” + +“You ought to have a church, George, for times like this. You must +have gone to church once. Didn’t you get married in a church? Listen, +George, listen to me. Didn’t you get married in a church?” + +“That was a long time ago.” + +The effort of answering broke the rhythm of his rocking—for a moment +he was silent. Then the same half-knowing, half-bewildered look came +back into his faded eyes. + +“Look in the drawer there,” he said, pointing at the desk. + +“Which drawer?” + +“That drawer—that one.” + +Michaelis opened the drawer nearest his hand. There was nothing in it +but a small, expensive dog-leash, made of leather and braided +silver. It was apparently new. + +“This?” he inquired, holding it up. + +Wilson stared and nodded. + +“I found it yesterday afternoon. She tried to tell me about it, but I +knew it was something funny.” + +“You mean your wife bought it?” + +“She had it wrapped in tissue paper on her bureau.” + +Michaelis didn’t see anything odd in that, and he gave Wilson a dozen +reasons why his wife might have bought the dog-leash. But conceivably +Wilson had heard some of these same explanations before, from Myrtle, +because he began saying “Oh, my God!” again in a whisper—his comforter +left several explanations in the air. + +“Then he killed her,” said Wilson. His mouth dropped open suddenly. + +“Who did?” + +“I have a way of finding out.” + +“You’re morbid, George,” said his friend. “This has been a strain to +you and you don’t know what you’re saying. You’d better try and sit +quiet till morning.” + +“He murdered her.” + +“It was an accident, George.” + +Wilson shook his head. His eyes narrowed and his mouth widened +slightly with the ghost of a superior “Hm!” + +“I know,” he said definitely. “I’m one of these trusting fellas and I +don’t think any harm to nobody, but when I get to know a thing I know +it. It was the man in that car. She ran out to speak to him and he +wouldn’t stop.” + +Michaelis had seen this too, but it hadn’t occurred to him that there +was any special significance in it. He believed that Mrs. Wilson had +been running away from her husband, rather than trying to stop any +particular car. + +“How could she of been like that?” + +“She’s a deep one,” said Wilson, as if that answered the question. +“Ah-h-h—” + +He began to rock again, and Michaelis stood twisting the leash in his +hand. + +“Maybe you got some friend that I could telephone for, George?” + +This was a forlorn hope—he was almost sure that Wilson had no friend: +there was not enough of him for his wife. He was glad a little later +when he noticed a change in the room, a blue quickening by the window, +and realized that dawn wasn’t far off. About five o’clock it was blue +enough outside to snap off the light. + +Wilson’s glazed eyes turned out to the ash-heaps, where small grey +clouds took on fantastic shapes and scurried here and there in the +faint dawn wind. + +“I spoke to her,” he muttered, after a long silence. “I told her she +might fool me but she couldn’t fool God. I took her to the +window”—with an effort he got up and walked to the rear window and +leaned with his face pressed against it—“and I said ‘God knows what +you’ve been doing, everything you’ve been doing. You may fool me, but +you can’t fool God!’ ” + +Standing behind him, Michaelis saw with a shock that he was looking at +the eyes of Doctor T. J. Eckleburg, which had just emerged, pale and +enormous, from the dissolving night. + +“God sees everything,” repeated Wilson. + +“That’s an advertisement,” Michaelis assured him. Something made him +turn away from the window and look back into the room. But Wilson +stood there a long time, his face close to the window pane, nodding +into the twilight. + +------------------------------------------------------------------------ + +By six o’clock Michaelis was worn out, and grateful for the sound of a +car stopping outside. It was one of the watchers of the night before +who had promised to come back, so he cooked breakfast for three, which +he and the other man ate together. Wilson was quieter now, and +Michaelis went home to sleep; when he awoke four hours later and +hurried back to the garage, Wilson was gone. + +His movements—he was on foot all the time—were afterward traced to +Port Roosevelt and then to Gad’s Hill, where he bought a sandwich that +he didn’t eat, and a cup of coffee. He must have been tired and +walking slowly, for he didn’t reach Gad’s Hill until noon. Thus far +there was no difficulty in accounting for his time—there were boys who +had seen a man “acting sort of crazy,” and motorists at whom he stared +oddly from the side of the road. Then for three hours he disappeared +from view. The police, on the strength of what he said to Michaelis, +that he “had a way of finding out,” supposed that he spent that time +going from garage to garage thereabout, inquiring for a yellow car. On +the other hand, no garage man who had seen him ever came forward, and +perhaps he had an easier, surer way of finding out what he wanted to +know. By half-past two he was in West Egg, where he asked someone the +way to Gatsby’s house. So by that time he knew Gatsby’s name. + +------------------------------------------------------------------------ + +At two o’clock Gatsby put on his bathing-suit and left word with the +butler that if anyone phoned word was to be brought to him at the +pool. He stopped at the garage for a pneumatic mattress that had +amused his guests during the summer, and the chauffeur helped him to +pump it up. Then he gave instructions that the open car wasn’t to be +taken out under any circumstances—and this was strange, because the +front right fender needed repair. + +Gatsby shouldered the mattress and started for the pool. Once he +stopped and shifted it a little, and the chauffeur asked him if he +needed help, but he shook his head and in a moment disappeared among +the yellowing trees. + +No telephone message arrived, but the butler went without his sleep +and waited for it until four o’clock—until long after there was anyone +to give it to if it came. I have an idea that Gatsby himself didn’t +believe it would come, and perhaps he no longer cared. If that was +true he must have felt that he had lost the old warm world, paid a +high price for living too long with a single dream. He must have +looked up at an unfamiliar sky through frightening leaves and shivered +as he found what a grotesque thing a rose is and how raw the sunlight +was upon the scarcely created grass. A new world, material without +being real, where poor ghosts, breathing dreams like air, drifted +fortuitously about … like that ashen, fantastic figure gliding toward +him through the amorphous trees. + +The chauffeur—he was one of Wolfshiem’s protégés—heard the +shots—afterwards he could only say that he hadn’t thought anything +much about them. I drove from the station directly to Gatsby’s house +and my rushing anxiously up the front steps was the first thing that +alarmed anyone. But they knew then, I firmly believe. With scarcely a +word said, four of us, the chauffeur, butler, gardener, and I hurried +down to the pool. + +There was a faint, barely perceptible movement of the water as the +fresh flow from one end urged its way toward the drain at the other. +With little ripples that were hardly the shadows of waves, the laden +mattress moved irregularly down the pool. A small gust of wind that +scarcely corrugated the surface was enough to disturb its accidental +course with its accidental burden. The touch of a cluster of leaves +revolved it slowly, tracing, like the leg of transit, a thin red +circle in the water. + +It was after we started with Gatsby toward the house that the gardener +saw Wilson’s body a little way off in the grass, and the holocaust was +complete. + + + IX + +After two years I remember the rest of that day, and that night and +the next day, only as an endless drill of police and photographers and +newspaper men in and out of Gatsby’s front door. A rope stretched +across the main gate and a policeman by it kept out the curious, but +little boys soon discovered that they could enter through my yard, and +there were always a few of them clustered open-mouthed about the +pool. Someone with a positive manner, perhaps a detective, used the +expression “madman” as he bent over Wilson’s body that afternoon, and +the adventitious authority of his voice set the key for the newspaper +reports next morning. + +Most of those reports were a nightmare—grotesque, circumstantial, +eager, and untrue. When Michaelis’s testimony at the inquest brought +to light Wilson’s suspicions of his wife I thought the whole tale +would shortly be served up in racy pasquinade—but Catherine, who might +have said anything, didn’t say a word. She showed a surprising amount +of character about it too—looked at the coroner with determined eyes +under that corrected brow of hers, and swore that her sister had never +seen Gatsby, that her sister was completely happy with her husband, +that her sister had been into no mischief whatever. She convinced +herself of it, and cried into her handkerchief, as if the very +suggestion was more than she could endure. So Wilson was reduced to a +man “deranged by grief” in order that the case might remain in its +simplest form. And it rested there. + +But all this part of it seemed remote and unessential. I found myself +on Gatsby’s side, and alone. From the moment I telephoned news of the +catastrophe to West Egg village, every surmise about him, and every +practical question, was referred to me. At first I was surprised and +confused; then, as he lay in his house and didn’t move or breathe or +speak, hour upon hour, it grew upon me that I was responsible, because +no one else was interested—interested, I mean, with that intense +personal interest to which everyone has some vague right at the end. + +I called up Daisy half an hour after we found him, called her +instinctively and without hesitation. But she and Tom had gone away +early that afternoon, and taken baggage with them. + +“Left no address?” + +“No.” + +“Say when they’d be back?” + +“No.” + +“Any idea where they are? How I could reach them?” + +“I don’t know. Can’t say.” + +I wanted to get somebody for him. I wanted to go into the room where +he lay and reassure him: “I’ll get somebody for you, Gatsby. Don’t +worry. Just trust me and I’ll get somebody for you—” + +Meyer Wolfshiem’s name wasn’t in the phone book. The butler gave me +his office address on Broadway, and I called Information, but by the +time I had the number it was long after five, and no one answered the +phone. + +“Will you ring again?” + +“I’ve rung three times.” + +“It’s very important.” + +“Sorry. I’m afraid no one’s there.” + +I went back to the drawing-room and thought for an instant that they +were chance visitors, all these official people who suddenly filled +it. But, though they drew back the sheet and looked at Gatsby with +shocked eyes, his protest continued in my brain: + +“Look here, old sport, you’ve got to get somebody for me. You’ve got +to try hard. I can’t go through this alone.” + +Someone started to ask me questions, but I broke away and going +upstairs looked hastily through the unlocked parts of his desk—he’d +never told me definitely that his parents were dead. But there was +nothing—only the picture of Dan Cody, a token of forgotten violence, +staring down from the wall. + +Next morning I sent the butler to New York with a letter to Wolfshiem, +which asked for information and urged him to come out on the next +train. That request seemed superfluous when I wrote it. I was sure +he’d start when he saw the newspapers, just as I was sure there’d be a +wire from Daisy before noon—but neither a wire nor Mr. Wolfshiem +arrived; no one arrived except more police and photographers and +newspaper men. When the butler brought back Wolfshiem’s answer I began +to have a feeling of defiance, of scornful solidarity between Gatsby +and me against them all. + + Dear Mr. Carraway. This has been one of the most terrible shocks of + my life to me I hardly can believe it that it is true at all. Such a + mad act as that man did should make us all think. I cannot come down + now as I am tied up in some very important business and cannot get + mixed up in this thing now. If there is anything I can do a little + later let me know in a letter by Edgar. I hardly know where I am when + I hear about a thing like this and am completely knocked down and + out. + + Yours truly + + Meyer Wolfshiem + +and then hasty addenda beneath: + + Let me know about the funeral etc do not know his family at all. + +When the phone rang that afternoon and Long Distance said Chicago was +calling I thought this would be Daisy at last. But the connection came +through as a man’s voice, very thin and far away. + +“This is Slagle speaking …” + +“Yes?” The name was unfamiliar. + +“Hell of a note, isn’t it? Get my wire?” + +“There haven’t been any wires.” + +“Young Parke’s in trouble,” he said rapidly. “They picked him up when +he handed the bonds over the counter. They got a circular from New +York giving ’em the numbers just five minutes before. What d’you know +about that, hey? You never can tell in these hick towns—” + +“Hello!” I interrupted breathlessly. “Look here—this isn’t Mr. +Gatsby. Mr. Gatsby’s dead.” + +There was a long silence on the other end of the wire, followed by an +exclamation … then a quick squawk as the connection was broken. + +------------------------------------------------------------------------ + +I think it was on the third day that a telegram signed Henry C. Gatz +arrived from a town in Minnesota. It said only that the sender was +leaving immediately and to postpone the funeral until he came. + +It was Gatsby’s father, a solemn old man, very helpless and dismayed, +bundled up in a long cheap ulster against the warm September day. His +eyes leaked continuously with excitement, and when I took the bag and +umbrella from his hands he began to pull so incessantly at his sparse +grey beard that I had difficulty in getting off his coat. He was on +the point of collapse, so I took him into the music-room and made him +sit down while I sent for something to eat. But he wouldn’t eat, and +the glass of milk spilled from his trembling hand. + +“I saw it in the Chicago newspaper,” he said. “It was all in the +Chicago newspaper. I started right away.” + +“I didn’t know how to reach you.” + +His eyes, seeing nothing, moved ceaselessly about the room. + +“It was a madman,” he said. “He must have been mad.” + +“Wouldn’t you like some coffee?” I urged him. + +“I don’t want anything. I’m all right now, Mr.—” + +“Carraway.” + +“Well, I’m all right now. Where have they got Jimmy?” + +I took him into the drawing-room, where his son lay, and left him +there. Some little boys had come up on the steps and were looking into +the hall; when I told them who had arrived, they went reluctantly +away. + +After a little while Mr. Gatz opened the door and came out, his mouth +ajar, his face flushed slightly, his eyes leaking isolated and +unpunctual tears. He had reached an age where death no longer has the +quality of ghastly surprise, and when he looked around him now for the +first time and saw the height and splendour of the hall and the great +rooms opening out from it into other rooms, his grief began to be +mixed with an awed pride. I helped him to a bedroom upstairs; while he +took off his coat and vest I told him that all arrangements had been +deferred until he came. + +“I didn’t know what you’d want, Mr. Gatsby—” + +“Gatz is my name.” + +“—Mr. Gatz. I thought you might want to take the body West.” + +He shook his head. + +“Jimmy always liked it better down East. He rose up to his position in +the East. Were you a friend of my boy’s, Mr.—?” + +“We were close friends.” + +“He had a big future before him, you know. He was only a young man, +but he had a lot of brain power here.” + +He touched his head impressively, and I nodded. + +“If he’d of lived, he’d of been a great man. A man like James J. +Hill. He’d of helped build up the country.” + +“That’s true,” I said, uncomfortably. + +He fumbled at the embroidered coverlet, trying to take it from the +bed, and lay down stiffly—was instantly asleep. + +That night an obviously frightened person called up, and demanded to +know who I was before he would give his name. + +“This is Mr. Carraway,” I said. + +“Oh!” He sounded relieved. “This is Klipspringer.” + +I was relieved too, for that seemed to promise another friend at +Gatsby’s grave. I didn’t want it to be in the papers and draw a +sightseeing crowd, so I’d been calling up a few people myself. They +were hard to find. + +“The funeral’s tomorrow,” I said. “Three o’clock, here at the house. +I wish you’d tell anybody who’d be interested.” + +“Oh, I will,” he broke out hastily. “Of course I’m not likely to see +anybody, but if I do.” + +His tone made me suspicious. + +“Of course you’ll be there yourself.” + +“Well, I’ll certainly try. What I called up about is—” + +“Wait a minute,” I interrupted. “How about saying you’ll come?” + +“Well, the fact is—the truth of the matter is that I’m staying with +some people up here in Greenwich, and they rather expect me to be with +them tomorrow. In fact, there’s a sort of picnic or something. Of +course I’ll do my best to get away.” + +I ejaculated an unrestrained “Huh!” and he must have heard me, for he +went on nervously: + +“What I called up about was a pair of shoes I left there. I wonder if +it’d be too much trouble to have the butler send them on. You see, +they’re tennis shoes, and I’m sort of helpless without them. My +address is care of B. F.—” + +I didn’t hear the rest of the name, because I hung up the receiver. + +After that I felt a certain shame for Gatsby—one gentleman to whom I +telephoned implied that he had got what he deserved. However, that was +my fault, for he was one of those who used to sneer most bitterly at +Gatsby on the courage of Gatsby’s liquor, and I should have known +better than to call him. + +The morning of the funeral I went up to New York to see Meyer +Wolfshiem; I couldn’t seem to reach him any other way. The door that I +pushed open, on the advice of an elevator boy, was marked “The +Swastika Holding Company,” and at first there didn’t seem to be anyone +inside. But when I’d shouted “hello” several times in vain, an +argument broke out behind a partition, and presently a lovely Jewess +appeared at an interior door and scrutinized me with black hostile +eyes. + +“Nobody’s in,” she said. “Mr. Wolfshiem’s gone to Chicago.” + +The first part of this was obviously untrue, for someone had begun to +whistle “The Rosary,” tunelessly, inside. + +“Please say that Mr. Carraway wants to see him.” + +“I can’t get him back from Chicago, can I?” + +At this moment a voice, unmistakably Wolfshiem’s, called “Stella!” +from the other side of the door. + +“Leave your name on the desk,” she said quickly. “I’ll give it to him +when he gets back.” + +“But I know he’s there.” + +She took a step toward me and began to slide her hands indignantly up +and down her hips. + +“You young men think you can force your way in here any time,” she +scolded. “We’re getting sickantired of it. When I say he’s in Chicago, +he’s in Chicago.” + +I mentioned Gatsby. + +“Oh-h!” She looked at me over again. “Will you just—What was your +name?” + +She vanished. In a moment Meyer Wolfshiem stood solemnly in the +doorway, holding out both hands. He drew me into his office, remarking +in a reverent voice that it was a sad time for all of us, and offered +me a cigar. + +“My memory goes back to when first I met him,” he said. “A young major +just out of the army and covered over with medals he got in the war. +He was so hard up he had to keep on wearing his uniform because he +couldn’t buy some regular clothes. First time I saw him was when he +came into Winebrenner’s poolroom at Forty-third Street and asked for a +job. He hadn’t eat anything for a couple of days. ‘Come on have some +lunch with me,’ I said. He ate more than four dollars’ worth of food +in half an hour.” + +“Did you start him in business?” I inquired. + +“Start him! I made him.” + +“Oh.” + +“I raised him up out of nothing, right out of the gutter. I saw right +away he was a fine-appearing, gentlemanly young man, and when he told +me he was at Oggsford I knew I could use him good. I got him to join +the American Legion and he used to stand high there. Right off he did +some work for a client of mine up to Albany. We were so thick like +that in everything”—he held up two bulbous fingers—“always together.” + +I wondered if this partnership had included the World’s Series +transaction in 1919. + +“Now he’s dead,” I said after a moment. “You were his closest friend, +so I know you’ll want to come to his funeral this afternoon.” + +“I’d like to come.” + +“Well, come then.” + +The hair in his nostrils quivered slightly, and as he shook his head +his eyes filled with tears. + +“I can’t do it—I can’t get mixed up in it,” he said. + +“There’s nothing to get mixed up in. It’s all over now.” + +“When a man gets killed I never like to get mixed up in it in any +way. I keep out. When I was a young man it was different—if a friend +of mine died, no matter how, I stuck with them to the end. You may +think that’s sentimental, but I mean it—to the bitter end.” + +I saw that for some reason of his own he was determined not to come, +so I stood up. + +“Are you a college man?” he inquired suddenly. + +For a moment I thought he was going to suggest a “gonnegtion,” but he +only nodded and shook my hand. + +“Let us learn to show our friendship for a man when he is alive and +not after he is dead,” he suggested. “After that my own rule is to let +everything alone.” + +When I left his office the sky had turned dark and I got back to West +Egg in a drizzle. After changing my clothes I went next door and found +Mr. Gatz walking up and down excitedly in the hall. His pride in his +son and in his son’s possessions was continually increasing and now he +had something to show me. + +“Jimmy sent me this picture.” He took out his wallet with trembling +fingers. “Look there.” + +It was a photograph of the house, cracked in the corners and dirty +with many hands. He pointed out every detail to me eagerly. “Look +there!” and then sought admiration from my eyes. He had shown it so +often that I think it was more real to him now than the house itself. + +“Jimmy sent it to me. I think it’s a very pretty picture. It shows up +well.” + +“Very well. Had you seen him lately?” + +“He come out to see me two years ago and bought me the house I live in +now. Of course we was broke up when he run off from home, but I see +now there was a reason for it. He knew he had a big future in front of +him. And ever since he made a success he was very generous with me.” + +He seemed reluctant to put away the picture, held it for another +minute, lingeringly, before my eyes. Then he returned the wallet and +pulled from his pocket a ragged old copy of a book called Hopalong +Cassidy. + +“Look here, this is a book he had when he was a boy. It just shows +you.” + +He opened it at the back cover and turned it around for me to see. On +the last flyleaf was printed the word schedule, and the date September +12, 1906. And underneath: + + Rise from bed 6:00 a.m. + Dumbell exercise and wall-scaling 6:15-6:30 ” + Study electricity, etc. 7:15-8:15 ” + Work 8:30-4:30 p.m. + Baseball and sports 4:30-5:00 ” + Practise elocution, poise and how to attain it 5:00-6:00 ” + Study needed inventions 7:00-9:00 ” + + General Resolves + + * No wasting time at Shafters or [a name, indecipherable] + + * No more smokeing or chewing. + + * Bath every other day + + * Read one improving book or magazine per week + + * Save $5.00 [crossed out] $3.00 per week + + * Be better to parents + +“I came across this book by accident,” said the old man. “It just +shows you, don’t it?” + +“It just shows you.” + +“Jimmy was bound to get ahead. He always had some resolves like this +or something. Do you notice what he’s got about improving his mind? He +was always great for that. He told me I et like a hog once, and I beat +him for it.” + +He was reluctant to close the book, reading each item aloud and then +looking eagerly at me. I think he rather expected me to copy down the +list for my own use. + +A little before three the Lutheran minister arrived from Flushing, and +I began to look involuntarily out the windows for other cars. So did +Gatsby’s father. And as the time passed and the servants came in and +stood waiting in the hall, his eyes began to blink anxiously, and he +spoke of the rain in a worried, uncertain way. The minister glanced +several times at his watch, so I took him aside and asked him to wait +for half an hour. But it wasn’t any use. Nobody came. + +------------------------------------------------------------------------ + +About five o’clock our procession of three cars reached the cemetery +and stopped in a thick drizzle beside the gate—first a motor hearse, +horribly black and wet, then Mr. Gatz and the minister and me in the +limousine, and a little later four or five servants and the postman +from West Egg, in Gatsby’s station wagon, all wet to the skin. As we +started through the gate into the cemetery I heard a car stop and then +the sound of someone splashing after us over the soggy ground. I +looked around. It was the man with owl-eyed glasses whom I had found +marvelling over Gatsby’s books in the library one night three months +before. + +I’d never seen him since then. I don’t know how he knew about the +funeral, or even his name. The rain poured down his thick glasses, and +he took them off and wiped them to see the protecting canvas unrolled +from Gatsby’s grave. + +I tried to think about Gatsby then for a moment, but he was already +too far away, and I could only remember, without resentment, that +Daisy hadn’t sent a message or a flower. Dimly I heard someone murmur +“Blessed are the dead that the rain falls on,” and then the owl-eyed +man said “Amen to that,” in a brave voice. + +We straggled down quickly through the rain to the cars. Owl-eyes spoke +to me by the gate. + +“I couldn’t get to the house,” he remarked. + +“Neither could anybody else.” + +“Go on!” He started. “Why, my God! they used to go there by the +hundreds.” + +He took off his glasses and wiped them again, outside and in. + +“The poor son-of-a-bitch,” he said. + +------------------------------------------------------------------------ + +One of my most vivid memories is of coming back West from prep school +and later from college at Christmas time. Those who went farther than +Chicago would gather in the old dim Union Station at six o’clock of a +December evening, with a few Chicago friends, already caught up into +their own holiday gaieties, to bid them a hasty goodbye. I remember +the fur coats of the girls returning from Miss This-or-That’s and the +chatter of frozen breath and the hands waving overhead as we caught +sight of old acquaintances, and the matchings of invitations: “Are you +going to the Ordways’? the Herseys’? the Schultzes’?” and the long +green tickets clasped tight in our gloved hands. And last the murky +yellow cars of the Chicago, Milwaukee and St. Paul railroad looking +cheerful as Christmas itself on the tracks beside the gate. + +When we pulled out into the winter night and the real snow, our snow, +began to stretch out beside us and twinkle against the windows, and +the dim lights of small Wisconsin stations moved by, a sharp wild +brace came suddenly into the air. We drew in deep breaths of it as we +walked back from dinner through the cold vestibules, unutterably aware +of our identity with this country for one strange hour, before we +melted indistinguishably into it again. + +That’s my Middle West—not the wheat or the prairies or the lost Swede +towns, but the thrilling returning trains of my youth, and the street +lamps and sleigh bells in the frosty dark and the shadows of holly +wreaths thrown by lighted windows on the snow. I am part of that, a +little solemn with the feel of those long winters, a little complacent +from growing up in the Carraway house in a city where dwellings are +still called through decades by a family’s name. I see now that this +has been a story of the West, after all—Tom and Gatsby, Daisy and +Jordan and I, were all Westerners, and perhaps we possessed some +deficiency in common which made us subtly unadaptable to Eastern life. + +Even when the East excited me most, even when I was most keenly aware +of its superiority to the bored, sprawling, swollen towns beyond the +Ohio, with their interminable inquisitions which spared only the +children and the very old—even then it had always for me a quality of +distortion. West Egg, especially, still figures in my more fantastic +dreams. I see it as a night scene by El Greco: a hundred houses, at +once conventional and grotesque, crouching under a sullen, overhanging +sky and a lustreless moon. In the foreground four solemn men in dress +suits are walking along the sidewalk with a stretcher on which lies a +drunken woman in a white evening dress. Her hand, which dangles over +the side, sparkles cold with jewels. Gravely the men turn in at a +house—the wrong house. But no one knows the woman’s name, and no one +cares. + +After Gatsby’s death the East was haunted for me like that, distorted +beyond my eyes’ power of correction. So when the blue smoke of brittle +leaves was in the air and the wind blew the wet laundry stiff on the +line I decided to come back home. + +There was one thing to be done before I left, an awkward, unpleasant +thing that perhaps had better have been let alone. But I wanted to +leave things in order and not just trust that obliging and indifferent +sea to sweep my refuse away. I saw Jordan Baker and talked over and +around what had happened to us together, and what had happened +afterward to me, and she lay perfectly still, listening, in a big +chair. + +She was dressed to play golf, and I remember thinking she looked like +a good illustration, her chin raised a little jauntily, her hair the +colour of an autumn leaf, her face the same brown tint as the +fingerless glove on her knee. When I had finished she told me without +comment that she was engaged to another man. I doubted that, though +there were several she could have married at a nod of her head, but I +pretended to be surprised. For just a minute I wondered if I wasn’t +making a mistake, then I thought it all over again quickly and got up +to say goodbye. + +“Nevertheless you did throw me over,” said Jordan suddenly. “You threw +me over on the telephone. I don’t give a damn about you now, but it +was a new experience for me, and I felt a little dizzy for a while.” + +We shook hands. + +“Oh, and do you remember”—she added—“a conversation we had once about +driving a car?” + +“Why—not exactly.” + +“You said a bad driver was only safe until she met another bad driver? +Well, I met another bad driver, didn’t I? I mean it was careless of me +to make such a wrong guess. I thought you were rather an honest, +straightforward person. I thought it was your secret pride.” + +“I’m thirty,” I said. “I’m five years too old to lie to myself and +call it honour.” + +She didn’t answer. Angry, and half in love with her, and tremendously +sorry, I turned away. + +------------------------------------------------------------------------ + +One afternoon late in October I saw Tom Buchanan. He was walking ahead +of me along Fifth Avenue in his alert, aggressive way, his hands out a +little from his body as if to fight off interference, his head moving +sharply here and there, adapting itself to his restless eyes. Just as +I slowed up to avoid overtaking him he stopped and began frowning into +the windows of a jewellery store. Suddenly he saw me and walked back, +holding out his hand. + +“What’s the matter, Nick? Do you object to shaking hands with me?” + +“Yes. You know what I think of you.” + +“You’re crazy, Nick,” he said quickly. “Crazy as hell. I don’t know +what’s the matter with you.” + +“Tom,” I inquired, “what did you say to Wilson that afternoon?” + +He stared at me without a word, and I knew I had guessed right about +those missing hours. I started to turn away, but he took a step after +me and grabbed my arm. + +“I told him the truth,” he said. “He came to the door while we were +getting ready to leave, and when I sent down word that we weren’t in +he tried to force his way upstairs. He was crazy enough to kill me if +I hadn’t told him who owned the car. His hand was on a revolver in his +pocket every minute he was in the house—” He broke off defiantly. +“What if I did tell him? That fellow had it coming to him. He threw +dust into your eyes just like he did in Daisy’s, but he was a tough +one. He ran over Myrtle like you’d run over a dog and never even +stopped his car.” + +There was nothing I could say, except the one unutterable fact that it +wasn’t true. + +“And if you think I didn’t have my share of suffering—look here, when +I went to give up that flat and saw that damn box of dog biscuits +sitting there on the sideboard, I sat down and cried like a baby. By +God it was awful—” + +I couldn’t forgive him or like him, but I saw that what he had done +was, to him, entirely justified. It was all very careless and +confused. They were careless people, Tom and Daisy—they smashed up +things and creatures and then retreated back into their money or their +vast carelessness, or whatever it was that kept them together, and let +other people clean up the mess they had made … + +I shook hands with him; it seemed silly not to, for I felt suddenly as +though I were talking to a child. Then he went into the jewellery +store to buy a pearl necklace—or perhaps only a pair of cuff +buttons—rid of my provincial squeamishness forever. + +------------------------------------------------------------------------ + +Gatsby’s house was still empty when I left—the grass on his lawn had +grown as long as mine. One of the taxi drivers in the village never +took a fare past the entrance gate without stopping for a minute and +pointing inside; perhaps it was he who drove Daisy and Gatsby over to +East Egg the night of the accident, and perhaps he had made a story +about it all his own. I didn’t want to hear it and I avoided him when +I got off the train. + +I spent my Saturday nights in New York because those gleaming, +dazzling parties of his were with me so vividly that I could still +hear the music and the laughter, faint and incessant, from his garden, +and the cars going up and down his drive. One night I did hear a +material car there, and saw its lights stop at his front steps. But I +didn’t investigate. Probably it was some final guest who had been away +at the ends of the earth and didn’t know that the party was over. + +On the last night, with my trunk packed and my car sold to the grocer, +I went over and looked at that huge incoherent failure of a house once +more. On the white steps an obscene word, scrawled by some boy with a +piece of brick, stood out clearly in the moonlight, and I erased it, +drawing my shoe raspingly along the stone. Then I wandered down to the +beach and sprawled out on the sand. + +Most of the big shore places were closed now and there were hardly any +lights except the shadowy, moving glow of a ferryboat across the +Sound. And as the moon rose higher the inessential houses began to +melt away until gradually I became aware of the old island here that +flowered once for Dutch sailors’ eyes—a fresh, green breast of the new +world. Its vanished trees, the trees that had made way for Gatsby’s +house, had once pandered in whispers to the last and greatest of all +human dreams; for a transitory enchanted moment man must have held his +breath in the presence of this continent, compelled into an aesthetic +contemplation he neither understood nor desired, face to face for the +last time in history with something commensurate to his capacity for +wonder. + +And as I sat there brooding on the old, unknown world, I thought of +Gatsby’s wonder when he first picked out the green light at the end of +Daisy’s dock. He had come a long way to this blue lawn, and his dream +must have seemed so close that he could hardly fail to grasp it. He +did not know that it was already behind him, somewhere back in that +vast obscurity beyond the city, where the dark fields of the republic +rolled on under the night. + +Gatsby believed in the green light, the orgiastic future that year by +year recedes before us. It eluded us then, but that’s no +matter—tomorrow we will run faster, stretch out our arms further … And +one fine morning— + +So we beat on, boats against the current, borne back ceaselessly into +the past. + + + + +--- + +The Age of Innocence + +by Edith Wharton + + + + +Book I + + + + +I. + + +On a January evening of the early seventies, Christine Nilsson was +singing in Faust at the Academy of Music in New York. + +Though there was already talk of the erection, in remote metropolitan +distances "above the Forties," of a new Opera House which should +compete in costliness and splendour with those of the great European +capitals, the world of fashion was still content to reassemble every +winter in the shabby red and gold boxes of the sociable old Academy. +Conservatives cherished it for being small and inconvenient, and thus +keeping out the "new people" whom New York was beginning to dread and +yet be drawn to; and the sentimental clung to it for its historic +associations, and the musical for its excellent acoustics, always so +problematic a quality in halls built for the hearing of music. + +It was Madame Nilsson's first appearance that winter, and what the +daily press had already learned to describe as "an exceptionally +brilliant audience" had gathered to hear her, transported through +the slippery, snowy streets in private broughams, in the spacious +family landau, or in the humbler but more convenient "Brown coupe." +To come to the Opera in a Brown coupe was almost as honourable a way +of arriving as in one's own carriage; and departure by the same means +had the immense advantage of enabling one (with a playful allusion to +democratic principles) to scramble into the first Brown conveyance in +the line, instead of waiting till the cold-and-gin congested nose of +one's own coachman gleamed under the portico of the Academy. It was +one of the great livery-stableman's most masterly intuitions to have +discovered that Americans want to get away from amusement even more +quickly than they want to get to it. + +When Newland Archer opened the door at the back of the club box the +curtain had just gone up on the garden scene. There was no reason +why the young man should not have come earlier, for he had dined at +seven, alone with his mother and sister, and had lingered afterward +over a cigar in the Gothic library with glazed black-walnut bookcases +and finial-topped chairs which was the only room in the house where +Mrs. Archer allowed smoking. But, in the first place, New York was +a metropolis, and perfectly aware that in metropolises it was "not +the thing" to arrive early at the opera; and what was or was not +"the thing" played a part as important in Newland Archer's New York +as the inscrutable totem terrors that had ruled the destinies of his +forefathers thousands of years ago. + +The second reason for his delay was a personal one. He had dawdled +over his cigar because he was at heart a dilettante, and thinking +over a pleasure to come often gave him a subtler satisfaction than +its realisation. This was especially the case when the pleasure was +a delicate one, as his pleasures mostly were; and on this occasion +the moment he looked forward to was so rare and exquisite in quality +that--well, if he had timed his arrival in accord with the prima +donna's stage-manager he could not have entered the Academy at a more +significant moment than just as she was singing: "He loves me--he loves +me not--_he loves me_!--" and sprinkling the falling daisy petals with +notes as clear as dew. + +She sang, of course, "_M'ama_!" and not "he loves me," since an +unalterable and unquestioned law of the musical world required +that the German text of French operas sung by Swedish artists +should be translated into Italian for the clearer understanding of +English-speaking audiences. This seemed as natural to Newland Archer +as all the other conventions on which his life was moulded: such as +the duty of using two silver-backed brushes with his monogram in blue +enamel to part his hair, and of never appearing in society without a +flower (preferably a gardenia) in his buttonhole. + +"_M'ama ... non m'ama ..._" the prima donna sang, and "_M'ama_!", with +a final burst of love triumphant, as she pressed the dishevelled daisy +to her lips and lifted her large eyes to the sophisticated countenance +of the little brown Faust-Capoul, who was vainly trying, in a tight +purple velvet doublet and plumed cap, to look as pure and true as his +artless victim. + +Newland Archer, leaning against the wall at the back of the club box, +turned his eyes from the stage and scanned the opposite side of the +house. Directly facing him was the box of old Mrs. Manson Mingott, +whose monstrous obesity had long since made it impossible for her +to attend the Opera, but who was always represented on fashionable +nights by some of the younger members of the family. On this occasion, +the front of the box was filled by her daughter-in-law, Mrs. Lovell +Mingott, and her daughter, Mrs. Welland; and slightly withdrawn behind +these brocaded matrons sat a young girl in white with eyes ecstatically +fixed on the stage-lovers. As Madame Nilsson's "_M'ama_!" thrilled +out above the silent house (the boxes always stopped talking during +the Daisy Song) a warm pink mounted to the girl's cheek, mantled her +brow to the roots of her fair braids, and suffused the young slope of +her breast to the line where it met a modest tulle tucker fastened +with a single gardenia. She dropped her eyes to the immense bouquet +of lilies-of-the-valley on her knee, and Newland Archer saw her +white-gloved finger-tips touch the flowers softly. He drew a breath of +satisfied vanity and his eyes returned to the stage. + +No expense had been spared on the setting, which was acknowledged to +be very beautiful even by people who shared his acquaintance with the +Opera houses of Paris and Vienna. The foreground, to the footlights, +was covered with emerald green cloth. In the middle distance +symmetrical mounds of woolly green moss bounded by croquet hoops formed +the base of shrubs shaped like orange-trees but studded with large +pink and red roses. Gigantic pansies, considerably larger than the +roses, and closely resembling the floral pen-wipers made by female +parishioners for fashionable clergymen, sprang from the moss beneath +the rose-trees; and here and there a daisy grafted on a rose-branch +flowered with a luxuriance prophetic of Mr. Luther Burbank's far-off +prodigies. + +In the centre of this enchanted garden Madame Nilsson, in white +cashmere slashed with pale blue satin, a reticule dangling from a +blue girdle, and large yellow braids carefully disposed on each side +of her muslin chemisette, listened with downcast eyes to M. Capoul's +impassioned wooing, and affected a guileless incomprehension of his +designs whenever, by word or glance, he persuasively indicated the +ground floor window of the neat brick villa projecting obliquely from +the right wing. + +"The darling!" thought Newland Archer, his glance flitting back to +the young girl with the lilies-of-the-valley. "She doesn't even guess +what it's all about." And he contemplated her absorbed young face +with a thrill of possessorship in which pride in his own masculine +initiation was mingled with a tender reverence for her abysmal purity. +"We'll read Faust together ... by the Italian lakes ..." he thought, +somewhat hazily confusing the scene of his projected honey-moon with +the masterpieces of literature which it would be his manly privilege to +reveal to his bride. It was only that afternoon that May Welland had +let him guess that she "cared" (New York's consecrated phrase of maiden +avowal), and already his imagination, leaping ahead of the engagement +ring, the betrothal kiss and the march from Lohengrin, pictured her at +his side in some scene of old European witchery. + +He did not in the least wish the future Mrs. Newland Archer to be a +simpleton. He meant her (thanks to his enlightening companionship) to +develop a social tact and readiness of wit enabling her to hold her own +with the most popular married women of the "younger set," in which it +was the recognised custom to attract masculine homage while playfully +discouraging it. If he had probed to the bottom of his vanity (as he +sometimes nearly did) he would have found there the wish that his wife +should be as worldly-wise and as eager to please as the married lady +whose charms had held his fancy through two mildly agitated years; +without, of course, any hint of the frailty which had so nearly marred +that unhappy being's life, and had disarranged his own plans for a +whole winter. + +How this miracle of fire and ice was to be created, and to sustain +itself in a harsh world, he had never taken the time to think out; +but he was content to hold his view without analysing it, since he +knew it was that of all the carefully-brushed, white-waistcoated, +button-hole-flowered gentlemen who succeeded each other in the +club box, exchanged friendly greetings with him, and turned their +opera-glasses critically on the circle of ladies who were the product +of the system. In matters intellectual and artistic Newland Archer felt +himself distinctly the superior of these chosen specimens of old New +York gentility; he had probably read more, thought more, and even seen +a good deal more of the world, than any other man of the number. Singly +they betrayed their inferiority; but grouped together they represented +"New York," and the habit of masculine solidarity made him accept their +doctrine on all the issues called moral. He instinctively felt that +in this respect it would be troublesome--and also rather bad form--to +strike out for himself. + +"Well--upon my soul!" exclaimed Lawrence Lefferts, turning his +opera-glass abruptly away from the stage. Lawrence Lefferts was, +on the whole, the foremost authority on "form" in New York. He had +probably devoted more time than any one else to the study of this +intricate and fascinating question; but study alone could not account +for his complete and easy competence. One had only to look at him, +from the slant of his bald forehead and the curve of his beautiful +fair moustache to the long patent-leather feet at the other end of +his lean and elegant person, to feel that the knowledge of "form" +must be congenital in any one who knew how to wear such good clothes +so carelessly and carry such height with so much lounging grace. As a +young admirer had once said of him: "If anybody can tell a fellow just +when to wear a black tie with evening clothes and when not to, it's +Larry Lefferts." And on the question of pumps versus patent-leather +"Oxfords" his authority had never been disputed. + +"My God!" he said; and silently handed his glass to old Sillerton +Jackson. + +Newland Archer, following Lefferts's glance, saw with surprise that his +exclamation had been occasioned by the entry of a new figure into old +Mrs. Mingott's box. It was that of a slim young woman, a little less +tall than May Welland, with brown hair growing in close curls about her +temples and held in place by a narrow band of diamonds. The suggestion +of this headdress, which gave her what was then called a "Josephine +look," was carried out in the cut of the dark blue velvet gown rather +theatrically caught up under her bosom by a girdle with a large +old-fashioned clasp. The wearer of this unusual dress, who seemed quite +unconscious of the attention it was attracting, stood a moment in the +centre of the box, discussing with Mrs. Welland the propriety of taking +the latter's place in the front right-hand corner; then she yielded +with a slight smile, and seated herself in line with Mrs. Welland's +sister-in-law, Mrs. Lovell Mingott, who was installed in the opposite +corner. + +Mr. Sillerton Jackson had returned the opera-glass to Lawrence +Lefferts. The whole of the club turned instinctively, waiting to +hear what the old man had to say; for old Mr. Jackson was as great +an authority on "family" as Lawrence Lefferts was on "form." He +knew all the ramifications of New York's cousinships; and could not +only elucidate such complicated questions as that of the connection +between the Mingotts (through the Thorleys) with the Dallases of +South Carolina, and that of the relationship of the elder branch of +Philadelphia Thorleys to the Albany Chiverses (on no account to be +confused with the Manson Chiverses of University Place), but could also +enumerate the leading characteristics of each family: as, for instance, +the fabulous stinginess of the younger lines of Leffertses (the Long +Island ones); or the fatal tendency of the Rushworths to make foolish +matches; or the insanity recurring in every second generation of the +Albany Chiverses, with whom their New York cousins had always refused +to intermarry--with the disastrous exception of poor Medora Manson, +who, as everybody knew ... but then her mother was a Rushworth. + +In addition to this forest of family trees, Mr. Sillerton Jackson +carried between his narrow hollow temples, and under his soft thatch +of silver hair, a register of most of the scandals and mysteries that +had smouldered under the unruffled surface of New York society within +the last fifty years. So far indeed did his information extend, and +so acutely retentive was his memory, that he was supposed to be the +only man who could have told you who Julius Beaufort, the banker, +really was, and what had become of handsome Bob Spicer, old Mrs. Manson +Mingott's father, who had disappeared so mysteriously (with a large +sum of trust money) less than a year after his marriage, on the very +day that a beautiful Spanish dancer who had been delighting thronged +audiences in the old Opera-house on the Battery had taken ship for +Cuba. But these mysteries, and many others, were closely locked in Mr. +Jackson's breast; for not only did his keen sense of honour forbid his +repeating anything privately imparted, but he was fully aware that his +reputation for discretion increased his opportunities of finding out +what he wanted to know. + +The club box, therefore, waited in visible suspense while Mr. Sillerton +Jackson handed back Lawrence Lefferts's opera-glass. For a moment he +silently scrutinised the attentive group out of his filmy blue eyes +overhung by old veined lids; then he gave his moustache a thoughtful +twist, and said simply: "I didn't think the Mingotts would have tried +it on." + + + + +II. + + +Newland Archer, during this brief episode, had been thrown into a +strange state of embarrassment. + +It was annoying that the box which was thus attracting the undivided +attention of masculine New York should be that in which his betrothed +was seated between her mother and aunt; and for a moment he could not +identify the lady in the Empire dress, nor imagine why her presence +created such excitement among the initiated. Then light dawned on him, +and with it came a momentary rush of indignation. No, indeed; no one +would have thought the Mingotts would have tried it on! + +But they had; they undoubtedly had; for the low-toned comments behind +him left no doubt in Archer's mind that the young woman was May +Welland's cousin, the cousin always referred to in the family as "poor +Ellen Olenska." Archer knew that she had suddenly arrived from Europe +a day or two previously; he had even heard from Miss Welland (not +disapprovingly) that she had been to see poor Ellen, who was staying +with old Mrs. Mingott. Archer entirely approved of family solidarity, +and one of the qualities he most admired in the Mingotts was their +resolute championship of the few black sheep that their blameless stock +had produced. There was nothing mean or ungenerous in the young man's +heart, and he was glad that his future wife should not be restrained by +false prudery from being kind (in private) to her unhappy cousin; but +to receive Countess Olenska in the family circle was a different thing +from producing her in public, at the Opera of all places, and in the +very box with the young girl whose engagement to him, Newland Archer, +was to be announced within a few weeks. No, he felt as old Sillerton +Jackson felt; he did not think the Mingotts would have tried it on! + +He knew, of course, that whatever man dared (within Fifth Avenue's +limits) that old Mrs. Manson Mingott, the Matriarch of the line, would +dare. He had always admired the high and mighty old lady, who, in spite +of having been only Catherine Spicer of Staten Island, with a father +mysteriously discredited, and neither money nor position enough to +make people forget it, had allied herself with the head of the wealthy +Mingott line, married two of her daughters to "foreigners" (an Italian +marquis and an English banker), and put the crowning touch to her +audacities by building a large house of pale cream-coloured stone (when +brown sandstone seemed as much the only wear as a frock-coat in the +afternoon) in an inaccessible wilderness near the Central Park. + +Old Mrs. Mingott's foreign daughters had become a legend. They never +came back to see their mother, and the latter being, like many persons +of active mind and dominating will, sedentary and corpulent in her +habit, had philosophically remained at home. But the cream-coloured +house (supposed to be modelled on the private hotels of the Parisian +aristocracy) was there as a visible proof of her moral courage; and +she throned in it, among pre-Revolutionary furniture and souvenirs of +the Tuileries of Louis Napoleon (where she had shone in her middle +age), as placidly as if there were nothing peculiar in living above +Thirty-fourth Street, or in having French windows that opened like +doors instead of sashes that pushed up. + +Every one (including Mr. Sillerton Jackson) was agreed that old +Catherine had never had beauty--a gift which, in the eyes of New York, +justified every success, and excused a certain number of failings. +Unkind people said that, like her Imperial namesake, she had won her +way to success by strength of will and hardness of heart, and a kind of +haughty effrontery that was somehow justified by the extreme decency +and dignity of her private life. Mr. Manson Mingott had died when she +was only twenty-eight, and had "tied up" the money with an additional +caution born of the general distrust of the Spicers; but his bold young +widow went her way fearlessly, mingled freely in foreign society, +married her daughters in heaven knew what corrupt and fashionable +circles, hobnobbed with Dukes and Ambassadors, associated familiarly +with Papists, entertained Opera singers, and was the intimate friend of +Mme. Taglioni; and all the while (as Sillerton Jackson was the first +to proclaim) there had never been a breath on her reputation; the +only respect, he always added, in which she differed from the earlier +Catherine. + +Mrs. Manson Mingott had long since succeeded in untying her husband's +fortune, and had lived in affluence for half a century; but memories +of her early straits had made her excessively thrifty, and though, +when she bought a dress or a piece of furniture, she took care that it +should be of the best, she could not bring herself to spend much on +the transient pleasures of the table. Therefore, for totally different +reasons, her food was as poor as Mrs. Archer's, and her wines did +nothing to redeem it. Her relatives considered that the penury of her +table discredited the Mingott name, which had always been associated +with good living; but people continued to come to her in spite of the +"made dishes" and flat champagne, and in reply to the remonstrances of +her son Lovell (who tried to retrieve the family credit by having the +best chef in New York) she used to say laughingly: "What's the use of +two good cooks in one family, now that I've married the girls and can't +eat sauces?" + +Newland Archer, as he mused on these things, had once more turned +his eyes toward the Mingott box. He saw that Mrs. Welland and her +sister-in-law were facing their semicircle of critics with the +Mingottian _aplomb_ which old Catherine had inculcated in all her +tribe, and that only May Welland betrayed, by a heightened colour +(perhaps due to the knowledge that he was watching her) a sense of the +gravity of the situation. As for the cause of the commotion, she sat +gracefully in her corner of the box, her eyes fixed on the stage, and +revealing, as she leaned forward, a little more shoulder and bosom than +New York was accustomed to seeing, at least in ladies who had reasons +for wishing to pass unnoticed. + +Few things seemed to Newland Archer more awful than an offence against +"Taste," that far-off divinity of whom "Form" was the mere visible +representative and vicegerent. Madame Olenska's pale and serious face +appealed to his fancy as suited to the occasion and to her unhappy +situation; but the way her dress (which had no tucker) sloped away from +her thin shoulders shocked and troubled him. He hated to think of May +Welland's being exposed to the influence of a young woman so careless +of the dictates of Taste. + +"After all," he heard one of the younger men begin behind him +(everybody talked through the Mephistopheles-and-Martha scenes), "after +all, just _what_ happened?" + +"Well--she left him; nobody attempts to deny that." + +"He's an awful brute, isn't he?" continued the young enquirer, a candid +Thorley, who was evidently preparing to enter the lists as the lady's +champion. + +"The very worst; I knew him at Nice," said Lawrence Lefferts with +authority. "A half-paralysed white sneering fellow--rather handsome +head, but eyes with a lot of lashes. Well, I'll tell you the sort: when +he wasn't with women he was collecting china. Paying any price for +both, I understand." + +There was a general laugh, and the young champion said: "Well, +then----?" + +"Well, then; she bolted with his secretary." + +"Oh, I see." The champion's face fell. + +"It didn't last long, though: I heard of her a few months later living +alone in Venice. I believe Lovell Mingott went out to get her. He said +she was desperately unhappy. That's all right--but this parading her at +the Opera's another thing." + +"Perhaps," young Thorley hazarded, "she's too unhappy to be left at +home." + +This was greeted with an irreverent laugh, and the youth blushed +deeply, and tried to look as if he had meant to insinuate what knowing +people called a "_double entendre_." + +"Well--it's queer to have brought Miss Welland, anyhow," some one said +in a low tone, with a side-glance at Archer. + +"Oh, that's part of the campaign: Granny's orders, no doubt," Lefferts +laughed. "When the old lady does a thing she does it thoroughly." + +The act was ending, and there was a general stir in the box. Suddenly +Newland Archer felt himself impelled to decisive action. The desire +to be the first man to enter Mrs. Mingott's box, to proclaim to +the waiting world his engagement to May Welland, and to see her +through whatever difficulties her cousin's anomalous situation might +involve her in; this impulse had abruptly overruled all scruples and +hesitations, and sent him hurrying through the red corridors to the +farther side of the house. + +As he entered the box his eyes met Miss Welland's, and he saw that she +had instantly understood his motive, though the family dignity which +both considered so high a virtue would not permit her to tell him so. +The persons of their world lived in an atmosphere of faint implications +and pale delicacies, and the fact that he and she understood each other +without a word seemed to the young man to bring them nearer than any +explanation would have done. Her eyes said: "You see why Mamma brought +me," and his answered: "I would not for the world have had you stay +away." + +"You know my niece Countess Olenska?" Mrs. Welland enquired as she +shook hands with her future son-in-law. Archer bowed without extending +his hand, as was the custom on being introduced to a lady; and Ellen +Olenska bent her head slightly, keeping her own pale-gloved hands +clasped on her huge fan of eagle feathers. Having greeted Mrs. Lovell +Mingott, a large blonde lady in creaking satin, he sat down beside his +betrothed, and said in a low tone: "I hope you've told Madame Olenska +that we're engaged? I want everybody to know--I want you to let me +announce it this evening at the ball." + +Miss Welland's face grew rosy as the dawn, and she looked at him with +radiant eyes. "If you can persuade Mamma," she said; "but why should we +change what is already settled?" He made no answer but that which his +eyes returned, and she added, still more confidently smiling: "Tell my +cousin yourself: I give you leave. She says she used to play with you +when you were children." + +She made way for him by pushing back her chair, and promptly, and a +little ostentatiously, with the desire that the whole house should see +what he was doing, Archer seated himself at the Countess Olenska's side. + +"We _did_ use to play together, didn't we?" she asked, turning her +grave eyes to his. "You were a horrid boy, and kissed me once behind a +door; but it was your cousin Vandie Newland, who never looked at me, +that I was in love with." Her glance swept the horse-shoe curve of +boxes. "Ah, how this brings it all back to me--I see everybody here in +knickerbockers and pantalettes," she said, with her trailing slightly +foreign accent, her eyes returning to his face. + +Agreeable as their expression was, the young man was shocked that they +should reflect so unseemly a picture of the august tribunal before +which, at that very moment, her case was being tried. Nothing could +be in worse taste than misplaced flippancy; and he answered somewhat +stiffly: "Yes, you have been away a very long time." + +"Oh, centuries and centuries; so long," she said, "that I'm sure +I'm dead and buried, and this dear old place is heaven;" which, for +reasons he could not define, struck Newland Archer as an even more +disrespectful way of describing New York society. + + + + +III. + + +It invariably happened in the same way. + +Mrs. Julius Beaufort, on the night of her annual ball, never failed to +appear at the Opera; indeed, she always gave her ball on an Opera night +in order to emphasise her complete superiority to household cares, +and her possession of a staff of servants competent to organise every +detail of the entertainment in her absence. + +The Beauforts' house was one of the few in New York that possessed +a ball-room (it antedated even Mrs. Manson Mingott's and the Headly +Chiverses'); and at a time when it was beginning to be thought +"provincial" to put a "crash" over the drawing-room floor and move the +furniture upstairs, the possession of a ball-room that was used for no +other purpose, and left for three-hundred-and-sixty-four days of the +year to shuttered darkness, with its gilt chairs stacked in a corner +and its chandelier in a bag; this undoubted superiority was felt to +compensate for whatever was regrettable in the Beaufort past. + +Mrs. Archer, who was fond of coining her social philosophy into axioms, +had once said: "We all have our pet common people--" and though the +phrase was a daring one, its truth was secretly admitted in many an +exclusive bosom. But the Beauforts were not exactly common; some people +said they were even worse. Mrs. Beaufort belonged indeed to one of +America's most honoured families; she had been the lovely Regina Dallas +(of the South Carolina branch), a penniless beauty introduced to New +York society by her cousin, the imprudent Medora Manson, who was always +doing the wrong thing from the right motive. When one was related +to the Mansons and the Rushworths one had a "_droit de cité_" (as Mr. +Sillerton Jackson, who had frequented the Tuileries, called it) in New +York society; but did one not forfeit it in marrying Julius Beaufort? + +The question was: who was Beaufort? He passed for an Englishman, +was agreeable, handsome, ill-tempered, hospitable and witty. He had +come to America with letters of recommendation from old Mrs. Manson +Mingott's English son-in-law, the banker, and had speedily made himself +an important position in the world of affairs; but his habits were +dissipated, his tongue was bitter, his antecedents were mysterious; and +when Medora Manson announced her cousin's engagement to him it was felt +to be one more act of folly in poor Medora's long record of imprudences. + +But folly is as often justified of her children as wisdom, and two +years after young Mrs. Beaufort's marriage it was admitted that she +had the most distinguished house in New York. No one knew exactly how +the miracle was accomplished. She was indolent, passive, the caustic +even called her dull; but dressed like an idol, hung with pearls, +growing younger and blonder and more beautiful each year, she throned +in Mr. Beaufort's heavy brown-stone palace, and drew all the world +there without lifting her jewelled little finger. The knowing people +said it was Beaufort himself who trained the servants, taught the chef +new dishes, told the gardeners what hot-house flowers to grow for +the dinner-table and the drawing-rooms, selected the guests, brewed +the after-dinner punch and dictated the little notes his wife wrote +to her friends. If he did, these domestic activities were privately +performed, and he presented to the world the appearance of a careless +and hospitable millionaire strolling into his own drawing-room with the +detachment of an invited guest, and saying: "My wife's gloxinias are a +marvel, aren't they? I believe she gets them out from Kew." + +Mr. Beaufort's secret, people were agreed, was the way he carried +things off. It was all very well to whisper that he had been "helped" +to leave England by the international banking-house in which he had +been employed; he carried off that rumour as easily as the rest--though +New York's business conscience was no less sensitive than its moral +standard--he carried everything before him, and all New York into his +drawing-rooms, and for over twenty years now people had said they +were "going to the Beauforts'" with the same tone of security as if +they had said they were going to Mrs. Manson Mingott's, and with the +added satisfaction of knowing they would get hot canvas-back ducks +and vintage wines, instead of tepid Veuve Clicquot without a year and +warmed-up croquettes from Philadelphia. + +Mrs. Beaufort, then, had as usual appeared in her box just before the +Jewel Song; and when, again as usual, she rose at the end of the third +act, drew her opera cloak about her lovely shoulders, and disappeared, +New York knew that meant that half an hour later the ball would begin. + +The Beaufort house was one that New Yorkers were proud to show to +foreigners, especially on the night of the annual ball. The Beauforts +had been among the first people in New York to own their own red +velvet carpet and have it rolled down the steps by their own footmen, +under their own awning, instead of hiring it with the supper and the +ball-room chairs. They had also inaugurated the custom of letting the +ladies take their cloaks off in the hall, instead of shuffling up to +the hostess's bedroom and recurling their hair with the aid of the +gas-burner; Beaufort was understood to have said that he supposed all +his wife's friends had maids who saw to it that they were properly +_coiffées_ when they left home. + +Then the house had been boldly planned with a ball-room, so that, +instead of squeezing through a narrow passage to get to it (as at +the Chiverses') one marched solemnly down a vista of enfiladed +drawing-rooms (the sea-green, the crimson and the bouton d'or), seeing +from afar the many-candled lustres reflected in the polished parquetry, +and beyond that the depths of a conservatory where camellias and +tree-ferns arched their costly foliage over seats of black and gold +bamboo. + +Newland Archer, as became a young man of his position, strolled in +somewhat late. He had left his overcoat with the silk-stockinged +footmen (the stockings were one of Beaufort's few fatuities), had +dawdled a while in the library hung with Spanish leather and furnished +with Buhl and malachite, where a few men were chatting and putting +on their dancing-gloves, and had finally joined the line of guests +whom Mrs. Beaufort was receiving on the threshold of the crimson +drawing-room. + +Archer was distinctly nervous. He had not gone back to his club after +the Opera (as the young bloods usually did), but, the night being fine, +had walked for some distance up Fifth Avenue before turning back in the +direction of the Beauforts' house. He was definitely afraid that the +Mingotts might be going too far; that, in fact, they might have Granny +Mingott's orders to bring the Countess Olenska to the ball. + +From the tone of the club box he had perceived how grave a mistake +that would be; and, though he was more than ever determined to "see +the thing through," he felt less chivalrously eager to champion his +betrothed's cousin than before their brief talk at the Opera. + +Wandering on to the bouton d'or drawing-room (where Beaufort had had +the audacity to hang "Love Victorious," the much-discussed nude of +Bouguereau) Archer found Mrs. Welland and her daughter standing near +the ball-room door. Couples were already gliding over the floor beyond: +the light of the wax candles fell on revolving tulle skirts, on girlish +heads wreathed with modest blossoms, on the dashing aigrettes and +ornaments of the young married women's coiffures, and on the glitter of +highly glazed shirt-fronts and fresh _glacé_ gloves. + +Miss Welland, evidently about to join the dancers, hung on the +threshold, her lilies-of-the-valley in her hand (she carried no other +bouquet), her face a little pale, her eyes burning with a candid +excitement. A group of young men and girls were gathered about her, +and there was much hand-clasping, laughing and pleasantry on which +Mrs. Welland, standing slightly apart, shed the beam of a qualified +approval. It was evident that Miss Welland was in the act of announcing +her engagement, while her mother affected the air of parental +reluctance considered suitable to the occasion. + +Archer paused a moment. It was at his express wish that the +announcement had been made, and yet it was not thus that he would have +wished to have his happiness known. To proclaim it in the heat and +noise of a crowded ball-room was to rob it of the fine bloom of privacy +which should belong to things nearest the heart. His joy was so deep +that this blurring of the surface left its essence untouched; but he +would have liked to keep the surface pure too. It was something of a +satisfaction to find that May Welland shared this feeling. Her eyes +fled to his beseechingly, and their look said: "Remember, we're doing +this because it's right." + +No appeal could have found a more immediate response in Archer's +breast; but he wished that the necessity of their action had been +represented by some ideal reason, and not simply by poor Ellen Olenska. +The group about Miss Welland made way for him with significant smiles, +and after taking his share of the felicitations he drew his betrothed +into the middle of the ball-room floor and put his arm about her waist. + +"Now we shan't have to talk," he said, smiling into her candid eyes, as +they floated away on the soft waves of the Blue Danube. + +She made no answer. Her lips trembled into a smile, but the eyes +remained distant and serious, as if bent on some ineffable vision. +"Dear," Archer whispered, pressing her to him: it was borne in on him +that the first hours of being engaged, even if spent in a ball-room, +had in them something grave and sacramental. What a new life it was +going to be, with this whiteness, radiance, goodness at one's side! + +The dance over, the two, as became an affianced couple, wandered into +the conservatory; and sitting behind a tall screen of tree-ferns and +camellias Newland pressed her gloved hand to his lips. + +"You see I did as you asked me to," she said. + +"Yes: I couldn't wait," he answered smiling. After a moment he added: +"Only I wish it hadn't had to be at a ball." + +"Yes, I know." She met his glance comprehendingly. "But after all--even +here we're alone together, aren't we?" + +"Oh, dearest--always!" Archer cried. + +Evidently she was always going to understand; she was always going +to say the right thing. The discovery made the cup of his bliss +overflow, and he went on gaily: "The worst of it is that I want to +kiss you and I can't." As he spoke he took a swift glance about the +conservatory, assured himself of their momentary privacy, and catching +her to him laid a fugitive pressure on her lips. To counteract the +audacity of this proceeding he led her to a bamboo sofa in a less +secluded part of the conservatory, and sitting down beside her broke a +lily-of-the-valley from her bouquet. She sat silent, and the world lay +like a sunlit valley at their feet. + +"Did you tell my cousin Ellen?" she asked presently, as if she spoke +through a dream. + +He roused himself, and remembered that he had not done so. Some +invincible repugnance to speak of such things to the strange foreign +woman had checked the words on his lips. + +"No--I hadn't the chance after all," he said, fibbing hastily. + +"Ah." She looked disappointed, but gently resolved on gaining her +point. "You must, then, for I didn't either; and I shouldn't like her +to think--" + +"Of course not. But aren't you, after all, the person to do it?" + +She pondered on this. "If I'd done it at the right time, yes: but +now that there's been a delay I think you must explain that I'd +asked you to tell her at the Opera, before our speaking about it to +everybody here. Otherwise she might think I had forgotten her. You +see, she's one of the family, and she's been away so long that she's +rather--sensitive." + +Archer looked at her glowingly. "Dear and great angel! Of course I'll +tell her." He glanced a trifle apprehensively toward the crowded +ball-room. "But I haven't seen her yet. Has she come?" + +"No; at the last minute she decided not to." + +"At the last minute?" he echoed, betraying his surprise that she should +ever have considered the alternative possible. + +"Yes. She's awfully fond of dancing," the young girl answered simply. +"But suddenly she made up her mind that her dress wasn't smart enough +for a ball, though we thought it so lovely; and so my aunt had to take +her home." + +"Oh, well--" said Archer with happy indifference. Nothing about his +betrothed pleased him more than her resolute determination to carry to +its utmost limit that ritual of ignoring the "unpleasant" in which they +had both been brought up. + +"She knows as well as I do," he reflected, "the real reason of her +cousin's staying away; but I shall never let her see by the least sign +that I am conscious of there being a shadow of a shade on poor Ellen +Olenska's reputation." + + + + +IV. + + +In the course of the next day the first of the usual betrothal visits +were exchanged. The New York ritual was precise and inflexible in such +matters; and in conformity with it Newland Archer first went with his +mother and sister to call on Mrs. Welland, after which he and Mrs. +Welland and May drove out to old Mrs. Manson Mingott's to receive that +venerable ancestress's blessing. + +A visit to Mrs. Manson Mingott was always an amusing episode to the +young man. The house in itself was already an historic document, +though not, of course, as venerable as certain other old family houses +in University Place and lower Fifth Avenue. Those were of the purest +1830, with a grim harmony of cabbage-rose-garlanded carpets, rosewood +consoles, round-arched fire-places with black marble mantels, and +immense glazed book-cases of mahogany; whereas old Mrs. Mingott, who +had built her house later, had bodily cast out the massive furniture +of her prime, and mingled with the Mingott heirlooms the frivolous +upholstery of the Second Empire. It was her habit to sit in a window +of her sitting-room on the ground floor, as if watching calmly for +life and fashion to flow northward to her solitary doors. She seemed +in no hurry to have them come, for her patience was equalled by her +confidence. She was sure that presently the hoardings, the quarries, +the one-story saloons, the wooden green-houses in ragged gardens, and +the rocks from which goats surveyed the scene, would vanish before +the advance of residences as stately as her own--perhaps (for she was +an impartial woman) even statelier; and that the cobble-stones over +which the old clattering omnibuses bumped would be replaced by smooth +asphalt, such as people reported having seen in Paris. Meanwhile, as +every one she cared to see came to _her_ (and she could fill her rooms +as easily as the Beauforts, and without adding a single item to the +menu of her suppers), she did not suffer from her geographic isolation. + +The immense accretion of flesh which had descended on her in middle +life like a flood of lava on a doomed city had changed her from a +plump active little woman with a neatly-turned foot and ankle into +something as vast and august as a natural phenomenon. She had accepted +this submergence as philosophically as all her other trials, and now, +in extreme old age, was rewarded by presenting to her mirror an almost +unwrinkled expanse of firm pink and white flesh, in the centre of which +the traces of a small face survived as if awaiting excavation. A flight +of smooth double chins led down to the dizzy depths of a still-snowy +bosom veiled in snowy muslins that were held in place by a miniature +portrait of the late Mr. Mingott; and around and below, wave after wave +of black silk surged away over the edges of a capacious armchair, with +two tiny white hands poised like gulls on the surface of the billows. + +The burden of Mrs. Manson Mingott's flesh had long since made it +impossible for her to go up and down stairs, and with characteristic +independence she had made her reception rooms upstairs and established +herself (in flagrant violation of all the New York proprieties) on the +ground floor of her house; so that, as you sat in her sitting-room +window with her, you caught (through a door that was always open, and a +looped-back yellow damask portière) the unexpected vista of a bedroom +with a huge low bed upholstered like a sofa, and a toilet-table with +frivolous lace flounces and a gilt-framed mirror. + +Her visitors were startled and fascinated by the foreignness of this +arrangement, which recalled scenes in French fiction, and architectural +incentives to immorality such as the simple American had never dreamed +of. That was how women with lovers lived in the wicked old societies, +in apartments with all the rooms on one floor, and all the indecent +propinquities that their novels described. It amused Newland Archer +(who had secretly situated the love-scenes of "Monsieur de Camors" +in Mrs. Mingott's bedroom) to picture her blameless life led in the +stage-setting of adultery; but he said to himself, with considerable +admiration, that if a lover had been what she wanted, the intrepid +woman would have had him too. + +To the general relief the Countess Olenska was not present in her +grandmother's drawing-room during the visit of the betrothed couple. +Mrs. Mingott said she had gone out; which, on a day of such glaring +sunlight, and at the "shopping hour," seemed in itself an indelicate +thing for a compromised woman to do. But at any rate it spared them the +embarrassment of her presence, and the faint shadow that her unhappy +past might seem to shed on their radiant future. The visit went off +successfully, as was to have been expected. Old Mrs. Mingott was +delighted with the engagement, which, being long foreseen by watchful +relatives, had been carefully passed upon in family council; and the +engagement ring, a large thick sapphire set in invisible claws, met +with her unqualified admiration. + +"It's the new setting: of course it shows the stone beautifully, but it +looks a little bare to old-fashioned eyes," Mrs. Welland had explained, +with a conciliatory side-glance at her future son-in-law. + +"Old-fashioned eyes? I hope you don't mean mine, my dear? I like all +the novelties," said the ancestress, lifting the stone to her small +bright orbs, which no glasses had ever disfigured. "Very handsome," +she added, returning the jewel; "very liberal. In my time a cameo set +in pearls was thought sufficient. But it's the hand that sets off the +ring, isn't it, my dear Mr. Archer?" and she waved one of her tiny +hands, with small pointed nails and rolls of aged fat encircling the +wrist like ivory bracelets. "Mine was modelled in Rome by the great +Ferrigiani. You should have May's done: no doubt he'll have it done, +my child. Her hand is large--it's these modern sports that spread the +joints--but the skin is white.--And when's the wedding to be?" she +broke off, fixing her eyes on Archer's face. + +"Oh--" Mrs. Welland murmured, while the young man, smiling at his +betrothed, replied: "As soon as ever it can, if only you'll back me up, +Mrs. Mingott." + +"We must give them time to get to know each other a little better, +mamma," Mrs. Welland interposed, with the proper affectation of +reluctance; to which the ancestress rejoined: "Know each other? +Fiddlesticks! Everybody in New York has always known everybody. Let the +young man have his way, my dear; don't wait till the bubble's off the +wine. Marry them before Lent; I may catch pneumonia any winter now, and +I want to give the wedding-breakfast." + +These successive statements were received with the proper expressions +of amusement, incredulity and gratitude; and the visit was breaking up +in a vein of mild pleasantry when the door opened to admit the Countess +Olenska, who entered in bonnet and mantle followed by the unexpected +figure of Julius Beaufort. + +There was a cousinly murmur of pleasure between the ladies, and Mrs. +Mingott held out Ferrigiani's model to the banker. "Ha! Beaufort, this +is a rare favour!" (She had an odd foreign way of addressing men by +their surnames.) + +"Thanks. I wish it might happen oftener," said the visitor in his easy +arrogant way. "I'm generally so tied down; but I met the Countess Ellen +in Madison Square, and she was good enough to let me walk home with +her." + +"Ah--I hope the house will be gayer, now that Ellen's here!" cried Mrs. +Mingott with a glorious effrontery. "Sit down--sit down, Beaufort: push +up the yellow armchair; now I've got you I want a good gossip. I hear +your ball was magnificent; and I understand you invited Mrs. Lemuel +Struthers? Well--I've a curiosity to see the woman myself." + +She had forgotten her relatives, who were drifting out into the hall +under Ellen Olenska's guidance. Old Mrs. Mingott had always professed +a great admiration for Julius Beaufort, and there was a kind of +kinship in their cool domineering way and their short-cuts through the +conventions. Now she was eagerly curious to know what had decided the +Beauforts to invite (for the first time) Mrs. Lemuel Struthers, the +widow of Struthers's Shoe-polish, who had returned the previous year +from a long initiatory sojourn in Europe to lay siege to the tight +little citadel of New York. "Of course if you and Regina invite her the +thing is settled. Well, we need new blood and new money--and I hear +she's still very good-looking," the carnivorous old lady declared. + +In the hall, while Mrs. Welland and May drew on their furs, Archer saw +that the Countess Olenska was looking at him with a faintly questioning +smile. + +"Of course you know already--about May and me," he said, answering her +look with a shy laugh. "She scolded me for not giving you the news +last night at the Opera: I had her orders to tell you that we were +engaged--but I couldn't, in that crowd." + +The smile passed from Countess Olenska's eyes to her lips: she looked +younger, more like the bold brown Ellen Mingott of his boyhood. "Of +course I know; yes. And I'm so glad. But one doesn't tell such things +first in a crowd." The ladies were on the threshold and she held out +her hand. + +"Good-bye; come and see me some day," she said, still looking at Archer. + +In the carriage, on the way down Fifth Avenue, they talked pointedly of +Mrs. Mingott, of her age, her spirit, and all her wonderful attributes. +No one alluded to Ellen Olenska; but Archer knew that Mrs. Welland was +thinking: "It's a mistake for Ellen to be seen, the very day after +her arrival, parading up Fifth Avenue at the crowded hour with Julius +Beaufort--" and the young man himself mentally added: "And she ought to +know that a man who's just engaged doesn't spend his time calling on +married women. But I daresay in the set she's lived in they do--they +never do anything else." And, in spite of the cosmopolitan views on +which he prided himself, he thanked heaven that he was a New Yorker, +and about to ally himself with one of his own kind. + + + + +V. + + +The next evening old Mr. Sillerton Jackson came to dine with the +Archers. + +Mrs. Archer was a shy woman and shrank from society; but she liked to +be well-informed as to its doings. Her old friend Mr. Sillerton Jackson +applied to the investigation of his friends' affairs the patience of a +collector and the science of a naturalist; and his sister, Miss Sophy +Jackson, who lived with him, and was entertained by all the people who +could not secure her much-sought-after brother, brought home bits of +minor gossip that filled out usefully the gaps in his picture. + +Therefore, whenever anything happened that Mrs. Archer wanted to +know about, she asked Mr. Jackson to dine; and as she honoured few +people with her invitations, and as she and her daughter Janey were an +excellent audience, Mr. Jackson usually came himself instead of sending +his sister. If he could have dictated all the conditions, he would have +chosen the evenings when Newland was out; not because the young man was +uncongenial to him (the two got on capitally at their club) but because +the old anecdotist sometimes felt, on Newland's part, a tendency to +weigh his evidence that the ladies of the family never showed. + +Mr. Jackson, if perfection had been attainable on earth, would also +have asked that Mrs. Archer's food should be a little better. But then +New York, as far back as the mind of man could travel, had been divided +into the two great fundamental groups of the Mingotts and Mansons and +all their clan, who cared about eating and clothes and money, and +the Archer-Newland-van-der-Luyden tribe, who were devoted to travel, +horticulture and the best fiction, and looked down on the grosser forms +of pleasure. + +You couldn't have everything, after all. If you dined with the Lovell +Mingotts you got canvas-back and terrapin and vintage wines; at Adeline +Archer's you could talk about Alpine scenery and "The Marble Faun"; +and luckily the Archer Madeira had gone round the Cape. Therefore when +a friendly summons came from Mrs. Archer, Mr. Jackson, who was a true +eclectic, would usually say to his sister: "I've been a little gouty +since my last dinner at the Lovell Mingotts'--it will do me good to +diet at Adeline's." + +Mrs. Archer, who had long been a widow, lived with her son and daughter +in West Twenty-eighth Street. An upper floor was dedicated to Newland, +and the two women squeezed themselves into narrower quarters below. +In an unclouded harmony of tastes and interests they cultivated ferns +in Wardian cases, made _macramé_ lace and wool embroidery on linen, +collected American revolutionary glazed ware, subscribed to "Good +Words," and read Ouida's novels for the sake of the Italian atmosphere. +(They preferred those about peasant life, because of the descriptions +of scenery and the pleasanter sentiments, though in general they liked +novels about people in society, whose motives and habits were more +comprehensible, spoke severely of Dickens, who "had never drawn a +gentleman," and considered Thackeray less at home in the great world +than Bulwer--who, however, was beginning to be thought old-fashioned.) +Mrs. and Miss Archer were both great lovers of scenery. It was what +they principally sought and admired on their occasional travels +abroad; considering architecture and painting as subjects for men, +and chiefly for learned persons who read Ruskin. Mrs. Archer had been +born a Newland, and mother and daughter, who were as like as sisters, +were both, as people said, "true Newlands"; tall, pale, and slightly +round-shouldered, with long noses, sweet smiles and a kind of drooping +distinction like that in certain faded Reynolds portraits. Their +physical resemblance would have been complete if an elderly embonpoint +had not stretched Mrs. Archer's black brocade, while Miss Archer's +brown and purple poplins hung, as the years went on, more and more +slackly on her virgin frame. + +Mentally, the likeness between them, as Newland was aware, was less +complete than their identical mannerisms often made it appear. The long +habit of living together in mutually dependent intimacy had given them +the same vocabulary, and the same habit of beginning their phrases +"Mother thinks" or "Janey thinks," according as one or the other wished +to advance an opinion of her own; but in reality, while Mrs. Archer's +serene unimaginativeness rested easily in the accepted and familiar, +Janey was subject to starts and aberrations of fancy welling up from +springs of suppressed romance. + +Mother and daughter adored each other and revered their son and +brother; and Archer loved them with a tenderness made compunctious and +uncritical by the sense of their exaggerated admiration, and by his +secret satisfaction in it. After all, he thought it a good thing for a +man to have his authority respected in his own house, even if his sense +of humour sometimes made him question the force of his mandate. + +On this occasion the young man was very sure that Mr. Jackson would +rather have had him dine out; but he had his own reasons for not doing +so. + +Of course old Jackson wanted to talk about Ellen Olenska, and of course +Mrs. Archer and Janey wanted to hear what he had to tell. All three +would be slightly embarrassed by Newland's presence, now that his +prospective relation to the Mingott clan had been made known; and the +young man waited with an amused curiosity to see how they would turn +the difficulty. + +They began, obliquely, by talking about Mrs. Lemuel Struthers. + +"It's a pity the Beauforts asked her," Mrs. Archer said gently. "But +then Regina always does what he tells her; and _Beaufort_--" + +"Certain _nuances_ escape Beaufort," said Mr. Jackson, cautiously +inspecting the broiled shad, and wondering for the thousandth time why +Mrs. Archer's cook always burnt the roe to a cinder. (Newland, who +had long shared his wonder, could always detect it in the older man's +expression of melancholy disapproval.) + +"Oh, necessarily; Beaufort is a vulgar man," said Mrs. Archer. "My +grandfather Newland always used to say to my mother: 'Whatever you do, +don't let that fellow Beaufort be introduced to the girls.' But at +least he's had the advantage of associating with gentlemen; in England +too, they say. It's all very mysterious--" She glanced at Janey and +paused. She and Janey knew every fold of the Beaufort mystery, but in +public Mrs. Archer continued to assume that the subject was not one for +the unmarried. + +"But this Mrs. Struthers," Mrs. Archer continued; "what did you say +_she_ was, Sillerton?" + +"Out of a mine: or rather out of the saloon at the head of the pit. +Then with Living Wax-Works, touring New England. After the police broke +_that_ up, they say she lived--" Mr. Jackson in his turn glanced at +Janey, whose eyes began to bulge from under her prominent lids. There +were still hiatuses for her in Mrs. Struthers's past. + +"Then," Mr. Jackson continued (and Archer saw he was wondering why no +one had told the butler never to slice cucumbers with a steel knife), +"then Lemuel Struthers came along. They say his advertiser used the +girl's head for the shoe-polish posters; her hair's intensely black, +you know--the Egyptian style. Anyhow, he--eventually--married her." +There were volumes of innuendo in the way the "eventually" was spaced, +and each syllable given its due stress. + +"Oh, well--at the pass we've come to nowadays, it doesn't matter," said +Mrs. Archer indifferently. The ladies were not really interested in +Mrs. Struthers just then; the subject of Ellen Olenska was too fresh +and too absorbing to them. Indeed, Mrs. Struthers's name had been +introduced by Mrs. Archer only that she might presently be able to say: +"And Newland's new cousin--Countess Olenska? Was _she_ at the ball too?" + +There was a faint touch of sarcasm in the reference to her son, and +Archer knew it and had expected it. Even Mrs. Archer, who was seldom +unduly pleased with human events, had been altogether glad of her +son's engagement. ("Especially after that silly business with Mrs. +Rushworth," as she had remarked to Janey, alluding to what had once +seemed to Newland a tragedy of which his soul would always bear the +scar.) + +There was no better match in New York than May Welland, look at the +question from whatever point you chose. Of course such a marriage was +only what Newland was entitled to; but young men are so foolish and +incalculable--and some women so ensnaring and unscrupulous--that it was +nothing short of a miracle to see one's only son safe past the Siren +Isle and in the haven of a blameless domesticity. + +All this Mrs. Archer felt, and her son knew she felt; but he knew +also that she had been perturbed by the premature announcement of his +engagement, or rather by its cause; and it was for that reason--because +on the whole he was a tender and indulgent master--that he had stayed +at home that evening. "It's not that I don't approve of the Mingotts' +_esprit de corps_; but why Newland's engagement should be mixed up with +that Olenska woman's comings and goings I don't see," Mrs. Archer +grumbled to Janey, the only witness of her slight lapses from perfect +sweetness. + +She had behaved beautifully--and in beautiful behaviour she was +unsurpassed--during the call on Mrs. Welland; but Newland knew (and his +betrothed doubtless guessed) that all through the visit she and Janey +were nervously on the watch for Madame Olenska's possible intrusion; +and when they left the house together she had permitted herself to say +to her son: "I'm thankful that Augusta Welland received us alone." + +These indications of inward disturbance moved Archer the more that he +too felt that the Mingotts had gone a little too far. But, as it was +against all the rules of their code that the mother and son should ever +allude to what was uppermost in their thoughts, he simply replied: "Oh, +well, there's always a phase of family parties to be gone through when +one gets engaged, and the sooner it's over the better." At which his +mother merely pursed her lips under the lace veil that hung down from +her grey velvet bonnet trimmed with frosted grapes. + +Her revenge, he felt--her lawful revenge--would be to "draw" Mr. +Jackson that evening on the Countess Olenska; and, having publicly done +his duty as a future member of the Mingott clan, the young man had no +objection to hearing the lady discussed in private--except that the +subject was already beginning to bore him. + +Mr. Jackson had helped himself to a slice of the tepid filet which the +mournful butler had handed him with a look as sceptical as his own, and +had rejected the mushroom sauce after a scarcely perceptible sniff. He +looked baffled and hungry, and Archer reflected that he would probably +finish his meal on Ellen Olenska. + +Mr. Jackson leaned back in his chair, and glanced up at the candlelit +Archers, Newlands and van der Luydens hanging in dark frames on the +dark walls. + +"Ah, how your grandfather Archer loved a good dinner, my dear Newland!" +he said, his eyes on the portrait of a plump full-chested young man in +a stock and a blue coat, with a view of a white-columned country-house +behind him. "Well--well--well ... I wonder what he would have said to +all these foreign marriages!" + +Mrs. Archer ignored the allusion to the ancestral cuisine and Mr. +Jackson continued with deliberation: "No, she was _not_ at the ball." + +"Ah--" Mrs. Archer murmured, in a tone that implied: "She had that +decency." + +"Perhaps the Beauforts don't know her," Janey suggested, with her +artless malice. + +Mr. Jackson gave a faint sip, as if he had been tasting invisible +Madeira. "Mrs. Beaufort may not--but Beaufort certainly does, for she +was seen walking up Fifth Avenue this afternoon with him by the whole +of New York." + +"Mercy--" moaned Mrs. Archer, evidently perceiving the uselessness of +trying to ascribe the actions of foreigners to a sense of delicacy. + +"I wonder if she wears a round hat or a bonnet in the afternoon," Janey +speculated. "At the Opera I know she had on dark blue velvet, perfectly +plain and flat--like a night-gown." + +"Janey!" said her mother; and Miss Archer blushed and tried to look +audacious. + +"It was, at any rate, in better taste not to go to the ball," Mrs. +Archer continued. + +A spirit of perversity moved her son to rejoin: "I don't think it was a +question of taste with her. May said she meant to go, and then decided +that the dress in question wasn't smart enough." + +Mrs. Archer smiled at this confirmation of her inference. "Poor Ellen," +she simply remarked; adding compassionately: "We must always bear in +mind what an eccentric bringing-up Medora Manson gave her. What can you +expect of a girl who was allowed to wear black satin at her coming-out +ball?" + +"Ah--don't I remember her in it!" said Mr. Jackson; adding: "Poor +girl!" in the tone of one who, while enjoying the memory, had fully +understood at the time what the sight portended. + +"It's odd," Janey remarked, "that she should have kept such an ugly +name as Ellen. I should have changed it to Elaine." She glanced about +the table to see the effect of this. + +Her brother laughed. "Why Elaine?" + +"I don't know; it sounds more--more Polish," said Janey, blushing. + +"It sounds more conspicuous; and that can hardly be what she wishes," +said Mrs. Archer distantly. + +"Why not?" broke in her son, growing suddenly argumentative. "Why +shouldn't she be conspicuous if she chooses? Why should she slink +about as if it were she who had disgraced herself? She's 'poor Ellen' +certainly, because she had the bad luck to make a wretched marriage; +but I don't see that that's a reason for hiding her head as if she were +the culprit." + +"That, I suppose," said Mr. Jackson, speculatively, "is the line the +Mingotts mean to take." + +The young man reddened. "I didn't have to wait for their cue, if that's +what you mean, sir. Madame Olenska has had an unhappy life: that +doesn't make her an outcast." + +"There are rumours," began Mr. Jackson, glancing at Janey. + +"Oh, I know: the secretary," the young man took him up. "Nonsense, +mother; Janey's grown-up. They say, don't they," he went on, "that the +secretary helped her to get away from her brute of a husband, who kept +her practically a prisoner? Well, what if he did? I hope there isn't a +man among us who wouldn't have done the same in such a case." + +Mr. Jackson glanced over his shoulder to say to the sad butler: +"Perhaps ... that sauce ... just a little, after all--"; then, having +helped himself, he remarked: "I'm told she's looking for a house. She +means to live here." + +"I hear she means to get a divorce," said Janey boldly. + +"I hope she will!" Archer exclaimed. + +The word had fallen like a bombshell in the pure and tranquil +atmosphere of the Archer dining-room. Mrs. Archer raised her delicate +eye-brows in the particular curve that signified: "The butler--" and +the young man, himself mindful of the bad taste of discussing such +intimate matters in public, hastily branched off into an account of his +visit to old Mrs. Mingott. + +After dinner, according to immemorial custom, Mrs. Archer and Janey +trailed their long silk draperies up to the drawing-room, where, while +the gentlemen smoked below stairs, they sat beside a Carcel lamp with +an engraved globe, facing each other across a rosewood work-table with +a green silk bag under it, and stitched at the two ends of a tapestry +band of field-flowers destined to adorn an "occasional" chair in the +drawing-room of young Mrs. Newland Archer. + +While this rite was in progress in the drawing-room, Archer settled Mr. +Jackson in an armchair near the fire in the Gothic library and handed +him a cigar. Mr. Jackson sank into the armchair with satisfaction, lit +his cigar with perfect confidence (it was Newland who bought them), +and stretching his thin old ankles to the coals, said: "You say the +secretary merely helped her to get away, my dear fellow? Well, he was +still helping her a year later, then; for somebody met 'em living at +Lausanne together." + +Newland reddened. "Living together? Well, why not? Who had the right +to make her life over if she hadn't? I'm sick of the hypocrisy that +would bury alive a woman of her age if her husband prefers to live with +harlots." + +He stopped and turned away angrily to light his cigar. "Women ought to +be free--as free as we are," he declared, making a discovery of which +he was too irritated to measure the terrific consequences. + +Mr. Sillerton Jackson stretched his ankles nearer the coals and emitted +a sardonic whistle. + +"Well," he said after a pause, "apparently Count Olenski takes your +view; for I never heard of his having lifted a finger to get his wife +back." + + + + +VI. + + +That evening, after Mr. Jackson had taken himself away, and the ladies +had retired to their chintz-curtained bedroom, Newland Archer mounted +thoughtfully to his own study. A vigilant hand had, as usual, kept +the fire alive and the lamp trimmed; and the room, with its rows and +rows of books, its bronze and steel statuettes of "The Fencers" on +the mantelpiece and its many photographs of famous pictures, looked +singularly home-like and welcoming. + +As he dropped into his armchair near the fire his eyes rested on a +large photograph of May Welland, which the young girl had given him +in the first days of their romance, and which had now displaced all +the other portraits on the table. With a new sense of awe he looked at +the frank forehead, serious eyes and gay innocent mouth of the young +creature whose soul's custodian he was to be. That terrifying product +of the social system he belonged to and believed in, the young girl +who knew nothing and expected everything, looked back at him like a +stranger through May Welland's familiar features; and once more it was +borne in on him that marriage was not the safe anchorage he had been +taught to think, but a voyage on uncharted seas. + +The case of the Countess Olenska had stirred up old settled +convictions and set them drifting dangerously through his mind. His +own exclamation: "Women should be free--as free as we are," struck +to the root of a problem that it was agreed in his world to regard +as non-existent. "Nice" women, however wronged, would never claim +the kind of freedom he meant, and generous-minded men like himself +were therefore--in the heat of argument--the more chivalrously ready +to concede it to them. Such verbal generosities were in fact only a +humbugging disguise of the inexorable conventions that tied things +together and bound people down to the old pattern. But here he was +pledged to defend, on the part of his betrothed's cousin, conduct +that, on his own wife's part, would justify him in calling down on +her all the thunders of Church and State. Of course the dilemma was +purely hypothetical; since he wasn't a blackguard Polish nobleman, it +was absurd to speculate what his wife's rights would be if he _were_. +But Newland Archer was too imaginative not to feel that, in his case +and May's, the tie might gall for reasons far less gross and palpable. +What could he and she really know of each other, since it was his duty, +as a "decent" fellow, to conceal his past from her, and hers, as a +marriageable girl, to have no past to conceal? What if, for some one +of the subtler reasons that would tell with both of them, they should +tire of each other, misunderstand or irritate each other? He reviewed +his friends' marriages--the supposedly happy ones--and saw none that +answered, even remotely, to the passionate and tender comradeship which +he pictured as his permanent relation with May Welland. He perceived +that such a picture presupposed, on her part, the experience, the +versatility, the freedom of judgment, which she had been carefully +trained not to possess; and with a shiver of foreboding he saw his +marriage becoming what most of the other marriages about him were: a +dull association of material and social interests held together by +ignorance on the one side and hypocrisy on the other. Lawrence Lefferts +occurred to him as the husband who had most completely realised this +enviable ideal. As became the high-priest of form, he had formed a wife +so completely to his own convenience that, in the most conspicuous +moments of his frequent love-affairs with other men's wives, she +went about in smiling unconsciousness, saying that "Lawrence was so +frightfully strict"; and had been known to blush indignantly, and avert +her gaze, when some one alluded in her presence to the fact that Julius +Beaufort (as became a "foreigner" of doubtful origin) had what was +known in New York as "another establishment." + +Archer tried to console himself with the thought that he was not +quite such an ass as Larry Lefferts, nor May such a simpleton as poor +Gertrude; but the difference was after all one of intelligence and +not of standards. In reality they all lived in a kind of hieroglyphic +world, where the real thing was never said or done or even thought, but +only represented by a set of arbitrary signs; as when Mrs. Welland, +who knew exactly why Archer had pressed her to announce her daughter's +engagement at the Beaufort ball (and had indeed expected him to do no +less), yet felt obliged to simulate reluctance, and the air of having +had her hand forced, quite as, in the books on Primitive Man that +people of advanced culture were beginning to read, the savage bride is +dragged with shrieks from her parents' tent. + +The result, of course, was that the young girl who was the centre of +this elaborate system of mystification remained the more inscrutable +for her very frankness and assurance. She was frank, poor darling, +because she had nothing to conceal, assured because she knew of nothing +to be on her guard against; and with no better preparation than this, +she was to be plunged overnight into what people evasively called "the +facts of life." + +The young man was sincerely but placidly in love. He delighted in the +radiant good looks of his betrothed, in her health, her horsemanship, +her grace and quickness at games, and the shy interest in books and +ideas that she was beginning to develop under his guidance. (She had +advanced far enough to join him in ridiculing the Idyls of the King, +but not to feel the beauty of Ulysses and the Lotus Eaters.) She was +straightforward, loyal and brave; she had a sense of humour (chiefly +proved by her laughing at _his_ jokes); and he suspected, in the depths +of her innocently-gazing soul, a glow of feeling that it would be a +joy to waken. But when he had gone the brief round of her he returned +discouraged by the thought that all this frankness and innocence were +only an artificial product. Untrained human nature was not frank and +innocent; it was full of the twists and defences of an instinctive +guile. And he felt himself oppressed by this creation of factitious +purity, so cunningly manufactured by a conspiracy of mothers and aunts +and grandmothers and long-dead ancestresses, because it was supposed +to be what he wanted, what he had a right to, in order that he might +exercise his lordly pleasure in smashing it like an image made of snow. + +There was a certain triteness in these reflections: they were those +habitual to young men on the approach of their wedding day. But they +were generally accompanied by a sense of compunction and self-abasement +of which Newland Archer felt no trace. He could not deplore (as +Thackeray's heroes so often exasperated him by doing) that he had not a +blank page to offer his bride in exchange for the unblemished one she +was to give to him. He could not get away from the fact that if he had +been brought up as she had they would have been no more fit to find +their way about than the Babes in the Wood; nor could he, for all his +anxious cogitations, see any honest reason (any, that is, unconnected +with his own momentary pleasure, and the passion of masculine vanity) +why his bride should not have been allowed the same freedom of +experience as himself. + +Such questions, at such an hour, were bound to drift through his +mind; but he was conscious that their uncomfortable persistence and +precision were due to the inopportune arrival of the Countess Olenska. +Here he was, at the very moment of his betrothal--a moment for pure +thoughts and cloudless hopes--pitchforked into a coil of scandal which +raised all the special problems he would have preferred to let lie. +"Hang Ellen Olenska!" he grumbled, as he covered his fire and began to +undress. He could not really see why her fate should have the least +bearing on his; yet he dimly felt that he had only just begun to +measure the risks of the championship which his engagement had forced +upon him. + + +A few days later the bolt fell. + +The Lovell Mingotts had sent out cards for what was known as "a formal +dinner" (that is, three extra footmen, two dishes for each course, and +a Roman punch in the middle), and had headed their invitations with the +words "To meet the Countess Olenska," in accordance with the hospitable +American fashion, which treats strangers as if they were royalties, or +at least as their ambassadors. + +The guests had been selected with a boldness and discrimination in +which the initiated recognised the firm hand of Catherine the Great. +Associated with such immemorial standbys as the Selfridge Merrys, who +were asked everywhere because they always had been, the Beauforts, +on whom there was a claim of relationship, and Mr. Sillerton Jackson +and his sister Sophy (who went wherever her brother told her to), +were some of the most fashionable and yet most irreproachable of the +dominant "young married" set; the Lawrence Leffertses, Mrs. Lefferts +Rushworth (the lovely widow), the Harry Thorleys, the Reggie Chiverses +and young Morris Dagonet and his wife (who was a van der Luyden). The +company indeed was perfectly assorted, since all the members belonged +to the little inner group of people who, during the long New York +season, disported themselves together daily and nightly with apparently +undiminished zest. + +Forty-eight hours later the unbelievable had happened; every one had +refused the Mingotts' invitation except the Beauforts and old Mr. +Jackson and his sister. The intended slight was emphasised by the fact +that even the Reggie Chiverses, who were of the Mingott clan, were +among those inflicting it; and by the uniform wording of the notes, in +all of which the writers "regretted that they were unable to accept," +without the mitigating plea of a "previous engagement" that ordinary +courtesy prescribed. + +New York society was, in those days, far too small, and too scant in +its resources, for every one in it (including livery-stable-keepers, +butlers and cooks) not to know exactly on which evenings people were +free; and it was thus possible for the recipients of Mrs. Lovell +Mingott's invitations to make cruelly clear their determination not to +meet the Countess Olenska. + +The blow was unexpected; but the Mingotts, as their way was, met it +gallantly. Mrs. Lovell Mingott confided the case to Mrs. Welland, who +confided it to Newland Archer; who, aflame at the outrage, appealed +passionately and authoritatively to his mother; who, after a painful +period of inward resistance and outward temporising, succumbed to his +instances (as she always did), and immediately embracing his cause with +an energy redoubled by her previous hesitations, put on her grey velvet +bonnet and said: "I'll go and see Louisa van der Luyden." + +The New York of Newland Archer's day was a small and slippery pyramid, +in which, as yet, hardly a fissure had been made or a foothold gained. +At its base was a firm foundation of what Mrs. Archer called "plain +people"; an honourable but obscure majority of respectable families who +(as in the case of the Spicers or the Leffertses or the Jacksons) had +been raised above their level by marriage with one of the ruling clans. +People, Mrs. Archer always said, were not as particular as they used to +be; and with old Catherine Spicer ruling one end of Fifth Avenue, and +Julius Beaufort the other, you couldn't expect the old traditions to +last much longer. + +Firmly narrowing upward from this wealthy but inconspicuous substratum +was the compact and dominant group which the Mingotts, Newlands, +Chiverses and Mansons so actively represented. Most people imagined +them to be the very apex of the pyramid; but they themselves (at least +those of Mrs. Archer's generation) were aware that, in the eyes of the +professional genealogist, only a still smaller number of families could +lay claim to that eminence. + +"Don't tell me," Mrs. Archer would say to her children, "all this +modern newspaper rubbish about a New York aristocracy. If there is one, +neither the Mingotts nor the Mansons belong to it; no, nor the Newlands +or the Chiverses either. Our grandfathers and great-grandfathers were +just respectable English or Dutch merchants, who came to the colonies +to make their fortune, and stayed here because they did so well. One +of your great-grandfathers signed the Declaration, and another was a +general on Washington's staff, and received General Burgoyne's sword +after the battle of Saratoga. These are things to be proud of, but +they have nothing to do with rank or class. New York has always been a +commercial community, and there are not more than three families in it +who can claim an aristocratic origin in the real sense of the word." + +Mrs. Archer and her son and daughter, like every one else in New York, +knew who these privileged beings were: the Dagonets of Washington +Square, who came of an old English county family allied with the Pitts +and Foxes; the Lannings, who had intermarried with the descendants of +Count de Grasse, and the van der Luydens, direct descendants of the +first Dutch governor of Manhattan, and related by pre-revolutionary +marriages to several members of the French and British aristocracy. + +The Lannings survived only in the person of two very old but lively +Miss Lannings, who lived cheerfully and reminiscently among family +portraits and Chippendale; the Dagonets were a considerable clan, +allied to the best names in Baltimore and Philadelphia; but the van +der Luydens, who stood above all of them, had faded into a kind of +super-terrestrial twilight, from which only two figures impressively +emerged; those of Mr. and Mrs. Henry van der Luyden. + +Mrs. Henry van der Luyden had been Louisa Dagonet, and her mother had +been the granddaughter of Colonel du Lac, of an old Channel Island +family, who had fought under Cornwallis and had settled in Maryland, +after the war, with his bride, Lady Angelica Trevenna, fifth daughter +of the Earl of St. Austrey. The tie between the Dagonets, the du Lacs +of Maryland, and their aristocratic Cornish kinsfolk, the Trevennas, +had always remained close and cordial. Mr. and Mrs. van der Luyden +had more than once paid long visits to the present head of the house +of Trevenna, the Duke of St. Austrey, at his country-seat in Cornwall +and at St. Austrey in Gloucestershire; and his Grace had frequently +announced his intention of some day returning their visit (without the +Duchess, who feared the Atlantic). + +Mr. and Mrs. van der Luyden divided their time between Trevenna, their +place in Maryland, and Skuytercliff, the great estate on the Hudson +which had been one of the colonial grants of the Dutch government to +the famous first Governor, and of which Mr. van der Luyden was still +"Patroon." Their large solemn house in Madison Avenue was seldom +opened, and when they came to town they received in it only their most +intimate friends. + +"I wish you would go with me, Newland," his mother said, suddenly +pausing at the door of the Brown coupe. "Louisa is fond of you; and of +course it's on account of dear May that I'm taking this step--and also +because, if we don't all stand together, there'll be no such thing as +Society left." + + + + +VII. + + +Mrs. Henry van der Luyden listened in silence to her cousin Mrs. +Archer's narrative. + +It was all very well to tell yourself in advance that Mrs. van der +Luyden was always silent, and that, though non-committal by nature +and training, she was very kind to the people she really liked. Even +personal experience of these facts was not always a protection from the +chill that descended on one in the high-ceilinged white-walled Madison +Avenue drawing-room, with the pale brocaded armchairs so obviously +uncovered for the occasion, and the gauze still veiling the ormolu +mantel ornaments and the beautiful old carved frame of Gainsborough's +"Lady Angelica du Lac." + +Mrs. van der Luyden's portrait by Huntington (in black velvet and +Venetian point) faced that of her lovely ancestress. It was generally +considered "as fine as a Cabanel," and, though twenty years had elapsed +since its execution, was still "a perfect likeness." Indeed the Mrs. +van der Luyden who sat beneath it listening to Mrs. Archer might have +been the twin-sister of the fair and still youngish woman drooping +against a gilt armchair before a green rep curtain. Mrs. van der +Luyden still wore black velvet and Venetian point when she went into +society--or rather (since she never dined out) when she threw open her +own doors to receive it. Her fair hair, which had faded without turning +grey, was still parted in flat overlapping points on her forehead, +and the straight nose that divided her pale blue eyes was only a +little more pinched about the nostrils than when the portrait had been +painted. She always, indeed, struck Newland Archer as having been +rather gruesomely preserved in the airless atmosphere of a perfectly +irreproachable existence, as bodies caught in glaciers keep for years a +rosy life-in-death. + +Like all his family, he esteemed and admired Mrs. van der Luyden; +but he found her gentle bending sweetness less approachable than the +grimness of some of his mother's old aunts, fierce spinsters who said +"No" on principle before they knew what they were going to be asked. + +Mrs. van der Luyden's attitude said neither yes nor no, but always +appeared to incline to clemency till her thin lips, wavering into the +shadow of a smile, made the almost invariable reply: "I shall first +have to talk this over with my husband." + +She and Mr. van der Luyden were so exactly alike that Archer often +wondered how, after forty years of the closest conjugality, two such +merged identities ever separated themselves enough for anything as +controversial as a talking-over. But as neither had ever reached a +decision without prefacing it by this mysterious conclave, Mrs. Archer +and her son, having set forth their case, waited resignedly for the +familiar phrase. + +Mrs. van der Luyden, however, who had seldom surprised any one, now +surprised them by reaching her long hand toward the bell-rope. + +"I think," she said, "I should like Henry to hear what you have told +me." + +A footman appeared, to whom she gravely added: "If Mr. van der Luyden +has finished reading the newspaper, please ask him to be kind enough to +come." + +She said "reading the newspaper" in the tone in which a Minister's +wife might have said: "Presiding at a Cabinet meeting"--not from any +arrogance of mind, but because the habit of a life-time, and the +attitude of her friends and relations, had led her to consider Mr. van +der Luyden's least gesture as having an almost sacerdotal importance. + +Her promptness of action showed that she considered the case as +pressing as Mrs. Archer; but, lest she should be thought to have +committed herself in advance, she added, with the sweetest look: +"Henry always enjoys seeing you, dear Adeline; and he will wish to +congratulate Newland." + +The double doors had solemnly reopened and between them appeared Mr. +Henry van der Luyden, tall, spare and frock-coated, with faded fair +hair, a straight nose like his wife's and the same look of frozen +gentleness in eyes that were merely pale grey instead of pale blue. + +Mr. van der Luyden greeted Mrs. Archer with cousinly affability, +proffered to Newland low-voiced congratulations couched in the same +language as his wife's, and seated himself in one of the brocade +armchairs with the simplicity of a reigning sovereign. + +"I had just finished reading the Times," he said, laying his long +finger-tips together. "In town my mornings are so much occupied that I +find it more convenient to read the newspapers after luncheon." + +"Ah, there's a great deal to be said for that plan--indeed I think my +uncle Egmont used to say he found it less agitating not to read the +morning papers till after dinner," said Mrs. Archer responsively. + +"Yes: my good father abhorred hurry. But now we live in a constant +rush," said Mr. van der Luyden in measured tones, looking with pleasant +deliberation about the large shrouded room which to Archer was so +complete an image of its owners. + +"But I hope you _had_ finished your reading, Henry?" his wife +interposed. + +"Quite--quite," he reassured her. + +"Then I should like Adeline to tell you--" + +"Oh, it's really Newland's story," said his mother smiling; and +proceeded to rehearse once more the monstrous tale of the affront +inflicted on Mrs. Lovell Mingott. + +"Of course," she ended, "Augusta Welland and Mary Mingott both felt +that, especially in view of Newland's engagement, you and Henry _ought +to know_." + +"Ah--" said Mr. van der Luyden, drawing a deep breath. + +There was a silence during which the tick of the monumental ormolu +clock on the white marble mantelpiece grew as loud as the boom of a +minute-gun. Archer contemplated with awe the two slender faded figures, +seated side by side in a kind of viceregal rigidity, mouthpieces of +some remote ancestral authority which fate compelled them to wield, +when they would so much rather have lived in simplicity and seclusion, +digging invisible weeds out of the perfect lawns of Skuytercliff, and +playing Patience together in the evenings. + +Mr. van der Luyden was the first to speak. + +"You really think this is due to some--some intentional interference of +Lawrence Lefferts's?" he enquired, turning to Archer. + +"I'm certain of it, sir. Larry has been going it rather harder than +usual lately--if cousin Louisa won't mind my mentioning it--having +rather a stiff affair with the postmaster's wife in their village, or +some one of that sort; and whenever poor Gertrude Lefferts begins to +suspect anything, and he's afraid of trouble, he gets up a fuss of +this kind, to show how awfully moral he is, and talks at the top of +his voice about the impertinence of inviting his wife to meet people +he doesn't wish her to know. He's simply using Madame Olenska as a +lightning-rod; I've seen him try the same thing often before." + +"The _Leffertses_!--" said Mrs. van der Luyden. + +"The _Leffertses_!--" echoed Mrs. Archer. "What would uncle Egmont have +said of Lawrence Lefferts's pronouncing on anybody's social position? +It shows what Society has come to." + +"We'll hope it has not quite come to that," said Mr. van der Luyden +firmly. + +"Ah, if only you and Louisa went out more!" sighed Mrs. Archer. + +But instantly she became aware of her mistake. The van der Luydens were +morbidly sensitive to any criticism of their secluded existence. They +were the arbiters of fashion, the Court of last Appeal, and they knew +it, and bowed to their fate. But being shy and retiring persons, with +no natural inclination for their part, they lived as much as possible +in the sylvan solitude of Skuytercliff, and when they came to town, +declined all invitations on the plea of Mrs. van der Luyden's health. + +Newland Archer came to his mother's rescue. "Everybody in New York +knows what you and cousin Louisa represent. That's why Mrs. Mingott +felt she ought not to allow this slight on Countess Olenska to pass +without consulting you." + +Mrs. van der Luyden glanced at her husband, who glanced back at her. + +"It is the principle that I dislike," said Mr. van der Luyden. "As +long as a member of a well-known family is backed up by that family it +should be considered--final." + +"It seems so to me," said his wife, as if she were producing a new +thought. + +"I had no idea," Mr. van der Luyden continued, "that things had +come to such a pass." He paused, and looked at his wife again. "It +occurs to me, my dear, that the Countess Olenska is already a sort of +relation--through Medora Manson's first husband. At any rate, she will +be when Newland marries." He turned toward the young man. "Have you +read this morning's Times, Newland?" + +"Why, yes, sir," said Archer, who usually tossed off half a dozen +papers with his morning coffee. + +Husband and wife looked at each other again. Their pale eyes clung +together in prolonged and serious consultation; then a faint smile +fluttered over Mrs. van der Luyden's face. She had evidently guessed +and approved. + +Mr. van der Luyden turned to Mrs. Archer. "If Louisa's health allowed +her to dine out--I wish you would say to Mrs. Lovell Mingott--she +and I would have been happy to--er--fill the places of the Lawrence +Leffertses at her dinner." He paused to let the irony of this sink in. +"As you know, this is impossible." Mrs. Archer sounded a sympathetic +assent. "But Newland tells me he has read this morning's Times; +therefore he has probably seen that Louisa's relative, the Duke of St. +Austrey, arrives next week on the Russia. He is coming to enter his +new sloop, the Guinevere, in next summer's International Cup Race; and +also to have a little canvasback shooting at Trevenna." Mr. van der +Luyden paused again, and continued with increasing benevolence: "Before +taking him down to Maryland we are inviting a few friends to meet him +here--only a little dinner--with a reception afterward. I am sure +Louisa will be as glad as I am if Countess Olenska will let us include +her among our guests." He got up, bent his long body with a stiff +friendliness toward his cousin, and added: "I think I have Louisa's +authority for saying that she will herself leave the invitation to +dine when she drives out presently: with our cards--of course with our +cards." + +Mrs. Archer, who knew this to be a hint that the seventeen-hand +chestnuts which were never kept waiting were at the door, rose with a +hurried murmur of thanks. Mrs. van der Luyden beamed on her with the +smile of Esther interceding with Ahasuerus; but her husband raised a +protesting hand. + +"There is nothing to thank me for, dear Adeline; nothing whatever. This +kind of thing must not happen in New York; it shall not, as long as I +can help it," he pronounced with sovereign gentleness as he steered his +cousins to the door. + +Two hours later, every one knew that the great C-spring barouche in +which Mrs. van der Luyden took the air at all seasons had been seen at +old Mrs. Mingott's door, where a large square envelope was handed in; +and that evening at the Opera Mr. Sillerton Jackson was able to state +that the envelope contained a card inviting the Countess Olenska to the +dinner which the van der Luydens were giving the following week for +their cousin, the Duke of St. Austrey. + +Some of the younger men in the club box exchanged a smile at this +announcement, and glanced sideways at Lawrence Lefferts, who sat +carelessly in the front of the box, pulling his long fair moustache, +and who remarked with authority, as the soprano paused: "No one but +Patti ought to attempt the Sonnambula." + + + + +VIII. + + +It was generally agreed in New York that the Countess Olenska had "lost +her looks." + +She had appeared there first, in Newland Archer's boyhood, as a +brilliantly pretty little girl of nine or ten, of whom people said that +she "ought to be painted." Her parents had been continental wanderers, +and after a roaming babyhood she had lost them both, and been taken in +charge by her aunt, Medora Manson, also a wanderer, who was herself +returning to New York to "settle down." + +Poor Medora, repeatedly widowed, was always coming home to settle down +(each time in a less expensive house), and bringing with her a new +husband or an adopted child; but after a few months she invariably +parted from her husband or quarrelled with her ward, and, having got +rid of her house at a loss, set out again on her wanderings. As her +mother had been a Rushworth, and her last unhappy marriage had linked +her to one of the crazy Chiverses, New York looked indulgently on her +eccentricities; but when she returned with her little orphaned niece, +whose parents had been popular in spite of their regrettable taste for +travel, people thought it a pity that the pretty child should be in +such hands. + +Every one was disposed to be kind to little Ellen Mingott, though her +dusky red cheeks and tight curls gave her an air of gaiety that seemed +unsuitable in a child who should still have been in black for her +parents. It was one of the misguided Medora's many peculiarities to +flout the unalterable rules that regulated American mourning, and when +she stepped from the steamer her family were scandalised to see that +the crape veil she wore for her own brother was seven inches shorter +than those of her sisters-in-law, while little Ellen was in crimson +merino and amber beads, like a gipsy foundling. + +But New York had so long resigned itself to Medora that only a few old +ladies shook their heads over Ellen's gaudy clothes, while her other +relations fell under the charm of her high colour and high spirits. +She was a fearless and familiar little thing, who asked disconcerting +questions, made precocious comments, and possessed outlandish arts, +such as dancing a Spanish shawl dance and singing Neapolitan love-songs +to a guitar. Under the direction of her aunt (whose real name was Mrs. +Thorley Chivers, but who, having received a Papal title, had resumed +her first husband's patronymic, and called herself the Marchioness +Manson, because in Italy she could turn it into Manzoni) the little +girl received an expensive but incoherent education, which included +"drawing from the model," a thing never dreamed of before, and playing +the piano in quintets with professional musicians. + +Of course no good could come of this; and when, a few years later, +poor Chivers finally died in a madhouse, his widow (draped in strange +weeds) again pulled up stakes and departed with Ellen, who had grown +into a tall bony girl with conspicuous eyes. For some time no more was +heard of them; then news came of Ellen's marriage to an immensely rich +Polish nobleman of legendary fame, whom she had met at a ball at the +Tuileries, and who was said to have princely establishments in Paris, +Nice and Florence, a yacht at Cowes, and many square miles of shooting +in Transylvania. She disappeared in a kind of sulphurous apotheosis, +and when a few years later Medora again came back to New York, subdued, +impoverished, mourning a third husband, and in quest of a still smaller +house, people wondered that her rich niece had not been able to do +something for her. Then came the news that Ellen's own marriage had +ended in disaster, and that she was herself returning home to seek rest +and oblivion among her kinsfolk. + +These things passed through Newland Archer's mind a week later as he +watched the Countess Olenska enter the van der Luyden drawing-room on +the evening of the momentous dinner. The occasion was a solemn one, +and he wondered a little nervously how she would carry it off. She +came rather late, one hand still ungloved, and fastening a bracelet +about her wrist; yet she entered without any appearance of haste or +embarrassment the drawing-room in which New York's most chosen company +was somewhat awfully assembled. + +In the middle of the room she paused, looking about her with a grave +mouth and smiling eyes; and in that instant Newland Archer rejected +the general verdict on her looks. It was true that her early radiance +was gone. The red cheeks had paled; she was thin, worn, a little +older-looking than her age, which must have been nearly thirty. But +there was about her the mysterious authority of beauty, a sureness in +the carriage of the head, the movement of the eyes, which, without +being in the least theatrical, struck him as highly trained and full +of a conscious power. At the same time she was simpler in manner than +most of the ladies present, and many people (as he heard afterward +from Janey) were disappointed that her appearance was not more +"stylish"--for stylishness was what New York most valued. It was, +perhaps, Archer reflected, because her early vivacity had disappeared; +because she was so quiet--quiet in her movements, her voice, and the +tones of her low-pitched voice. New York had expected something a good +deal more resonant in a young woman with such a history. + +The dinner was a somewhat formidable business. Dining with the van +der Luydens was at best no light matter, and dining there with a Duke +who was their cousin was almost a religious solemnity. It pleased +Archer to think that only an old New Yorker could perceive the shade +of difference (to New York) between being merely a Duke and being the +van der Luydens' Duke. New York took stray noblemen calmly, and even +(except in the Struthers set) with a certain distrustful hauteur; but +when they presented such credentials as these they were received with +an old-fashioned cordiality that they would have been greatly mistaken +in ascribing solely to their standing in Debrett. It was for just such +distinctions that the young man cherished his old New York even while +he smiled at it. + +The van der Luydens had done their best to emphasise the importance +of the occasion. The du Lac Sevres and the Trevenna George II plate +were out; so was the van der Luyden "Lowestoft" (East India Company) +and the Dagonet Crown Derby. Mrs. van der Luyden looked more than ever +like a Cabanel, and Mrs. Archer, in her grandmother's seed-pearls and +emeralds, reminded her son of an Isabey miniature. All the ladies had +on their handsomest jewels, but it was characteristic of the house +and the occasion that these were mostly in rather heavy old-fashioned +settings; and old Miss Lanning, who had been persuaded to come, +actually wore her mother's cameos and a Spanish blonde shawl. + +The Countess Olenska was the only young woman at the dinner; yet, as +Archer scanned the smooth plump elderly faces between their diamond +necklaces and towering ostrich feathers, they struck him as curiously +immature compared with hers. It frightened him to think what must have +gone to the making of her eyes. + +The Duke of St. Austrey, who sat at his hostess's right, was naturally +the chief figure of the evening. But if the Countess Olenska was less +conspicuous than had been hoped, the Duke was almost invisible. Being +a well-bred man he had not (like another recent ducal visitor) come to +the dinner in a shooting-jacket; but his evening clothes were so shabby +and baggy, and he wore them with such an air of their being homespun, +that (with his stooping way of sitting, and the vast beard spreading +over his shirt-front) he hardly gave the appearance of being in dinner +attire. He was short, round-shouldered, sunburnt, with a thick nose, +small eyes and a sociable smile; but he seldom spoke, and when he +did it was in such low tones that, despite the frequent silences of +expectation about the table, his remarks were lost to all but his +neighbours. + +When the men joined the ladies after dinner the Duke went straight up +to the Countess Olenska, and they sat down in a corner and plunged +into animated talk. Neither seemed aware that the Duke should first +have paid his respects to Mrs. Lovell Mingott and Mrs. Headly Chivers, +and the Countess have conversed with that amiable hypochondriac, Mr. +Urban Dagonet of Washington Square, who, in order to have the pleasure +of meeting her, had broken through his fixed rule of not dining out +between January and April. The two chatted together for nearly twenty +minutes; then the Countess rose and, walking alone across the wide +drawing-room, sat down at Newland Archer's side. + +It was not the custom in New York drawing-rooms for a lady to get +up and walk away from one gentleman in order to seek the company of +another. Etiquette required that she should wait, immovable as an idol, +while the men who wished to converse with her succeeded each other at +her side. But the Countess was apparently unaware of having broken any +rule; she sat at perfect ease in a corner of the sofa beside Archer, +and looked at him with the kindest eyes. + +"I want you to talk to me about May," she said. + +Instead of answering her he asked: "You knew the Duke before?" + +"Oh, yes--we used to see him every winter at Nice. He's very fond of +gambling--he used to come to the house a great deal." She said it in +the simplest manner, as if she had said: "He's fond of wild-flowers"; +and after a moment she added candidly: "I think he's the dullest man I +ever met." + +This pleased her companion so much that he forgot the slight shock her +previous remark had caused him. It was undeniably exciting to meet a +lady who found the van der Luydens' Duke dull, and dared to utter the +opinion. He longed to question her, to hear more about the life of +which her careless words had given him so illuminating a glimpse; but +he feared to touch on distressing memories, and before he could think +of anything to say she had strayed back to her original subject. + +"May is a darling; I've seen no young girl in New York so handsome and +so intelligent. Are you very much in love with her?" + +Newland Archer reddened and laughed. "As much as a man can be." + +She continued to consider him thoughtfully, as if not to miss any shade +of meaning in what he said, "Do you think, then, there is a limit?" + +"To being in love? If there is, I haven't found it!" + +She glowed with sympathy. "Ah--it's really and truly a romance?" + +"The most romantic of romances!" + +"How delightful! And you found it all out for yourselves--it was not in +the least arranged for you?" + +Archer looked at her incredulously. "Have you forgotten," he asked +with a smile, "that in our country we don't allow our marriages to be +arranged for us?" + +A dusky blush rose to her cheek, and he instantly regretted his words. + +"Yes," she answered, "I'd forgotten. You must forgive me if I sometimes +make these mistakes. I don't always remember that everything here is +good that was--that was bad where I've come from." She looked down at +her Viennese fan of eagle feathers, and he saw that her lips trembled. + +"I'm so sorry," he said impulsively; "but you _are_ among friends here, +you know." + +"Yes--I know. Wherever I go I have that feeling. That's why I came +home. I want to forget everything else, to become a complete American +again, like the Mingotts and Wellands, and you and your delightful +mother, and all the other good people here tonight. Ah, here's May +arriving, and you will want to hurry away to her," she added, but +without moving; and her eyes turned back from the door to rest on the +young man's face. + +The drawing-rooms were beginning to fill up with after-dinner guests, +and following Madame Olenska's glance Archer saw May Welland entering +with her mother. In her dress of white and silver, with a wreath of +silver blossoms in her hair, the tall girl looked like a Diana just +alight from the chase. + +"Oh," said Archer, "I have so many rivals; you see she's already +surrounded. There's the Duke being introduced." + +"Then stay with me a little longer," Madame Olenska said in a low tone, +just touching his knee with her plumed fan. It was the lightest touch, +but it thrilled him like a caress. + +"Yes, let me stay," he answered in the same tone, hardly knowing what +he said; but just then Mr. van der Luyden came up, followed by old +Mr. Urban Dagonet. The Countess greeted them with her grave smile, +and Archer, feeling his host's admonitory glance on him, rose and +surrendered his seat. + +Madame Olenska held out her hand as if to bid him goodbye. + +"Tomorrow, then, after five--I shall expect you," she said; and then +turned back to make room for Mr. Dagonet. + +"Tomorrow--" Archer heard himself repeating, though there had been no +engagement, and during their talk she had given him no hint that she +wished to see him again. + +As he moved away he saw Lawrence Lefferts, tall and resplendent, +leading his wife up to be introduced; and heard Gertrude Lefferts +say, as she beamed on the Countess with her large unperceiving smile: +"But I think we used to go to dancing-school together when we were +children--." Behind her, waiting their turn to name themselves to the +Countess, Archer noticed a number of the recalcitrant couples who had +declined to meet her at Mrs. Lovell Mingott's. As Mrs. Archer remarked: +when the van der Luydens chose, they knew how to give a lesson. The +wonder was that they chose so seldom. + +The young man felt a touch on his arm and saw Mrs. van der Luyden +looking down on him from the pure eminence of black velvet and the +family diamonds. "It was good of you, dear Newland, to devote yourself +so unselfishly to Madame Olenska. I told your cousin Henry he must +really come to the rescue." + +He was aware of smiling at her vaguely, and she added, as if +condescending to his natural shyness: "I've never seen May looking +lovelier. The Duke thinks her the handsomest girl in the room." + + + + +IX. + + +The Countess Olenska had said "after five"; and at half after the hour +Newland Archer rang the bell of the peeling stucco house with a giant +wisteria throttling its feeble cast-iron balcony, which she had hired, +far down West Twenty-third Street, from the vagabond Medora. + +It was certainly a strange quarter to have settled in. Small +dress-makers, bird-stuffers and "people who wrote" were her nearest +neighbours; and further down the dishevelled street Archer recognised +a dilapidated wooden house, at the end of a paved path, in which a +writer and journalist called Winsett, whom he used to come across now +and then, had mentioned that he lived. Winsett did not invite people +to his house; but he had once pointed it out to Archer in the course +of a nocturnal stroll, and the latter had asked himself, with a little +shiver, if the humanities were so meanly housed in other capitals. + +Madame Olenska's own dwelling was redeemed from the same appearance +only by a little more paint about the window-frames; and as Archer +mustered its modest front he said to himself that the Polish Count must +have robbed her of her fortune as well as of her illusions. + +The young man had spent an unsatisfactory day. He had lunched with the +Wellands, hoping afterward to carry off May for a walk in the Park. +He wanted to have her to himself, to tell her how enchanting she had +looked the night before, and how proud he was of her, and to press her +to hasten their marriage. But Mrs. Welland had firmly reminded him that +the round of family visits was not half over, and, when he hinted at +advancing the date of the wedding, had raised reproachful eye-brows and +sighed out: "Twelve dozen of everything--hand-embroidered--" + +Packed in the family landau they rolled from one tribal doorstep to +another, and Archer, when the afternoon's round was over, parted from +his betrothed with the feeling that he had been shown off like a wild +animal cunningly trapped. He supposed that his readings in anthropology +caused him to take such a coarse view of what was after all a simple +and natural demonstration of family feeling; but when he remembered +that the Wellands did not expect the wedding to take place till the +following autumn, and pictured what his life would be till then, a +dampness fell upon his spirit. + +"Tomorrow," Mrs. Welland called after him, "we'll do the Chiverses and +the Dallases"; and he perceived that she was going through their two +families alphabetically, and that they were only in the first quarter +of the alphabet. + +He had meant to tell May of the Countess Olenska's request--her +command, rather--that he should call on her that afternoon; but in the +brief moments when they were alone he had had more pressing things to +say. Besides, it struck him as a little absurd to allude to the matter. +He knew that May most particularly wanted him to be kind to her cousin; +was it not that wish which had hastened the announcement of their +engagement? It gave him an odd sensation to reflect that, but for the +Countess's arrival, he might have been, if not still a free man, at +least a man less irrevocably pledged. But May had willed it so, and he +felt himself somehow relieved of further responsibility--and therefore +at liberty, if he chose, to call on her cousin without telling her. + +As he stood on Madame Olenska's threshold curiosity was his uppermost +feeling. He was puzzled by the tone in which she had summoned him; he +concluded that she was less simple than she seemed. + +The door was opened by a swarthy foreign-looking maid, with a prominent +bosom under a gay neckerchief, whom he vaguely fancied to be Sicilian. +She welcomed him with all her white teeth, and answering his enquiries +by a head-shake of incomprehension led him through the narrow hall +into a low firelit drawing-room. The room was empty, and she left him, +for an appreciable time, to wonder whether she had gone to find her +mistress, or whether she had not understood what he was there for, and +thought it might be to wind the clock--of which he perceived that the +only visible specimen had stopped. He knew that the southern races +communicated with each other in the language of pantomime, and was +mortified to find her shrugs and smiles so unintelligible. At length +she returned with a lamp; and Archer, having meanwhile put together +a phrase out of Dante and Petrarch, evoked the answer: "La signora e +fuori; ma verra subito"; which he took to mean: "She's out--but you'll +soon see." + +What he saw, meanwhile, with the help of the lamp, was the faded +shadowy charm of a room unlike any room he had known. He knew that the +Countess Olenska had brought some of her possessions with her--bits of +wreckage, she called them--and these, he supposed, were represented +by some small slender tables of dark wood, a delicate little Greek +bronze on the chimney-piece, and a stretch of red damask nailed on the +discoloured wallpaper behind a couple of Italian-looking pictures in +old frames. + +Newland Archer prided himself on his knowledge of Italian art. His +boyhood had been saturated with Ruskin, and he had read all the latest +books: John Addington Symonds, Vernon Lee's "Euphorion," the essays of +P. G. Hamerton, and a wonderful new volume called "The Renaissance" by +Walter Pater. He talked easily of Botticelli, and spoke of Fra Angelico +with a faint condescension. But these pictures bewildered him, for they +were like nothing that he was accustomed to look at (and therefore able +to see) when he travelled in Italy; and perhaps, also, his powers of +observation were impaired by the oddness of finding himself in this +strange empty house, where apparently no one expected him. He was sorry +that he had not told May Welland of Countess Olenska's request, and a +little disturbed by the thought that his betrothed might come in to see +her cousin. What would she think if she found him sitting there with +the air of intimacy implied by waiting alone in the dusk at a lady's +fireside? + +But since he had come he meant to wait; and he sank into a chair and +stretched his feet to the logs. + +It was odd to have summoned him in that way, and then forgotten him; +but Archer felt more curious than mortified. The atmosphere of the room +was so different from any he had ever breathed that self-consciousness +vanished in the sense of adventure. He had been before in drawing-rooms +hung with red damask, with pictures "of the Italian school"; what +struck him was the way in which Medora Manson's shabby hired house, +with its blighted background of pampas grass and Rogers statuettes, +had, by a turn of the hand, and the skilful use of a few properties, +been transformed into something intimate, "foreign," subtly suggestive +of old romantic scenes and sentiments. He tried to analyse the trick, +to find a clue to it in the way the chairs and tables were grouped, +in the fact that only two Jacqueminot roses (of which nobody ever +bought less than a dozen) had been placed in the slender vase at his +elbow, and in the vague pervading perfume that was not what one put +on handkerchiefs, but rather like the scent of some far-off bazaar, a +smell made up of Turkish coffee and ambergris and dried roses. + +His mind wandered away to the question of what May's drawing-room +would look like. He knew that Mr. Welland, who was behaving "very +handsomely," already had his eye on a newly built house in East +Thirty-ninth Street. The neighbourhood was thought remote, and the +house was built in a ghastly greenish-yellow stone that the younger +architects were beginning to employ as a protest against the brownstone +of which the uniform hue coated New York like a cold chocolate sauce; +but the plumbing was perfect. Archer would have liked to travel, to +put off the housing question; but, though the Wellands approved of an +extended European honeymoon (perhaps even a winter in Egypt), they were +firm as to the need of a house for the returning couple. The young man +felt that his fate was sealed: for the rest of his life he would go up +every evening between the cast-iron railings of that greenish-yellow +doorstep, and pass through a Pompeian vestibule into a hall with a +wainscoting of varnished yellow wood. But beyond that his imagination +could not travel. He knew the drawing-room above had a bay window, but +he could not fancy how May would deal with it. She submitted cheerfully +to the purple satin and yellow tuftings of the Welland drawing-room, +to its sham Buhl tables and gilt vitrines full of modern Saxe. He saw +no reason to suppose that she would want anything different in her own +house; and his only comfort was to reflect that she would probably let +him arrange his library as he pleased--which would be, of course, with +"sincere" Eastlake furniture, and the plain new bookcases without glass +doors. + +The round-bosomed maid came in, drew the curtains, pushed back a log, +and said consolingly: "Verra--verra." When she had gone Archer stood +up and began to wander about. Should he wait any longer? His position +was becoming rather foolish. Perhaps he had misunderstood Madame +Olenska--perhaps she had not invited him after all. + +Down the cobblestones of the quiet street came the ring of a stepper's +hoofs; they stopped before the house, and he caught the opening of a +carriage door. Parting the curtains he looked out into the early dusk. +A street-lamp faced him, and in its light he saw Julius Beaufort's +compact English brougham, drawn by a big roan, and the banker +descending from it, and helping out Madame Olenska. + +Beaufort stood, hat in hand, saying something which his companion +seemed to negative; then they shook hands, and he jumped into his +carriage while she mounted the steps. + +When she entered the room she showed no surprise at seeing Archer +there; surprise seemed the emotion that she was least addicted to. + +"How do you like my funny house?" she asked. "To me it's like heaven." + +As she spoke she untied her little velvet bonnet and tossing it away +with her long cloak stood looking at him with meditative eyes. + +"You've arranged it delightfully," he rejoined, alive to the flatness +of the words, but imprisoned in the conventional by his consuming +desire to be simple and striking. + +"Oh, it's a poor little place. My relations despise it. But at any rate +it's less gloomy than the van der Luydens'." + +The words gave him an electric shock, for few were the rebellious +spirits who would have dared to call the stately home of the van der +Luydens gloomy. Those privileged to enter it shivered there, and spoke +of it as "handsome." But suddenly he was glad that she had given voice +to the general shiver. + +"It's delicious--what you've done here," he repeated. + +"I like the little house," she admitted; "but I suppose what I like is +the blessedness of its being here, in my own country and my own town; +and then, of being alone in it." She spoke so low that he hardly heard +the last phrase; but in his awkwardness he took it up. + +"You like so much to be alone?" + +"Yes; as long as my friends keep me from feeling lonely." She sat down +near the fire, said: "Nastasia will bring the tea presently," and +signed to him to return to his armchair, adding: "I see you've already +chosen your corner." + +Leaning back, she folded her arms behind her head, and looked at the +fire under drooping lids. + +"This is the hour I like best--don't you?" + +A proper sense of his dignity caused him to answer: "I was afraid you'd +forgotten the hour. Beaufort must have been very engrossing." + +She looked amused. "Why--have you waited long? Mr. Beaufort took me to +see a number of houses--since it seems I'm not to be allowed to stay in +this one." She appeared to dismiss both Beaufort and himself from her +mind, and went on: "I've never been in a city where there seems to be +such a feeling against living in _des quartiers excentriques_. What does +it matter where one lives? I'm told this street is respectable." + +"It's not fashionable." + +"Fashionable! Do you all think so much of that? Why not make one's own +fashions? But I suppose I've lived too independently; at any rate, I +want to do what you all do--I want to feel cared for and safe." + +He was touched, as he had been the evening before when she spoke of her +need of guidance. + +"That's what your friends want you to feel. New York's an awfully safe +place," he added with a flash of sarcasm. + +"Yes, isn't it? One feels that," she cried, missing the mockery. "Being +here is like--like--being taken on a holiday when one has been a good +little girl and done all one's lessons." + +The analogy was well meant, but did not altogether please him. He did +not mind being flippant about New York, but disliked to hear any one +else take the same tone. He wondered if she did not begin to see what a +powerful engine it was, and how nearly it had crushed her. The Lovell +Mingotts' dinner, patched up in extremis out of all sorts of social +odds and ends, ought to have taught her the narrowness of her escape; +but either she had been all along unaware of having skirted disaster, +or else she had lost sight of it in the triumph of the van der Luyden +evening. Archer inclined to the former theory; he fancied that her New +York was still completely undifferentiated, and the conjecture nettled +him. + +"Last night," he said, "New York laid itself out for you. The van der +Luydens do nothing by halves." + +"No: how kind they are! It was such a nice party. Every one seems to +have such an esteem for them." + +The terms were hardly adequate; she might have spoken in that way of a +tea-party at the dear old Miss Lannings'. + +"The van der Luydens," said Archer, feeling himself pompous as +he spoke, "are the most powerful influence in New York society. +Unfortunately--owing to her health--they receive very seldom." + +She unclasped her hands from behind her head, and looked at him +meditatively. + +"Isn't that perhaps the reason?" + +"The reason--?" + +"For their great influence; that they make themselves so rare." + +He coloured a little, stared at her--and suddenly felt the penetration +of the remark. At a stroke she had pricked the van der Luydens and they +collapsed. He laughed, and sacrificed them. + +Nastasia brought the tea, with handleless Japanese cups and little +covered dishes, placing the tray on a low table. + +"But you'll explain these things to me--you'll tell me all I ought to +know," Madame Olenska continued, leaning forward to hand him his cup. + +"It's you who are telling me; opening my eyes to things I'd looked at +so long that I'd ceased to see them." + +She detached a small gold cigarette-case from one of her bracelets, +held it out to him, and took a cigarette herself. On the chimney were +long spills for lighting them. + +"Ah, then we can both help each other. But I want help so much more. +You must tell me just what to do." + +It was on the tip of his tongue to reply: "Don't be seen driving about +the streets with Beaufort--" but he was being too deeply drawn into the +atmosphere of the room, which was her atmosphere, and to give advice +of that sort would have been like telling some one who was bargaining +for attar-of-roses in Samarkand that one should always be provided with +arctics for a New York winter. New York seemed much farther off than +Samarkand, and if they were indeed to help each other she was rendering +what might prove the first of their mutual services by making him look +at his native city objectively. Viewed thus, as through the wrong end +of a telescope, it looked disconcertingly small and distant; but then +from Samarkand it would. + +A flame darted from the logs and she bent over the fire, stretching her +thin hands so close to it that a faint halo shone about the oval nails. +The light touched to russet the rings of dark hair escaping from her +braids, and made her pale face paler. + +"There are plenty of people to tell you what to do," Archer rejoined, +obscurely envious of them. + +"Oh--all my aunts? And my dear old Granny?" She considered the idea +impartially. "They're all a little vexed with me for setting up for +myself--poor Granny especially. She wanted to keep me with her; but I +had to be free--" He was impressed by this light way of speaking of the +formidable Catherine, and moved by the thought of what must have given +Madame Olenska this thirst for even the loneliest kind of freedom. But +the idea of Beaufort gnawed him. + +"I think I understand how you feel," he said. "Still, your family can +advise you; explain differences; show you the way." + +She lifted her thin black eyebrows. "Is New York such a labyrinth? I +thought it so straight up and down--like Fifth Avenue. And with all the +cross streets numbered!" She seemed to guess his faint disapproval of +this, and added, with the rare smile that enchanted her whole face: "If +you knew how I like it for just _that_--the straight-up-and-downness, +and the big honest labels on everything!" + +He saw his chance. "Everything may be labelled--but everybody is not." + +"Perhaps. I may simplify too much--but you'll warn me if I do." She +turned from the fire to look at him. "There are only two people here +who make me feel as if they understood what I mean and could explain +things to me: you and Mr. Beaufort." + +Archer winced at the joining of the names, and then, with a quick +readjustment, understood, sympathised and pitied. So close to the +powers of evil she must have lived that she still breathed more freely +in their air. But since she felt that he understood her also, his +business would be to make her see Beaufort as he really was, with all +he represented--and abhor it. + +He answered gently: "I understand. But just at first don't let go of +your old friends' hands: I mean the older women, your Granny Mingott, +Mrs. Welland, Mrs. van der Luyden. They like and admire you--they want +to help you." + +She shook her head and sighed. "Oh, I know--I know! But on condition +that they don't hear anything unpleasant. Aunt Welland put it in those +very words when I tried.... Does no one want to know the truth here, +Mr. Archer? The real loneliness is living among all these kind people +who only ask one to pretend!" She lifted her hands to her face, and he +saw her thin shoulders shaken by a sob. + +"Madame Olenska!--Oh, don't, Ellen," he cried, starting up and bending +over her. He drew down one of her hands, clasping and chafing it like a +child's while he murmured reassuring words; but in a moment she freed +herself, and looked up at him with wet lashes. + +"Does no one cry here, either? I suppose there's no need to, in +heaven," she said, straightening her loosened braids with a laugh, and +bending over the tea-kettle. It was burnt into his consciousness that +he had called her "Ellen"--called her so twice; and that she had not +noticed it. Far down the inverted telescope he saw the faint white +figure of May Welland--in New York. + +Suddenly Nastasia put her head in to say something in her rich Italian. + +Madame Olenska, again with a hand at her hair, uttered an exclamation +of assent--a flashing "Gia--gia"--and the Duke of St. Austrey entered, +piloting a tremendous black-wigged and red-plumed lady in overflowing +furs. + +"My dear Countess, I've brought an old friend of mine to see you--Mrs. +Struthers. She wasn't asked to the party last night, and she wants to +know you." + +The Duke beamed on the group, and Madame Olenska advanced with a +murmur of welcome toward the queer couple. She seemed to have no idea +how oddly matched they were, nor what a liberty the Duke had taken in +bringing his companion--and to do him justice, as Archer perceived, the +Duke seemed as unaware of it himself. + +"Of course I want to know you, my dear," cried Mrs. Struthers in a +round rolling voice that matched her bold feathers and her brazen wig. +"I want to know everybody who's young and interesting and charming. +And the Duke tells me you like music--didn't you, Duke? You're a +pianist yourself, I believe? Well, do you want to hear Sarasate play +tomorrow evening at my house? You know I've something going on every +Sunday evening--it's the day when New York doesn't know what to do with +itself, and so I say to it: 'Come and be amused.' And the Duke thought +you'd be tempted by Sarasate. You'll find a number of your friends." + +Madame Olenska's face grew brilliant with pleasure. "How kind! How good +of the Duke to think of me!" She pushed a chair up to the tea-table and +Mrs. Struthers sank into it delectably. "Of course I shall be too happy +to come." + +"That's all right, my dear. And bring your young gentleman with you." +Mrs. Struthers extended a hail-fellow hand to Archer. "I can't put a +name to you--but I'm sure I've met you--I've met everybody, here, or in +Paris or London. Aren't you in diplomacy? All the diplomatists come to +me. You like music too? Duke, you must be sure to bring him." + +The Duke said "Rather" from the depths of his beard, and Archer +withdrew with a stiffly circular bow that made him feel as full of +spine as a self-conscious school-boy among careless and unnoticing +elders. + +He was not sorry for the denouement of his visit: he only wished it had +come sooner, and spared him a certain waste of emotion. As he went out +into the wintry night, New York again became vast and imminent, and May +Welland the loveliest woman in it. He turned into his florist's to send +her the daily box of lilies-of-the-valley which, to his confusion, he +found he had forgotten that morning. + +As he wrote a word on his card and waited for an envelope he glanced +about the embowered shop, and his eye lit on a cluster of yellow roses. +He had never seen any as sun-golden before, and his first impulse was +to send them to May instead of the lilies. But they did not look like +her--there was something too rich, too strong, in their fiery beauty. +In a sudden revulsion of mood, and almost without knowing what he did, +he signed to the florist to lay the roses in another long box, and +slipped his card into a second envelope, on which he wrote the name of +the Countess Olenska; then, just as he was turning away, he drew the +card out again, and left the empty envelope on the box. + +"They'll go at once?" he enquired, pointing to the roses. + +The florist assured him that they would. + + + + +X. + + +The next day he persuaded May to escape for a walk in the Park after +luncheon. As was the custom in old-fashioned Episcopalian New York, +she usually accompanied her parents to church on Sunday afternoons; +but Mrs. Welland condoned her truancy, having that very morning won +her over to the necessity of a long engagement, with time to prepare a +hand-embroidered trousseau containing the proper number of dozens. + +The day was delectable. The bare vaulting of trees along the Mall +was ceiled with lapis lazuli, and arched above snow that shone like +splintered crystals. It was the weather to call out May's radiance, and +she burned like a young maple in the frost. Archer was proud of the +glances turned on her, and the simple joy of possessorship cleared away +his underlying perplexities. + +"It's so delicious--waking every morning to smell lilies-of-the-valley +in one's room!" she said. + +"Yesterday they came late. I hadn't time in the morning--" + +"But your remembering each day to send them makes me love them so much +more than if you'd given a standing order, and they came every morning +on the minute, like one's music-teacher--as I know Gertrude Lefferts's +did, for instance, when she and Lawrence were engaged." + +"Ah--they would!" laughed Archer, amused at her keenness. He looked +sideways at her fruit-like cheek and felt rich and secure enough to +add: "When I sent your lilies yesterday afternoon I saw some rather +gorgeous yellow roses and packed them off to Madame Olenska. Was that +right?" + +"How dear of you! Anything of that kind delights her. It's odd she +didn't mention it: she lunched with us today, and spoke of Mr. +Beaufort's having sent her wonderful orchids, and cousin Henry van der +Luyden a whole hamper of carnations from Skuytercliff. She seems so +surprised to receive flowers. Don't people send them in Europe? She +thinks it such a pretty custom." + +"Oh, well, no wonder mine were overshadowed by Beaufort's," said Archer +irritably. Then he remembered that he had not put a card with the +roses, and was vexed at having spoken of them. He wanted to say: "I +called on your cousin yesterday," but hesitated. If Madame Olenska had +not spoken of his visit it might seem awkward that he should. Yet not +to do so gave the affair an air of mystery that he disliked. To shake +off the question he began to talk of their own plans, their future, and +Mrs. Welland's insistence on a long engagement. + +"If you call it long! Isabel Chivers and Reggie were engaged for two +years: Grace and Thorley for nearly a year and a half. Why aren't we +very well off as we are?" + +It was the traditional maidenly interrogation, and he felt ashamed of +himself for finding it singularly childish. No doubt she simply echoed +what was said for her; but she was nearing her twenty-second birthday, +and he wondered at what age "nice" women began to speak for themselves. + +"Never, if we won't let them, I suppose," he mused, and recalled his +mad outburst to Mr. Sillerton Jackson: "Women ought to be as free as we +are--" + +It would presently be his task to take the bandage from this young +woman's eyes, and bid her look forth on the world. But how many +generations of the women who had gone to her making had descended +bandaged to the family vault? He shivered a little, remembering some of +the new ideas in his scientific books, and the much-cited instance of +the Kentucky cave-fish, which had ceased to develop eyes because they +had no use for them. What if, when he had bidden May Welland to open +hers, they could only look out blankly at blankness? + +"We might be much better off. We might be altogether together--we might +travel." + +Her face lit up. "That would be lovely," she owned: she would love to +travel. But her mother would not understand their wanting to do things +so differently. + +"As if the mere 'differently' didn't account for it!" the wooer +insisted. + +"Newland! You're so original!" she exulted. + +His heart sank, for he saw that he was saying all the things that young +men in the same situation were expected to say, and that she was making +the answers that instinct and tradition taught her to make--even to the +point of calling him original. + +"Original! We're all as like each other as those dolls cut out of the +same folded paper. We're like patterns stencilled on a wall. Can't you +and I strike out for ourselves, May?" + +He had stopped and faced her in the excitement of their discussion, and +her eyes rested on him with a bright unclouded admiration. + +"Mercy--shall we elope?" she laughed. + +"If you would--" + +"You _do_ love me, Newland! I'm so happy." + +"But then--why not be happier?" + +"We can't behave like people in novels, though, can we?" + +"Why not--why not--why not?" + +She looked a little bored by his insistence. She knew very well that +they couldn't, but it was troublesome to have to produce a reason. +"I'm not clever enough to argue with you. But that kind of thing is +rather--vulgar, isn't it?" she suggested, relieved to have hit on a +word that would assuredly extinguish the whole subject. + +"Are you so much afraid, then, of being vulgar?" + +She was evidently staggered by this. "Of course I should hate it--so +would you," she rejoined, a trifle irritably. + +He stood silent, beating his stick nervously against his boot-top; +and feeling that she had indeed found the right way of closing the +discussion, she went on light-heartedly: "Oh, did I tell you that I +showed Ellen my ring? She thinks it the most beautiful setting she ever +saw. There's nothing like it in the rue de la Paix, she said. I do love +you, Newland, for being so artistic!" + + +The next afternoon, as Archer, before dinner, sat smoking sullenly in +his study, Janey wandered in on him. He had failed to stop at his club +on the way up from the office where he exercised the profession of the +law in the leisurely manner common to well-to-do New Yorkers of his +class. He was out of spirits and slightly out of temper, and a haunting +horror of doing the same thing every day at the same hour besieged his +brain. + +"Sameness--sameness!" he muttered, the word running through his head +like a persecuting tune as he saw the familiar tall-hatted figures +lounging behind the plate-glass; and because he usually dropped in +at the club at that hour he had gone home instead. He knew not only +what they were likely to be talking about, but the part each one would +take in the discussion. The Duke of course would be their principal +theme; though the appearance in Fifth Avenue of a golden-haired lady +in a small canary-coloured brougham with a pair of black cobs (for +which Beaufort was generally thought responsible) would also doubtless +be thoroughly gone into. Such "women" (as they were called) were few +in New York, those driving their own carriages still fewer, and the +appearance of Miss Fanny Ring in Fifth Avenue at the fashionable hour +had profoundly agitated society. Only the day before, her carriage had +passed Mrs. Lovell Mingott's, and the latter had instantly rung the +little bell at her elbow and ordered the coachman to drive her home. +"What if it had happened to Mrs. van der Luyden?" people asked each +other with a shudder. Archer could hear Lawrence Lefferts, at that very +hour, holding forth on the disintegration of society. + +He raised his head irritably when his sister Janey entered, and then +quickly bent over his book (Swinburne's "Chastelard"--just out) as +if he had not seen her. She glanced at the writing-table heaped with +books, opened a volume of the "Contes Drolatiques," made a wry face +over the archaic French, and sighed: "What learned things you read!" + +"Well--?" he asked, as she hovered Cassandra-like before him. + +"Mother's very angry." + +"Angry? With whom? About what?" + +"Miss Sophy Jackson has just been here. She brought word that her +brother would come in after dinner: she couldn't say very much, because +he forbade her to: he wishes to give all the details himself. He's with +cousin Louisa van der Luyden now." + +"For heaven's sake, my dear girl, try a fresh start. It would take an +omniscient Deity to know what you're talking about." + +"It's not a time to be profane, Newland.... Mother feels badly enough +about your not going to church ..." + +With a groan he plunged back into his book. + +"_Newland_! Do listen. Your friend Madame Olenska was at Mrs. Lemuel +Struthers's party last night: she went there with the Duke and Mr. +Beaufort." + +At the last clause of this announcement a senseless anger swelled the +young man's breast. To smother it he laughed. "Well, what of it? I knew +she meant to." + +Janey paled and her eyes began to project. "You knew she meant to--and +you didn't try to stop her? To warn her?" + +"Stop her? Warn her?" He laughed again. "I'm not engaged to be married +to the Countess Olenska!" The words had a fantastic sound in his own +ears. + +"You're marrying into her family." + +"Oh, family--family!" he jeered. + +"Newland--don't you care about Family?" + +"Not a brass farthing." + +"Nor about what cousin Louisa van der Luyden will think?" + +"Not the half of one--if she thinks such old maid's rubbish." + +"Mother is not an old maid," said his virgin sister with pinched lips. + +He felt like shouting back: "Yes, she is, and so are the van der +Luydens, and so we all are, when it comes to being so much as brushed +by the wing-tip of Reality." But he saw her long gentle face puckering +into tears, and felt ashamed of the useless pain he was inflicting. + +"Hang Countess Olenska! Don't be a goose, Janey--I'm not her keeper." + +"No; but you _did_ ask the Wellands to announce your engagement sooner +so that we might all back her up; and if it hadn't been for that cousin +Louisa would never have invited her to the dinner for the Duke." + +"Well--what harm was there in inviting her? She was the best-looking +woman in the room; she made the dinner a little less funereal than the +usual van der Luyden banquet." + +"You know cousin Henry asked her to please you: he persuaded +cousin Louisa. And now they're so upset that they're going back to +Skuytercliff tomorrow. I think, Newland, you'd better come down. You +don't seem to understand how mother feels." + +In the drawing-room Newland found his mother. She raised a troubled +brow from her needlework to ask: "Has Janey told you?" + +"Yes." He tried to keep his tone as measured as her own. "But I can't +take it very seriously." + +"Not the fact of having offended cousin Louisa and cousin Henry?" + +"The fact that they can be offended by such a trifle as Countess +Olenska's going to the house of a woman they consider common." + +"Consider--!" + +"Well, who is; but who has good music, and amuses people on Sunday +evenings, when the whole of New York is dying of inanition." + +"Good music? All I know is, there was a woman who got up on a table and +sang the things they sing at the places you go to in Paris. There was +smoking and champagne." + +"Well--that kind of thing happens in other places, and the world still +goes on." + +"I don't suppose, dear, you're really defending the French Sunday?" + +"I've heard you often enough, mother, grumble at the English Sunday +when we've been in London." + +"New York is neither Paris nor London." + +"Oh, no, it's not!" her son groaned. + +"You mean, I suppose, that society here is not as brilliant? You're +right, I daresay; but we belong here, and people should respect our +ways when they come among us. Ellen Olenska especially: she came back +to get away from the kind of life people lead in brilliant societies." + +Newland made no answer, and after a moment his mother ventured: "I was +going to put on my bonnet and ask you to take me to see cousin Louisa +for a moment before dinner." He frowned, and she continued: "I thought +you might explain to her what you've just said: that society abroad +is different ... that people are not as particular, and that Madame +Olenska may not have realised how we feel about such things. It would +be, you know, dear," she added with an innocent adroitness, "in Madame +Olenska's interest if you did." + +"Dearest mother, I really don't see how we're concerned in the matter. +The Duke took Madame Olenska to Mrs. Struthers's--in fact he brought +Mrs. Struthers to call on her. I was there when they came. If the van +der Luydens want to quarrel with anybody, the real culprit is under +their own roof." + +"Quarrel? Newland, did you ever know of cousin Henry's quarrelling? +Besides, the Duke's his guest; and a stranger too. Strangers don't +discriminate: how should they? Countess Olenska is a New Yorker, and +should have respected the feelings of New York." + +"Well, then, if they must have a victim, you have my leave to throw +Madame Olenska to them," cried her son, exasperated. "I don't see +myself--or you either--offering ourselves up to expiate her crimes." + +"Oh, of course you see only the Mingott side," his mother answered, in +the sensitive tone that was her nearest approach to anger. + +The sad butler drew back the drawing-room portières and announced: "Mr. +Henry van der Luyden." + +Mrs. Archer dropped her needle and pushed her chair back with an +agitated hand. + +"Another lamp," she cried to the retreating servant, while Janey bent +over to straighten her mother's cap. + +Mr. van der Luyden's figure loomed on the threshold, and Newland Archer +went forward to greet his cousin. + +"We were just talking about you, sir," he said. + +Mr. van der Luyden seemed overwhelmed by the announcement. He drew off +his glove to shake hands with the ladies, and smoothed his tall hat +shyly, while Janey pushed an arm-chair forward, and Archer continued: +"And the Countess Olenska." + +Mrs. Archer paled. + +"Ah--a charming woman. I have just been to see her," said Mr. van der +Luyden, complacency restored to his brow. He sank into the chair, laid +his hat and gloves on the floor beside him in the old-fashioned way, +and went on: "She has a real gift for arranging flowers. I had sent +her a few carnations from Skuytercliff, and I was astonished. Instead +of massing them in big bunches as our head-gardener does, she had +scattered them about loosely, here and there ... I can't say how. The +Duke had told me: he said: 'Go and see how cleverly she's arranged her +drawing-room.' And she has. I should really like to take Louisa to see +her, if the neighbourhood were not so--unpleasant." + +A dead silence greeted this unusual flow of words from Mr. van der +Luyden. Mrs. Archer drew her embroidery out of the basket into which +she had nervously tumbled it, and Newland, leaning against the +chimney-place and twisting a humming-bird-feather screen in his hand, +saw Janey's gaping countenance lit up by the coming of the second lamp. + +"The fact is," Mr. van der Luyden continued, stroking his long grey leg +with a bloodless hand weighed down by the Patroon's great signet-ring, +"the fact is, I dropped in to thank her for the very pretty note she +wrote me about my flowers; and also--but this is between ourselves, of +course--to give her a friendly warning about allowing the Duke to carry +her off to parties with him. I don't know if you've heard--" + +Mrs. Archer produced an indulgent smile. "Has the Duke been carrying +her off to parties?" + +"You know what these English grandees are. They're all alike. Louisa +and I are very fond of our cousin--but it's hopeless to expect people +who are accustomed to the European courts to trouble themselves about +our little republican distinctions. The Duke goes where he's amused." +Mr. van der Luyden paused, but no one spoke. "Yes--it seems he took her +with him last night to Mrs. Lemuel Struthers's. Sillerton Jackson has +just been to us with the foolish story, and Louisa was rather troubled. +So I thought the shortest way was to go straight to Countess Olenska +and explain--by the merest hint, you know--how we feel in New York +about certain things. I felt I might, without indelicacy, because the +evening she dined with us she rather suggested ... rather let me see +that she would be grateful for guidance. And she _was_." + +Mr. van der Luyden looked about the room with what would have been +self-satisfaction on features less purged of the vulgar passions. On +his face it became a mild benevolence which Mrs. Archer's countenance +dutifully reflected. + +"How kind you both are, dear Henry--always! Newland will particularly +appreciate what you have done because of dear May and his new +relations." + +She shot an admonitory glance at her son, who said: "Immensely, sir. +But I was sure you'd like Madame Olenska." + +Mr. van der Luyden looked at him with extreme gentleness. "I never ask +to my house, my dear Newland," he said, "any one whom I do not like. +And so I have just told Sillerton Jackson." With a glance at the clock +he rose and added: "But Louisa will be waiting. We are dining early, to +take the Duke to the Opera." + +After the portières had solemnly closed behind their visitor a silence +fell upon the Archer family. + +"Gracious--how romantic!" at last broke explosively from Janey. No one +knew exactly what inspired her elliptic comments, and her relations had +long since given up trying to interpret them. + +Mrs. Archer shook her head with a sigh. "Provided it all turns out for +the best," she said, in the tone of one who knows how surely it will +not. "Newland, you must stay and see Sillerton Jackson when he comes +this evening: I really shan't know what to say to him." + +"Poor mother! But he won't come--" her son laughed, stooping to kiss +away her frown. + + + + +XI. + + +Some two weeks later, Newland Archer, sitting in abstracted idleness in +his private compartment of the office of Letterblair, Lamson and Low, +attorneys at law, was summoned by the head of the firm. + +Old Mr. Letterblair, the accredited legal adviser of three generations +of New York gentility, throned behind his mahogany desk in evident +perplexity. As he stroked his close-clipped white whiskers and ran +his hand through the rumpled grey locks above his jutting brows, his +disrespectful junior partner thought how much he looked like the Family +Physician annoyed with a patient whose symptoms refuse to be classified. + +"My dear sir--" he always addressed Archer as "sir"--"I have sent +for you to go into a little matter; a matter which, for the moment, +I prefer not to mention either to Mr. Skipworth or Mr. Redwood." The +gentlemen he spoke of were the other senior partners of the firm; for, +as was always the case with legal associations of old standing in New +York, all the partners named on the office letter-head were long since +dead; and Mr. Letterblair, for example, was, professionally speaking, +his own grandson. + +He leaned back in his chair with a furrowed brow. "For family +reasons--" he continued. + +Archer looked up. + +"The Mingott family," said Mr. Letterblair with an explanatory smile +and bow. "Mrs. Manson Mingott sent for me yesterday. Her grand-daughter +the Countess Olenska wishes to sue her husband for divorce. Certain +papers have been placed in my hands." He paused and drummed on his +desk. "In view of your prospective alliance with the family I should +like to consult you--to consider the case with you--before taking any +farther steps." + +Archer felt the blood in his temples. He had seen the Countess Olenska +only once since his visit to her, and then at the Opera, in the Mingott +box. During this interval she had become a less vivid and importunate +image, receding from his foreground as May Welland resumed her rightful +place in it. He had not heard her divorce spoken of since Janey's first +random allusion to it, and had dismissed the tale as unfounded gossip. +Theoretically, the idea of divorce was almost as distasteful to him +as to his mother; and he was annoyed that Mr. Letterblair (no doubt +prompted by old Catherine Mingott) should be so evidently planning to +draw him into the affair. After all, there were plenty of Mingott men +for such jobs, and as yet he was not even a Mingott by marriage. + +He waited for the senior partner to continue. Mr. Letterblair unlocked +a drawer and drew out a packet. "If you will run your eye over these +papers--" + +Archer frowned. "I beg your pardon, sir; but just because of the +prospective relationship, I should prefer your consulting Mr. Skipworth +or Mr. Redwood." + +Mr. Letterblair looked surprised and slightly offended. It was unusual +for a junior to reject such an opening. + +He bowed. "I respect your scruple, sir; but in this case I believe +true delicacy requires you to do as I ask. Indeed, the suggestion is +not mine but Mrs. Manson Mingott's and her son's. I have seen Lovell +Mingott; and also Mr. Welland. They all named you." + +Archer felt his temper rising. He had been somewhat languidly drifting +with events for the last fortnight, and letting May's fair looks and +radiant nature obliterate the rather importunate pressure of the +Mingott claims. But this behest of old Mrs. Mingott's roused him to +a sense of what the clan thought they had the right to exact from a +prospective son-in-law; and he chafed at the role. + +"Her uncles ought to deal with this," he said. + +"They have. The matter has been gone into by the family. They are +opposed to the Countess's idea; but she is firm, and insists on a legal +opinion." + +The young man was silent: he had not opened the packet in his hand. + +"Does she want to marry again?" + +"I believe it is suggested; but she denies it." + +"Then--" + +"Will you oblige me, Mr. Archer, by first looking through these papers? +Afterward, when we have talked the case over, I will give you my +opinion." + +Archer withdrew reluctantly with the unwelcome documents. Since their +last meeting he had half-unconsciously collaborated with events in +ridding himself of the burden of Madame Olenska. His hour alone with +her by the firelight had drawn them into a momentary intimacy on which +the Duke of St. Austrey's intrusion with Mrs. Lemuel Struthers, and the +Countess's joyous greeting of them, had rather providentially broken. +Two days later Archer had assisted at the comedy of her reinstatement +in the van der Luydens' favour, and had said to himself, with a +touch of tartness, that a lady who knew how to thank all-powerful +elderly gentlemen to such good purpose for a bunch of flowers did +not need either the private consolations or the public championship +of a young man of his small compass. To look at the matter in this +light simplified his own case and surprisingly furbished up all the +dim domestic virtues. He could not picture May Welland, in whatever +conceivable emergency, hawking about her private difficulties and +lavishing her confidences on strange men; and she had never seemed +to him finer or fairer than in the week that followed. He had even +yielded to her wish for a long engagement, since she had found the one +disarming answer to his plea for haste. + +"You know, when it comes to the point, your parents have always let you +have your way ever since you were a little girl," he argued; and she +had answered, with her clearest look: "Yes; and that's what makes it so +hard to refuse the very last thing they'll ever ask of me as a little +girl." + +That was the old New York note; that was the kind of answer he would +like always to be sure of his wife's making. If one had habitually +breathed the New York air there were times when anything less +crystalline seemed stifling. + + +The papers he had retired to read did not tell him much in fact; but +they plunged him into an atmosphere in which he choked and spluttered. +They consisted mainly of an exchange of letters between Count Olenski's +solicitors and a French legal firm to whom the Countess had applied +for the settlement of her financial situation. There was also a short +letter from the Count to his wife: after reading it, Newland Archer +rose, jammed the papers back into their envelope, and reentered Mr. +Letterblair's office. + +"Here are the letters, sir. If you wish, I'll see Madame Olenska," he +said in a constrained voice. + +"Thank you--thank you, Mr. Archer. Come and dine with me tonight if +you're free, and we'll go into the matter afterward: in case you wish +to call on our client tomorrow." + +Newland Archer walked straight home again that afternoon. It was a +winter evening of transparent clearness, with an innocent young moon +above the house-tops; and he wanted to fill his soul's lungs with the +pure radiance, and not exchange a word with any one till he and Mr. +Letterblair were closeted together after dinner. It was impossible to +decide otherwise than he had done: he must see Madame Olenska himself +rather than let her secrets be bared to other eyes. A great wave of +compassion had swept away his indifference and impatience: she stood +before him as an exposed and pitiful figure, to be saved at all costs +from farther wounding herself in her mad plunges against fate. + +He remembered what she had told him of Mrs. Welland's request to be +spared whatever was "unpleasant" in her history, and winced at the +thought that it was perhaps this attitude of mind which kept the New +York air so pure. "Are we only Pharisees after all?" he wondered, +puzzled by the effort to reconcile his instinctive disgust at human +vileness with his equally instinctive pity for human frailty. + +For the first time he perceived how elementary his own principles +had always been. He passed for a young man who had not been afraid +of risks, and he knew that his secret love-affair with poor silly +Mrs. Thorley Rushworth had not been too secret to invest him with a +becoming air of adventure. But Mrs. Rushworth was "that kind of woman"; +foolish, vain, clandestine by nature, and far more attracted by the +secrecy and peril of the affair than by such charms and qualities as +he possessed. When the fact dawned on him it nearly broke his heart, +but now it seemed the redeeming feature of the case. The affair, in +short, had been of the kind that most of the young men of his age had +been through, and emerged from with calm consciences and an undisturbed +belief in the abysmal distinction between the women one loved and +respected and those one enjoyed--and pitied. In this view they were +sedulously abetted by their mothers, aunts and other elderly female +relatives, who all shared Mrs. Archer's belief that when "such things +happened" it was undoubtedly foolish of the man, but somehow always +criminal of the woman. All the elderly ladies whom Archer knew regarded +any woman who loved imprudently as necessarily unscrupulous and +designing, and mere simple-minded man as powerless in her clutches. The +only thing to do was to persuade him, as early as possible, to marry a +nice girl, and then trust to her to look after him. + +In the complicated old European communities, Archer began to guess, +love-problems might be less simple and less easily classified. Rich and +idle and ornamental societies must produce many more such situations; +and there might even be one in which a woman naturally sensitive +and aloof would yet, from the force of circumstances, from sheer +defencelessness and loneliness, be drawn into a tie inexcusable by +conventional standards. + +On reaching home he wrote a line to the Countess Olenska, asking at +what hour of the next day she could receive him, and despatched it by +a messenger-boy, who returned presently with a word to the effect that +she was going to Skuytercliff the next morning to stay over Sunday with +the van der Luydens, but that he would find her alone that evening +after dinner. The note was written on a rather untidy half-sheet, +without date or address, but her hand was firm and free. He was amused +at the idea of her week-ending in the stately solitude of Skuytercliff, +but immediately afterward felt that there, of all places, she would +most feel the chill of minds rigorously averted from the "unpleasant." + + +He was at Mr. Letterblair's punctually at seven, glad of the pretext +for excusing himself soon after dinner. He had formed his own opinion +from the papers entrusted to him, and did not especially want to go +into the matter with his senior partner. Mr. Letterblair was a widower, +and they dined alone, copiously and slowly, in a dark shabby room hung +with yellowing prints of "The Death of Chatham" and "The Coronation of +Napoleon." On the sideboard, between fluted Sheraton knife-cases, stood +a decanter of Haut Brion, and another of the old Lanning port (the gift +of a client), which the wastrel Tom Lanning had sold off a year or two +before his mysterious and discreditable death in San Francisco--an +incident less publicly humiliating to the family than the sale of the +cellar. + +After a velvety oyster soup came shad and cucumbers, then a young +broiled turkey with corn fritters, followed by a canvas-back with +currant jelly and a celery mayonnaise. Mr. Letterblair, who lunched +on a sandwich and tea, dined deliberately and deeply, and insisted +on his guest's doing the same. Finally, when the closing rites had +been accomplished, the cloth was removed, cigars were lit, and Mr. +Letterblair, leaning back in his chair and pushing the port westward, +said, spreading his back agreeably to the coal fire behind him: "The +whole family are against a divorce. And I think rightly." + +Archer instantly felt himself on the other side of the argument. "But +why, sir? If there ever was a case--" + +"Well--what's the use? _she's_ here--he's there; the Atlantic's between +them. She'll never get back a dollar more of her money than what he's +voluntarily returned to her: their damned heathen marriage settlements +take precious good care of that. As things go over there, Olenski's +acted generously: he might have turned her out without a penny." + +The young man knew this and was silent. + +"I understand, though," Mr. Letterblair continued, "that she attaches +no importance to the money. Therefore, as the family say, why not let +well enough alone?" + +Archer had gone to the house an hour earlier in full agreement with Mr. +Letterblair's view; but put into words by this selfish, well-fed and +supremely indifferent old man it suddenly became the Pharisaic voice of +a society wholly absorbed in barricading itself against the unpleasant. + +"I think that's for her to decide." + +"H'm--have you considered the consequences if she decides for divorce?" + +"You mean the threat in her husband's letter? What weight would that +carry? It's no more than the vague charge of an angry blackguard." + +"Yes; but it might make some unpleasant talk if he really defends the +suit." + +"Unpleasant--!" said Archer explosively. + +Mr. Letterblair looked at him from under enquiring eyebrows, and the +young man, aware of the uselessness of trying to explain what was in +his mind, bowed acquiescently while his senior continued: "Divorce is +always unpleasant." + +"You agree with me?" Mr. Letterblair resumed, after a waiting silence. + +"Naturally," said Archer. + +"Well, then, I may count on you; the Mingotts may count on you; to use +your influence against the idea?" + +Archer hesitated. "I can't pledge myself till I've seen the Countess +Olenska," he said at length. + +"Mr. Archer, I don't understand you. Do you want to marry into a family +with a scandalous divorce-suit hanging over it?" + +"I don't think that has anything to do with the case." + +Mr. Letterblair put down his glass of port and fixed on his young +partner a cautious and apprehensive gaze. + +Archer understood that he ran the risk of having his mandate withdrawn, +and for some obscure reason he disliked the prospect. Now that the +job had been thrust on him he did not propose to relinquish it; and, +to guard against the possibility, he saw that he must reassure the +unimaginative old man who was the legal conscience of the Mingotts. + +"You may be sure, sir, that I shan't commit myself till I've reported +to you; what I meant was that I'd rather not give an opinion till I've +heard what Madame Olenska has to say." + +Mr. Letterblair nodded approvingly at an excess of caution worthy of +the best New York tradition, and the young man, glancing at his watch, +pleaded an engagement and took leave. + + + + +XII. + + +Old-fashioned New York dined at seven, and the habit of after-dinner +calls, though derided in Archer's set, still generally prevailed. As +the young man strolled up Fifth Avenue from Waverley Place, the long +thoroughfare was deserted but for a group of carriages standing before +the Reggie Chiverses' (where there was a dinner for the Duke), and the +occasional figure of an elderly gentleman in heavy overcoat and muffler +ascending a brownstone doorstep and disappearing into a gas-lit hall. +Thus, as Archer crossed Washington Square, he remarked that old Mr. +du Lac was calling on his cousins the Dagonets, and turning down the +corner of West Tenth Street he saw Mr. Skipworth, of his own firm, +obviously bound on a visit to the Miss Lannings. A little farther up +Fifth Avenue, Beaufort appeared on his doorstep, darkly projected +against a blaze of light, descended to his private brougham, and rolled +away to a mysterious and probably unmentionable destination. It was +not an Opera night, and no one was giving a party, so that Beaufort's +outing was undoubtedly of a clandestine nature. Archer connected it +in his mind with a little house beyond Lexington Avenue in which +beribboned window curtains and flower-boxes had recently appeared, and +before whose newly painted door the canary-coloured brougham of Miss +Fanny Ring was frequently seen to wait. + +Beyond the small and slippery pyramid which composed Mrs. Archer's +world lay the almost unmapped quarter inhabited by artists, musicians +and "people who wrote." These scattered fragments of humanity had +never shown any desire to be amalgamated with the social structure. +In spite of odd ways they were said to be, for the most part, quite +respectable; but they preferred to keep to themselves. Medora Manson, +in her prosperous days, had inaugurated a "literary salon"; but it had +soon died out owing to the reluctance of the literary to frequent it. + +Others had made the same attempt, and there was a household of +Blenkers--an intense and voluble mother, and three blowsy daughters +who imitated her--where one met Edwin Booth and Patti and William +Winter, and the new Shakespearian actor George Rignold, and some of the +magazine editors and musical and literary critics. + +Mrs. Archer and her group felt a certain timidity concerning these +persons. They were odd, they were uncertain, they had things one didn't +know about in the background of their lives and minds. Literature and +art were deeply respected in the Archer set, and Mrs. Archer was always +at pains to tell her children how much more agreeable and cultivated +society had been when it included such figures as Washington Irving, +Fitz-Greene Halleck and the poet of "The Culprit Fay." The most +celebrated authors of that generation had been "gentlemen"; perhaps +the unknown persons who succeeded them had gentlemanly sentiments, but +their origin, their appearance, their hair, their intimacy with the +stage and the Opera, made any old New York criterion inapplicable to +them. + +"When I was a girl," Mrs. Archer used to say, "we knew everybody +between the Battery and Canal Street; and only the people one knew had +carriages. It was perfectly easy to place any one then; now one can't +tell, and I prefer not to try." + +Only old Catherine Mingott, with her absence of moral prejudices and +almost parvenu indifference to the subtler distinctions, might have +bridged the abyss; but she had never opened a book or looked at a +picture, and cared for music only because it reminded her of gala +nights at the Italiens, in the days of her triumph at the Tuileries. +Possibly Beaufort, who was her match in daring, would have succeeded +in bringing about a fusion; but his grand house and silk-stockinged +footmen were an obstacle to informal sociability. Moreover, he was as +illiterate as old Mrs. Mingott, and considered "fellows who wrote" as +the mere paid purveyors of rich men's pleasures; and no one rich enough +to influence his opinion had ever questioned it. + +Newland Archer had been aware of these things ever since he could +remember, and had accepted them as part of the structure of his +universe. He knew that there were societies where painters and poets +and novelists and men of science, and even great actors, were as sought +after as Dukes; he had often pictured to himself what it would have +been to live in the intimacy of drawing-rooms dominated by the talk of +Mérimée (whose "Lettres à une Inconnue" was one of his inseparables), +of Thackeray, Browning or William Morris. But such things were +inconceivable in New York, and unsettling to think of. Archer knew most +of the "fellows who wrote," the musicians and the painters: he met them +at the Century, or at the little musical and theatrical clubs that were +beginning to come into existence. He enjoyed them there, and was bored +with them at the Blenkers', where they were mingled with fervid and +dowdy women who passed them about like captured curiosities; and even +after his most exciting talks with Ned Winsett he always came away with +the feeling that if his world was small, so was theirs, and that the +only way to enlarge either was to reach a stage of manners where they +would naturally merge. + +He was reminded of this by trying to picture the society in which the +Countess Olenska had lived and suffered, and also--perhaps--tasted +mysterious joys. He remembered with what amusement she had told him +that her grandmother Mingott and the Wellands objected to her living in +a "Bohemian" quarter given over to "people who wrote." It was not the +peril but the poverty that her family disliked; but that shade escaped +her, and she supposed they considered literature compromising. + +She herself had no fears of it, and the books scattered about her +drawing-room (a part of the house in which books were usually supposed +to be "out of place"), though chiefly works of fiction, had whetted +Archer's interest with such new names as those of Paul Bourget, +Huysmans, and the Goncourt brothers. Ruminating on these things as he +approached her door, he was once more conscious of the curious way in +which she reversed his values, and of the need of thinking himself into +conditions incredibly different from any that he knew if he were to be +of use in her present difficulty. + + +Nastasia opened the door, smiling mysteriously. On the bench in the +hall lay a sable-lined overcoat, a folded opera hat of dull silk with +a gold J. B. on the lining, and a white silk muffler: there was no +mistaking the fact that these costly articles were the property of +Julius Beaufort. + +Archer was angry: so angry that he came near scribbling a word on his +card and going away; then he remembered that in writing to Madame +Olenska he had been kept by excess of discretion from saying that he +wished to see her privately. He had therefore no one but himself to +blame if she had opened her doors to other visitors; and he entered +the drawing-room with the dogged determination to make Beaufort feel +himself in the way, and to outstay him. + +The banker stood leaning against the mantelshelf, which was draped +with an old embroidery held in place by brass candelabra containing +church candles of yellowish wax. He had thrust his chest out, +supporting his shoulders against the mantel and resting his weight +on one large patent-leather foot. As Archer entered he was smiling +and looking down on his hostess, who sat on a sofa placed at right +angles to the chimney. A table banked with flowers formed a screen +behind it, and against the orchids and azaleas which the young man +recognised as tributes from the Beaufort hot-houses, Madame Olenska sat +half-reclined, her head propped on a hand and her wide sleeve leaving +the arm bare to the elbow. + +It was usual for ladies who received in the evenings to wear what were +called "simple dinner dresses": a close-fitting armour of whale-boned +silk, slightly open in the neck, with lace ruffles filling in the +crack, and tight sleeves with a flounce uncovering just enough wrist to +show an Etruscan gold bracelet or a velvet band. But Madame Olenska, +heedless of tradition, was attired in a long robe of red velvet +bordered about the chin and down the front with glossy black fur. +Archer remembered, on his last visit to Paris, seeing a portrait by the +new painter, Carolus Duran, whose pictures were the sensation of the +Salon, in which the lady wore one of these bold sheath-like robes with +her chin nestling in fur. There was something perverse and provocative +in the notion of fur worn in the evening in a heated drawing-room, and +in the combination of a muffled throat and bare arms; but the effect +was undeniably pleasing. + +"Lord love us--three whole days at Skuytercliff!" Beaufort was saying +in his loud sneering voice as Archer entered. "You'd better take all +your furs, and a hot-water-bottle." + +"Why? Is the house so cold?" she asked, holding out her left hand to +Archer in a way mysteriously suggesting that she expected him to kiss +it. + +"No; but the missus is," said Beaufort, nodding carelessly to the young +man. + +"But I thought her so kind. She came herself to invite me. Granny says +I must certainly go." + +"Granny would, of course. And I say it's a shame you're going to miss +the little oyster supper I'd planned for you at Delmonico's next +Sunday, with Campanini and Scalchi and a lot of jolly people." + +She looked doubtfully from the banker to Archer. + +"Ah--that does tempt me! Except the other evening at Mrs. Struthers's +I've not met a single artist since I've been here." + +"What kind of artists? I know one or two painters, very good fellows, +that I could bring to see you if you'd allow me," said Archer boldly. + +"Painters? Are there painters in New York?" asked Beaufort, in a tone +implying that there could be none since he did not buy their pictures; +and Madame Olenska said to Archer, with her grave smile: "That would +be charming. But I was really thinking of dramatic artists, singers, +actors, musicians. My husband's house was always full of them." + +She said the words "my husband" as if no sinister associations were +connected with them, and in a tone that seemed almost to sigh over the +lost delights of her married life. Archer looked at her perplexedly, +wondering if it were lightness or dissimulation that enabled her to +touch so easily on the past at the very moment when she was risking her +reputation in order to break with it. + +"I do think," she went on, addressing both men, "that the _imprévu_ adds +to one's enjoyment. It's perhaps a mistake to see the same people every +day." + +"It's confoundedly dull, anyhow; New York is dying of dullness," +Beaufort grumbled. "And when I try to liven it up for you, you go +back on me. Come--think better of it! Sunday is your last chance, for +Campanini leaves next week for Baltimore and Philadelphia; and I've a +private room, and a Steinway, and they'll sing all night for me." + +"How delicious! May I think it over, and write to you tomorrow morning?" + +She spoke amiably, yet with the least hint of dismissal in her voice. +Beaufort evidently felt it, and being unused to dismissals, stood +staring at her with an obstinate line between his eyes. + +"Why not now?" + +"It's too serious a question to decide at this late hour." + +"Do you call it late?" + +She returned his glance coolly. "Yes; because I have still to talk +business with Mr. Archer for a little while." + +"Ah," Beaufort snapped. There was no appeal from her tone, and with a +slight shrug he recovered his composure, took her hand, which he kissed +with a practised air, and calling out from the threshold: "I say, +Newland, if you can persuade the Countess to stop in town of course +you're included in the supper," left the room with his heavy important +step. + +For a moment Archer fancied that Mr. Letterblair must have told her of +his coming; but the irrelevance of her next remark made him change his +mind. + +"You know painters, then? You live in their milieu?" she asked, her +eyes full of interest. + +"Oh, not exactly. I don't know that the arts have a milieu here, any of +them; they're more like a very thinly settled outskirt." + +"But you care for such things?" + +"Immensely. When I'm in Paris or London I never miss an exhibition. I +try to keep up." + +She looked down at the tip of the little satin boot that peeped from +her long draperies. + +"I used to care immensely too: my life was full of such things. But now +I want to try not to." + +"You want to try not to?" + +"Yes: I want to cast off all my old life, to become just like everybody +else here." + +Archer reddened. "You'll never be like everybody else," he said. + +She raised her straight eyebrows a little. "Ah, don't say that. If you +knew how I hate to be different!" + +Her face had grown as sombre as a tragic mask. She leaned forward, +clasping her knee in her thin hands, and looking away from him into +remote dark distances. + +"I want to get away from it all," she insisted. + +He waited a moment and cleared his throat. "I know. Mr. Letterblair has +told me." + +"Ah?" + +"That's the reason I've come. He asked me to--you see I'm in the firm." + +She looked slightly surprised, and then her eyes brightened. "You mean +you can manage it for me? I can talk to you instead of Mr. Letterblair? +Oh, that will be so much easier!" + +Her tone touched him, and his confidence grew with his +self-satisfaction. He perceived that she had spoken of business to +Beaufort simply to get rid of him; and to have routed Beaufort was +something of a triumph. + +"I am here to talk about it," he repeated. + +She sat silent, her head still propped by the arm that rested on the +back of the sofa. Her face looked pale and extinguished, as if dimmed +by the rich red of her dress. She struck Archer, of a sudden, as a +pathetic and even pitiful figure. + +"Now we're coming to hard facts," he thought, conscious in himself +of the same instinctive recoil that he had so often criticised in +his mother and her contemporaries. How little practice he had had in +dealing with unusual situations! Their very vocabulary was unfamiliar +to him, and seemed to belong to fiction and the stage. In face of what +was coming he felt as awkward and embarrassed as a boy. + +After a pause Madame Olenska broke out with unexpected vehemence: "I +want to be free; I want to wipe out all the past." + +"I understand that." + +Her face warmed. "Then you'll help me?" + +"First--" he hesitated--"perhaps I ought to know a little more." + +She seemed surprised. "You know about my husband--my life with him?" + +He made a sign of assent. + +"Well--then--what more is there? In this country are such things +tolerated? I'm a Protestant--our church does not forbid divorce in such +cases." + +"Certainly not." + +They were both silent again, and Archer felt the spectre of Count +Olenski's letter grimacing hideously between them. The letter filled +only half a page, and was just what he had described it to be in +speaking of it to Mr. Letterblair: the vague charge of an angry +blackguard. But how much truth was behind it? Only Count Olenski's wife +could tell. + +"I've looked through the papers you gave to Mr. Letterblair," he said +at length. + +"Well--can there be anything more abominable?" + +"No." + +She changed her position slightly, screening her eyes with her lifted +hand. + +"Of course you know," Archer continued, "that if your husband chooses +to fight the case--as he threatens to--" + +"Yes--?" + +"He can say things--things that might be unpl--might be disagreeable to +you: say them publicly, so that they would get about, and harm you even +if--" + +"If--?" + +"I mean: no matter how unfounded they were." + +She paused for a long interval; so long that, not wishing to keep his +eyes on her shaded face, he had time to imprint on his mind the exact +shape of her other hand, the one on her knee, and every detail of the +three rings on her fourth and fifth fingers; among which, he noticed, a +wedding ring did not appear. + +"What harm could such accusations, even if he made them publicly, do me +here?" + +It was on his lips to exclaim: "My poor child--far more harm than +anywhere else!" Instead, he answered, in a voice that sounded in his +ears like Mr. Letterblair's: "New York society is a very small world +compared with the one you've lived in. And it's ruled, in spite of +appearances, by a few people with--well, rather old-fashioned ideas." + +She said nothing, and he continued: "Our ideas about marriage and +divorce are particularly old-fashioned. Our legislation favours +divorce--our social customs don't." + +"Never?" + +"Well--not if the woman, however injured, however irreproachable, has +appearances in the least degree against her, has exposed herself by any +unconventional action to--to offensive insinuations--" + +She drooped her head a little lower, and he waited again, intensely +hoping for a flash of indignation, or at least a brief cry of denial. +None came. + +A little travelling clock ticked purringly at her elbow, and a log +broke in two and sent up a shower of sparks. The whole hushed and +brooding room seemed to be waiting silently with Archer. + +"Yes," she murmured at length, "that's what my family tell me." + +He winced a little. "It's not unnatural--" + +"_Our_ family," she corrected herself; and Archer coloured. "For you'll +be my cousin soon," she continued gently. + +"I hope so." + +"And you take their view?" + +He stood up at this, wandered across the room, stared with void eyes +at one of the pictures against the old red damask, and came back +irresolutely to her side. How could he say: "Yes, if what your husband +hints is true, or if you've no way of disproving it?" + +"Sincerely--" she interjected, as he was about to speak. + +He looked down into the fire. "Sincerely, then--what should you gain +that would compensate for the possibility--the certainty--of a lot of +beastly talk?" + +"But my freedom--is that nothing?" + +It flashed across him at that instant that the charge in the letter was +true, and that she hoped to marry the partner of her guilt. How was +he to tell her that, if she really cherished such a plan, the laws of +the State were inexorably opposed to it? The mere suspicion that the +thought was in her mind made him feel harshly and impatiently toward +her. "But aren't you as free as air as it is?" he returned. "Who can +touch you? Mr. Letterblair tells me the financial question has been +settled--" + +"Oh, yes," she said indifferently. + +"Well, then: is it worth while to risk what may be infinitely +disagreeable and painful? Think of the newspapers--their vileness! It's +all stupid and narrow and unjust--but one can't make over society." + +"No," she acquiesced; and her tone was so faint and desolate that he +felt a sudden remorse for his own hard thoughts. + +"The individual, in such cases, is nearly always sacrificed to what is +supposed to be the collective interest: people cling to any convention +that keeps the family together--protects the children, if there are +any," he rambled on, pouring out all the stock phrases that rose to his +lips in his intense desire to cover over the ugly reality which her +silence seemed to have laid bare. Since she would not or could not say +the one word that would have cleared the air, his wish was not to let +her feel that he was trying to probe into her secret. Better keep on +the surface, in the prudent old New York way, than risk uncovering a +wound he could not heal. + +"It's my business, you know," he went on, "to help you to see these +things as the people who are fondest of you see them. The Mingotts, the +Wellands, the van der Luydens, all your friends and relations: if I +didn't show you honestly how they judge such questions, it wouldn't be +fair of me, would it?" He spoke insistently, almost pleading with her +in his eagerness to cover up that yawning silence. + +She said slowly: "No; it wouldn't be fair." + +The fire had crumbled down to greyness, and one of the lamps made a +gurgling appeal for attention. Madame Olenska rose, wound it up and +returned to the fire, but without resuming her seat. + +Her remaining on her feet seemed to signify that there was nothing more +for either of them to say, and Archer stood up also. + +"Very well; I will do what you wish," she said abruptly. The blood +rushed to his forehead; and, taken aback by the suddenness of her +surrender, he caught her two hands awkwardly in his. + +"I--I do want to help you," he said. + +"You do help me. Good night, my cousin." + +He bent and laid his lips on her hands, which were cold and lifeless. +She drew them away, and he turned to the door, found his coat and hat +under the faint gas-light of the hall, and plunged out into the winter +night bursting with the belated eloquence of the inarticulate. + + + + +XIII. + + +It was a crowded night at Wallack's theatre. + +The play was "The Shaughraun," with Dion Boucicault in the title role +and Harry Montague and Ada Dyas as the lovers. The popularity of the +admirable English company was at its height, and the Shaughraun always +packed the house. In the galleries the enthusiasm was unreserved; +in the stalls and boxes, people smiled a little at the hackneyed +sentiments and clap-trap situations, and enjoyed the play as much as +the galleries did. + +There was one episode, in particular, that held the house from floor +to ceiling. It was that in which Harry Montague, after a sad, almost +monosyllabic scene of parting with Miss Dyas, bade her good-bye, and +turned to go. The actress, who was standing near the mantelpiece +and looking down into the fire, wore a gray cashmere dress without +fashionable loopings or trimmings, moulded to her tall figure and +flowing in long lines about her feet. Around her neck was a narrow +black velvet ribbon with the ends falling down her back. + +When her wooer turned from her she rested her arms against the +mantel-shelf and bowed her face in her hands. On the threshold he +paused to look at her; then he stole back, lifted one of the ends of +velvet ribbon, kissed it, and left the room without her hearing him or +changing her attitude. And on this silent parting the curtain fell. + +It was always for the sake of that particular scene that Newland Archer +went to see "The Shaughraun." He thought the adieux of Montague and Ada +Dyas as fine as anything he had ever seen Croisette and Bressant do +in Paris, or Madge Robertson and Kendal in London; in its reticence, +its dumb sorrow, it moved him more than the most famous histrionic +outpourings. + +On the evening in question the little scene acquired an added poignancy +by reminding him--he could not have said why--of his leave-taking from +Madame Olenska after their confidential talk a week or ten days earlier. + +It would have been as difficult to discover any resemblance between +the two situations as between the appearance of the persons concerned. +Newland Archer could not pretend to anything approaching the young +English actor's romantic good looks, and Miss Dyas was a tall +red-haired woman of monumental build whose pale and pleasantly ugly +face was utterly unlike Ellen Olenska's vivid countenance. Nor were +Archer and Madame Olenska two lovers parting in heart-broken silence; +they were client and lawyer separating after a talk which had given the +lawyer the worst possible impression of the client's case. Wherein, +then, lay the resemblance that made the young man's heart beat with a +kind of retrospective excitement? It seemed to be in Madame Olenska's +mysterious faculty of suggesting tragic and moving possibilities +outside the daily run of experience. She had hardly ever said a word +to him to produce this impression, but it was a part of her, either a +projection of her mysterious and outlandish background or of something +inherently dramatic, passionate and unusual in herself. Archer had +always been inclined to think that chance and circumstance played a +small part in shaping people's lots compared with their innate tendency +to have things happen to them. This tendency he had felt from the first +in Madame Olenska. The quiet, almost passive young woman struck him +as exactly the kind of person to whom things were bound to happen, no +matter how much she shrank from them and went out of her way to avoid +them. The exciting fact was her having lived in an atmosphere so thick +with drama that her own tendency to provoke it had apparently passed +unperceived. It was precisely the odd absence of surprise in her that +gave him the sense of her having been plucked out of a very maelstrom: +the things she took for granted gave the measure of those she had +rebelled against. + +Archer had left her with the conviction that Count Olenski's accusation +was not unfounded. The mysterious person who figured in his wife's past +as "the secretary" had probably not been unrewarded for his share in +her escape. The conditions from which she had fled were intolerable, +past speaking of, past believing: she was young, she was frightened, +she was desperate--what more natural than that she should be grateful +to her rescuer? The pity was that her gratitude put her, in the law's +eyes and the world's, on a par with her abominable husband. Archer had +made her understand this, as he was bound to do; he had also made her +understand that simple-hearted kindly New York, on whose larger charity +she had apparently counted, was precisely the place where she could +least hope for indulgence. + +To have to make this fact plain to her--and to witness her resigned +acceptance of it--had been intolerably painful to him. He felt himself +drawn to her by obscure feelings of jealousy and pity, as if her +dumbly-confessed error had put her at his mercy, humbling yet endearing +her. He was glad it was to him she had revealed her secret, rather than +to the cold scrutiny of Mr. Letterblair, or the embarrassed gaze of her +family. He immediately took it upon himself to assure them both that +she had given up her idea of seeking a divorce, basing her decision on +the fact that she had understood the uselessness of the proceeding; +and with infinite relief they had all turned their eyes from the +"unpleasantness" she had spared them. + +"I was sure Newland would manage it," Mrs. Welland had said proudly of +her future son-in-law; and old Mrs. Mingott, who had summoned him for +a confidential interview, had congratulated him on his cleverness, and +added impatiently: "Silly goose! I told her myself what nonsense it +was. Wanting to pass herself off as Ellen Mingott and an old maid, when +she has the luck to be a married woman and a Countess!" + +These incidents had made the memory of his last talk with Madame +Olenska so vivid to the young man that as the curtain fell on the +parting of the two actors his eyes filled with tears, and he stood up +to leave the theatre. + +In doing so, he turned to the side of the house behind him, and saw +the lady of whom he was thinking seated in a box with the Beauforts, +Lawrence Lefferts and one or two other men. He had not spoken with +her alone since their evening together, and had tried to avoid being +with her in company; but now their eyes met, and as Mrs. Beaufort +recognised him at the same time, and made her languid little gesture of +invitation, it was impossible not to go into the box. + +Beaufort and Lefferts made way for him, and after a few words with Mrs. +Beaufort, who always preferred to look beautiful and not have to talk, +Archer seated himself behind Madame Olenska. There was no one else in +the box but Mr. Sillerton Jackson, who was telling Mrs. Beaufort in +a confidential undertone about Mrs. Lemuel Struthers's last Sunday +reception (where some people reported that there had been dancing). +Under cover of this circumstantial narrative, to which Mrs. Beaufort +listened with her perfect smile, and her head at just the right angle +to be seen in profile from the stalls, Madame Olenska turned and spoke +in a low voice. + +"Do you think," she asked, glancing toward the stage, "he will send her +a bunch of yellow roses tomorrow morning?" + +Archer reddened, and his heart gave a leap of surprise. He had called +only twice on Madame Olenska, and each time he had sent her a box of +yellow roses, and each time without a card. She had never before made +any allusion to the flowers, and he supposed she had never thought of +him as the sender. Now her sudden recognition of the gift, and her +associating it with the tender leave-taking on the stage, filled him +with an agitated pleasure. + +"I was thinking of that too--I was going to leave the theatre in order +to take the picture away with me," he said. + +To his surprise her colour rose, reluctantly and duskily. She looked +down at the mother-of-pearl opera-glass in her smoothly gloved hands, +and said, after a pause: "What do you do while May is away?" + +"I stick to my work," he answered, faintly annoyed by the question. + +In obedience to a long-established habit, the Wellands had left the +previous week for St. Augustine, where, out of regard for the supposed +susceptibility of Mr. Welland's bronchial tubes, they always spent +the latter part of the winter. Mr. Welland was a mild and silent man, +with no opinions but with many habits. With these habits none might +interfere; and one of them demanded that his wife and daughter should +always go with him on his annual journey to the south. To preserve an +unbroken domesticity was essential to his peace of mind; he would not +have known where his hair-brushes were, or how to provide stamps for +his letters, if Mrs. Welland had not been there to tell him. + +As all the members of the family adored each other, and as Mr. Welland +was the central object of their idolatry, it never occurred to his wife +and May to let him go to St. Augustine alone; and his sons, who were +both in the law, and could not leave New York during the winter, always +joined him for Easter and travelled back with him. + +It was impossible for Archer to discuss the necessity of May's +accompanying her father. The reputation of the Mingotts' family +physician was largely based on the attack of pneumonia which Mr. +Welland had never had; and his insistence on St. Augustine was +therefore inflexible. Originally, it had been intended that May's +engagement should not be announced till her return from Florida, and +the fact that it had been made known sooner could not be expected +to alter Mr. Welland's plans. Archer would have liked to join the +travellers and have a few weeks of sunshine and boating with his +betrothed; but he too was bound by custom and conventions. Little +arduous as his professional duties were, he would have been convicted +of frivolity by the whole Mingott clan if he had suggested asking for +a holiday in mid-winter; and he accepted May's departure with the +resignation which he perceived would have to be one of the principal +constituents of married life. + +He was conscious that Madame Olenska was looking at him under lowered +lids. "I have done what you wished--what you advised," she said +abruptly. + +"Ah--I'm glad," he returned, embarrassed by her broaching the subject +at such a moment. + +"I understand--that you were right," she went on a little breathlessly; +"but sometimes life is difficult ... perplexing..." + +"I know." + +"And I wanted to tell you that I _do_ feel you were right; and that I'm +grateful to you," she ended, lifting her opera-glass quickly to her +eyes as the door of the box opened and Beaufort's resonant voice broke +in on them. + +Archer stood up, and left the box and the theatre. + +Only the day before he had received a letter from May Welland in +which, with characteristic candour, she had asked him to "be kind to +Ellen" in their absence. "She likes you and admires you so much--and +you know, though she doesn't show it, she's still very lonely and +unhappy. I don't think Granny understands her, or uncle Lovell Mingott +either; they really think she's much worldlier and fonder of society +than she is. And I can quite see that New York must seem dull to her, +though the family won't admit it. I think she's been used to lots +of things we haven't got; wonderful music, and picture shows, and +celebrities--artists and authors and all the clever people you admire. +Granny can't understand her wanting anything but lots of dinners and +clothes--but I can see that you're almost the only person in New York +who can talk to her about what she really cares for." + +His wise May--how he had loved her for that letter! But he had not +meant to act on it; he was too busy, to begin with, and he did not +care, as an engaged man, to play too conspicuously the part of Madame +Olenska's champion. He had an idea that she knew how to take care of +herself a good deal better than the ingenuous May imagined. She had +Beaufort at her feet, Mr. van der Luyden hovering above her like a +protecting deity, and any number of candidates (Lawrence Lefferts among +them) waiting their opportunity in the middle distance. Yet he never +saw her, or exchanged a word with her, without feeling that, after all, +May's ingenuousness almost amounted to a gift of divination. Ellen +Olenska was lonely and she was unhappy. + + + + +XIV. + + +As he came out into the lobby Archer ran across his friend Ned Winsett, +the only one among what Janey called his "clever people" with whom he +cared to probe into things a little deeper than the average level of +club and chop-house banter. + +He had caught sight, across the house, of Winsett's shabby +round-shouldered back, and had once noticed his eyes turned toward the +Beaufort box. The two men shook hands, and Winsett proposed a bock at a +little German restaurant around the corner. Archer, who was not in the +mood for the kind of talk they were likely to get there, declined on +the plea that he had work to do at home; and Winsett said: "Oh, well so +have I for that matter, and I'll be the Industrious Apprentice too." + +They strolled along together, and presently Winsett said: "Look here, +what I'm really after is the name of the dark lady in that swell box +of yours--with the Beauforts, wasn't she? The one your friend Lefferts +seems so smitten by." + +Archer, he could not have said why, was slightly annoyed. What the +devil did Ned Winsett want with Ellen Olenska's name? And above all, +why did he couple it with Lefferts's? It was unlike Winsett to manifest +such curiosity; but after all, Archer remembered, he was a journalist. + +"It's not for an interview, I hope?" he laughed. + +"Well--not for the press; just for myself," Winsett rejoined. "The +fact is she's a neighbour of mine--queer quarter for such a beauty to +settle in--and she's been awfully kind to my little boy, who fell down +her area chasing his kitten, and gave himself a nasty cut. She rushed +in bareheaded, carrying him in her arms, with his knee all beautifully +bandaged, and was so sympathetic and beautiful that my wife was too +dazzled to ask her name." + +A pleasant glow dilated Archer's heart. There was nothing extraordinary +in the tale: any woman would have done as much for a neighbour's child. +But it was just like Ellen, he felt, to have rushed in bareheaded, +carrying the boy in her arms, and to have dazzled poor Mrs. Winsett +into forgetting to ask who she was. + +"That is the Countess Olenska--a granddaughter of old Mrs. Mingott's." + +"Whew--a Countess!" whistled Ned Winsett. "Well, I didn't know +Countesses were so neighbourly. Mingotts ain't." + +"They would be, if you'd let them." + +"Ah, well--" It was their old interminable argument as to the obstinate +unwillingness of the "clever people" to frequent the fashionable, and +both men knew that there was no use in prolonging it. + +"I wonder," Winsett broke off, "how a Countess happens to live in our +slum?" + +"Because she doesn't care a hang about where she lives--or about any of +our little social sign-posts," said Archer, with a secret pride in his +own picture of her. + +"H'm--been in bigger places, I suppose," the other commented. "Well, +here's my corner." + +He slouched off across Broadway, and Archer stood looking after him and +musing on his last words. + +Ned Winsett had those flashes of penetration; they were the most +interesting thing about him, and always made Archer wonder why they had +allowed him to accept failure so stolidly at an age when most men are +still struggling. + +Archer had known that Winsett had a wife and child, but he had never +seen them. The two men always met at the Century, or at some haunt of +journalists and theatrical people, such as the restaurant where Winsett +had proposed to go for a bock. He had given Archer to understand that +his wife was an invalid; which might be true of the poor lady, or +might merely mean that she was lacking in social gifts or in evening +clothes, or in both. Winsett himself had a savage abhorrence of social +observances: Archer, who dressed in the evening because he thought it +cleaner and more comfortable to do so, and who had never stopped to +consider that cleanliness and comfort are two of the costliest items +in a modest budget, regarded Winsett's attitude as part of the boring +"Bohemian" pose that always made fashionable people, who changed +their clothes without talking about it, and were not forever harping +on the number of servants one kept, seem so much simpler and less +self-conscious than the others. Nevertheless, he was always stimulated +by Winsett, and whenever he caught sight of the journalist's lean +bearded face and melancholy eyes he would rout him out of his corner +and carry him off for a long talk. + +Winsett was not a journalist by choice. He was a pure man of letters, +untimely born in a world that had no need of letters; but after +publishing one volume of brief and exquisite literary appreciations, +of which one hundred and twenty copies were sold, thirty given away, +and the balance eventually destroyed by the publishers (as per +contract) to make room for more marketable material, he had abandoned +his real calling, and taken a sub-editorial job on a women's weekly, +where fashion-plates and paper patterns alternated with New England +love-stories and advertisements of temperance drinks. + +On the subject of "Hearth-fires" (as the paper was called) he was +inexhaustibly entertaining; but beneath his fun lurked the sterile +bitterness of the still young man who has tried and given up. His +conversation always made Archer take the measure of his own life, and +feel how little it contained; but Winsett's, after all, contained +still less, and though their common fund of intellectual interests and +curiosities made their talks exhilarating, their exchange of views +usually remained within the limits of a pensive dilettantism. + +"The fact is, life isn't much a fit for either of us," Winsett had once +said. "I'm down and out; nothing to be done about it. I've got only one +ware to produce, and there's no market for it here, and won't be in +my time. But you're free and you're well-off. Why don't _you_ get into +touch? There's only one way to do it: to go into politics." + +Archer threw his head back and laughed. There one saw at a flash +the unbridgeable difference between men like Winsett and the +others--Archer's kind. Every one in polite circles knew that, in +America, "a gentleman couldn't go into politics." But, since he could +hardly put it in that way to Winsett, he answered evasively: "Look at +the career of the honest man in American politics! They don't want us." + +"Who's 'they'? Why don't you all get together and be 'they' yourselves?" + +Archer's laugh lingered on his lips in a slightly condescending smile. +It was useless to prolong the discussion: everybody knew the melancholy +fate of the few gentlemen who had risked their clean linen in municipal +or state politics in New York. The day was past when that sort of thing +was possible: the country was in possession of the bosses and the +emigrant, and decent people had to fall back on sport or culture. + +"Culture! Yes--if we had it! But there are just a few little local +patches, dying out here and there for lack of--well, hoeing and +cross-fertilising: the last remnants of the old European tradition +that your forebears brought with them. But you're in a pitiful little +minority: you've got no centre, no competition, no audience. You're +like the pictures on the walls of a deserted house: 'The Portrait of a +Gentleman.' You'll never amount to anything, any of you, till you roll +up your sleeves and get right down into the muck. That, or emigrate ... +God! If I could emigrate ..." + +Archer mentally shrugged his shoulders and turned the conversation +back to books, where Winsett, if uncertain, was always interesting. +Emigrate! As if a gentleman could abandon his own country! One could no +more do that than one could roll up one's sleeves and go down into the +muck. A gentleman simply stayed at home and abstained. But you couldn't +make a man like Winsett see that; and that was why the New York of +literary clubs and exotic restaurants, though a first shake made it +seem more of a kaleidoscope, turned out, in the end, to be a smaller +box, with a more monotonous pattern, than the assembled atoms of Fifth +Avenue. + + +The next morning Archer scoured the town in vain for more yellow +roses. In consequence of this search he arrived late at the office, +perceived that his doing so made no difference whatever to any one, +and was filled with sudden exasperation at the elaborate futility +of his life. Why should he not be, at that moment, on the sands of +St. Augustine with May Welland? No one was deceived by his pretense +of professional activity. In old-fashioned legal firms like that of +which Mr. Letterblair was the head, and which were mainly engaged in +the management of large estates and "conservative" investments, there +were always two or three young men, fairly well-off, and without +professional ambition, who, for a certain number of hours of each day, +sat at their desks accomplishing trivial tasks, or simply reading +the newspapers. Though it was supposed to be proper for them to have +an occupation, the crude fact of money-making was still regarded as +derogatory, and the law, being a profession, was accounted a more +gentlemanly pursuit than business. But none of these young men had much +hope of really advancing in his profession, or any earnest desire to +do so; and over many of them the green mould of the perfunctory was +already perceptibly spreading. + +It made Archer shiver to think that it might be spreading over him too. +He had, to be sure, other tastes and interests; he spent his vacations +in European travel, cultivated the "clever people" May spoke of, and +generally tried to "keep up," as he had somewhat wistfully put it to +Madame Olenska. But once he was married, what would become of this +narrow margin of life in which his real experiences were lived? He +had seen enough of other young men who had dreamed his dream, though +perhaps less ardently, and who had gradually sunk into the placid and +luxurious routine of their elders. + +From the office he sent a note by messenger to Madame Olenska, asking +if he might call that afternoon, and begging her to let him find a +reply at his club; but at the club he found nothing, nor did he receive +any letter the following day. This unexpected silence mortified him +beyond reason, and though the next morning he saw a glorious cluster +of yellow roses behind a florist's window-pane, he left it there. It +was only on the third morning that he received a line by post from +the Countess Olenska. To his surprise it was dated from Skuytercliff, +whither the van der Luydens had promptly retreated after putting the +Duke on board his steamer. + +"I ran away," the writer began abruptly (without the usual +preliminaries), "the day after I saw you at the play, and these kind +friends have taken me in. I wanted to be quiet, and think things over. +You were right in telling me how kind they were; I feel myself so safe +here. I wish that you were with us." She ended with a conventional +"Yours sincerely," and without any allusion to the date of her return. + +The tone of the note surprised the young man. What was Madame Olenska +running away from, and why did she feel the need to be safe? His first +thought was of some dark menace from abroad; then he reflected that he +did not know her epistolary style, and that it might run to picturesque +exaggeration. Women always exaggerated; and moreover she was not +wholly at her ease in English, which she often spoke as if she were +translating from the French. "Je me suis évadée--" put in that way, +the opening sentence immediately suggested that she might merely have +wanted to escape from a boring round of engagements; which was very +likely true, for he judged her to be capricious, and easily wearied of +the pleasure of the moment. + +It amused him to think of the van der Luydens' having carried her off +to Skuytercliff on a second visit, and this time for an indefinite +period. The doors of Skuytercliff were rarely and grudgingly opened +to visitors, and a chilly week-end was the most ever offered to the +few thus privileged. But Archer had seen, on his last visit to Paris, +the delicious play of Labiche, "Le Voyage de M. Perrichon," and he +remembered M. Perrichon's dogged and undiscouraged attachment to the +young man whom he had pulled out of the glacier. The van der Luydens +had rescued Madame Olenska from a doom almost as icy; and though there +were many other reasons for being attracted to her, Archer knew that +beneath them all lay the gentle and obstinate determination to go on +rescuing her. + +He felt a distinct disappointment on learning that she was away; and +almost immediately remembered that, only the day before, he had refused +an invitation to spend the following Sunday with the Reggie Chiverses +at their house on the Hudson, a few miles below Skuytercliff. + +He had had his fill long ago of the noisy friendly parties at Highbank, +with coasting, ice-boating, sleighing, long tramps in the snow, and a +general flavour of mild flirting and milder practical jokes. He had +just received a box of new books from his London book-seller, and had +preferred the prospect of a quiet Sunday at home with his spoils. But +he now went into the club writing-room, wrote a hurried telegram, and +told the servant to send it immediately. He knew that Mrs. Reggie +didn't object to her visitors' suddenly changing their minds, and that +there was always a room to spare in her elastic house. + + + + +XV. + + +Newland Archer arrived at the Chiverses' on Friday evening, and on +Saturday went conscientiously through all the rites appertaining to a +week-end at Highbank. + +In the morning he had a spin in the ice-boat with his hostess and a few +of the hardier guests; in the afternoon he "went over the farm" with +Reggie, and listened, in the elaborately appointed stables, to long +and impressive disquisitions on the horse; after tea he talked in a +corner of the firelit hall with a young lady who had professed herself +broken-hearted when his engagement was announced, but was now eager to +tell him of her own matrimonial hopes; and finally, about midnight, +he assisted in putting a gold-fish in one visitor's bed, dressed up a +burglar in the bath-room of a nervous aunt, and saw in the small hours +by joining in a pillow-fight that ranged from the nurseries to the +basement. But on Sunday after luncheon he borrowed a cutter, and drove +over to Skuytercliff. + +People had always been told that the house at Skuytercliff was an +Italian villa. Those who had never been to Italy believed it; so did +some who had. The house had been built by Mr. van der Luyden in his +youth, on his return from the "grand tour," and in anticipation of his +approaching marriage with Miss Louisa Dagonet. It was a large square +wooden structure, with tongued and grooved walls painted pale green and +white, a Corinthian portico, and fluted pilasters between the windows. +From the high ground on which it stood a series of terraces bordered +by balustrades and urns descended in the steel-engraving style to a +small irregular lake with an asphalt edge overhung by rare weeping +conifers. To the right and left, the famous weedless lawns studded with +"specimen" trees (each of a different variety) rolled away to long +ranges of grass crested with elaborate cast-iron ornaments; and below, +in a hollow, lay the four-roomed stone house which the first Patroon +had built on the land granted him in 1612. + +Against the uniform sheet of snow and the greyish winter sky the +Italian villa loomed up rather grimly; even in summer it kept its +distance, and the boldest coleus bed had never ventured nearer than +thirty feet from its awful front. Now, as Archer rang the bell, the +long tinkle seemed to echo through a mausoleum; and the surprise of the +butler who at length responded to the call was as great as though he +had been summoned from his final sleep. + +Happily Archer was of the family, and therefore, irregular though his +arrival was, entitled to be informed that the Countess Olenska was out, +having driven to afternoon service with Mrs. van der Luyden exactly +three quarters of an hour earlier. + +"Mr. van der Luyden," the butler continued, "is in, sir; but my +impression is that he is either finishing his nap or else reading +yesterday's Evening Post. I heard him say, sir, on his return from +church this morning, that he intended to look through the Evening Post +after luncheon; if you like, sir, I might go to the library door and +listen--" + +But Archer, thanking him, said that he would go and meet the ladies; +and the butler, obviously relieved, closed the door on him majestically. + +A groom took the cutter to the stables, and Archer struck through the +park to the high-road. The village of Skuytercliff was only a mile and +a half away, but he knew that Mrs. van der Luyden never walked, and +that he must keep to the road to meet the carriage. Presently, however, +coming down a foot-path that crossed the highway, he caught sight of a +slight figure in a red cloak, with a big dog running ahead. He hurried +forward, and Madame Olenska stopped short with a smile of welcome. + +"Ah, you've come!" she said, and drew her hand from her muff. + +The red cloak made her look gay and vivid, like the Ellen Mingott of +old days; and he laughed as he took her hand, and answered: "I came to +see what you were running away from." + +Her face clouded over, but she answered: "Ah, well--you will see, +presently." + +The answer puzzled him. "Why--do you mean that you've been overtaken?" + +She shrugged her shoulders, with a little movement like Nastasia's, and +rejoined in a lighter tone: "Shall we walk on? I'm so cold after the +sermon. And what does it matter, now you're here to protect me?" + +The blood rose to his temples and he caught a fold of her cloak. +"Ellen--what is it? You must tell me." + +"Oh, presently--let's run a race first: my feet are freezing to the +ground," she cried; and gathering up the cloak she fled away across +the snow, the dog leaping about her with challenging barks. For a +moment Archer stood watching, his gaze delighted by the flash of the +red meteor against the snow; then he started after her, and they met, +panting and laughing, at a wicket that led into the park. + +She looked up at him and smiled. "I knew you'd come!" + +"That shows you wanted me to," he returned, with a disproportionate joy +in their nonsense. The white glitter of the trees filled the air with +its own mysterious brightness, and as they walked on over the snow the +ground seemed to sing under their feet. + +"Where did you come from?" Madame Olenska asked. + +He told her, and added: "It was because I got your note." + +After a pause she said, with a just perceptible chill in her voice: +"May asked you to take care of me." + +"I didn't need any asking." + +"You mean--I'm so evidently helpless and defenceless? What a poor thing +you must all think me! But women here seem not--seem never to feel the +need: any more than the blessed in heaven." + +He lowered his voice to ask: "What sort of a need?" + +"Ah, don't ask me! I don't speak your language," she retorted +petulantly. + +The answer smote him like a blow, and he stood still in the path, +looking down at her. + +"What did I come for, if I don't speak yours?" + +"Oh, my friend--!" She laid her hand lightly on his arm, and he pleaded +earnestly: "Ellen--why won't you tell me what's happened?" + +She shrugged again. "Does anything ever happen in heaven?" + +He was silent, and they walked on a few yards without exchanging a +word. Finally she said: "I will tell you--but where, where, where? One +can't be alone for a minute in that great seminary of a house, with all +the doors wide open, and always a servant bringing tea, or a log for +the fire, or the newspaper! Is there nowhere in an American house where +one may be by one's self? You're so shy, and yet you're so public. I +always feel as if I were in the convent again--or on the stage, before +a dreadfully polite audience that never applauds." + +"Ah, you don't like us!" Archer exclaimed. + +They were walking past the house of the old Patroon, with its squat +walls and small square windows compactly grouped about a central +chimney. The shutters stood wide, and through one of the newly-washed +windows Archer caught the light of a fire. + +"Why--the house is open!" he said. + +She stood still. "No; only for today, at least. I wanted to see it, and +Mr. van der Luyden had the fire lit and the windows opened, so that we +might stop there on the way back from church this morning." She ran up +the steps and tried the door. "It's still unlocked--what luck! Come in +and we can have a quiet talk. Mrs. van der Luyden has driven over to +see her old aunts at Rhinebeck and we shan't be missed at the house for +another hour." + +He followed her into the narrow passage. His spirits, which had dropped +at her last words, rose with an irrational leap. The homely little +house stood there, its panels and brasses shining in the firelight, as +if magically created to receive them. A big bed of embers still gleamed +in the kitchen chimney, under an iron pot hung from an ancient crane. +Rush-bottomed arm-chairs faced each other across the tiled hearth, and +rows of Delft plates stood on shelves against the walls. Archer stooped +over and threw a log upon the embers. + +Madame Olenska, dropping her cloak, sat down in one of the chairs. +Archer leaned against the chimney and looked at her. + +"You're laughing now; but when you wrote me you were unhappy," he said. + +"Yes." She paused. "But I can't feel unhappy when you're here." + +"I sha'n't be here long," he rejoined, his lips stiffening with the +effort to say just so much and no more. + +"No; I know. But I'm improvident: I live in the moment when I'm happy." + +The words stole through him like a temptation, and to close his senses +to it he moved away from the hearth and stood gazing out at the black +tree-boles against the snow. But it was as if she too had shifted her +place, and he still saw her, between himself and the trees, drooping +over the fire with her indolent smile. Archer's heart was beating +insubordinately. What if it were from him that she had been running +away, and if she had waited to tell him so till they were here alone +together in this secret room? + +"Ellen, if I'm really a help to you--if you really wanted me to +come--tell me what's wrong, tell me what it is you're running away +from," he insisted. + +He spoke without shifting his position, without even turning to look at +her: if the thing was to happen, it was to happen in this way, with the +whole width of the room between them, and his eyes still fixed on the +outer snow. + +For a long moment she was silent; and in that moment Archer imagined +her, almost heard her, stealing up behind him to throw her light +arms about his neck. While he waited, soul and body throbbing with +the miracle to come, his eyes mechanically received the image of a +heavily-coated man with his fur collar turned up who was advancing +along the path to the house. The man was Julius Beaufort. + +"Ah--!" Archer cried, bursting into a laugh. + +Madame Olenska had sprung up and moved to his side, slipping her hand +into his; but after a glance through the window her face paled and she +shrank back. + +"So that was it?" Archer said derisively. + +"I didn't know he was here," Madame Olenska murmured. Her hand still +clung to Archer's; but he drew away from her, and walking out into the +passage threw open the door of the house. + +"Hallo, Beaufort--this way! Madame Olenska was expecting you," he said. + + +During his journey back to New York the next morning, Archer relived +with a fatiguing vividness his last moments at Skuytercliff. + +Beaufort, though clearly annoyed at finding him with Madame Olenska, +had, as usual, carried off the situation high-handedly. His way of +ignoring people whose presence inconvenienced him actually gave +them, if they were sensitive to it, a feeling of invisibility, of +nonexistence. Archer, as the three strolled back through the park, was +aware of this odd sense of disembodiment; and humbling as it was to his +vanity it gave him the ghostly advantage of observing unobserved. + +Beaufort had entered the little house with his usual easy assurance; +but he could not smile away the vertical line between his eyes. It was +fairly clear that Madame Olenska had not known that he was coming, +though her words to Archer had hinted at the possibility; at any rate, +she had evidently not told him where she was going when she left New +York, and her unexplained departure had exasperated him. The ostensible +reason of his appearance was the discovery, the very night before, of +a "perfect little house," not in the market, which was really just the +thing for her, but would be snapped up instantly if she didn't take it; +and he was loud in mock-reproaches for the dance she had led him in +running away just as he had found it. + +"If only this new dodge for talking along a wire had been a little +bit nearer perfection I might have told you all this from town, and +been toasting my toes before the club fire at this minute, instead of +tramping after you through the snow," he grumbled, disguising a real +irritation under the pretence of it; and at this opening Madame Olenska +twisted the talk away to the fantastic possibility that they might +one day actually converse with each other from street to street, or +even--incredible dream!--from one town to another. This struck from +all three allusions to Edgar Poe and Jules Verne, and such platitudes +as naturally rise to the lips of the most intelligent when they are +talking against time, and dealing with a new invention in which it +would seem ingenuous to believe too soon; and the question of the +telephone carried them safely back to the big house. + +Mrs. van der Luyden had not yet returned; and Archer took his leave and +walked off to fetch the cutter, while Beaufort followed the Countess +Olenska indoors. It was probable that, little as the van der Luydens +encouraged unannounced visits, he could count on being asked to dine, +and sent back to the station to catch the nine o'clock train; but more +than that he would certainly not get, for it would be inconceivable to +his hosts that a gentleman travelling without luggage should wish to +spend the night, and distasteful to them to propose it to a person with +whom they were on terms of such limited cordiality as Beaufort. + +Beaufort knew all this, and must have foreseen it; and his taking the +long journey for so small a reward gave the measure of his impatience. +He was undeniably in pursuit of the Countess Olenska; and Beaufort had +only one object in view in his pursuit of pretty women. His dull and +childless home had long since palled on him; and in addition to more +permanent consolations he was always in quest of amorous adventures in +his own set. This was the man from whom Madame Olenska was avowedly +flying: the question was whether she had fled because his importunities +displeased her, or because she did not wholly trust herself to resist +them; unless, indeed, all her talk of flight had been a blind, and her +departure no more than a manœuvre. + +Archer did not really believe this. Little as he had actually seen of +Madame Olenska, he was beginning to think that he could read her face, +and if not her face, her voice; and both had betrayed annoyance, and +even dismay, at Beaufort's sudden appearance. But, after all, if this +were the case, was it not worse than if she had left New York for the +express purpose of meeting him? If she had done that, she ceased to +be an object of interest, she threw in her lot with the vulgarest of +dissemblers: a woman engaged in a love affair with Beaufort "classed" +herself irretrievably. + +No, it was worse a thousand times if, judging Beaufort, and probably +despising him, she was yet drawn to him by all that gave him an +advantage over the other men about her: his habit of two continents +and two societies, his familiar association with artists and actors +and people generally in the world's eye, and his careless contempt +for local prejudices. Beaufort was vulgar, he was uneducated, he was +purse-proud; but the circumstances of his life, and a certain native +shrewdness, made him better worth talking to than many men, morally and +socially his betters, whose horizon was bounded by the Battery and the +Central Park. How should any one coming from a wider world not feel the +difference and be attracted by it? + +Madame Olenska, in a burst of irritation, had said to Archer that he +and she did not talk the same language; and the young man knew that +in some respects this was true. But Beaufort understood every turn of +her dialect, and spoke it fluently: his view of life, his tone, his +attitude, were merely a coarser reflection of those revealed in Count +Olenski's letter. This might seem to be to his disadvantage with Count +Olenski's wife; but Archer was too intelligent to think that a young +woman like Ellen Olenska would necessarily recoil from everything that +reminded her of her past. She might believe herself wholly in revolt +against it; but what had charmed her in it would still charm her, even +though it were against her will. + +Thus, with a painful impartiality, did the young man make out the case +for Beaufort, and for Beaufort's victim. A longing to enlighten her was +strong in him; and there were moments when he imagined that all she +asked was to be enlightened. + +That evening he unpacked his books from London. The box was full of +things he had been waiting for impatiently; a new volume of Herbert +Spencer, another collection of the prolific Alphonse Daudet's brilliant +tales, and a novel called "Middlemarch," as to which there had lately +been interesting things said in the reviews. He had declined three +dinner invitations in favour of this feast; but though he turned the +pages with the sensuous joy of the book-lover, he did not know what +he was reading, and one book after another dropped from his hand. +Suddenly, among them, he lit on a small volume of verse which he had +ordered because the name had attracted him: "The House of Life." He +took it up, and found himself plunged in an atmosphere unlike any he +had ever breathed in books; so warm, so rich, and yet so ineffably +tender, that it gave a new and haunting beauty to the most elementary +of human passions. All through the night he pursued through those +enchanted pages the vision of a woman who had the face of Ellen +Olenska; but when he woke the next morning, and looked out at the +brownstone houses across the street, and thought of his desk in Mr. +Letterblair's office, and the family pew in Grace Church, his hour in +the park of Skuytercliff became as far outside the pale of probability +as the visions of the night. + +"Mercy, how pale you look, Newland!" Janey commented over the +coffee-cups at breakfast; and his mother added: "Newland, dear, I've +noticed lately that you've been coughing; I do hope you're not letting +yourself be overworked?" For it was the conviction of both ladies that, +under the iron despotism of his senior partners, the young man's life +was spent in the most exhausting professional labours--and he had never +thought it necessary to undeceive them. + +The next two or three days dragged by heavily. The taste of the usual +was like cinders in his mouth, and there were moments when he felt as +if he were being buried alive under his future. He heard nothing of +the Countess Olenska, or of the perfect little house, and though he +met Beaufort at the club they merely nodded at each other across the +whist-tables. It was not till the fourth evening that he found a note +awaiting him on his return home. "Come late tomorrow: I must explain to +you. Ellen." These were the only words it contained. + +The young man, who was dining out, thrust the note into his pocket, +smiling a little at the Frenchness of the "to you." After dinner he +went to a play; and it was not until his return home, after midnight, +that he drew Madame Olenska's missive out again and re-read it slowly a +number of times. There were several ways of answering it, and he gave +considerable thought to each one during the watches of an agitated +night. That on which, when morning came, he finally decided was to +pitch some clothes into a portmanteau and jump on board a boat that was +leaving that very afternoon for St. Augustine. + + + + +XVI. + + +When Archer walked down the sandy main street of St. Augustine to the +house which had been pointed out to him as Mr. Welland's, and saw May +Welland standing under a magnolia with the sun in her hair, he wondered +why he had waited so long to come. + +Here was the truth, here was reality, here was the life that belonged +to him; and he, who fancied himself so scornful of arbitrary +restraints, had been afraid to break away from his desk because of what +people might think of his stealing a holiday! + +Her first exclamation was: "Newland--has anything happened?" and it +occurred to him that it would have been more "feminine" if she had +instantly read in his eyes why he had come. But when he answered: +"Yes--I found I had to see you," her happy blushes took the chill from +her surprise, and he saw how easily he would be forgiven, and how soon +even Mr. Letterblair's mild disapproval would be smiled away by a +tolerant family. + +Early as it was, the main street was no place for any but formal +greetings, and Archer longed to be alone with May, and to pour out +all his tenderness and his impatience. It still lacked an hour to the +late Welland breakfast-time, and instead of asking him to come in she +proposed that they should walk out to an old orange-garden beyond the +town. She had just been for a row on the river, and the sun that netted +the little waves with gold seemed to have caught her in its meshes. +Across the warm brown of her cheek her blown hair glittered like silver +wire; and her eyes too looked lighter, almost pale in their youthful +limpidity. As she walked beside Archer with her long swinging gait her +face wore the vacant serenity of a young marble athlete. + +To Archer's strained nerves the vision was as soothing as the sight of +the blue sky and the lazy river. They sat down on a bench under the +orange-trees and he put his arm about her and kissed her. It was like +drinking at a cold spring with the sun on it; but his pressure may have +been more vehement than he had intended, for the blood rose to her face +and she drew back as if he had startled her. + +"What is it?" he asked, smiling; and she looked at him with surprise, +and answered: "Nothing." + +A slight embarrassment fell on them, and her hand slipped out of his. +It was the only time that he had kissed her on the lips except for +their fugitive embrace in the Beaufort conservatory, and he saw that +she was disturbed, and shaken out of her cool boyish composure. + +"Tell me what you do all day," he said, crossing his arms under his +tilted-back head, and pushing his hat forward to screen the sun-dazzle. +To let her talk about familiar and simple things was the easiest way of +carrying on his own independent train of thought; and he sat listening +to her simple chronicle of swimming, sailing and riding, varied by an +occasional dance at the primitive inn when a man-of-war came in. A few +pleasant people from Philadelphia and Baltimore were picknicking at the +inn, and the Selfridge Merrys had come down for three weeks because +Kate Merry had had bronchitis. They were planning to lay out a lawn +tennis court on the sands; but no one but Kate and May had racquets, +and most of the people had not even heard of the game. + +All this kept her very busy, and she had not had time to do more than +look at the little vellum book that Archer had sent her the week before +(the "Sonnets from the Portuguese"); but she was learning by heart +"How they brought the Good News from Ghent to Aix," because it was one +of the first things he had ever read to her; and it amused her to be +able to tell him that Kate Merry had never even heard of a poet called +Robert Browning. + +Presently she started up, exclaiming that they would be late for +breakfast; and they hurried back to the tumble-down house with its +pointless porch and unpruned hedge of plumbago and pink geraniums where +the Wellands were installed for the winter. Mr. Welland's sensitive +domesticity shrank from the discomforts of the slovenly southern +hotel, and at immense expense, and in face of almost insuperable +difficulties, Mrs. Welland was obliged, year after year, to improvise +an establishment partly made up of discontented New York servants and +partly drawn from the local African supply. + +"The doctors want my husband to feel that he is in his own home; +otherwise he would be so wretched that the climate would not do him +any good," she explained, winter after winter, to the sympathising +Philadelphians and Baltimoreans; and Mr. Welland, beaming across a +breakfast table miraculously supplied with the most varied delicacies, +was presently saying to Archer: "You see, my dear fellow, we camp--we +literally camp. I tell my wife and May that I want to teach them how to +rough it." + +Mr. and Mrs. Welland had been as much surprised as their daughter by +the young man's sudden arrival; but it had occurred to him to explain +that he had felt himself on the verge of a nasty cold, and this seemed +to Mr. Welland an all-sufficient reason for abandoning any duty. + +"You can't be too careful, especially toward spring," he said, heaping +his plate with straw-coloured griddle-cakes and drowning them in golden +syrup. "If I'd only been as prudent at your age May would have been +dancing at the Assemblies now, instead of spending her winters in a +wilderness with an old invalid." + +"Oh, but I love it here, Papa; you know I do. If only Newland could +stay I should like it a thousand times better than New York." + +"Newland must stay till he has quite thrown off his cold," said Mrs. +Welland indulgently; and the young man laughed, and said he supposed +there was such a thing as one's profession. + +He managed, however, after an exchange of telegrams with the firm, +to make his cold last a week; and it shed an ironic light on the +situation to know that Mr. Letterblair's indulgence was partly due to +the satisfactory way in which his brilliant young junior partner had +settled the troublesome matter of the Olenski divorce. Mr. Letterblair +had let Mrs. Welland know that Mr. Archer had "rendered an invaluable +service" to the whole family, and that old Mrs. Manson Mingott had been +particularly pleased; and one day when May had gone for a drive with +her father in the only vehicle the place produced Mrs. Welland took +occasion to touch on a topic which she always avoided in her daughter's +presence. + +"I'm afraid Ellen's ideas are not at all like ours. She was barely +eighteen when Medora Manson took her back to Europe--you remember the +excitement when she appeared in black at her coming-out ball? Another +of Medora's fads--really this time it was almost prophetic! That must +have been at least twelve years ago; and since then Ellen has never +been to America. No wonder she is completely Europeanised." + +"But European society is not given to divorce: Countess Olenska thought +she would be conforming to American ideas in asking for her freedom." +It was the first time that the young man had pronounced her name since +he had left Skuytercliff, and he felt the colour rise to his cheek. + +Mrs. Welland smiled compassionately. "That is just like the +extraordinary things that foreigners invent about us. They think we +dine at two o'clock and countenance divorce! That is why it seems to me +so foolish to entertain them when they come to New York. They accept +our hospitality, and then they go home and repeat the same stupid +stories." + +Archer made no comment on this, and Mrs. Welland continued: "But we do +most thoroughly appreciate your persuading Ellen to give up the idea. +Her grandmother and her uncle Lovell could do nothing with her; both of +them have written that her changing her mind was entirely due to your +influence--in fact she said so to her grandmother. She has an unbounded +admiration for you. Poor Ellen--she was always a wayward child. I +wonder what her fate will be?" + +"What we've all contrived to make it," he felt like answering. "If +you'd all of you rather she should be Beaufort's mistress than some +decent fellow's wife you've certainly gone the right way about it." + +He wondered what Mrs. Welland would have said if he had uttered the +words instead of merely thinking them. He could picture the sudden +decomposure of her firm placid features, to which a lifelong mastery +over trifles had given an air of factitious authority. Traces still +lingered on them of a fresh beauty like her daughter's; and he asked +himself if May's face was doomed to thicken into the same middle-aged +image of invincible innocence. + +Ah, no, he did not want May to have that kind of innocence, the +innocence that seals the mind against imagination and the heart against +experience! + +"I verily believe," Mrs. Welland continued, "that if the horrible +business had come out in the newspapers it would have been my husband's +death-blow. I don't know any of the details; I only ask not to, as +I told poor Ellen when she tried to talk to me about it. Having an +invalid to care for, I have to keep my mind bright and happy. But Mr. +Welland was terribly upset; he had a slight temperature every morning +while we were waiting to hear what had been decided. It was the horror +of his girl's learning that such things were possible--but of course, +dear Newland, you felt that too. We all knew that you were thinking of +May." + +"I'm always thinking of May," the young man rejoined, rising to cut +short the conversation. + +He had meant to seize the opportunity of his private talk with Mrs. +Welland to urge her to advance the date of his marriage. But he could +think of no arguments that would move her, and with a sense of relief +he saw Mr. Welland and May driving up to the door. + +His only hope was to plead again with May, and on the day before his +departure he walked with her to the ruinous garden of the Spanish +Mission. The background lent itself to allusions to European scenes; +and May, who was looking her loveliest under a wide-brimmed hat +that cast a shadow of mystery over her too-clear eyes, kindled into +eagerness as he spoke of Granada and the Alhambra. + +"We might be seeing it all this spring--even the Easter ceremonies at +Seville," he urged, exaggerating his demands in the hope of a larger +concession. + +"Easter in Seville? And it will be Lent next week!" she laughed. + +"Why shouldn't we be married in Lent?" he rejoined; but she looked so +shocked that he saw his mistake. + +"Of course I didn't mean that, dearest; but soon after Easter--so that +we could sail at the end of April. I know I could arrange it at the +office." + +She smiled dreamily upon the possibility; but he perceived that to +dream of it sufficed her. It was like hearing him read aloud out of his +poetry books the beautiful things that could not possibly happen in +real life. + +"Oh, do go on, Newland; I do love your descriptions." + +"But why should they be only descriptions? Why shouldn't we make them +real?" + +"We shall, dearest, of course; next year." Her voice lingered over it. + +"Don't you want them to be real sooner? Can't I persuade you to break +away now?" + +She bowed her head, vanishing from him under her conniving hat-brim. + +"Why should we dream away another year? Look at me, dear! Don't you +understand how I want you for my wife?" + +For a moment she remained motionless; then she raised on him eyes of +such despairing clearness that he half-released her waist from his hold. +But suddenly her look changed and deepened inscrutably. "I'm not sure +if I _do_ understand," she said. "Is it--is it because you're not certain +of continuing to care for me?" + +Archer sprang up from his seat. "My God--perhaps--I don't know," he +broke out angrily. + +May Welland rose also; as they faced each other she seemed to grow +in womanly stature and dignity. Both were silent for a moment, as if +dismayed by the unforeseen trend of their words: then she said in a low +voice: "If that is it--is there some one else?" + +"Some one else--between you and me?" He echoed her words slowly, as +though they were only half-intelligible and he wanted time to repeat +the question to himself. She seemed to catch the uncertainty of his +voice, for she went on in a deepening tone: "Let us talk frankly, +Newland. Sometimes I've felt a difference in you; especially since our +engagement has been announced." + +"Dear--what madness!" he recovered himself to exclaim. + +She met his protest with a faint smile. "If it is, it won't hurt us to +talk about it." She paused, and added, lifting her head with one of her +noble movements: "Or even if it's true: why shouldn't we speak of it? +You might so easily have made a mistake." + +He lowered his head, staring at the black leaf-pattern on the sunny +path at their feet. "Mistakes are always easy to make; but if I had +made one of the kind you suggest, is it likely that I should be +imploring you to hasten our marriage?" + +She looked downward too, disturbing the pattern with the point of her +sunshade while she struggled for expression. "Yes," she said at length. +"You might want--once for all--to settle the question: it's one way." + +Her quiet lucidity startled him, but did not mislead him into thinking +her insensible. Under her hat-brim he saw the pallor of her profile, +and a slight tremor of the nostril above her resolutely steadied lips. + +"Well--?" he questioned, sitting down on the bench, and looking up at +her with a frown that he tried to make playful. + +She dropped back into her seat and went on: "You mustn't think that +a girl knows as little as her parents imagine. One hears and one +notices--one has one's feelings and ideas. And of course, long before +you told me that you cared for me, I'd known that there was some one +else you were interested in; every one was talking about it two years +ago at Newport. And once I saw you sitting together on the verandah at +a dance--and when she came back into the house her face was sad, and I +felt sorry for her; I remembered it afterward, when we were engaged." + +Her voice had sunk almost to a whisper, and she sat clasping and +unclasping her hands about the handle of her sunshade. The young man +laid his upon them with a gentle pressure; his heart dilated with an +inexpressible relief. + +"My dear child--was _that_ it? If you only knew the truth!" + +She raised her head quickly. "Then there is a truth I don't know?" + +He kept his hand over hers. "I meant, the truth about the old story you +speak of." + +"But that's what I want to know, Newland--what I ought to know. I +couldn't have my happiness made out of a wrong--an unfairness--to +somebody else. And I want to believe that it would be the same with +you. What sort of a life could we build on such foundations?" + +Her face had taken on a look of such tragic courage that he felt like +bowing himself down at her feet. "I've wanted to say this for a long +time," she went on. "I've wanted to tell you that, when two people +really love each other, I understand that there may be situations which +make it right that they should--should go against public opinion. And +if you feel yourself in any way pledged ... pledged to the person +we've spoken of ... and if there is any way ... any way in which you +can fulfill your pledge ... even by her getting a divorce ... Newland, +don't give her up because of me!" + +His surprise at discovering that her fears had fastened upon an episode +so remote and so completely of the past as his love-affair with Mrs. +Thorley Rushworth gave way to wonder at the generosity of her view. +There was something superhuman in an attitude so recklessly unorthodox, +and if other problems had not pressed on him he would have been lost +in wonder at the prodigy of the Wellands' daughter urging him to marry +his former mistress. But he was still dizzy with the glimpse of the +precipice they had skirted, and full of a new awe at the mystery of +young-girlhood. + +For a moment he could not speak; then he said: "There is no pledge--no +obligation whatever--of the kind you think. Such cases don't +always--present themselves quite as simply as ... But that's no matter +... I love your generosity, because I feel as you do about those things +... I feel that each case must be judged individually, on its own +merits ... irrespective of stupid conventionalities ... I mean, each +woman's right to her liberty--" He pulled himself up, startled by the +turn his thoughts had taken, and went on, looking at her with a smile: +"Since you understand so many things, dearest, can't you go a little +farther, and understand the uselessness of our submitting to another +form of the same foolish conventionalities? If there's no one and +nothing between us, isn't that an argument for marrying quickly, rather +than for more delay?" + +She flushed with joy and lifted her face to his; as he bent to it he +saw that her eyes were full of happy tears. But in another moment she +seemed to have descended from her womanly eminence to helpless and +timorous girlhood; and he understood that her courage and initiative +were all for others, and that she had none for herself. It was evident +that the effort of speaking had been much greater than her studied +composure betrayed, and that at his first word of reassurance she had +dropped back into the usual, as a too-adventurous child takes refuge in +its mother's arms. + +Archer had no heart to go on pleading with her; he was too much +disappointed at the vanishing of the new being who had cast that one +deep look at him from her transparent eyes. May seemed to be aware of +his disappointment, but without knowing how to alleviate it; and they +stood up and walked silently home. + + + + +XVII. + + +"Your cousin the Countess called on mother while you were away," Janey +Archer announced to her brother on the evening of his return. + +The young man, who was dining alone with his mother and sister, glanced +up in surprise and saw Mrs. Archer's gaze demurely bent on her plate. +Mrs. Archer did not regard her seclusion from the world as a reason +for being forgotten by it; and Newland guessed that she was slightly +annoyed that he should be surprised by Madame Olenska's visit. + +"She had on a black velvet polonaise with jet buttons, and a tiny green +monkey muff; I never saw her so stylishly dressed," Janey continued. +"She came alone, early on Sunday afternoon; luckily the fire was lit +in the drawing-room. She had one of those new card-cases. She said she +wanted to know us because you'd been so good to her." + +Newland laughed. "Madame Olenska always takes that tone about her +friends. She's very happy at being among her own people again." + +"Yes, so she told us," said Mrs. Archer. "I must say she seems thankful +to be here." + +"I hope you liked her, mother." + +Mrs. Archer drew her lips together. "She certainly lays herself out to +please, even when she is calling on an old lady." + +"Mother doesn't think her simple," Janey interjected, her eyes screwed +upon her brother's face. + +"It's just my old-fashioned feeling; dear May is my ideal," said Mrs. +Archer. + +"Ah," said her son, "they're not alike." + + +Archer had left St. Augustine charged with many messages for old Mrs. +Mingott; and a day or two after his return to town he called on her. + +The old lady received him with unusual warmth; she was grateful to him +for persuading the Countess Olenska to give up the idea of a divorce; +and when he told her that he had deserted the office without leave, and +rushed down to St. Augustine simply because he wanted to see May, she +gave an adipose chuckle and patted his knee with her puff-ball hand. + +"Ah, ah--so you kicked over the traces, did you? And I suppose Augusta +and Welland pulled long faces, and behaved as if the end of the world +had come? But little May--she knew better, I'll be bound?" + +"I hoped she did; but after all she wouldn't agree to what I'd gone +down to ask for." + +"Wouldn't she indeed? And what was that?" + +"I wanted to get her to promise that we should be married in April. +What's the use of our wasting another year?" + +Mrs. Manson Mingott screwed up her little mouth into a grimace of mimic +prudery and twinkled at him through malicious lids. "'Ask Mamma,' I +suppose--the usual story. Ah, these Mingotts--all alike! Born in a +rut, and you can't root 'em out of it. When I built this house you'd +have thought I was moving to California! Nobody ever _had_ built above +Fortieth Street--no, says I, nor above the Battery either, before +Christopher Columbus discovered America. No, no; not one of them wants +to be different; they're as scared of it as the small-pox. Ah, my dear +Mr. Archer, I thank my stars I'm nothing but a vulgar Spicer; but +there's not one of my own children that takes after me but my little +Ellen." She broke off, still twinkling at him, and asked, with the +casual irrelevance of old age: "Now, why in the world didn't you marry +my little Ellen?" + +Archer laughed. "For one thing, she wasn't there to be married." + +"No--to be sure; more's the pity. And now it's too late; her life is +finished." She spoke with the cold-blooded complacency of the aged +throwing earth into the grave of young hopes. The young man's heart +grew chill, and he said hurriedly: "Can't I persuade you to use your +influence with the Wellands, Mrs. Mingott? I wasn't made for long +engagements." + +Old Catherine beamed on him approvingly. "No; I can see that. You've +got a quick eye. When you were a little boy I've no doubt you liked +to be helped first." She threw back her head with a laugh that made +her chins ripple like little waves. "Ah, here's my Ellen now!" she +exclaimed, as the portières parted behind her. + +Madame Olenska came forward with a smile. Her face looked vivid and +happy, and she held out her hand gaily to Archer while she stooped to +her grandmother's kiss. + +"I was just saying to him, my dear: 'Now, why didn't you marry my +little Ellen?'" + +Madame Olenska looked at Archer, still smiling. "And what did he +answer?" + +"Oh, my darling, I leave you to find that out! He's been down to +Florida to see his sweetheart." + +"Yes, I know." She still looked at him. "I went to see your mother, to +ask where you'd gone. I sent a note that you never answered, and I was +afraid you were ill." + +He muttered something about leaving unexpectedly, in a great hurry, and +having intended to write to her from St. Augustine. + +"And of course once you were there you never thought of me again!" She +continued to beam on him with a gaiety that might have been a studied +assumption of indifference. + +"If she still needs me, she's determined not to let me see it," he +thought, stung by her manner. He wanted to thank her for having been +to see his mother, but under the ancestress's malicious eye he felt +himself tongue-tied and constrained. + +"Look at him--in such hot haste to get married that he took French +leave and rushed down to implore the silly girl on his knees! That's +something like a lover--that's the way handsome Bob Spicer carried off +my poor mother; and then got tired of her before I was weaned--though +they only had to wait eight months for me! But there--you're not a +Spicer, young man; luckily for you and for May. It's only my poor Ellen +that has kept any of their wicked blood; the rest of them are all model +Mingotts," cried the old lady scornfully. + +Archer was aware that Madame Olenska, who had seated herself at her +grandmother's side, was still thoughtfully scrutinising him. The gaiety +had faded from her eyes, and she said with great gentleness: "Surely, +Granny, we can persuade them between us to do as he wishes." + +Archer rose to go, and as his hand met Madame Olenska's he felt that +she was waiting for him to make some allusion to her unanswered letter. + +"When can I see you?" he asked, as she walked with him to the door of +the room. + +"Whenever you like; but it must be soon if you want to see the little +house again. I am moving next week." + +A pang shot through him at the memory of his lamplit hours in the +low-studded drawing-room. Few as they had been, they were thick with +memories. + +"Tomorrow evening?" + +She nodded. "Tomorrow; yes; but early. I'm going out." + +The next day was a Sunday, and if she were "going out" on a Sunday +evening it could, of course, be only to Mrs. Lemuel Struthers's. He +felt a slight movement of annoyance, not so much at her going there +(for he rather liked her going where she pleased in spite of the van +der Luydens), but because it was the kind of house at which she was +sure to meet Beaufort, where she must have known beforehand that she +would meet him--and where she was probably going for that purpose. + +"Very well; tomorrow evening," he repeated, inwardly resolved that +he would not go early, and that by reaching her door late he would +either prevent her from going to Mrs. Struthers's, or else arrive after +she had started--which, all things considered, would no doubt be the +simplest solution. + + +It was only half-past eight, after all, when he rang the bell under +the wisteria; not as late as he had intended by half an hour--but +a singular restlessness had driven him to her door. He reflected, +however, that Mrs. Struthers's Sunday evenings were not like a ball, +and that her guests, as if to minimise their delinquency, usually went +early. + +The one thing he had not counted on, in entering Madame Olenska's hall, +was to find hats and overcoats there. Why had she bidden him to come +early if she was having people to dine? On a closer inspection of the +garments besides which Nastasia was laying his own, his resentment +gave way to curiosity. The overcoats were in fact the very strangest +he had ever seen under a polite roof; and it took but a glance to +assure himself that neither of them belonged to Julius Beaufort. One +was a shaggy yellow ulster of "reach-me-down" cut, the other a very +old and rusty cloak with a cape--something like what the French called +a "Macfarlane." This garment, which appeared to be made for a person +of prodigious size, had evidently seen long and hard wear, and its +greenish-black folds gave out a moist sawdusty smell suggestive of +prolonged sessions against bar-room walls. On it lay a ragged grey +scarf and an odd felt hat of semiclerical shape. + +Archer raised his eyebrows enquiringly at Nastasia, who raised hers in +return with a fatalistic "Gia!" as she threw open the drawing-room door. + +The young man saw at once that his hostess was not in the room; then, +with surprise, he discovered another lady standing by the fire. This +lady, who was long, lean and loosely put together, was clad in raiment +intricately looped and fringed, with plaids and stripes and bands of +plain colour disposed in a design to which the clue seemed missing. Her +hair, which had tried to turn white and only succeeded in fading, was +surmounted by a Spanish comb and black lace scarf, and silk mittens, +visibly darned, covered her rheumatic hands. + +Beside her, in a cloud of cigar-smoke, stood the owners of the two +overcoats, both in morning clothes that they had evidently not taken +off since morning. In one of the two, Archer, to his surprise, +recognised Ned Winsett; the other and older, who was unknown to +him, and whose gigantic frame declared him to be the wearer of the +"Macfarlane," had a feebly leonine head with crumpled grey hair, +and moved his arms with large pawing gestures, as though he were +distributing lay blessings to a kneeling multitude. + +These three persons stood together on the hearth-rug, their eyes fixed +on an extraordinarily large bouquet of crimson roses, with a knot of +purple pansies at their base, that lay on the sofa where Madame Olenska +usually sat. + +"What they must have cost at this season--though of course it's the +sentiment one cares about!" the lady was saying in a sighing staccato +as Archer came in. + +The three turned with surprise at his appearance, and the lady, +advancing, held out her hand. + +"Dear Mr. Archer--almost my cousin Newland!" she said. "I am the +Marchioness Manson." + +Archer bowed, and she continued: "My Ellen has taken me in for a few +days. I came from Cuba, where I have been spending the winter with +Spanish friends--such delightful distinguished people: the highest +nobility of old Castile--how I wish you could know them! But I was +called away by our dear great friend here, Dr. Carver. You don't know +Dr. Agathon Carver, founder of the Valley of Love Community?" + +Dr. Carver inclined his leonine head, and the Marchioness continued: +"Ah, New York--New York--how little the life of the spirit has reached +it! But I see you do know Mr. Winsett." + +"Oh, yes--I reached him some time ago; but not by that route," Winsett +said with his dry smile. + +The Marchioness shook her head reprovingly. "How do you know, Mr. +Winsett? The spirit bloweth where it listeth." + +"List--oh, list!" interjected Dr. Carver in a stentorian murmur. + +"But do sit down, Mr. Archer. We four have been having a delightful +little dinner together, and my child has gone up to dress. She expects +you; she will be down in a moment. We were just admiring these +marvellous flowers, which will surprise her when she reappears." + +Winsett remained on his feet. "I'm afraid I must be off. Please tell +Madame Olenska that we shall all feel lost when she abandons our +street. This house has been an oasis." + +"Ah, but she won't abandon _you_. Poetry and art are the breath of life +to her. It _is_ poetry you write, Mr. Winsett?" + +"Well, no; but I sometimes read it," said Winsett, including the group +in a general nod and slipping out of the room. + +"A caustic spirit--_un peu sauvage_. But so witty; Dr. Carver, you _do_ +think him witty?" + +"I never think of wit," said Dr. Carver severely. + +"Ah--ah--you never think of wit! How merciless he is to us weak +mortals, Mr. Archer! But he lives only in the life of the spirit; and +tonight he is mentally preparing the lecture he is to deliver presently +at Mrs. Blenker's. Dr. Carver, would there be time, before you start +for the Blenkers' to explain to Mr. Archer your illuminating discovery +of the Direct Contact? But no; I see it is nearly nine o'clock, and we +have no right to detain you while so many are waiting for your message." + +Dr. Carver looked slightly disappointed at this conclusion, but, having +compared his ponderous gold time-piece with Madame Olenska's little +travelling-clock, he reluctantly gathered up his mighty limbs for +departure. + +"I shall see you later, dear friend?" he suggested to the Marchioness, +who replied with a smile: "As soon as Ellen's carriage comes I will +join you; I do hope the lecture won't have begun." + +Dr. Carver looked thoughtfully at Archer. "Perhaps, if this young +gentleman is interested in my experiences, Mrs. Blenker might allow you +to bring him with you?" + +"Oh, dear friend, if it were possible--I am sure she would be too +happy. But I fear my Ellen counts on Mr. Archer herself." + +"That," said Dr. Carver, "is unfortunate--but here is my card." He +handed it to Archer, who read on it, in Gothic characters: + +/c ++-----------------------+ +| Agathon Carver | +| The Valley of Love | +| Kittasquattamy, N. Y. | ++-----------------------+ +c/ + +Dr. Carver bowed himself out, and Mrs. Manson, with a sigh that might +have been either of regret or relief, again waved Archer to a seat. + +"Ellen will be down in a moment; and before she comes, I am so glad of +this quiet moment with you." + +Archer murmured his pleasure at their meeting, and the Marchioness +continued, in her low sighing accents: "I know everything, dear Mr. +Archer--my child has told me all you have done for her. Your wise +advice: your courageous firmness--thank heaven it was not too late!" + +The young man listened with considerable embarrassment. Was there +any one, he wondered, to whom Madame Olenska had not proclaimed his +intervention in her private affairs? + +"Madame Olenska exaggerates; I simply gave her a legal opinion, as she +asked me to." + +"Ah, but in doing it--in doing it you were the unconscious instrument +of--of--what word have we moderns for Providence, Mr. Archer?" +cried the lady, tilting her head on one side and drooping her lids +mysteriously. "Little did you know that at that very moment I was being +appealed to: being approached, in fact--from the other side of the +Atlantic!" + +She glanced over her shoulder, as though fearful of being overheard, +and then, drawing her chair nearer, and raising a tiny ivory fan to her +lips, breathed behind it: "By the Count himself--my poor, mad, foolish +Olenski; who asks only to take her back on her own terms." + +"Good God!" Archer exclaimed, springing up. + +"You are horrified? Yes, of course; I understand. I don't defend poor +Stanislas, though he has always called me his best friend. He does not +defend himself--he casts himself at her feet: in my person." She tapped +her emaciated bosom. "I have his letter here." + +"A letter?--Has Madame Olenska seen it?" Archer stammered, his brain +whirling with the shock of the announcement. + +The Marchioness Manson shook her head softly. "Time--time; I must have +time. I know my Ellen--haughty, intractable; shall I say, just a shade +unforgiving?" + +"But, good heavens, to forgive is one thing; to go back into that +hell--" + +"Ah, yes," the Marchioness acquiesced. "So she describes it--my +sensitive child! But on the material side, Mr. Archer, if one may stoop +to consider such things; do you know what she is giving up? Those roses +there on the sofa--acres like them, under glass and in the open, in +his matchless terraced gardens at Nice! Jewels--historic pearls: the +Sobieski emeralds--sables,--but she cares nothing for all these! Art +and beauty, those she does care for, she lives for, as I always have; +and those also surrounded her. Pictures, priceless furniture, music, +brilliant conversation--ah, that, my dear young man, if you'll excuse +me, is what you've no conception of here! And she had it all; and the +homage of the greatest. She tells me she is not thought handsome in +New York--good heavens! Her portrait has been painted nine times; the +greatest artists in Europe have begged for the privilege. Are these +things nothing? And the remorse of an adoring husband?" + +As the Marchioness Manson rose to her climax her face assumed an +expression of ecstatic retrospection which would have moved Archer's +mirth had he not been numb with amazement. + +He would have laughed if any one had foretold to him that his first +sight of poor Medora Manson would have been in the guise of a messenger +of Satan; but he was in no mood for laughing now, and she seemed to +him to come straight out of the hell from which Ellen Olenska had just +escaped. + +"She knows nothing yet--of all this?" he asked abruptly. + +Mrs. Manson laid a purple finger on her lips. "Nothing directly--but +does she suspect? Who can tell? The truth is, Mr. Archer, I have been +waiting to see you. From the moment I heard of the firm stand you had +taken, and of your influence over her, I hoped it might be possible to +count on your support--to convince you ..." + +"That she ought to go back? I would rather see her dead!" cried the +young man violently. + +"Ah," the Marchioness murmured, without visible resentment. For a while +she sat in her arm-chair, opening and shutting the absurd ivory fan +between her mittened fingers; but suddenly she lifted her head and +listened. + +"Here she comes," she said in a rapid whisper; and then, pointing to +the bouquet on the sofa: "Am I to understand that you prefer _that_, Mr. +Archer? After all, marriage is marriage ... and my niece is still a +wife..." + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_16384.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_16384.txt new file mode 100644 index 0000000000..4267c15845 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_16384.txt @@ -0,0 +1,1490 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I decided to go East and learn the bond +business. Everybody I knew was in the bond business, so I supposed it +could support one more single man. All my aunts and uncles talked it +over as if they were choosing a prep school for me, and finally said, +“Why—ye-es,” with very grave, hesitant faces. Father agreed to finance +me for a year, and after various delays I came East, permanently, I +thought, in the spring of twenty-two. + +The practical thing was to find rooms in the city, but it was a warm +season, and I had just left a country of wide lawns and friendly +trees, so when a young man at the office suggested that we take a +house together in a commuting town, it sounded like a great idea. He +found the house, a weather-beaten cardboard bungalow at eighty a +month, but at the last minute the firm ordered him to Washington, and +I went out to the country alone. I had a dog—at least I had him for a +few days until he ran away—and an old Dodge and a Finnish woman, who +made my bed and cooked breakfast and muttered Finnish wisdom to +herself over the electric stove. + +It was lonely for a day or so until one morning some man, more +recently arrived than I, stopped me on the road. + +“How do you get to West Egg village?” he asked helplessly. + +I told him. And as I walked on I was lonely no longer. I was a guide, +a pathfinder, an original settler. He had casually conferred on me the +freedom of the neighbourhood. + +And so with the sunshine and the great bursts of leaves growing on the +trees, just as things grow in fast movies, I had that familiar +conviction that life was beginning over again with the summer. + +There was so much to read, for one thing, and so much fine health to +be pulled down out of the young breath-giving air. I bought a dozen +volumes on banking and credit and investment securities, and they +stood on my shelf in red and gold like new money from the mint, +promising to unfold the shining secrets that only Midas and Morgan and +Maecenas knew. And I had the high intention of reading many other +books besides. I was rather literary in college—one year I wrote a +series of very solemn and obvious editorials for the Yale News—and now +I was going to bring back all such things into my life and become +again that most limited of all specialists, the “well-rounded man.” +This isn’t just an epigram—life is much more successfully looked at +from a single window, after all. + +It was a matter of chance that I should have rented a house in one of +the strangest communities in North America. It was on that slender +riotous island which extends itself due east of New York—and where +there are, among other natural curiosities, two unusual formations of +land. Twenty miles from the city a pair of enormous eggs, identical in +contour and separated only by a courtesy bay, jut out into the most +domesticated body of salt water in the Western hemisphere, the great +wet barnyard of Long Island Sound. They are not perfect ovals—like the +egg in the Columbus story, they are both crushed flat at the contact +end—but their physical resemblance must be a source of perpetual +wonder to the gulls that fly overhead. To the wingless a more +interesting phenomenon is their dissimilarity in every particular +except shape and size. + +I lived at West Egg, the—well, the less fashionable of the two, though +this is a most superficial tag to express the bizarre and not a little +sinister contrast between them. My house was at the very tip of the +egg, only fifty yards from the Sound, and squeezed between two huge +places that rented for twelve or fifteen thousand a season. The one on +my right was a colossal affair by any standard—it was a factual +imitation of some Hôtel de Ville in Normandy, with a tower on one +side, spanking new under a thin beard of raw ivy, and a marble +swimming pool, and more than forty acres of lawn and garden. It was +Gatsby’s mansion. Or, rather, as I didn’t know Mr. Gatsby, it was a +mansion inhabited by a gentleman of that name. My own house was an +eyesore, but it was a small eyesore, and it had been overlooked, so I +had a view of the water, a partial view of my neighbour’s lawn, and +the consoling proximity of millionaires—all for eighty dollars a +month. + +Across the courtesy bay the white palaces of fashionable East Egg +glittered along the water, and the history of the summer really begins +on the evening I drove over there to have dinner with the Tom +Buchanans. Daisy was my second cousin once removed, and I’d known Tom +in college. And just after the war I spent two days with them in +Chicago. + +Her husband, among various physical accomplishments, had been one of +the most powerful ends that ever played football at New Haven—a +national figure in a way, one of those men who reach such an acute +limited excellence at twenty-one that everything afterward savours of +anticlimax. His family were enormously wealthy—even in college his +freedom with money was a matter for reproach—but now he’d left Chicago +and come East in a fashion that rather took your breath away: for +instance, he’d brought down a string of polo ponies from Lake +Forest. It was hard to realize that a man in my own generation was +wealthy enough to do that. + +Why they came East I don’t know. They had spent a year in France for +no particular reason, and then drifted here and there unrestfully +wherever people played polo and were rich together. This was a +permanent move, said Daisy over the telephone, but I didn’t believe +it—I had no sight into Daisy’s heart, but I felt that Tom would drift +on forever seeking, a little wistfully, for the dramatic turbulence of +some irrecoverable football game. + +And so it happened that on a warm windy evening I drove over to East +Egg to see two old friends whom I scarcely knew at all. Their house +was even more elaborate than I expected, a cheerful red-and-white +Georgian Colonial mansion, overlooking the bay. The lawn started at +the beach and ran towards the front door for a quarter of a mile, +jumping over sundials and brick walks and burning gardens—finally when +it reached the house drifting up the side in bright vines as though +from the momentum of its run. The front was broken by a line of French +windows, glowing now with reflected gold and wide open to the warm +windy afternoon, and Tom Buchanan in riding clothes was standing with +his legs apart on the front porch. + +He had changed since his New Haven years. Now he was a sturdy +straw-haired man of thirty, with a rather hard mouth and a +supercilious manner. Two shining arrogant eyes had established +dominance over his face and gave him the appearance of always leaning +aggressively forward. Not even the effeminate swank of his riding +clothes could hide the enormous power of that body—he seemed to fill +those glistening boots until he strained the top lacing, and you could +see a great pack of muscle shifting when his shoulder moved under his +thin coat. It was a body capable of enormous leverage—a cruel body. + +His speaking voice, a gruff husky tenor, added to the impression of +fractiousness he conveyed. There was a touch of paternal contempt in +it, even toward people he liked—and there were men at New Haven who +had hated his guts. + +“Now, don’t think my opinion on these matters is final,” he seemed to +say, “just because I’m stronger and more of a man than you are.” We +were in the same senior society, and while we were never intimate I +always had the impression that he approved of me and wanted me to like +him with some harsh, defiant wistfulness of his own. + +We talked for a few minutes on the sunny porch. + +“I’ve got a nice place here,” he said, his eyes flashing about +restlessly. + +Turning me around by one arm, he moved a broad flat hand along the +front vista, including in its sweep a sunken Italian garden, a half +acre of deep, pungent roses, and a snub-nosed motorboat that bumped +the tide offshore. + +“It belonged to Demaine, the oil man.” He turned me around again, +politely and abruptly. “We’ll go inside.” + +We walked through a high hallway into a bright rosy-coloured space, +fragilely bound into the house by French windows at either end. The +windows were ajar and gleaming white against the fresh grass outside +that seemed to grow a little way into the house. A breeze blew through +the room, blew curtains in at one end and out the other like pale +flags, twisting them up toward the frosted wedding-cake of the +ceiling, and then rippled over the wine-coloured rug, making a shadow +on it as wind does on the sea. + +The only completely stationary object in the room was an enormous +couch on which two young women were buoyed up as though upon an +anchored balloon. They were both in white, and their dresses were +rippling and fluttering as if they had just been blown back in after a +short flight around the house. I must have stood for a few moments +listening to the whip and snap of the curtains and the groan of a +picture on the wall. Then there was a boom as Tom Buchanan shut the +rear windows and the caught wind died out about the room, and the +curtains and the rugs and the two young women ballooned slowly to the +floor. + +The younger of the two was a stranger to me. She was extended full +length at her end of the divan, completely motionless, and with her +chin raised a little, as if she were balancing something on it which +was quite likely to fall. If she saw me out of the corner of her eyes +she gave no hint of it—indeed, I was almost surprised into murmuring +an apology for having disturbed her by coming in. + +The other girl, Daisy, made an attempt to rise—she leaned slightly +forward with a conscientious expression—then she laughed, an absurd, +charming little laugh, and I laughed too and came forward into the +room. + +“I’m p-paralysed with happiness.” + +She laughed again, as if she said something very witty, and held my +hand for a moment, looking up into my face, promising that there was +no one in the world she so much wanted to see. That was a way she +had. She hinted in a murmur that the surname of the balancing girl was +Baker. (I’ve heard it said that Daisy’s murmur was only to make people +lean toward her; an irrelevant criticism that made it no less +charming.) + +At any rate, Miss Baker’s lips fluttered, she nodded at me almost +imperceptibly, and then quickly tipped her head back again—the object +she was balancing had obviously tottered a little and given her +something of a fright. Again a sort of apology arose to my lips. +Almost any exhibition of complete self-sufficiency draws a stunned +tribute from me. + +I looked back at my cousin, who began to ask me questions in her low, +thrilling voice. It was the kind of voice that the ear follows up and +down, as if each speech is an arrangement of notes that will never be +played again. Her face was sad and lovely with bright things in it, +bright eyes and a bright passionate mouth, but there was an excitement +in her voice that men who had cared for her found difficult to forget: +a singing compulsion, a whispered “Listen,” a promise that she had +done gay, exciting things just a while since and that there were gay, +exciting things hovering in the next hour. + +I told her how I had stopped off in Chicago for a day on my way East, +and how a dozen people had sent their love through me. + +“Do they miss me?” she cried ecstatically. + +“The whole town is desolate. All the cars have the left rear wheel +painted black as a mourning wreath, and there’s a persistent wail all +night along the north shore.” + +“How gorgeous! Let’s go back, Tom. Tomorrow!” Then she added +irrelevantly: “You ought to see the baby.” + +“I’d like to.” + +“She’s asleep. She’s three years old. Haven’t you ever seen her?” + +“Never.” + +“Well, you ought to see her. She’s—” + +Tom Buchanan, who had been hovering restlessly about the room, stopped +and rested his hand on my shoulder. + +“What you doing, Nick?” + +“I’m a bond man.” + +“Who with?” + +I told him. + +“Never heard of them,” he remarked decisively. + +This annoyed me. + +“You will,” I answered shortly. “You will if you stay in the East.” + +“Oh, I’ll stay in the East, don’t you worry,” he said, glancing at +Daisy and then back at me, as if he were alert for something +more. “I’d be a God damned fool to live anywhere else.” + +At this point Miss Baker said: “Absolutely!” with such suddenness that +I started—it was the first word she had uttered since I came into the +room. Evidently it surprised her as much as it did me, for she yawned +and with a series of rapid, deft movements stood up into the room. + +“I’m stiff,” she complained, “I’ve been lying on that sofa for as long +as I can remember.” + +“Don’t look at me,” Daisy retorted, “I’ve been trying to get you to +New York all afternoon.” + +“No, thanks,” said Miss Baker to the four cocktails just in from the +pantry. “I’m absolutely in training.” + +Her host looked at her incredulously. + +“You are!” He took down his drink as if it were a drop in the bottom +of a glass. “How you ever get anything done is beyond me.” + +I looked at Miss Baker, wondering what it was she “got done.” I +enjoyed looking at her. She was a slender, small-breasted girl, with +an erect carriage, which she accentuated by throwing her body backward +at the shoulders like a young cadet. Her grey sun-strained eyes looked +back at me with polite reciprocal curiosity out of a wan, charming, +discontented face. It occurred to me now that I had seen her, or a +picture of her, somewhere before. + +“You live in West Egg,” she remarked contemptuously. “I know somebody +there.” + +“I don’t know a single—” + +“You must know Gatsby.” + +“Gatsby?” demanded Daisy. “What Gatsby?” + +Before I could reply that he was my neighbour dinner was announced; +wedging his tense arm imperatively under mine, Tom Buchanan compelled +me from the room as though he were moving a checker to another square. + +Slenderly, languidly, their hands set lightly on their hips, the two +young women preceded us out on to a rosy-coloured porch, open toward +the sunset, where four candles flickered on the table in the +diminished wind. + +“Why candles?” objected Daisy, frowning. She snapped them out with her +fingers. “In two weeks it’ll be the longest day in the year.” She +looked at us all radiantly. “Do you always watch for the longest day +of the year and then miss it? I always watch for the longest day in +the year and then miss it.” + +“We ought to plan something,” yawned Miss Baker, sitting down at the +table as if she were getting into bed. + +“All right,” said Daisy. “What’ll we plan?” She turned to me +helplessly: “What do people plan?” + +Before I could answer her eyes fastened with an awed expression on her +little finger. + +“Look!” she complained; “I hurt it.” + +We all looked—the knuckle was black and blue. + +“You did it, Tom,” she said accusingly. “I know you didn’t mean to, +but you did do it. That’s what I get for marrying a brute of a man, a +great, big, hulking physical specimen of a—” + +“I hate that word ‘hulking,’ ” objected Tom crossly, “even in +kidding.” + +“Hulking,” insisted Daisy. + +Sometimes she and Miss Baker talked at once, unobtrusively and with a +bantering inconsequence that was never quite chatter, that was as cool +as their white dresses and their impersonal eyes in the absence of all +desire. They were here, and they accepted Tom and me, making only a +polite pleasant effort to entertain or to be entertained. They knew +that presently dinner would be over and a little later the evening too +would be over and casually put away. It was sharply different from the +West, where an evening was hurried from phase to phase towards its +close, in a continually disappointed anticipation or else in sheer +nervous dread of the moment itself. + +“You make me feel uncivilized, Daisy,” I confessed on my second glass +of corky but rather impressive claret. “Can’t you talk about crops or +something?” + +I meant nothing in particular by this remark, but it was taken up in +an unexpected way. + +“Civilization’s going to pieces,” broke out Tom violently. “I’ve +gotten to be a terrible pessimist about things. Have you read The Rise +of the Coloured Empires by this man Goddard?” + +“Why, no,” I answered, rather surprised by his tone. + +“Well, it’s a fine book, and everybody ought to read it. The idea is +if we don’t look out the white race will be—will be utterly +submerged. It’s all scientific stuff; it’s been proved.” + +“Tom’s getting very profound,” said Daisy, with an expression of +unthoughtful sadness. “He reads deep books with long words in +them. What was that word we—” + +“Well, these books are all scientific,” insisted Tom, glancing at her +impatiently. “This fellow has worked out the whole thing. It’s up to +us, who are the dominant race, to watch out or these other races will +have control of things.” + +“We’ve got to beat them down,” whispered Daisy, winking ferociously +toward the fervent sun. + +“You ought to live in California—” began Miss Baker, but Tom +interrupted her by shifting heavily in his chair. + +“This idea is that we’re Nordics. I am, and you are, and you are, +and—” After an infinitesimal hesitation he included Daisy with a +slight nod, and she winked at me again. “—And we’ve produced all the +things that go to make civilization—oh, science and art, and all +that. Do you see?” + +There was something pathetic in his concentration, as if his +complacency, more acute than of old, was not enough to him any more. +When, almost immediately, the telephone rang inside and the butler +left the porch Daisy seized upon the momentary interruption and leaned +towards me. + +“I’ll tell you a family secret,” she whispered enthusiastically. +“It’s about the butler’s nose. Do you want to hear about the butler’s +nose?” + +“That’s why I came over tonight.” + +“Well, he wasn’t always a butler; he used to be the silver polisher +for some people in New York that had a silver service for two hundred +people. He had to polish it from morning till night, until finally it +began to affect his nose—” + +“Things went from bad to worse,” suggested Miss Baker. + +“Yes. Things went from bad to worse, until finally he had to give up +his position.” + +For a moment the last sunshine fell with romantic affection upon her +glowing face; her voice compelled me forward breathlessly as I +listened—then the glow faded, each light deserting her with lingering +regret, like children leaving a pleasant street at dusk. + +The butler came back and murmured something close to Tom’s ear, +whereupon Tom frowned, pushed back his chair, and without a word went +inside. As if his absence quickened something within her, Daisy leaned +forward again, her voice glowing and singing. + +“I love to see you at my table, Nick. You remind me of a—of a rose, an +absolute rose. Doesn’t he?” She turned to Miss Baker for confirmation: +“An absolute rose?” + +This was untrue. I am not even faintly like a rose. She was only +extemporizing, but a stirring warmth flowed from her, as if her heart +was trying to come out to you concealed in one of those breathless, +thrilling words. Then suddenly she threw her napkin on the table and +excused herself and went into the house. + +Miss Baker and I exchanged a short glance consciously devoid of +meaning. I was about to speak when she sat up alertly and said “Sh!” +in a warning voice. A subdued impassioned murmur was audible in the +room beyond, and Miss Baker leaned forward unashamed, trying to +hear. The murmur trembled on the verge of coherence, sank down, +mounted excitedly, and then ceased altogether. + +“This Mr. Gatsby you spoke of is my neighbour—” I began. + +“Don’t talk. I want to hear what happens.” + +“Is something happening?” I inquired innocently. + +“You mean to say you don’t know?” said Miss Baker, honestly surprised. +“I thought everybody knew.” + +“I don’t.” + +“Why—” she said hesitantly. “Tom’s got some woman in New York.” + +“Got some woman?” I repeated blankly. + +Miss Baker nodded. + +“She might have the decency not to telephone him at dinner time. +Don’t you think?” + +Almost before I had grasped her meaning there was the flutter of a +dress and the crunch of leather boots, and Tom and Daisy were back at +the table. + +“It couldn’t be helped!” cried Daisy with tense gaiety. + +She sat down, glanced searchingly at Miss Baker and then at me, and +continued: “I looked outdoors for a minute, and it’s very romantic +outdoors. There’s a bird on the lawn that I think must be a +nightingale come over on the Cunard or White Star Line. He’s singing +away—” Her voice sang: “It’s romantic, isn’t it, Tom?” + +“Very romantic,” he said, and then miserably to me: “If it’s light +enough after dinner, I want to take you down to the stables.” + +The telephone rang inside, startlingly, and as Daisy shook her head +decisively at Tom the subject of the stables, in fact all subjects, +vanished into air. Among the broken fragments of the last five minutes +at table I remember the candles being lit again, pointlessly, and I +was conscious of wanting to look squarely at everyone, and yet to +avoid all eyes. I couldn’t guess what Daisy and Tom were thinking, but +I doubt if even Miss Baker, who seemed to have mastered a certain +hardy scepticism, was able utterly to put this fifth guest’s shrill +metallic urgency out of mind. To a certain temperament the situation +might have seemed intriguing—my own instinct was to telephone +immediately for the police. + +The horses, needless to say, were not mentioned again. Tom and Miss +Baker, with several feet of twilight between them, strolled back into +the library, as if to a vigil beside a perfectly tangible body, while, +trying to look pleasantly interested and a little deaf, I followed +Daisy around a chain of connecting verandas to the porch in front. In +its deep gloom we sat down side by side on a wicker settee. + +Daisy took her face in her hands as if feeling its lovely shape, and +her eyes moved gradually out into the velvet dusk. I saw that +turbulent emotions possessed her, so I asked what I thought would be +some sedative questions about her little girl. + +“We don’t know each other very well, Nick,” she said suddenly. “Even +if we are cousins. You didn’t come to my wedding.” + +“I wasn’t back from the war.” + +“That’s true.” She hesitated. “Well, I’ve had a very bad time, Nick, +and I’m pretty cynical about everything.” + +Evidently she had reason to be. I waited but she didn’t say any more, +and after a moment I returned rather feebly to the subject of her +daughter. + +“I suppose she talks, and—eats, and everything.” + +“Oh, yes.” She looked at me absently. “Listen, Nick; let me tell you +what I said when she was born. Would you like to hear?” + +“Very much.” + +“It’ll show you how I’ve gotten to feel about—things. Well, she was +less than an hour old and Tom was God knows where. I woke up out of +the ether with an utterly abandoned feeling, and asked the nurse right +away if it was a boy or a girl. She told me it was a girl, and so I +turned my head away and wept. ‘All right,’ I said, ‘I’m glad it’s a +girl. And I hope she’ll be a fool—that’s the best thing a girl can be +in this world, a beautiful little fool.’ + +“You see I think everything’s terrible anyhow,” she went on in a +convinced way. “Everybody thinks so—the most advanced people. And I +know. I’ve been everywhere and seen everything and done everything.” +Her eyes flashed around her in a defiant way, rather like Tom’s, and +she laughed with thrilling scorn. “Sophisticated—God, I’m +sophisticated!” + +The instant her voice broke off, ceasing to compel my attention, my +belief, I felt the basic insincerity of what she had said. It made me +uneasy, as though the whole evening had been a trick of some sort to +exact a contributory emotion from me. I waited, and sure enough, in a +moment she looked at me with an absolute smirk on her lovely face, as +if she had asserted her membership in a rather distinguished secret +society to which she and Tom belonged. + +------------------------------------------------------------------------ + +Inside, the crimson room bloomed with light. Tom and Miss Baker sat at +either end of the long couch and she read aloud to him from the +Saturday Evening Post—the words, murmurous and uninflected, running +together in a soothing tune. The lamplight, bright on his boots and +dull on the autumn-leaf yellow of her hair, glinted along the paper as +she turned a page with a flutter of slender muscles in her arms. + +When we came in she held us silent for a moment with a lifted hand. + +“To be continued,” she said, tossing the magazine on the table, “in +our very next issue.” + +Her body asserted itself with a restless movement of her knee, and she +stood up. + +“Ten o’clock,” she remarked, apparently finding the time on the +ceiling. “Time for this good girl to go to bed.” + +“Jordan’s going to play in the tournament tomorrow,” explained Daisy, +“over at Westchester.” + +“Oh—you’re Jordan Baker.” + +I knew now why her face was familiar—its pleasing contemptuous +expression had looked out at me from many rotogravure pictures of the +sporting life at Asheville and Hot Springs and Palm Beach. I had heard +some story of her too, a critical, unpleasant story, but what it was I +had forgotten long ago. + +“Good night,” she said softly. “Wake me at eight, won’t you.” + +“If you’ll get up.” + +“I will. Good night, Mr. Carraway. See you anon.” + +“Of course you will,” confirmed Daisy. “In fact I think I’ll arrange a +marriage. Come over often, Nick, and I’ll sort of—oh—fling you +together. You know—lock you up accidentally in linen closets and push +you out to sea in a boat, and all that sort of thing—” + +“Good night,” called Miss Baker from the stairs. “I haven’t heard a +word.” + +“She’s a nice girl,” said Tom after a moment. “They oughtn’t to let +her run around the country this way.” + +“Who oughtn’t to?” inquired Daisy coldly. + +“Her family.” + +“Her family is one aunt about a thousand years old. Besides, Nick’s +going to look after her, aren’t you, Nick? She’s going to spend lots +of weekends out here this summer. I think the home influence will be +very good for her.” + +Daisy and Tom looked at each other for a moment in silence. + +“Is she from New York?” I asked quickly. + +“From Louisville. Our white girlhood was passed together there. Our +beautiful white—” + +“Did you give Nick a little heart to heart talk on the veranda?” +demanded Tom suddenly. + +“Did I?” She looked at me. “I can’t seem to remember, but I think we +talked about the Nordic race. Yes, I’m sure we did. It sort of crept +up on us and first thing you know—” + +“Don’t believe everything you hear, Nick,” he advised me. + +I said lightly that I had heard nothing at all, and a few minutes +later I got up to go home. They came to the door with me and stood +side by side in a cheerful square of light. As I started my motor +Daisy peremptorily called: “Wait! + +“I forgot to ask you something, and it’s important. We heard you were +engaged to a girl out West.” + +“That’s right,” corroborated Tom kindly. “We heard that you were +engaged.” + +“It’s a libel. I’m too poor.” + +“But we heard it,” insisted Daisy, surprising me by opening up again +in a flower-like way. “We heard it from three people, so it must be +true.” + +Of course I knew what they were referring to, but I wasn’t even +vaguely engaged. The fact that gossip had published the banns was one +of the reasons I had come East. You can’t stop going with an old +friend on account of rumours, and on the other hand I had no intention +of being rumoured into marriage. + +Their interest rather touched me and made them less remotely +rich—nevertheless, I was confused and a little disgusted as I drove +away. It seemed to me that the thing for Daisy to do was to rush out +of the house, child in arms—but apparently there were no such +intentions in her head. As for Tom, the fact that he “had some woman +in New York” was really less surprising than that he had been +depressed by a book. Something was making him nibble at the edge of +stale ideas as if his sturdy physical egotism no longer nourished his +peremptory heart. + +Already it was deep summer on roadhouse roofs and in front of wayside +garages, where new red petrol-pumps sat out in pools of light, and +when I reached my estate at West Egg I ran the car under its shed and +sat for a while on an abandoned grass roller in the yard. The wind had +blown off, leaving a loud, bright night, with wings beating in the +trees and a persistent organ sound as the full bellows of the earth +blew the frogs full of life. The silhouette of a moving cat wavered +across the moonlight, and, turning my head to watch it, I saw that I +was not alone—fifty feet away a figure had emerged from the shadow of +my neighbour’s mansion and was standing with his hands in his pockets +regarding the silver pepper of the stars. Something in his leisurely +movements and the secure position of his feet upon the lawn suggested +that it was Mr. Gatsby himself, come out to determine what share was +his of our local heavens. + +I decided to call to him. Miss Baker had mentioned him at dinner, and +that would do for an introduction. But I didn’t call to him, for he +gave a sudden intimation that he was content to be alone—he stretched +out his arms toward the dark water in a curious way, and, far as I was +from him, I could have sworn he was trembling. Involuntarily I glanced +seaward—and distinguished nothing except a single green light, minute +and far away, that might have been the end of a dock. When I looked +once more for Gatsby he had vanished, and I was alone again in the +unquiet darkness. + + + II + +About halfway between West Egg and New York the motor road hastily +joins the railroad and runs beside it for a quarter of a mile, so as +to shrink away from a certain desolate area of land. This is a valley +of ashes—a fantastic farm where ashes grow like wheat into ridges and +hills and grotesque gardens; where ashes take the forms of houses and +chimneys and rising smoke and, finally, with a transcendent effort, of +ash-grey men, who move dimly and already crumbling through the powdery +air. Occasionally a line of grey cars crawls along an invisible track, +gives out a ghastly creak, and comes to rest, and immediately the +ash-grey men swarm up with leaden spades and stir up an impenetrable +cloud, which screens their obscure operations from your sight. + +But above the grey land and the spasms of bleak dust which drift +endlessly over it, you perceive, after a moment, the eyes of Doctor T. +J. Eckleburg. The eyes of Doctor T. J. Eckleburg are blue and +gigantic—their retinas are one yard high. They look out of no face, +but, instead, from a pair of enormous yellow spectacles which pass +over a nonexistent nose. Evidently some wild wag of an oculist set +them there to fatten his practice in the borough of Queens, and then +sank down himself into eternal blindness, or forgot them and moved +away. But his eyes, dimmed a little by many paintless days, under sun +and rain, brood on over the solemn dumping ground. + +The valley of ashes is bounded on one side by a small foul river, and, +when the drawbridge is up to let barges through, the passengers on +waiting trains can stare at the dismal scene for as long as half an +hour. There is always a halt there of at least a minute, and it was +because of this that I first met Tom Buchanan’s mistress. + +The fact that he had one was insisted upon wherever he was known. His +acquaintances resented the fact that he turned up in popular cafés +with her and, leaving her at a table, sauntered about, chatting with +whomsoever he knew. Though I was curious to see her, I had no desire +to meet her—but I did. I went up to New York with Tom on the train one +afternoon, and when we stopped by the ash-heaps he jumped to his feet +and, taking hold of my elbow, literally forced me from the car. + +“We’re getting off,” he insisted. “I want you to meet my girl.” + +I think he’d tanked up a good deal at luncheon, and his determination +to have my company bordered on violence. The supercilious assumption +was that on Sunday afternoon I had nothing better to do. + +I followed him over a low whitewashed railroad fence, and we walked +back a hundred yards along the road under Doctor Eckleburg’s +persistent stare. The only building in sight was a small block of +yellow brick sitting on the edge of the waste land, a sort of compact +Main Street ministering to it, and contiguous to absolutely nothing. +One of the three shops it contained was for rent and another was an +all-night restaurant, approached by a trail of ashes; the third was a +garage—Repairs. George B. Wilson. Cars bought and sold.—and I followed +Tom inside. + +The interior was unprosperous and bare; the only car visible was the +dust-covered wreck of a Ford which crouched in a dim corner. It had +occurred to me that this shadow of a garage must be a blind, and that +sumptuous and romantic apartments were concealed overhead, when the +proprietor himself appeared in the door of an office, wiping his hands +on a piece of waste. He was a blond, spiritless man, anaemic, and +faintly handsome. When he saw us a damp gleam of hope sprang into his +light blue eyes. + +“Hello, Wilson, old man,” said Tom, slapping him jovially on the +shoulder. “How’s business?” + +“I can’t complain,” answered Wilson unconvincingly. “When are you +going to sell me that car?” + +“Next week; I’ve got my man working on it now.” + +“Works pretty slow, don’t he?” + +“No, he doesn’t,” said Tom coldly. “And if you feel that way about it, +maybe I’d better sell it somewhere else after all.” + +“I don’t mean that,” explained Wilson quickly. “I just meant—” + +His voice faded off and Tom glanced impatiently around the garage. +Then I heard footsteps on a stairs, and in a moment the thickish +figure of a woman blocked out the light from the office door. She was +in the middle thirties, and faintly stout, but she carried her flesh +sensuously as some women can. Her face, above a spotted dress of dark +blue crêpe-de-chine, contained no facet or gleam of beauty, but there +was an immediately perceptible vitality about her as if the nerves of +her body were continually smouldering. She smiled slowly and, walking +through her husband as if he were a ghost, shook hands with Tom, +looking him flush in the eye. Then she wet her lips, and without +turning around spoke to her husband in a soft, coarse voice: + +“Get some chairs, why don’t you, so somebody can sit down.” + +“Oh, sure,” agreed Wilson hurriedly, and went toward the little +office, mingling immediately with the cement colour of the walls. A +white ashen dust veiled his dark suit and his pale hair as it veiled +everything in the vicinity—except his wife, who moved close to Tom. + +“I want to see you,” said Tom intently. “Get on the next train.” + +“All right.” + +“I’ll meet you by the newsstand on the lower level.” + +She nodded and moved away from him just as George Wilson emerged with +two chairs from his office door. + +We waited for her down the road and out of sight. It was a few days +before the Fourth of July, and a grey, scrawny Italian child was +setting torpedoes in a row along the railroad track. + +“Terrible place, isn’t it,” said Tom, exchanging a frown with Doctor +Eckleburg. + +“Awful.” + +“It does her good to get away.” + +“Doesn’t her husband object?” + +“Wilson? He thinks she goes to see her sister in New York. He’s so +dumb he doesn’t know he’s alive.” + +So Tom Buchanan and his girl and I went up together to New York—or not +quite together, for Mrs. Wilson sat discreetly in another car. Tom +deferred that much to the sensibilities of those East Eggers who might +be on the train. + +She had changed her dress to a brown figured muslin, which stretched +tight over her rather wide hips as Tom helped her to the platform in +New York. At the newsstand she bought a copy of Town Tattle and a +moving-picture magazine, and in the station drugstore some cold cream +and a small flask of perfume. Upstairs, in the solemn echoing drive +she let four taxicabs drive away before she selected a new one, +lavender-coloured with grey upholstery, and in this we slid out from +the mass of the station into the glowing sunshine. But immediately she +turned sharply from the window and, leaning forward, tapped on the +front glass. + +“I want to get one of those dogs,” she said earnestly. “I want to get +one for the apartment. They’re nice to have—a dog.” + +We backed up to a grey old man who bore an absurd resemblance to John +D. Rockefeller. In a basket swung from his neck cowered a dozen very +recent puppies of an indeterminate breed. + +“What kind are they?” asked Mrs. Wilson eagerly, as he came to the +taxi-window. + +“All kinds. What kind do you want, lady?” + +“I’d like to get one of those police dogs; I don’t suppose you got +that kind?” + +The man peered doubtfully into the basket, plunged in his hand and +drew one up, wriggling, by the back of the neck. + +“That’s no police dog,” said Tom. + +“No, it’s not exactly a police dog,” said the man with disappointment +in his voice. “It’s more of an Airedale.” He passed his hand over the +brown washrag of a back. “Look at that coat. Some coat. That’s a dog +that’ll never bother you with catching cold.” + +“I think it’s cute,” said Mrs. Wilson enthusiastically. “How much is +it?” + +“That dog?” He looked at it admiringly. “That dog will cost you ten +dollars.” + +The Airedale—undoubtedly there was an Airedale concerned in it +somewhere, though its feet were startlingly white—changed hands and +settled down into Mrs. Wilson’s lap, where she fondled the +weatherproof coat with rapture. + +“Is it a boy or a girl?” she asked delicately. + +“That dog? That dog’s a boy.” + +“It’s a bitch,” said Tom decisively. “Here’s your money. Go and buy +ten more dogs with it.” + +We drove over to Fifth Avenue, warm and soft, almost pastoral, on the +summer Sunday afternoon. I wouldn’t have been surprised to see a great +flock of white sheep turn the corner. + +“Hold on,” I said, “I have to leave you here.” + +“No you don’t,” interposed Tom quickly. “Myrtle’ll be hurt if you +don’t come up to the apartment. Won’t you, Myrtle?” + +“Come on,” she urged. “I’ll telephone my sister Catherine. She’s said +to be very beautiful by people who ought to know.” + +“Well, I’d like to, but—” + +We went on, cutting back again over the Park toward the West Hundreds. +At 158th Street the cab stopped at one slice in a long white cake of +apartment-houses. Throwing a regal homecoming glance around the +neighbourhood, Mrs. Wilson gathered up her dog and her other +purchases, and went haughtily in. + +“I’m going to have the McKees come up,” she announced as we rose in +the elevator. “And, of course, I got to call up my sister, too.” + +The apartment was on the top floor—a small living-room, a small +dining-room, a small bedroom, and a bath. The living-room was crowded +to the doors with a set of tapestried furniture entirely too large for +it, so that to move about was to stumble continually over scenes of +ladies swinging in the gardens of Versailles. The only picture was an +over-enlarged photograph, apparently a hen sitting on a blurred rock. +Looked at from a distance, however, the hen resolved itself into a +bonnet, and the countenance of a stout old lady beamed down into the +room. Several old copies of Town Tattle lay on the table together with +a copy of Simon Called Peter, and some of the small scandal magazines +of Broadway. Mrs. Wilson was first concerned with the dog. A reluctant +elevator boy went for a box full of straw and some milk, to which he +added on his own initiative a tin of large, hard dog biscuits—one of +which decomposed apathetically in the saucer of milk all +afternoon. Meanwhile Tom brought out a bottle of whisky from a locked +bureau door. + +I have been drunk just twice in my life, and the second time was that +afternoon; so everything that happened has a dim, hazy cast over it, +although until after eight o’clock the apartment was full of cheerful +sun. Sitting on Tom’s lap Mrs. Wilson called up several people on the +telephone; then there were no cigarettes, and I went out to buy some +at the drugstore on the corner. When I came back they had both +disappeared, so I sat down discreetly in the living-room and read a +chapter of Simon Called Peter—either it was terrible stuff or the +whisky distorted things, because it didn’t make any sense to me. + +Just as Tom and Myrtle (after the first drink Mrs. Wilson and I called +each other by our first names) reappeared, company commenced to arrive +at the apartment door. + +The sister, Catherine, was a slender, worldly girl of about thirty, +with a solid, sticky bob of red hair, and a complexion powdered milky +white. Her eyebrows had been plucked and then drawn on again at a more +rakish angle, but the efforts of nature toward the restoration of the +old alignment gave a blurred air to her face. When she moved about +there was an incessant clicking as innumerable pottery bracelets +jingled up and down upon her arms. She came in with such a proprietary +haste, and looked around so possessively at the furniture that I +wondered if she lived here. But when I asked her she laughed +immoderately, repeated my question aloud, and told me she lived with a +girl friend at a hotel. + +Mr. McKee was a pale, feminine man from the flat below. He had just +shaved, for there was a white spot of lather on his cheekbone, and he +was most respectful in his greeting to everyone in the room. He +informed me that he was in the “artistic game,” and I gathered later +that he was a photographer and had made the dim enlargement of +Mrs. Wilson’s mother which hovered like an ectoplasm on the wall. His +wife was shrill, languid, handsome, and horrible. She told me with +pride that her husband had photographed her a hundred and twenty-seven +times since they had been married. + +Mrs. Wilson had changed her costume some time before, and was now +attired in an elaborate afternoon dress of cream-coloured chiffon, +which gave out a continual rustle as she swept about the room. With +the influence of the dress her personality had also undergone a +change. The intense vitality that had been so remarkable in the garage +was converted into impressive hauteur. Her laughter, her gestures, her +assertions became more violently affected moment by moment, and as she +expanded the room grew smaller around her, until she seemed to be +revolving on a noisy, creaking pivot through the smoky air. + +“My dear,” she told her sister in a high, mincing shout, “most of +these fellas will cheat you every time. All they think of is money. I +had a woman up here last week to look at my feet, and when she gave me +the bill you’d of thought she had my appendicitis out.” + +“What was the name of the woman?” asked Mrs. McKee. + +“Mrs. Eberhardt. She goes around looking at people’s feet in their own +homes.” + +“I like your dress,” remarked Mrs. McKee, “I think it’s adorable.” + +Mrs. Wilson rejected the compliment by raising her eyebrow in disdain. + +“It’s just a crazy old thing,” she said. “I just slip it on sometimes +when I don’t care what I look like.” + +“But it looks wonderful on you, if you know what I mean,” pursued Mrs. +McKee. “If Chester could only get you in that pose I think he could +make something of it.” + +We all looked in silence at Mrs. Wilson, who removed a strand of hair +from over her eyes and looked back at us with a brilliant smile. Mr. +McKee regarded her intently with his head on one side, and then moved +his hand back and forth slowly in front of his face. + +“I should change the light,” he said after a moment. “I’d like to +bring out the modelling of the features. And I’d try to get hold of +all the back hair.” + +“I wouldn’t think of changing the light,” cried Mrs. McKee. “I think +it’s—” + +Her husband said “Sh!” and we all looked at the subject again, +whereupon Tom Buchanan yawned audibly and got to his feet. + +“You McKees have something to drink,” he said. “Get some more ice and +mineral water, Myrtle, before everybody goes to sleep.” + +“I told that boy about the ice.” Myrtle raised her eyebrows in despair +at the shiftlessness of the lower orders. “These people! You have to +keep after them all the time.” + +She looked at me and laughed pointlessly. Then she flounced over to +the dog, kissed it with ecstasy, and swept into the kitchen, implying +that a dozen chefs awaited her orders there. + +“I’ve done some nice things out on Long Island,” asserted Mr. McKee. + +Tom looked at him blankly. + +“Two of them we have framed downstairs.” + +“Two what?” demanded Tom. + +“Two studies. One of them I call Montauk Point—The Gulls, and the +other I call Montauk Point—The Sea.” + +The sister Catherine sat down beside me on the couch. + +“Do you live down on Long Island, too?” she inquired. + +“I live at West Egg.” + +“Really? I was down there at a party about a month ago. At a man named +Gatsby’s. Do you know him?” + +“I live next door to him.” + +“Well, they say he’s a nephew or a cousin of Kaiser Wilhelm’s. That’s +where all his money comes from.” + +“Really?” + +She nodded. + +“I’m scared of him. I’d hate to have him get anything on me.” + +This absorbing information about my neighbour was interrupted by Mrs. +McKee’s pointing suddenly at Catherine: + +“Chester, I think you could do something with her,” she broke out, but +Mr. McKee only nodded in a bored way, and turned his attention to Tom. + +“I’d like to do more work on Long Island, if I could get the entry. +All I ask is that they should give me a start.” + +“Ask Myrtle,” said Tom, breaking into a short shout of laughter as +Mrs. Wilson entered with a tray. “She’ll give you a letter of +introduction, won’t you, Myrtle?” + +“Do what?” she asked, startled. + +“You’ll give McKee a letter of introduction to your husband, so he can +do some studies of him.” His lips moved silently for a moment as he +invented, “ ‘George B. Wilson at the Gasoline Pump,’ or something like +that.” + +Catherine leaned close to me and whispered in my ear: + +“Neither of them can stand the person they’re married to.” + +“Can’t they?” + +“Can’t stand them.” She looked at Myrtle and then at Tom. “What I say +is, why go on living with them if they can’t stand them? If I was them +I’d get a divorce and get married to each other right away.” + +“Doesn’t she like Wilson either?” + +The answer to this was unexpected. It came from Myrtle, who had +overheard the question, and it was violent and obscene. + +“You see,” cried Catherine triumphantly. She lowered her voice again. +“It’s really his wife that’s keeping them apart. She’s a Catholic, and +they don’t believe in divorce.” + +Daisy was not a Catholic, and I was a little shocked at the +elaborateness of the lie. + +“When they do get married,” continued Catherine, “they’re going West +to live for a while until it blows over.” + +“It’d be more discreet to go to Europe.” + +“Oh, do you like Europe?” she exclaimed surprisingly. “I just got back +from Monte Carlo.” + +“Really.” + +“Just last year. I went over there with another girl.” + +“Stay long?” + +“No, we just went to Monte Carlo and back. We went by way of +Marseilles. We had over twelve hundred dollars when we started, but we +got gyped out of it all in two days in the private rooms. We had an +awful time getting back, I can tell you. God, how I hated that town!” + +The late afternoon sky bloomed in the window for a moment like the +blue honey of the Mediterranean—then the shrill voice of Mrs. McKee +called me back into the room. + +“I almost made a mistake, too,” she declared vigorously. “I almost +married a little kike who’d been after me for years. I knew he was +below me. Everybody kept saying to me: ‘Lucille, that man’s way below +you!’ But if I hadn’t met Chester, he’d of got me sure.” + +“Yes, but listen,” said Myrtle Wilson, nodding her head up and down, +“at least you didn’t marry him.” + +“I know I didn’t.” + +“Well, I married him,” said Myrtle, ambiguously. “And that’s the +difference between your case and mine.” + +“Why did you, Myrtle?” demanded Catherine. “Nobody forced you to.” + +Myrtle considered. + +“I married him because I thought he was a gentleman,” she said +finally. “I thought he knew something about breeding, but he wasn’t +fit to lick my shoe.” + +“You were crazy about him for a while,” said Catherine. + +“Crazy about him!” cried Myrtle incredulously. “Who said I was crazy +about him? I never was any more crazy about him than I was about that +man there.” + +She pointed suddenly at me, and everyone looked at me accusingly. I +tried to show by my expression that I expected no affection. + +“The only crazy I was was when I married him. I knew right away I made +a mistake. He borrowed somebody’s best suit to get married in, and +never even told me about it, and the man came after it one day when he +was out: ‘Oh, is that your suit?’ I said. ‘This is the first I ever +heard about it.’ But I gave it to him and then I lay down and cried to +beat the band all afternoon.” + +“She really ought to get away from him,” resumed Catherine to me. +“They’ve been living over that garage for eleven years. And Tom’s the +first sweetie she ever had.” + +The bottle of whisky—a second one—was now in constant demand by all +present, excepting Catherine, who “felt just as good on nothing at +all.” Tom rang for the janitor and sent him for some celebrated +sandwiches, which were a complete supper in themselves. I wanted to +get out and walk eastward toward the park through the soft twilight, +but each time I tried to go I became entangled in some wild, strident +argument which pulled me back, as if with ropes, into my chair. Yet +high over the city our line of yellow windows must have contributed +their share of human secrecy to the casual watcher in the darkening +streets, and I saw him too, looking up and wondering. I was within and +without, simultaneously enchanted and repelled by the inexhaustible +variety of life. + +Myrtle pulled her chair close to mine, and suddenly her warm breath +poured over me the story of her first meeting with Tom. + +“It was on the two little seats facing each other that are always the +last ones left on the train. I was going up to New York to see my +sister and spend the night. He had on a dress suit and patent leather +shoes, and I couldn’t keep my eyes off him, but every time he looked +at me I had to pretend to be looking at the advertisement over his +head. When we came into the station he was next to me, and his white +shirtfront pressed against my arm, and so I told him I’d have to call +a policeman, but he knew I lied. I was so excited that when I got into +a taxi with him I didn’t hardly know I wasn’t getting into a subway +train. All I kept thinking about, over and over, was ‘You can’t live +forever; you can’t live forever.’ ” + +She turned to Mrs. McKee and the room rang full of her artificial +laughter. + +“My dear,” she cried, “I’m going to give you this dress as soon as I’m +through with it. I’ve got to get another one tomorrow. I’m going to +make a list of all the things I’ve got to get. A massage and a wave, +and a collar for the dog, and one of those cute little ashtrays where +you touch a spring, and a wreath with a black silk bow for mother’s +grave that’ll last all summer. I got to write down a list so I won’t +forget all the things I got to do.” + +It was nine o’clock—almost immediately afterward I looked at my watch +and found it was ten. Mr. McKee was asleep on a chair with his fists +clenched in his lap, like a photograph of a man of action. Taking out +my handkerchief I wiped from his cheek the spot of dried lather that +had worried me all the afternoon. + +The little dog was sitting on the table looking with blind eyes +through the smoke, and from time to time groaning faintly. People +disappeared, reappeared, made plans to go somewhere, and then lost +each other, searched for each other, found each other a few feet +away. Some time toward midnight Tom Buchanan and Mrs. Wilson stood +face to face discussing, in impassioned voices, whether Mrs. Wilson +had any right to mention Daisy’s name. + +“Daisy! Daisy! Daisy!” shouted Mrs. Wilson. “I’ll say it whenever I +want to! Daisy! Dai—” + +Making a short deft movement, Tom Buchanan broke her nose with his +open hand. + +Then there were bloody towels upon the bathroom floor, and women’s +voices scolding, and high over the confusion a long broken wail of +pain. Mr. McKee awoke from his doze and started in a daze toward the +door. When he had gone halfway he turned around and stared at the +scene—his wife and Catherine scolding and consoling as they stumbled +here and there among the crowded furniture with articles of aid, and +the despairing figure on the couch, bleeding fluently, and trying to +spread a copy of Town Tattle over the tapestry scenes of +Versailles. Then Mr. McKee turned and continued on out the door. +Taking my hat from the chandelier, I followed. + +“Come to lunch some day,” he suggested, as we groaned down in the +elevator. + +“Where?” + +“Anywhere.” + +“Keep your hands off the lever,” snapped the elevator boy. + +“I beg your pardon,” said Mr. McKee with dignity, “I didn’t know I was +touching it.” + +“All right,” I agreed, “I’ll be glad to.” + +… I was standing beside his bed and he was sitting up between the +sheets, clad in his underwear, with a great portfolio in his hands. + +“Beauty and the Beast … Loneliness … Old Grocery Horse … Brook’n +Bridge …” + +Then I was lying half asleep in the cold lower level of the +Pennsylvania Station, staring at the morning Tribune, and waiting for +the four o’clock train. + + + III + +There was music from my neighbour’s house through the summer nights. +In his blue gardens men and girls came and went like moths among the +whisperings and the champagne and the stars. At high tide in the +afternoon I watched his guests diving from the tower of his raft, or +taking the sun on the hot sand of his beach while his two motorboats +slit the waters of the Sound, drawing aquaplanes over cataracts of +foam. On weekends his Rolls-Royce became an omnibus, bearing parties +to and from the city between nine in the morning and long past +midnight, while his station wagon scampered like a brisk yellow bug to +meet all trains. And on Mondays eight servants, including an extra +gardener, toiled all day with mops and scrubbing-brushes and hammers +and garden-shears, repairing the ravages of the night before. + +Every Friday five crates of oranges and lemons arrived from a +fruiterer in New York—every Monday these same oranges and lemons left +his back door in a pyramid of pulpless halves. There was a machine in +the kitchen which could extract the juice of two hundred oranges in +half an hour if a little button was pressed two hundred times by a +butler’s thumb. + +At least once a fortnight a corps of caterers came down with several +hundred feet of canvas and enough coloured lights to make a Christmas +tree of Gatsby’s enormous garden. On buffet tables, garnished with +glistening hors-d’oeuvre, spiced baked hams crowded against salads of +harlequin designs and pastry pigs and turkeys bewitched to a dark +gold. In the main hall a bar with a real brass rail was set up, and +stocked with gins and liquors and with cordials so long forgotten that +most of his female guests were too young to know one from another. + +By seven o’clock the orchestra has arrived, no thin five-piece affair, +but a whole pitful of oboes and trombones and saxophones and viols and +cornets and piccolos, and low and high drums. The last swimmers have +come in from the beach now and are dressing upstairs; the cars from +New York are parked five deep in the drive, and already the halls and +salons and verandas are gaudy with primary colours, and hair bobbed in +strange new ways, and shawls beyond the dreams of Castile. The bar is +in full swing, and floating rounds of cocktails permeate the garden +outside, until the air is alive with chatter and laughter, and casual +innuendo and introductions forgotten on the spot, and enthusiastic +meetings between women who never knew each other’s names. + +The lights grow brighter as the earth lurches away from the sun, and +now the orchestra is playing yellow cocktail music, and the opera of +voices pitches a key higher. Laughter is easier minute by minute, +spilled with prodigality, tipped out at a cheerful word. The groups +change more swiftly, swell with new arrivals, dissolve and form in the +same breath; already there are wanderers, confident girls who weave +here and there among the stouter and more stable, become for a sharp, +joyous moment the centre of a group, and then, excited with triumph, +glide on through the sea-change of faces and voices and colour under +the constantly changing light. + +Suddenly one of these gypsies, in trembling opal, seizes a cocktail +out of the air, dumps it down for courage and, moving her hands like +Frisco, dances out alone on the canvas platform. A momentary hush; the +orchestra leader varies his rhythm obligingly for her, and there is a +burst of chatter as the erroneous news goes around that she is Gilda +Gray’s understudy from the Follies. The party has begun. + +I believe that on the first night I went to Gatsby’s house I was one +of the few guests who had actually been invited. People were not +invited—they went there. They got into automobiles which bore them out +to Long Island, and somehow they ended up at Gatsby’s door. Once there +they were introduced by somebody who knew Gatsby, and after that they +conducted themselves according to the rules of behaviour associated +with an amusement park. Sometimes they came and went without having +met Gatsby at all, came for the party with a simplicity of heart that +was its own ticket of admission. + +I had been actually invited. A chauffeur in a uniform of robin’s-egg +blue crossed my lawn early that Saturday morning with a surprisingly +formal note from his employer: the honour would be entirely Gatsby’s, +it said, if I would attend his “little party” that night. He had seen +me several times, and had intended to call on me long before, but a +peculiar combination of circumstances had prevented it—signed Jay +Gatsby, in a majestic hand. + +Dressed up in white flannels I went over to his lawn a little after +seven, and wandered around rather ill at ease among swirls and eddies +of people I didn’t know—though here and there was a face I had noticed +on the commuting train. I was immediately struck by the number of +young Englishmen dotted about; all well dressed, all looking a little +hungry, and all talking in low, earnest voices to solid and prosperous +Americans. I was sure that they were selling something: bonds or +insurance or automobiles. They were at least agonizingly aware of the +easy money in the vicinity and convinced that it was theirs for a few +words in the right key. + +As soon as I arrived I made an attempt to find my host, but the two or +three people of whom I asked his whereabouts stared at me in such an +amazed way, and denied so vehemently any knowledge of his movements, +that I slunk off in the direction of the cocktail table—the only place +in the garden where a single man could linger without looking +purposeless and alone. + +I was on my way to get roaring drunk from sheer embarrassment when +Jordan Baker came out of the house and stood at the head of the marble +steps, leaning a little backward and looking with contemptuous +interest down into the garden. + +Welcome or not, I found it necessary to attach myself to someone +before I should begin to address cordial remarks to the passersby. + +“Hello!” I roared, advancing toward her. My voice seemed unnaturally +loud across the garden. + +“I thought you might be here,” she responded absently as I came up. +“I remembered you lived next door to—” + +She held my hand impersonally, as a promise that she’d take care of me +in a minute, and gave ear to two girls in twin yellow dresses, who +stopped at the foot of the steps. + +“Hello!” they cried together. “Sorry you didn’t win.” + +That was for the golf tournament. She had lost in the finals the week +before. + +“You don’t know who we are,” said one of the girls in yellow, “but we +met you here about a month ago.” + +“You’ve dyed your hair since then,” remarked Jordan, and I started, +but the girls had moved casually on and her remark was addressed to +the premature moon, produced like the supper, no doubt, out of a +caterer’s basket. With Jordan’s slender golden arm resting in mine, we +descended the steps and sauntered about the garden. A tray of +cocktails floated at us through the twilight, and we sat down at a +table with the two girls in yellow and three men, each one introduced +to us as Mr. Mumble. + +“Do you come to these parties often?” inquired Jordan of the girl +beside her. + +“The last one was the one I met you at,” answered the girl, in an +alert confident voice. She turned to her companion: “Wasn’t it for +you, Lucille?” + +It was for Lucille, too. + +“I like to come,” Lucille said. “I never care what I do, so I always +have a good time. When I was here last I tore my gown on a chair, and +he asked me my name and address—inside of a week I got a package from +Croirier’s with a new evening gown in it.” + +“Did you keep it?” asked Jordan. + +“Sure I did. I was going to wear it tonight, but it was too big in the +bust and had to be altered. It was gas blue with lavender beads. Two +hundred and sixty-five dollars.” + +“There’s something funny about a fellow that’ll do a thing like that,” +said the other girl eagerly. “He doesn’t want any trouble with +anybody.” + +“Who doesn’t?” I inquired. + +“Gatsby. Somebody told me—” + +The two girls and Jordan leaned together confidentially. + +“Somebody told me they thought he killed a man once.” + +A thrill passed over all of us. The three Mr. Mumbles bent forward and +listened eagerly. + +“I don’t think it’s so much that,” argued Lucille sceptically; “It’s +more that he was a German spy during the war.” + +One of the men nodded in confirmation. + +“I heard that from a man who knew all about him, grew up with him in +Germany,” he assured us positively. + +“Oh, no,” said the first girl, “it couldn’t be that, because he was in +the American army during the war.” As our credulity switched back to +her she leaned forward with enthusiasm. “You look at him sometimes +when he thinks nobody’s looking at him. I’ll bet he killed a man.” + +She narrowed her eyes and shivered. Lucille shivered. We all turned +and looked around for Gatsby. It was testimony to the romantic +speculation he inspired that there were whispers about him from those +who had found little that it was necessary to whisper about in this +world. + +The first supper—there would be another one after midnight—was now +being served, and Jordan invited me to join her own party, who were +spread around a table on the other side of the garden. There were +three married couples and Jordan’s escort, a persistent undergraduate +given to + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_2048.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_2048.txt new file mode 100644 index 0000000000..c332d7ee75 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_2048.txt @@ -0,0 +1,179 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I decided to go East and learn the bond +business. Everybody I knew was in the bond business, so I supposed it +could support one more single man. All my aunts and uncles talked it +over as if they were choosing a prep school for me, and finally said, +“Why—ye-es,” with very grave, hesitant faces. Father agreed to finance +me for a year, and after various delays I came East, permanently, I +thought, in the spring of twenty-two. + +The practical thing was to find rooms in the city, but it was a warm +season, and I had just left a country of wide lawns and friendly +trees, so when a young man at the office suggested that we take a +house together in a commuting town, it sounded like a great idea. He +found the house, a weather-beaten cardboard bungalow at eighty a +month, but at the last minute the firm ordered him to Washington, and +I went out to the country alone. I had a dog—at least I had him for a +few days until he ran away—and an old Dodge and a Finnish woman, who +made my bed and cooked breakfast and muttered Finnish wisdom to +herself over the electric stove. + +It was lonely for a day or so until one morning some man, more +recently arrived than I, stopped me on the road. + +“How do you get to West Egg village?” he asked helplessly. + +I told him. And as I walked on I was lonely no longer. I was a guide, +a pathfinder, an original settler. He had casually conferred on me the +freedom of the neighbourhood. + +And so with the sunshine and the great bursts of leaves growing on the +trees, just as things grow in fast movies, I had that familiar +conviction that life was beginning over again with the summer. + +There was so much to read, for one thing, and so much fine health to +be pulled down out of the young breath-giving air. I bought a dozen +volumes on banking and credit and investment securities, and they +stood on my shelf in red and gold like new money from the mint, +promising to unfold the shining secrets that only Midas and Morgan and +Maecenas knew. And I had the high intention of reading many other +books besides. I was rather literary in college—one year I wrote a +series of very solemn and obvious editorials for the Yale News—and now +I was going to bring back all such things into my life and become +again that most limited of all specialists, the “well-rounded man.” +This isn’t just an epigram—life is much more successfully looked at +from a single window, after all. + +It was a matter of chance that I should have rented a house in one of +the strangest communities in North America. It was on that slender +riotous island which extends itself due east of New York—and where +there are, among other natural curiosities, two unusual formations of +land. Twenty miles from the city a pair of enormous eggs, identical in +contour and separated only by a courtesy bay, jut out into the most +domesticated body of salt water in the Western hemisphere, the great +wet barnyard of Long Island Sound. They are not perfect ovals—like the +egg in the Columbus story, they are both crushed flat at the contact +end—but their physical resemblance must be a source of perpetual +wonder to the gulls that fly overhead. To the wingless a more +interesting phenomenon is their dissimilarity in every particular +except shape and size. + +I lived at West Egg, the—well, the less fashionable of the two, though +this is a most superficial tag to express the bizarre and not a little +sinister contrast between them. My house was at the very tip of the +egg, only fifty yards from the Sound, and squeezed between two huge +places that rented for twelve or fifteen thousand a season. The one on +my right was a colossal affair by any standard—it was a factual +imitation of some Hôtel de Ville in Normandy, with a tower on one +side, spanking new under a thin beard of raw ivy, and a marble +swimming pool, and more than forty acres of lawn and garden. It was +Gatsby’s mansion. Or, rather, as I didn’t know Mr. Gatsby, it was a +mansion inhabited by a gentleman of that name. My own house was an +eyesore, but it was a small eyesore, and it had been overlooked, so I +had a view of the water, a partial view of my neighbour’s lawn, and +the consoling proximity of millionaires—all for eighty dollars a +month. + +Across the courtesy bay the white palaces of fashionable East Egg +glittered along the water, and the history of the summer really begins +on the + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_256.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_256.txt new file mode 100644 index 0000000000..01ed6794d7 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_256.txt @@ -0,0 +1,47 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_32768.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_32768.txt new file mode 100644 index 0000000000..1843a7fe3a --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_32768.txt @@ -0,0 +1,3028 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I decided to go East and learn the bond +business. Everybody I knew was in the bond business, so I supposed it +could support one more single man. All my aunts and uncles talked it +over as if they were choosing a prep school for me, and finally said, +“Why—ye-es,” with very grave, hesitant faces. Father agreed to finance +me for a year, and after various delays I came East, permanently, I +thought, in the spring of twenty-two. + +The practical thing was to find rooms in the city, but it was a warm +season, and I had just left a country of wide lawns and friendly +trees, so when a young man at the office suggested that we take a +house together in a commuting town, it sounded like a great idea. He +found the house, a weather-beaten cardboard bungalow at eighty a +month, but at the last minute the firm ordered him to Washington, and +I went out to the country alone. I had a dog—at least I had him for a +few days until he ran away—and an old Dodge and a Finnish woman, who +made my bed and cooked breakfast and muttered Finnish wisdom to +herself over the electric stove. + +It was lonely for a day or so until one morning some man, more +recently arrived than I, stopped me on the road. + +“How do you get to West Egg village?” he asked helplessly. + +I told him. And as I walked on I was lonely no longer. I was a guide, +a pathfinder, an original settler. He had casually conferred on me the +freedom of the neighbourhood. + +And so with the sunshine and the great bursts of leaves growing on the +trees, just as things grow in fast movies, I had that familiar +conviction that life was beginning over again with the summer. + +There was so much to read, for one thing, and so much fine health to +be pulled down out of the young breath-giving air. I bought a dozen +volumes on banking and credit and investment securities, and they +stood on my shelf in red and gold like new money from the mint, +promising to unfold the shining secrets that only Midas and Morgan and +Maecenas knew. And I had the high intention of reading many other +books besides. I was rather literary in college—one year I wrote a +series of very solemn and obvious editorials for the Yale News—and now +I was going to bring back all such things into my life and become +again that most limited of all specialists, the “well-rounded man.” +This isn’t just an epigram—life is much more successfully looked at +from a single window, after all. + +It was a matter of chance that I should have rented a house in one of +the strangest communities in North America. It was on that slender +riotous island which extends itself due east of New York—and where +there are, among other natural curiosities, two unusual formations of +land. Twenty miles from the city a pair of enormous eggs, identical in +contour and separated only by a courtesy bay, jut out into the most +domesticated body of salt water in the Western hemisphere, the great +wet barnyard of Long Island Sound. They are not perfect ovals—like the +egg in the Columbus story, they are both crushed flat at the contact +end—but their physical resemblance must be a source of perpetual +wonder to the gulls that fly overhead. To the wingless a more +interesting phenomenon is their dissimilarity in every particular +except shape and size. + +I lived at West Egg, the—well, the less fashionable of the two, though +this is a most superficial tag to express the bizarre and not a little +sinister contrast between them. My house was at the very tip of the +egg, only fifty yards from the Sound, and squeezed between two huge +places that rented for twelve or fifteen thousand a season. The one on +my right was a colossal affair by any standard—it was a factual +imitation of some Hôtel de Ville in Normandy, with a tower on one +side, spanking new under a thin beard of raw ivy, and a marble +swimming pool, and more than forty acres of lawn and garden. It was +Gatsby’s mansion. Or, rather, as I didn’t know Mr. Gatsby, it was a +mansion inhabited by a gentleman of that name. My own house was an +eyesore, but it was a small eyesore, and it had been overlooked, so I +had a view of the water, a partial view of my neighbour’s lawn, and +the consoling proximity of millionaires—all for eighty dollars a +month. + +Across the courtesy bay the white palaces of fashionable East Egg +glittered along the water, and the history of the summer really begins +on the evening I drove over there to have dinner with the Tom +Buchanans. Daisy was my second cousin once removed, and I’d known Tom +in college. And just after the war I spent two days with them in +Chicago. + +Her husband, among various physical accomplishments, had been one of +the most powerful ends that ever played football at New Haven—a +national figure in a way, one of those men who reach such an acute +limited excellence at twenty-one that everything afterward savours of +anticlimax. His family were enormously wealthy—even in college his +freedom with money was a matter for reproach—but now he’d left Chicago +and come East in a fashion that rather took your breath away: for +instance, he’d brought down a string of polo ponies from Lake +Forest. It was hard to realize that a man in my own generation was +wealthy enough to do that. + +Why they came East I don’t know. They had spent a year in France for +no particular reason, and then drifted here and there unrestfully +wherever people played polo and were rich together. This was a +permanent move, said Daisy over the telephone, but I didn’t believe +it—I had no sight into Daisy’s heart, but I felt that Tom would drift +on forever seeking, a little wistfully, for the dramatic turbulence of +some irrecoverable football game. + +And so it happened that on a warm windy evening I drove over to East +Egg to see two old friends whom I scarcely knew at all. Their house +was even more elaborate than I expected, a cheerful red-and-white +Georgian Colonial mansion, overlooking the bay. The lawn started at +the beach and ran towards the front door for a quarter of a mile, +jumping over sundials and brick walks and burning gardens—finally when +it reached the house drifting up the side in bright vines as though +from the momentum of its run. The front was broken by a line of French +windows, glowing now with reflected gold and wide open to the warm +windy afternoon, and Tom Buchanan in riding clothes was standing with +his legs apart on the front porch. + +He had changed since his New Haven years. Now he was a sturdy +straw-haired man of thirty, with a rather hard mouth and a +supercilious manner. Two shining arrogant eyes had established +dominance over his face and gave him the appearance of always leaning +aggressively forward. Not even the effeminate swank of his riding +clothes could hide the enormous power of that body—he seemed to fill +those glistening boots until he strained the top lacing, and you could +see a great pack of muscle shifting when his shoulder moved under his +thin coat. It was a body capable of enormous leverage—a cruel body. + +His speaking voice, a gruff husky tenor, added to the impression of +fractiousness he conveyed. There was a touch of paternal contempt in +it, even toward people he liked—and there were men at New Haven who +had hated his guts. + +“Now, don’t think my opinion on these matters is final,” he seemed to +say, “just because I’m stronger and more of a man than you are.” We +were in the same senior society, and while we were never intimate I +always had the impression that he approved of me and wanted me to like +him with some harsh, defiant wistfulness of his own. + +We talked for a few minutes on the sunny porch. + +“I’ve got a nice place here,” he said, his eyes flashing about +restlessly. + +Turning me around by one arm, he moved a broad flat hand along the +front vista, including in its sweep a sunken Italian garden, a half +acre of deep, pungent roses, and a snub-nosed motorboat that bumped +the tide offshore. + +“It belonged to Demaine, the oil man.” He turned me around again, +politely and abruptly. “We’ll go inside.” + +We walked through a high hallway into a bright rosy-coloured space, +fragilely bound into the house by French windows at either end. The +windows were ajar and gleaming white against the fresh grass outside +that seemed to grow a little way into the house. A breeze blew through +the room, blew curtains in at one end and out the other like pale +flags, twisting them up toward the frosted wedding-cake of the +ceiling, and then rippled over the wine-coloured rug, making a shadow +on it as wind does on the sea. + +The only completely stationary object in the room was an enormous +couch on which two young women were buoyed up as though upon an +anchored balloon. They were both in white, and their dresses were +rippling and fluttering as if they had just been blown back in after a +short flight around the house. I must have stood for a few moments +listening to the whip and snap of the curtains and the groan of a +picture on the wall. Then there was a boom as Tom Buchanan shut the +rear windows and the caught wind died out about the room, and the +curtains and the rugs and the two young women ballooned slowly to the +floor. + +The younger of the two was a stranger to me. She was extended full +length at her end of the divan, completely motionless, and with her +chin raised a little, as if she were balancing something on it which +was quite likely to fall. If she saw me out of the corner of her eyes +she gave no hint of it—indeed, I was almost surprised into murmuring +an apology for having disturbed her by coming in. + +The other girl, Daisy, made an attempt to rise—she leaned slightly +forward with a conscientious expression—then she laughed, an absurd, +charming little laugh, and I laughed too and came forward into the +room. + +“I’m p-paralysed with happiness.” + +She laughed again, as if she said something very witty, and held my +hand for a moment, looking up into my face, promising that there was +no one in the world she so much wanted to see. That was a way she +had. She hinted in a murmur that the surname of the balancing girl was +Baker. (I’ve heard it said that Daisy’s murmur was only to make people +lean toward her; an irrelevant criticism that made it no less +charming.) + +At any rate, Miss Baker’s lips fluttered, she nodded at me almost +imperceptibly, and then quickly tipped her head back again—the object +she was balancing had obviously tottered a little and given her +something of a fright. Again a sort of apology arose to my lips. +Almost any exhibition of complete self-sufficiency draws a stunned +tribute from me. + +I looked back at my cousin, who began to ask me questions in her low, +thrilling voice. It was the kind of voice that the ear follows up and +down, as if each speech is an arrangement of notes that will never be +played again. Her face was sad and lovely with bright things in it, +bright eyes and a bright passionate mouth, but there was an excitement +in her voice that men who had cared for her found difficult to forget: +a singing compulsion, a whispered “Listen,” a promise that she had +done gay, exciting things just a while since and that there were gay, +exciting things hovering in the next hour. + +I told her how I had stopped off in Chicago for a day on my way East, +and how a dozen people had sent their love through me. + +“Do they miss me?” she cried ecstatically. + +“The whole town is desolate. All the cars have the left rear wheel +painted black as a mourning wreath, and there’s a persistent wail all +night along the north shore.” + +“How gorgeous! Let’s go back, Tom. Tomorrow!” Then she added +irrelevantly: “You ought to see the baby.” + +“I’d like to.” + +“She’s asleep. She’s three years old. Haven’t you ever seen her?” + +“Never.” + +“Well, you ought to see her. She’s—” + +Tom Buchanan, who had been hovering restlessly about the room, stopped +and rested his hand on my shoulder. + +“What you doing, Nick?” + +“I’m a bond man.” + +“Who with?” + +I told him. + +“Never heard of them,” he remarked decisively. + +This annoyed me. + +“You will,” I answered shortly. “You will if you stay in the East.” + +“Oh, I’ll stay in the East, don’t you worry,” he said, glancing at +Daisy and then back at me, as if he were alert for something +more. “I’d be a God damned fool to live anywhere else.” + +At this point Miss Baker said: “Absolutely!” with such suddenness that +I started—it was the first word she had uttered since I came into the +room. Evidently it surprised her as much as it did me, for she yawned +and with a series of rapid, deft movements stood up into the room. + +“I’m stiff,” she complained, “I’ve been lying on that sofa for as long +as I can remember.” + +“Don’t look at me,” Daisy retorted, “I’ve been trying to get you to +New York all afternoon.” + +“No, thanks,” said Miss Baker to the four cocktails just in from the +pantry. “I’m absolutely in training.” + +Her host looked at her incredulously. + +“You are!” He took down his drink as if it were a drop in the bottom +of a glass. “How you ever get anything done is beyond me.” + +I looked at Miss Baker, wondering what it was she “got done.” I +enjoyed looking at her. She was a slender, small-breasted girl, with +an erect carriage, which she accentuated by throwing her body backward +at the shoulders like a young cadet. Her grey sun-strained eyes looked +back at me with polite reciprocal curiosity out of a wan, charming, +discontented face. It occurred to me now that I had seen her, or a +picture of her, somewhere before. + +“You live in West Egg,” she remarked contemptuously. “I know somebody +there.” + +“I don’t know a single—” + +“You must know Gatsby.” + +“Gatsby?” demanded Daisy. “What Gatsby?” + +Before I could reply that he was my neighbour dinner was announced; +wedging his tense arm imperatively under mine, Tom Buchanan compelled +me from the room as though he were moving a checker to another square. + +Slenderly, languidly, their hands set lightly on their hips, the two +young women preceded us out on to a rosy-coloured porch, open toward +the sunset, where four candles flickered on the table in the +diminished wind. + +“Why candles?” objected Daisy, frowning. She snapped them out with her +fingers. “In two weeks it’ll be the longest day in the year.” She +looked at us all radiantly. “Do you always watch for the longest day +of the year and then miss it? I always watch for the longest day in +the year and then miss it.” + +“We ought to plan something,” yawned Miss Baker, sitting down at the +table as if she were getting into bed. + +“All right,” said Daisy. “What’ll we plan?” She turned to me +helplessly: “What do people plan?” + +Before I could answer her eyes fastened with an awed expression on her +little finger. + +“Look!” she complained; “I hurt it.” + +We all looked—the knuckle was black and blue. + +“You did it, Tom,” she said accusingly. “I know you didn’t mean to, +but you did do it. That’s what I get for marrying a brute of a man, a +great, big, hulking physical specimen of a—” + +“I hate that word ‘hulking,’ ” objected Tom crossly, “even in +kidding.” + +“Hulking,” insisted Daisy. + +Sometimes she and Miss Baker talked at once, unobtrusively and with a +bantering inconsequence that was never quite chatter, that was as cool +as their white dresses and their impersonal eyes in the absence of all +desire. They were here, and they accepted Tom and me, making only a +polite pleasant effort to entertain or to be entertained. They knew +that presently dinner would be over and a little later the evening too +would be over and casually put away. It was sharply different from the +West, where an evening was hurried from phase to phase towards its +close, in a continually disappointed anticipation or else in sheer +nervous dread of the moment itself. + +“You make me feel uncivilized, Daisy,” I confessed on my second glass +of corky but rather impressive claret. “Can’t you talk about crops or +something?” + +I meant nothing in particular by this remark, but it was taken up in +an unexpected way. + +“Civilization’s going to pieces,” broke out Tom violently. “I’ve +gotten to be a terrible pessimist about things. Have you read The Rise +of the Coloured Empires by this man Goddard?” + +“Why, no,” I answered, rather surprised by his tone. + +“Well, it’s a fine book, and everybody ought to read it. The idea is +if we don’t look out the white race will be—will be utterly +submerged. It’s all scientific stuff; it’s been proved.” + +“Tom’s getting very profound,” said Daisy, with an expression of +unthoughtful sadness. “He reads deep books with long words in +them. What was that word we—” + +“Well, these books are all scientific,” insisted Tom, glancing at her +impatiently. “This fellow has worked out the whole thing. It’s up to +us, who are the dominant race, to watch out or these other races will +have control of things.” + +“We’ve got to beat them down,” whispered Daisy, winking ferociously +toward the fervent sun. + +“You ought to live in California—” began Miss Baker, but Tom +interrupted her by shifting heavily in his chair. + +“This idea is that we’re Nordics. I am, and you are, and you are, +and—” After an infinitesimal hesitation he included Daisy with a +slight nod, and she winked at me again. “—And we’ve produced all the +things that go to make civilization—oh, science and art, and all +that. Do you see?” + +There was something pathetic in his concentration, as if his +complacency, more acute than of old, was not enough to him any more. +When, almost immediately, the telephone rang inside and the butler +left the porch Daisy seized upon the momentary interruption and leaned +towards me. + +“I’ll tell you a family secret,” she whispered enthusiastically. +“It’s about the butler’s nose. Do you want to hear about the butler’s +nose?” + +“That’s why I came over tonight.” + +“Well, he wasn’t always a butler; he used to be the silver polisher +for some people in New York that had a silver service for two hundred +people. He had to polish it from morning till night, until finally it +began to affect his nose—” + +“Things went from bad to worse,” suggested Miss Baker. + +“Yes. Things went from bad to worse, until finally he had to give up +his position.” + +For a moment the last sunshine fell with romantic affection upon her +glowing face; her voice compelled me forward breathlessly as I +listened—then the glow faded, each light deserting her with lingering +regret, like children leaving a pleasant street at dusk. + +The butler came back and murmured something close to Tom’s ear, +whereupon Tom frowned, pushed back his chair, and without a word went +inside. As if his absence quickened something within her, Daisy leaned +forward again, her voice glowing and singing. + +“I love to see you at my table, Nick. You remind me of a—of a rose, an +absolute rose. Doesn’t he?” She turned to Miss Baker for confirmation: +“An absolute rose?” + +This was untrue. I am not even faintly like a rose. She was only +extemporizing, but a stirring warmth flowed from her, as if her heart +was trying to come out to you concealed in one of those breathless, +thrilling words. Then suddenly she threw her napkin on the table and +excused herself and went into the house. + +Miss Baker and I exchanged a short glance consciously devoid of +meaning. I was about to speak when she sat up alertly and said “Sh!” +in a warning voice. A subdued impassioned murmur was audible in the +room beyond, and Miss Baker leaned forward unashamed, trying to +hear. The murmur trembled on the verge of coherence, sank down, +mounted excitedly, and then ceased altogether. + +“This Mr. Gatsby you spoke of is my neighbour—” I began. + +“Don’t talk. I want to hear what happens.” + +“Is something happening?” I inquired innocently. + +“You mean to say you don’t know?” said Miss Baker, honestly surprised. +“I thought everybody knew.” + +“I don’t.” + +“Why—” she said hesitantly. “Tom’s got some woman in New York.” + +“Got some woman?” I repeated blankly. + +Miss Baker nodded. + +“She might have the decency not to telephone him at dinner time. +Don’t you think?” + +Almost before I had grasped her meaning there was the flutter of a +dress and the crunch of leather boots, and Tom and Daisy were back at +the table. + +“It couldn’t be helped!” cried Daisy with tense gaiety. + +She sat down, glanced searchingly at Miss Baker and then at me, and +continued: “I looked outdoors for a minute, and it’s very romantic +outdoors. There’s a bird on the lawn that I think must be a +nightingale come over on the Cunard or White Star Line. He’s singing +away—” Her voice sang: “It’s romantic, isn’t it, Tom?” + +“Very romantic,” he said, and then miserably to me: “If it’s light +enough after dinner, I want to take you down to the stables.” + +The telephone rang inside, startlingly, and as Daisy shook her head +decisively at Tom the subject of the stables, in fact all subjects, +vanished into air. Among the broken fragments of the last five minutes +at table I remember the candles being lit again, pointlessly, and I +was conscious of wanting to look squarely at everyone, and yet to +avoid all eyes. I couldn’t guess what Daisy and Tom were thinking, but +I doubt if even Miss Baker, who seemed to have mastered a certain +hardy scepticism, was able utterly to put this fifth guest’s shrill +metallic urgency out of mind. To a certain temperament the situation +might have seemed intriguing—my own instinct was to telephone +immediately for the police. + +The horses, needless to say, were not mentioned again. Tom and Miss +Baker, with several feet of twilight between them, strolled back into +the library, as if to a vigil beside a perfectly tangible body, while, +trying to look pleasantly interested and a little deaf, I followed +Daisy around a chain of connecting verandas to the porch in front. In +its deep gloom we sat down side by side on a wicker settee. + +Daisy took her face in her hands as if feeling its lovely shape, and +her eyes moved gradually out into the velvet dusk. I saw that +turbulent emotions possessed her, so I asked what I thought would be +some sedative questions about her little girl. + +“We don’t know each other very well, Nick,” she said suddenly. “Even +if we are cousins. You didn’t come to my wedding.” + +“I wasn’t back from the war.” + +“That’s true.” She hesitated. “Well, I’ve had a very bad time, Nick, +and I’m pretty cynical about everything.” + +Evidently she had reason to be. I waited but she didn’t say any more, +and after a moment I returned rather feebly to the subject of her +daughter. + +“I suppose she talks, and—eats, and everything.” + +“Oh, yes.” She looked at me absently. “Listen, Nick; let me tell you +what I said when she was born. Would you like to hear?” + +“Very much.” + +“It’ll show you how I’ve gotten to feel about—things. Well, she was +less than an hour old and Tom was God knows where. I woke up out of +the ether with an utterly abandoned feeling, and asked the nurse right +away if it was a boy or a girl. She told me it was a girl, and so I +turned my head away and wept. ‘All right,’ I said, ‘I’m glad it’s a +girl. And I hope she’ll be a fool—that’s the best thing a girl can be +in this world, a beautiful little fool.’ + +“You see I think everything’s terrible anyhow,” she went on in a +convinced way. “Everybody thinks so—the most advanced people. And I +know. I’ve been everywhere and seen everything and done everything.” +Her eyes flashed around her in a defiant way, rather like Tom’s, and +she laughed with thrilling scorn. “Sophisticated—God, I’m +sophisticated!” + +The instant her voice broke off, ceasing to compel my attention, my +belief, I felt the basic insincerity of what she had said. It made me +uneasy, as though the whole evening had been a trick of some sort to +exact a contributory emotion from me. I waited, and sure enough, in a +moment she looked at me with an absolute smirk on her lovely face, as +if she had asserted her membership in a rather distinguished secret +society to which she and Tom belonged. + +------------------------------------------------------------------------ + +Inside, the crimson room bloomed with light. Tom and Miss Baker sat at +either end of the long couch and she read aloud to him from the +Saturday Evening Post—the words, murmurous and uninflected, running +together in a soothing tune. The lamplight, bright on his boots and +dull on the autumn-leaf yellow of her hair, glinted along the paper as +she turned a page with a flutter of slender muscles in her arms. + +When we came in she held us silent for a moment with a lifted hand. + +“To be continued,” she said, tossing the magazine on the table, “in +our very next issue.” + +Her body asserted itself with a restless movement of her knee, and she +stood up. + +“Ten o’clock,” she remarked, apparently finding the time on the +ceiling. “Time for this good girl to go to bed.” + +“Jordan’s going to play in the tournament tomorrow,” explained Daisy, +“over at Westchester.” + +“Oh—you’re Jordan Baker.” + +I knew now why her face was familiar—its pleasing contemptuous +expression had looked out at me from many rotogravure pictures of the +sporting life at Asheville and Hot Springs and Palm Beach. I had heard +some story of her too, a critical, unpleasant story, but what it was I +had forgotten long ago. + +“Good night,” she said softly. “Wake me at eight, won’t you.” + +“If you’ll get up.” + +“I will. Good night, Mr. Carraway. See you anon.” + +“Of course you will,” confirmed Daisy. “In fact I think I’ll arrange a +marriage. Come over often, Nick, and I’ll sort of—oh—fling you +together. You know—lock you up accidentally in linen closets and push +you out to sea in a boat, and all that sort of thing—” + +“Good night,” called Miss Baker from the stairs. “I haven’t heard a +word.” + +“She’s a nice girl,” said Tom after a moment. “They oughtn’t to let +her run around the country this way.” + +“Who oughtn’t to?” inquired Daisy coldly. + +“Her family.” + +“Her family is one aunt about a thousand years old. Besides, Nick’s +going to look after her, aren’t you, Nick? She’s going to spend lots +of weekends out here this summer. I think the home influence will be +very good for her.” + +Daisy and Tom looked at each other for a moment in silence. + +“Is she from New York?” I asked quickly. + +“From Louisville. Our white girlhood was passed together there. Our +beautiful white—” + +“Did you give Nick a little heart to heart talk on the veranda?” +demanded Tom suddenly. + +“Did I?” She looked at me. “I can’t seem to remember, but I think we +talked about the Nordic race. Yes, I’m sure we did. It sort of crept +up on us and first thing you know—” + +“Don’t believe everything you hear, Nick,” he advised me. + +I said lightly that I had heard nothing at all, and a few minutes +later I got up to go home. They came to the door with me and stood +side by side in a cheerful square of light. As I started my motor +Daisy peremptorily called: “Wait! + +“I forgot to ask you something, and it’s important. We heard you were +engaged to a girl out West.” + +“That’s right,” corroborated Tom kindly. “We heard that you were +engaged.” + +“It’s a libel. I’m too poor.” + +“But we heard it,” insisted Daisy, surprising me by opening up again +in a flower-like way. “We heard it from three people, so it must be +true.” + +Of course I knew what they were referring to, but I wasn’t even +vaguely engaged. The fact that gossip had published the banns was one +of the reasons I had come East. You can’t stop going with an old +friend on account of rumours, and on the other hand I had no intention +of being rumoured into marriage. + +Their interest rather touched me and made them less remotely +rich—nevertheless, I was confused and a little disgusted as I drove +away. It seemed to me that the thing for Daisy to do was to rush out +of the house, child in arms—but apparently there were no such +intentions in her head. As for Tom, the fact that he “had some woman +in New York” was really less surprising than that he had been +depressed by a book. Something was making him nibble at the edge of +stale ideas as if his sturdy physical egotism no longer nourished his +peremptory heart. + +Already it was deep summer on roadhouse roofs and in front of wayside +garages, where new red petrol-pumps sat out in pools of light, and +when I reached my estate at West Egg I ran the car under its shed and +sat for a while on an abandoned grass roller in the yard. The wind had +blown off, leaving a loud, bright night, with wings beating in the +trees and a persistent organ sound as the full bellows of the earth +blew the frogs full of life. The silhouette of a moving cat wavered +across the moonlight, and, turning my head to watch it, I saw that I +was not alone—fifty feet away a figure had emerged from the shadow of +my neighbour’s mansion and was standing with his hands in his pockets +regarding the silver pepper of the stars. Something in his leisurely +movements and the secure position of his feet upon the lawn suggested +that it was Mr. Gatsby himself, come out to determine what share was +his of our local heavens. + +I decided to call to him. Miss Baker had mentioned him at dinner, and +that would do for an introduction. But I didn’t call to him, for he +gave a sudden intimation that he was content to be alone—he stretched +out his arms toward the dark water in a curious way, and, far as I was +from him, I could have sworn he was trembling. Involuntarily I glanced +seaward—and distinguished nothing except a single green light, minute +and far away, that might have been the end of a dock. When I looked +once more for Gatsby he had vanished, and I was alone again in the +unquiet darkness. + + + II + +About halfway between West Egg and New York the motor road hastily +joins the railroad and runs beside it for a quarter of a mile, so as +to shrink away from a certain desolate area of land. This is a valley +of ashes—a fantastic farm where ashes grow like wheat into ridges and +hills and grotesque gardens; where ashes take the forms of houses and +chimneys and rising smoke and, finally, with a transcendent effort, of +ash-grey men, who move dimly and already crumbling through the powdery +air. Occasionally a line of grey cars crawls along an invisible track, +gives out a ghastly creak, and comes to rest, and immediately the +ash-grey men swarm up with leaden spades and stir up an impenetrable +cloud, which screens their obscure operations from your sight. + +But above the grey land and the spasms of bleak dust which drift +endlessly over it, you perceive, after a moment, the eyes of Doctor T. +J. Eckleburg. The eyes of Doctor T. J. Eckleburg are blue and +gigantic—their retinas are one yard high. They look out of no face, +but, instead, from a pair of enormous yellow spectacles which pass +over a nonexistent nose. Evidently some wild wag of an oculist set +them there to fatten his practice in the borough of Queens, and then +sank down himself into eternal blindness, or forgot them and moved +away. But his eyes, dimmed a little by many paintless days, under sun +and rain, brood on over the solemn dumping ground. + +The valley of ashes is bounded on one side by a small foul river, and, +when the drawbridge is up to let barges through, the passengers on +waiting trains can stare at the dismal scene for as long as half an +hour. There is always a halt there of at least a minute, and it was +because of this that I first met Tom Buchanan’s mistress. + +The fact that he had one was insisted upon wherever he was known. His +acquaintances resented the fact that he turned up in popular cafés +with her and, leaving her at a table, sauntered about, chatting with +whomsoever he knew. Though I was curious to see her, I had no desire +to meet her—but I did. I went up to New York with Tom on the train one +afternoon, and when we stopped by the ash-heaps he jumped to his feet +and, taking hold of my elbow, literally forced me from the car. + +“We’re getting off,” he insisted. “I want you to meet my girl.” + +I think he’d tanked up a good deal at luncheon, and his determination +to have my company bordered on violence. The supercilious assumption +was that on Sunday afternoon I had nothing better to do. + +I followed him over a low whitewashed railroad fence, and we walked +back a hundred yards along the road under Doctor Eckleburg’s +persistent stare. The only building in sight was a small block of +yellow brick sitting on the edge of the waste land, a sort of compact +Main Street ministering to it, and contiguous to absolutely nothing. +One of the three shops it contained was for rent and another was an +all-night restaurant, approached by a trail of ashes; the third was a +garage—Repairs. George B. Wilson. Cars bought and sold.—and I followed +Tom inside. + +The interior was unprosperous and bare; the only car visible was the +dust-covered wreck of a Ford which crouched in a dim corner. It had +occurred to me that this shadow of a garage must be a blind, and that +sumptuous and romantic apartments were concealed overhead, when the +proprietor himself appeared in the door of an office, wiping his hands +on a piece of waste. He was a blond, spiritless man, anaemic, and +faintly handsome. When he saw us a damp gleam of hope sprang into his +light blue eyes. + +“Hello, Wilson, old man,” said Tom, slapping him jovially on the +shoulder. “How’s business?” + +“I can’t complain,” answered Wilson unconvincingly. “When are you +going to sell me that car?” + +“Next week; I’ve got my man working on it now.” + +“Works pretty slow, don’t he?” + +“No, he doesn’t,” said Tom coldly. “And if you feel that way about it, +maybe I’d better sell it somewhere else after all.” + +“I don’t mean that,” explained Wilson quickly. “I just meant—” + +His voice faded off and Tom glanced impatiently around the garage. +Then I heard footsteps on a stairs, and in a moment the thickish +figure of a woman blocked out the light from the office door. She was +in the middle thirties, and faintly stout, but she carried her flesh +sensuously as some women can. Her face, above a spotted dress of dark +blue crêpe-de-chine, contained no facet or gleam of beauty, but there +was an immediately perceptible vitality about her as if the nerves of +her body were continually smouldering. She smiled slowly and, walking +through her husband as if he were a ghost, shook hands with Tom, +looking him flush in the eye. Then she wet her lips, and without +turning around spoke to her husband in a soft, coarse voice: + +“Get some chairs, why don’t you, so somebody can sit down.” + +“Oh, sure,” agreed Wilson hurriedly, and went toward the little +office, mingling immediately with the cement colour of the walls. A +white ashen dust veiled his dark suit and his pale hair as it veiled +everything in the vicinity—except his wife, who moved close to Tom. + +“I want to see you,” said Tom intently. “Get on the next train.” + +“All right.” + +“I’ll meet you by the newsstand on the lower level.” + +She nodded and moved away from him just as George Wilson emerged with +two chairs from his office door. + +We waited for her down the road and out of sight. It was a few days +before the Fourth of July, and a grey, scrawny Italian child was +setting torpedoes in a row along the railroad track. + +“Terrible place, isn’t it,” said Tom, exchanging a frown with Doctor +Eckleburg. + +“Awful.” + +“It does her good to get away.” + +“Doesn’t her husband object?” + +“Wilson? He thinks she goes to see her sister in New York. He’s so +dumb he doesn’t know he’s alive.” + +So Tom Buchanan and his girl and I went up together to New York—or not +quite together, for Mrs. Wilson sat discreetly in another car. Tom +deferred that much to the sensibilities of those East Eggers who might +be on the train. + +She had changed her dress to a brown figured muslin, which stretched +tight over her rather wide hips as Tom helped her to the platform in +New York. At the newsstand she bought a copy of Town Tattle and a +moving-picture magazine, and in the station drugstore some cold cream +and a small flask of perfume. Upstairs, in the solemn echoing drive +she let four taxicabs drive away before she selected a new one, +lavender-coloured with grey upholstery, and in this we slid out from +the mass of the station into the glowing sunshine. But immediately she +turned sharply from the window and, leaning forward, tapped on the +front glass. + +“I want to get one of those dogs,” she said earnestly. “I want to get +one for the apartment. They’re nice to have—a dog.” + +We backed up to a grey old man who bore an absurd resemblance to John +D. Rockefeller. In a basket swung from his neck cowered a dozen very +recent puppies of an indeterminate breed. + +“What kind are they?” asked Mrs. Wilson eagerly, as he came to the +taxi-window. + +“All kinds. What kind do you want, lady?” + +“I’d like to get one of those police dogs; I don’t suppose you got +that kind?” + +The man peered doubtfully into the basket, plunged in his hand and +drew one up, wriggling, by the back of the neck. + +“That’s no police dog,” said Tom. + +“No, it’s not exactly a police dog,” said the man with disappointment +in his voice. “It’s more of an Airedale.” He passed his hand over the +brown washrag of a back. “Look at that coat. Some coat. That’s a dog +that’ll never bother you with catching cold.” + +“I think it’s cute,” said Mrs. Wilson enthusiastically. “How much is +it?” + +“That dog?” He looked at it admiringly. “That dog will cost you ten +dollars.” + +The Airedale—undoubtedly there was an Airedale concerned in it +somewhere, though its feet were startlingly white—changed hands and +settled down into Mrs. Wilson’s lap, where she fondled the +weatherproof coat with rapture. + +“Is it a boy or a girl?” she asked delicately. + +“That dog? That dog’s a boy.” + +“It’s a bitch,” said Tom decisively. “Here’s your money. Go and buy +ten more dogs with it.” + +We drove over to Fifth Avenue, warm and soft, almost pastoral, on the +summer Sunday afternoon. I wouldn’t have been surprised to see a great +flock of white sheep turn the corner. + +“Hold on,” I said, “I have to leave you here.” + +“No you don’t,” interposed Tom quickly. “Myrtle’ll be hurt if you +don’t come up to the apartment. Won’t you, Myrtle?” + +“Come on,” she urged. “I’ll telephone my sister Catherine. She’s said +to be very beautiful by people who ought to know.” + +“Well, I’d like to, but—” + +We went on, cutting back again over the Park toward the West Hundreds. +At 158th Street the cab stopped at one slice in a long white cake of +apartment-houses. Throwing a regal homecoming glance around the +neighbourhood, Mrs. Wilson gathered up her dog and her other +purchases, and went haughtily in. + +“I’m going to have the McKees come up,” she announced as we rose in +the elevator. “And, of course, I got to call up my sister, too.” + +The apartment was on the top floor—a small living-room, a small +dining-room, a small bedroom, and a bath. The living-room was crowded +to the doors with a set of tapestried furniture entirely too large for +it, so that to move about was to stumble continually over scenes of +ladies swinging in the gardens of Versailles. The only picture was an +over-enlarged photograph, apparently a hen sitting on a blurred rock. +Looked at from a distance, however, the hen resolved itself into a +bonnet, and the countenance of a stout old lady beamed down into the +room. Several old copies of Town Tattle lay on the table together with +a copy of Simon Called Peter, and some of the small scandal magazines +of Broadway. Mrs. Wilson was first concerned with the dog. A reluctant +elevator boy went for a box full of straw and some milk, to which he +added on his own initiative a tin of large, hard dog biscuits—one of +which decomposed apathetically in the saucer of milk all +afternoon. Meanwhile Tom brought out a bottle of whisky from a locked +bureau door. + +I have been drunk just twice in my life, and the second time was that +afternoon; so everything that happened has a dim, hazy cast over it, +although until after eight o’clock the apartment was full of cheerful +sun. Sitting on Tom’s lap Mrs. Wilson called up several people on the +telephone; then there were no cigarettes, and I went out to buy some +at the drugstore on the corner. When I came back they had both +disappeared, so I sat down discreetly in the living-room and read a +chapter of Simon Called Peter—either it was terrible stuff or the +whisky distorted things, because it didn’t make any sense to me. + +Just as Tom and Myrtle (after the first drink Mrs. Wilson and I called +each other by our first names) reappeared, company commenced to arrive +at the apartment door. + +The sister, Catherine, was a slender, worldly girl of about thirty, +with a solid, sticky bob of red hair, and a complexion powdered milky +white. Her eyebrows had been plucked and then drawn on again at a more +rakish angle, but the efforts of nature toward the restoration of the +old alignment gave a blurred air to her face. When she moved about +there was an incessant clicking as innumerable pottery bracelets +jingled up and down upon her arms. She came in with such a proprietary +haste, and looked around so possessively at the furniture that I +wondered if she lived here. But when I asked her she laughed +immoderately, repeated my question aloud, and told me she lived with a +girl friend at a hotel. + +Mr. McKee was a pale, feminine man from the flat below. He had just +shaved, for there was a white spot of lather on his cheekbone, and he +was most respectful in his greeting to everyone in the room. He +informed me that he was in the “artistic game,” and I gathered later +that he was a photographer and had made the dim enlargement of +Mrs. Wilson’s mother which hovered like an ectoplasm on the wall. His +wife was shrill, languid, handsome, and horrible. She told me with +pride that her husband had photographed her a hundred and twenty-seven +times since they had been married. + +Mrs. Wilson had changed her costume some time before, and was now +attired in an elaborate afternoon dress of cream-coloured chiffon, +which gave out a continual rustle as she swept about the room. With +the influence of the dress her personality had also undergone a +change. The intense vitality that had been so remarkable in the garage +was converted into impressive hauteur. Her laughter, her gestures, her +assertions became more violently affected moment by moment, and as she +expanded the room grew smaller around her, until she seemed to be +revolving on a noisy, creaking pivot through the smoky air. + +“My dear,” she told her sister in a high, mincing shout, “most of +these fellas will cheat you every time. All they think of is money. I +had a woman up here last week to look at my feet, and when she gave me +the bill you’d of thought she had my appendicitis out.” + +“What was the name of the woman?” asked Mrs. McKee. + +“Mrs. Eberhardt. She goes around looking at people’s feet in their own +homes.” + +“I like your dress,” remarked Mrs. McKee, “I think it’s adorable.” + +Mrs. Wilson rejected the compliment by raising her eyebrow in disdain. + +“It’s just a crazy old thing,” she said. “I just slip it on sometimes +when I don’t care what I look like.” + +“But it looks wonderful on you, if you know what I mean,” pursued Mrs. +McKee. “If Chester could only get you in that pose I think he could +make something of it.” + +We all looked in silence at Mrs. Wilson, who removed a strand of hair +from over her eyes and looked back at us with a brilliant smile. Mr. +McKee regarded her intently with his head on one side, and then moved +his hand back and forth slowly in front of his face. + +“I should change the light,” he said after a moment. “I’d like to +bring out the modelling of the features. And I’d try to get hold of +all the back hair.” + +“I wouldn’t think of changing the light,” cried Mrs. McKee. “I think +it’s—” + +Her husband said “Sh!” and we all looked at the subject again, +whereupon Tom Buchanan yawned audibly and got to his feet. + +“You McKees have something to drink,” he said. “Get some more ice and +mineral water, Myrtle, before everybody goes to sleep.” + +“I told that boy about the ice.” Myrtle raised her eyebrows in despair +at the shiftlessness of the lower orders. “These people! You have to +keep after them all the time.” + +She looked at me and laughed pointlessly. Then she flounced over to +the dog, kissed it with ecstasy, and swept into the kitchen, implying +that a dozen chefs awaited her orders there. + +“I’ve done some nice things out on Long Island,” asserted Mr. McKee. + +Tom looked at him blankly. + +“Two of them we have framed downstairs.” + +“Two what?” demanded Tom. + +“Two studies. One of them I call Montauk Point—The Gulls, and the +other I call Montauk Point—The Sea.” + +The sister Catherine sat down beside me on the couch. + +“Do you live down on Long Island, too?” she inquired. + +“I live at West Egg.” + +“Really? I was down there at a party about a month ago. At a man named +Gatsby’s. Do you know him?” + +“I live next door to him.” + +“Well, they say he’s a nephew or a cousin of Kaiser Wilhelm’s. That’s +where all his money comes from.” + +“Really?” + +She nodded. + +“I’m scared of him. I’d hate to have him get anything on me.” + +This absorbing information about my neighbour was interrupted by Mrs. +McKee’s pointing suddenly at Catherine: + +“Chester, I think you could do something with her,” she broke out, but +Mr. McKee only nodded in a bored way, and turned his attention to Tom. + +“I’d like to do more work on Long Island, if I could get the entry. +All I ask is that they should give me a start.” + +“Ask Myrtle,” said Tom, breaking into a short shout of laughter as +Mrs. Wilson entered with a tray. “She’ll give you a letter of +introduction, won’t you, Myrtle?” + +“Do what?” she asked, startled. + +“You’ll give McKee a letter of introduction to your husband, so he can +do some studies of him.” His lips moved silently for a moment as he +invented, “ ‘George B. Wilson at the Gasoline Pump,’ or something like +that.” + +Catherine leaned close to me and whispered in my ear: + +“Neither of them can stand the person they’re married to.” + +“Can’t they?” + +“Can’t stand them.” She looked at Myrtle and then at Tom. “What I say +is, why go on living with them if they can’t stand them? If I was them +I’d get a divorce and get married to each other right away.” + +“Doesn’t she like Wilson either?” + +The answer to this was unexpected. It came from Myrtle, who had +overheard the question, and it was violent and obscene. + +“You see,” cried Catherine triumphantly. She lowered her voice again. +“It’s really his wife that’s keeping them apart. She’s a Catholic, and +they don’t believe in divorce.” + +Daisy was not a Catholic, and I was a little shocked at the +elaborateness of the lie. + +“When they do get married,” continued Catherine, “they’re going West +to live for a while until it blows over.” + +“It’d be more discreet to go to Europe.” + +“Oh, do you like Europe?” she exclaimed surprisingly. “I just got back +from Monte Carlo.” + +“Really.” + +“Just last year. I went over there with another girl.” + +“Stay long?” + +“No, we just went to Monte Carlo and back. We went by way of +Marseilles. We had over twelve hundred dollars when we started, but we +got gyped out of it all in two days in the private rooms. We had an +awful time getting back, I can tell you. God, how I hated that town!” + +The late afternoon sky bloomed in the window for a moment like the +blue honey of the Mediterranean—then the shrill voice of Mrs. McKee +called me back into the room. + +“I almost made a mistake, too,” she declared vigorously. “I almost +married a little kike who’d been after me for years. I knew he was +below me. Everybody kept saying to me: ‘Lucille, that man’s way below +you!’ But if I hadn’t met Chester, he’d of got me sure.” + +“Yes, but listen,” said Myrtle Wilson, nodding her head up and down, +“at least you didn’t marry him.” + +“I know I didn’t.” + +“Well, I married him,” said Myrtle, ambiguously. “And that’s the +difference between your case and mine.” + +“Why did you, Myrtle?” demanded Catherine. “Nobody forced you to.” + +Myrtle considered. + +“I married him because I thought he was a gentleman,” she said +finally. “I thought he knew something about breeding, but he wasn’t +fit to lick my shoe.” + +“You were crazy about him for a while,” said Catherine. + +“Crazy about him!” cried Myrtle incredulously. “Who said I was crazy +about him? I never was any more crazy about him than I was about that +man there.” + +She pointed suddenly at me, and everyone looked at me accusingly. I +tried to show by my expression that I expected no affection. + +“The only crazy I was was when I married him. I knew right away I made +a mistake. He borrowed somebody’s best suit to get married in, and +never even told me about it, and the man came after it one day when he +was out: ‘Oh, is that your suit?’ I said. ‘This is the first I ever +heard about it.’ But I gave it to him and then I lay down and cried to +beat the band all afternoon.” + +“She really ought to get away from him,” resumed Catherine to me. +“They’ve been living over that garage for eleven years. And Tom’s the +first sweetie she ever had.” + +The bottle of whisky—a second one—was now in constant demand by all +present, excepting Catherine, who “felt just as good on nothing at +all.” Tom rang for the janitor and sent him for some celebrated +sandwiches, which were a complete supper in themselves. I wanted to +get out and walk eastward toward the park through the soft twilight, +but each time I tried to go I became entangled in some wild, strident +argument which pulled me back, as if with ropes, into my chair. Yet +high over the city our line of yellow windows must have contributed +their share of human secrecy to the casual watcher in the darkening +streets, and I saw him too, looking up and wondering. I was within and +without, simultaneously enchanted and repelled by the inexhaustible +variety of life. + +Myrtle pulled her chair close to mine, and suddenly her warm breath +poured over me the story of her first meeting with Tom. + +“It was on the two little seats facing each other that are always the +last ones left on the train. I was going up to New York to see my +sister and spend the night. He had on a dress suit and patent leather +shoes, and I couldn’t keep my eyes off him, but every time he looked +at me I had to pretend to be looking at the advertisement over his +head. When we came into the station he was next to me, and his white +shirtfront pressed against my arm, and so I told him I’d have to call +a policeman, but he knew I lied. I was so excited that when I got into +a taxi with him I didn’t hardly know I wasn’t getting into a subway +train. All I kept thinking about, over and over, was ‘You can’t live +forever; you can’t live forever.’ ” + +She turned to Mrs. McKee and the room rang full of her artificial +laughter. + +“My dear,” she cried, “I’m going to give you this dress as soon as I’m +through with it. I’ve got to get another one tomorrow. I’m going to +make a list of all the things I’ve got to get. A massage and a wave, +and a collar for the dog, and one of those cute little ashtrays where +you touch a spring, and a wreath with a black silk bow for mother’s +grave that’ll last all summer. I got to write down a list so I won’t +forget all the things I got to do.” + +It was nine o’clock—almost immediately afterward I looked at my watch +and found it was ten. Mr. McKee was asleep on a chair with his fists +clenched in his lap, like a photograph of a man of action. Taking out +my handkerchief I wiped from his cheek the spot of dried lather that +had worried me all the afternoon. + +The little dog was sitting on the table looking with blind eyes +through the smoke, and from time to time groaning faintly. People +disappeared, reappeared, made plans to go somewhere, and then lost +each other, searched for each other, found each other a few feet +away. Some time toward midnight Tom Buchanan and Mrs. Wilson stood +face to face discussing, in impassioned voices, whether Mrs. Wilson +had any right to mention Daisy’s name. + +“Daisy! Daisy! Daisy!” shouted Mrs. Wilson. “I’ll say it whenever I +want to! Daisy! Dai—” + +Making a short deft movement, Tom Buchanan broke her nose with his +open hand. + +Then there were bloody towels upon the bathroom floor, and women’s +voices scolding, and high over the confusion a long broken wail of +pain. Mr. McKee awoke from his doze and started in a daze toward the +door. When he had gone halfway he turned around and stared at the +scene—his wife and Catherine scolding and consoling as they stumbled +here and there among the crowded furniture with articles of aid, and +the despairing figure on the couch, bleeding fluently, and trying to +spread a copy of Town Tattle over the tapestry scenes of +Versailles. Then Mr. McKee turned and continued on out the door. +Taking my hat from the chandelier, I followed. + +“Come to lunch some day,” he suggested, as we groaned down in the +elevator. + +“Where?” + +“Anywhere.” + +“Keep your hands off the lever,” snapped the elevator boy. + +“I beg your pardon,” said Mr. McKee with dignity, “I didn’t know I was +touching it.” + +“All right,” I agreed, “I’ll be glad to.” + +… I was standing beside his bed and he was sitting up between the +sheets, clad in his underwear, with a great portfolio in his hands. + +“Beauty and the Beast … Loneliness … Old Grocery Horse … Brook’n +Bridge …” + +Then I was lying half asleep in the cold lower level of the +Pennsylvania Station, staring at the morning Tribune, and waiting for +the four o’clock train. + + + III + +There was music from my neighbour’s house through the summer nights. +In his blue gardens men and girls came and went like moths among the +whisperings and the champagne and the stars. At high tide in the +afternoon I watched his guests diving from the tower of his raft, or +taking the sun on the hot sand of his beach while his two motorboats +slit the waters of the Sound, drawing aquaplanes over cataracts of +foam. On weekends his Rolls-Royce became an omnibus, bearing parties +to and from the city between nine in the morning and long past +midnight, while his station wagon scampered like a brisk yellow bug to +meet all trains. And on Mondays eight servants, including an extra +gardener, toiled all day with mops and scrubbing-brushes and hammers +and garden-shears, repairing the ravages of the night before. + +Every Friday five crates of oranges and lemons arrived from a +fruiterer in New York—every Monday these same oranges and lemons left +his back door in a pyramid of pulpless halves. There was a machine in +the kitchen which could extract the juice of two hundred oranges in +half an hour if a little button was pressed two hundred times by a +butler’s thumb. + +At least once a fortnight a corps of caterers came down with several +hundred feet of canvas and enough coloured lights to make a Christmas +tree of Gatsby’s enormous garden. On buffet tables, garnished with +glistening hors-d’oeuvre, spiced baked hams crowded against salads of +harlequin designs and pastry pigs and turkeys bewitched to a dark +gold. In the main hall a bar with a real brass rail was set up, and +stocked with gins and liquors and with cordials so long forgotten that +most of his female guests were too young to know one from another. + +By seven o’clock the orchestra has arrived, no thin five-piece affair, +but a whole pitful of oboes and trombones and saxophones and viols and +cornets and piccolos, and low and high drums. The last swimmers have +come in from the beach now and are dressing upstairs; the cars from +New York are parked five deep in the drive, and already the halls and +salons and verandas are gaudy with primary colours, and hair bobbed in +strange new ways, and shawls beyond the dreams of Castile. The bar is +in full swing, and floating rounds of cocktails permeate the garden +outside, until the air is alive with chatter and laughter, and casual +innuendo and introductions forgotten on the spot, and enthusiastic +meetings between women who never knew each other’s names. + +The lights grow brighter as the earth lurches away from the sun, and +now the orchestra is playing yellow cocktail music, and the opera of +voices pitches a key higher. Laughter is easier minute by minute, +spilled with prodigality, tipped out at a cheerful word. The groups +change more swiftly, swell with new arrivals, dissolve and form in the +same breath; already there are wanderers, confident girls who weave +here and there among the stouter and more stable, become for a sharp, +joyous moment the centre of a group, and then, excited with triumph, +glide on through the sea-change of faces and voices and colour under +the constantly changing light. + +Suddenly one of these gypsies, in trembling opal, seizes a cocktail +out of the air, dumps it down for courage and, moving her hands like +Frisco, dances out alone on the canvas platform. A momentary hush; the +orchestra leader varies his rhythm obligingly for her, and there is a +burst of chatter as the erroneous news goes around that she is Gilda +Gray’s understudy from the Follies. The party has begun. + +I believe that on the first night I went to Gatsby’s house I was one +of the few guests who had actually been invited. People were not +invited—they went there. They got into automobiles which bore them out +to Long Island, and somehow they ended up at Gatsby’s door. Once there +they were introduced by somebody who knew Gatsby, and after that they +conducted themselves according to the rules of behaviour associated +with an amusement park. Sometimes they came and went without having +met Gatsby at all, came for the party with a simplicity of heart that +was its own ticket of admission. + +I had been actually invited. A chauffeur in a uniform of robin’s-egg +blue crossed my lawn early that Saturday morning with a surprisingly +formal note from his employer: the honour would be entirely Gatsby’s, +it said, if I would attend his “little party” that night. He had seen +me several times, and had intended to call on me long before, but a +peculiar combination of circumstances had prevented it—signed Jay +Gatsby, in a majestic hand. + +Dressed up in white flannels I went over to his lawn a little after +seven, and wandered around rather ill at ease among swirls and eddies +of people I didn’t know—though here and there was a face I had noticed +on the commuting train. I was immediately struck by the number of +young Englishmen dotted about; all well dressed, all looking a little +hungry, and all talking in low, earnest voices to solid and prosperous +Americans. I was sure that they were selling something: bonds or +insurance or automobiles. They were at least agonizingly aware of the +easy money in the vicinity and convinced that it was theirs for a few +words in the right key. + +As soon as I arrived I made an attempt to find my host, but the two or +three people of whom I asked his whereabouts stared at me in such an +amazed way, and denied so vehemently any knowledge of his movements, +that I slunk off in the direction of the cocktail table—the only place +in the garden where a single man could linger without looking +purposeless and alone. + +I was on my way to get roaring drunk from sheer embarrassment when +Jordan Baker came out of the house and stood at the head of the marble +steps, leaning a little backward and looking with contemptuous +interest down into the garden. + +Welcome or not, I found it necessary to attach myself to someone +before I should begin to address cordial remarks to the passersby. + +“Hello!” I roared, advancing toward her. My voice seemed unnaturally +loud across the garden. + +“I thought you might be here,” she responded absently as I came up. +“I remembered you lived next door to—” + +She held my hand impersonally, as a promise that she’d take care of me +in a minute, and gave ear to two girls in twin yellow dresses, who +stopped at the foot of the steps. + +“Hello!” they cried together. “Sorry you didn’t win.” + +That was for the golf tournament. She had lost in the finals the week +before. + +“You don’t know who we are,” said one of the girls in yellow, “but we +met you here about a month ago.” + +“You’ve dyed your hair since then,” remarked Jordan, and I started, +but the girls had moved casually on and her remark was addressed to +the premature moon, produced like the supper, no doubt, out of a +caterer’s basket. With Jordan’s slender golden arm resting in mine, we +descended the steps and sauntered about the garden. A tray of +cocktails floated at us through the twilight, and we sat down at a +table with the two girls in yellow and three men, each one introduced +to us as Mr. Mumble. + +“Do you come to these parties often?” inquired Jordan of the girl +beside her. + +“The last one was the one I met you at,” answered the girl, in an +alert confident voice. She turned to her companion: “Wasn’t it for +you, Lucille?” + +It was for Lucille, too. + +“I like to come,” Lucille said. “I never care what I do, so I always +have a good time. When I was here last I tore my gown on a chair, and +he asked me my name and address—inside of a week I got a package from +Croirier’s with a new evening gown in it.” + +“Did you keep it?” asked Jordan. + +“Sure I did. I was going to wear it tonight, but it was too big in the +bust and had to be altered. It was gas blue with lavender beads. Two +hundred and sixty-five dollars.” + +“There’s something funny about a fellow that’ll do a thing like that,” +said the other girl eagerly. “He doesn’t want any trouble with +anybody.” + +“Who doesn’t?” I inquired. + +“Gatsby. Somebody told me—” + +The two girls and Jordan leaned together confidentially. + +“Somebody told me they thought he killed a man once.” + +A thrill passed over all of us. The three Mr. Mumbles bent forward and +listened eagerly. + +“I don’t think it’s so much that,” argued Lucille sceptically; “It’s +more that he was a German spy during the war.” + +One of the men nodded in confirmation. + +“I heard that from a man who knew all about him, grew up with him in +Germany,” he assured us positively. + +“Oh, no,” said the first girl, “it couldn’t be that, because he was in +the American army during the war.” As our credulity switched back to +her she leaned forward with enthusiasm. “You look at him sometimes +when he thinks nobody’s looking at him. I’ll bet he killed a man.” + +She narrowed her eyes and shivered. Lucille shivered. We all turned +and looked around for Gatsby. It was testimony to the romantic +speculation he inspired that there were whispers about him from those +who had found little that it was necessary to whisper about in this +world. + +The first supper—there would be another one after midnight—was now +being served, and Jordan invited me to join her own party, who were +spread around a table on the other side of the garden. There were +three married couples and Jordan’s escort, a persistent undergraduate +given to violent innuendo, and obviously under the impression that +sooner or later Jordan was going to yield him up her person to a +greater or lesser degree. Instead of rambling, this party had +preserved a dignified homogeneity, and assumed to itself the function +of representing the staid nobility of the countryside—East Egg +condescending to West Egg and carefully on guard against its +spectroscopic gaiety. + +“Let’s get out,” whispered Jordan, after a somehow wasteful and +inappropriate half-hour; “this is much too polite for me.” + +We got up, and she explained that we were going to find the host: I +had never met him, she said, and it was making me uneasy. The +undergraduate nodded in a cynical, melancholy way. + +The bar, where we glanced first, was crowded, but Gatsby was not +there. She couldn’t find him from the top of the steps, and he wasn’t +on the veranda. On a chance we tried an important-looking door, and +walked into a high Gothic library, panelled with carved English oak, +and probably transported complete from some ruin overseas. + +A stout, middle-aged man, with enormous owl-eyed spectacles, was +sitting somewhat drunk on the edge of a great table, staring with +unsteady concentration at the shelves of books. As we entered he +wheeled excitedly around and examined Jordan from head to foot. + +“What do you think?” he demanded impetuously. + +“About what?” + +He waved his hand toward the bookshelves. + +“About that. As a matter of fact you needn’t bother to ascertain. I +ascertained. They’re real.” + +“The books?” + +He nodded. + +“Absolutely real—have pages and everything. I thought they’d be a nice +durable cardboard. Matter of fact, they’re absolutely real. Pages +and—Here! Lemme show you.” + +Taking our scepticism for granted, he rushed to the bookcases and +returned with Volume One of the Stoddard Lectures. + +“See!” he cried triumphantly. “It’s a bona-fide piece of printed +matter. It fooled me. This fella’s a regular Belasco. It’s a +triumph. What thoroughness! What realism! Knew when to stop, +too—didn’t cut the pages. But what do you want? What do you expect?” + +He snatched the book from me and replaced it hastily on its shelf, +muttering that if one brick was removed the whole library was liable +to collapse. + +“Who brought you?” he demanded. “Or did you just come? I was brought. +Most people were brought.” + +Jordan looked at him alertly, cheerfully, without answering. + +“I was brought by a woman named Roosevelt,” he continued. “Mrs. Claud +Roosevelt. Do you know her? I met her somewhere last night. I’ve been +drunk for about a week now, and I thought it might sober me up to sit +in a library.” + +“Has it?” + +“A little bit, I think. I can’t tell yet. I’ve only been here an hour. +Did I tell you about the books? They’re real. They’re—” + +“You told us.” + +We shook hands with him gravely and went back outdoors. + +There was dancing now on the canvas in the garden; old men pushing +young girls backward in eternal graceless circles, superior couples +holding each other tortuously, fashionably, and keeping in the +corners—and a great number of single girls dancing individually or +relieving the orchestra for a moment of the burden of the banjo or the +traps. By midnight the hilarity had increased. A celebrated tenor had +sung in Italian, and a notorious contralto had sung in jazz, and +between the numbers people were doing “stunts” all over the garden, +while happy, vacuous bursts of laughter rose toward the summer sky. A +pair of stage twins, who turned out to be the girls in yellow, did a +baby act in costume, and champagne was served in glasses bigger than +finger-bowls. The moon had risen higher, and floating in the Sound was +a triangle of silver scales, trembling a little to the stiff, tinny +drip of the banjoes on the lawn. + +I was still with Jordan Baker. We were sitting at a table with a man +of about my age and a rowdy little girl, who gave way upon the +slightest provocation to uncontrollable laughter. I was enjoying +myself now. I had taken two finger-bowls of champagne, and the scene +had changed before my eyes into something significant, elemental, and +profound. + +At a lull in the entertainment the man looked at me and smiled. + +“Your face is familiar,” he said politely. “Weren’t you in the First +Division during the war?” + +“Why yes. I was in the Twenty-eighth Infantry.” + +“I was in the Sixteenth until June nineteen-eighteen. I knew I’d seen +you somewhere before.” + +We talked for a moment about some wet, grey little villages in France. +Evidently he lived in this vicinity, for he told me that he had just +bought a hydroplane, and was going to try it out in the morning. + +“Want to go with me, old sport? Just near the shore along the Sound.” + +“What time?” + +“Any time that suits you best.” + +It was on the tip of my tongue to ask his name when Jordan looked +around and smiled. + +“Having a gay time now?” she inquired. + +“Much better.” I turned again to my new acquaintance. “This is an +unusual party for me. I haven’t even seen the host. I live over +there—” I waved my hand at the invisible hedge in the distance, “and +this man Gatsby sent over his chauffeur with an invitation.” + +For a moment he looked at me as if he failed to understand. + +“I’m Gatsby,” he said suddenly. + +“What!” I exclaimed. “Oh, I beg your pardon.” + +“I thought you knew, old sport. I’m afraid I’m not a very good host.” + +He smiled understandingly—much more than understandingly. It was one +of those rare smiles with a quality of eternal reassurance in it, that +you may come across four or five times in life. It faced—or seemed to +face—the whole eternal world for an instant, and then concentrated on +you with an irresistible prejudice in your favour. It understood you +just so far as you wanted to be understood, believed in you as you +would like to believe in yourself, and assured you that it had +precisely the impression of you that, at your best, you hoped to +convey. Precisely at that point it vanished—and I was looking at an +elegant young roughneck, a year or two over thirty, whose elaborate +formality of speech just missed being absurd. Some time before he +introduced himself I’d got a strong impression that he was picking his +words with care. + +Almost at the moment when Mr. Gatsby identified himself a butler +hurried toward him with the information that Chicago was calling him +on the wire. He excused himself with a small bow that included each of +us in turn. + +“If you want anything just ask for it, old sport,” he urged me. +“Excuse me. I will rejoin you later.” + +When he was gone I turned immediately to Jordan—constrained to assure +her of my surprise. I had expected that Mr. Gatsby would be a florid +and corpulent person in his middle years. + +“Who is he?” I demanded. “Do you know?” + +“He’s just a man named Gatsby.” + +“Where is he from, I mean? And what does he do?” + +“Now you’re started on the subject,” she answered with a wan smile. +“Well, he told me once he was an Oxford man.” + +A dim background started to take shape behind him, but at her next +remark it faded away. + +“However, I don’t believe it.” + +“Why not?” + +“I don’t know,” she insisted, “I just don’t think he went there.” + +Something in her tone reminded me of the other girl’s “I think he +killed a man,” and had the effect of stimulating my curiosity. I would +have accepted without question the information that Gatsby sprang from +the swamps of Louisiana or from the lower East Side of New York. That +was comprehensible. But young men didn’t—at least in my provincial +inexperience I believed they didn’t—drift coolly out of nowhere and +buy a palace on Long Island Sound. + +“Anyhow, he gives large parties,” said Jordan, changing the subject +with an urban distaste for the concrete. “And I like large parties. +They’re so intimate. At small parties there isn’t any privacy.” + +There was the boom of a bass drum, and the voice of the orchestra +leader rang out suddenly above the echolalia of the garden. + +“Ladies and gentlemen,” he cried. “At the request of Mr. Gatsby we are +going to play for you Mr. Vladmir Tostoff’s latest work, which +attracted so much attention at Carnegie Hall last May. If you read the +papers you know there was a big sensation.” He smiled with jovial +condescension, and added: “Some sensation!” Whereupon everybody +laughed. + +“The piece is known,” he concluded lustily, “as ‘Vladmir Tostoff’s +Jazz History of the World!’ ” + +The nature of Mr. Tostoff’s composition eluded me, because just as it +began my eyes fell on Gatsby, standing alone on the marble steps and +looking from one group to another with approving eyes. His tanned skin +was drawn attractively tight on his face and his short hair looked as +though it were trimmed every day. I could see nothing sinister about +him. I wondered if the fact that he was not drinking helped to set him +off from his guests, for it seemed to me that he grew more correct as +the fraternal hilarity increased. When the “Jazz History of the World” +was over, girls were putting their heads on men’s shoulders in a +puppyish, convivial way, girls were swooning backward playfully into +men’s arms, even into groups, knowing that someone would arrest their +falls—but no one swooned backward on Gatsby, and no French bob touched +Gatsby’s shoulder, and no singing quartets were formed with Gatsby’s +head for one link. + +“I beg your pardon.” + +Gatsby’s butler was suddenly standing beside us. + +“Miss Baker?” he inquired. “I beg your pardon, but Mr. Gatsby would +like to speak to you alone.” + +“With me?” she exclaimed in surprise. + +“Yes, madame.” + +She got up slowly, raising her eyebrows at me in astonishment, and +followed the butler toward the house. I noticed that she wore her +evening-dress, all her dresses, like sports clothes—there was a +jauntiness about her movements as if she had first learned to walk +upon golf courses on clean, crisp mornings. + +I was alone and it was almost two. For some time confused and +intriguing sounds had issued from a long, many-windowed room which +overhung the terrace. Eluding Jordan’s undergraduate, who was now +engaged in an obstetrical conversation with two chorus girls, and who +implored me to join him, I went inside. + +The large room was full of people. One of the girls in yellow was +playing the piano, and beside her stood a tall, red-haired young lady +from a famous chorus, engaged in song. She had drunk a quantity of +champagne, and during the course of her song she had decided, ineptly, +that everything was very, very sad—she was not only singing, she was +weeping too. Whenever there was a pause in the song she filled it with +gasping, broken sobs, and then took up the lyric again in a quavering +soprano. The tears coursed down her cheeks—not freely, however, for +when they came into contact with her heavily beaded eyelashes they +assumed an inky colour, and pursued the rest of their way in slow +black rivulets. A humorous suggestion was made that she sing the notes +on her face, whereupon she threw up her hands, sank into a chair, and +went off into a deep vinous sleep. + +“She had a fight with a man who says he’s her husband,” explained a +girl at my elbow. + +I looked around. Most of the remaining women were now having fights +with men said to be their husbands. Even Jordan’s party, the quartet +from East Egg, were rent asunder by dissension. One of the men was +talking with curious intensity to a young actress, and his wife, after +attempting to laugh at the situation in a dignified and indifferent +way, broke down entirely and resorted to flank attacks—at intervals +she appeared suddenly at his side like an angry diamond, and hissed: +“You promised!” into his ear. + +The reluctance to go home was not confined to wayward men. The hall +was at present occupied by two deplorably sober men and their highly +indignant wives. The wives were sympathizing with each other in +slightly raised voices. + +“Whenever he sees I’m having a good time he wants to go home.” + +“Never heard anything so selfish in my life.” + +“We’re always the first ones to leave.” + +“So are we.” + +“Well, we’re almost the last tonight,” said one of the men sheepishly. +“The orchestra left half an hour ago.” + +In spite of the wives’ agreement that such malevolence was beyond +credibility, the dispute ended in a short struggle, and both wives +were lifted, kicking, into the night. + +As I waited for my hat in the hall the door of the library opened and +Jordan Baker and Gatsby came out together. He was saying some last +word to her, but the eagerness in his manner tightened abruptly into +formality as several people approached him to say goodbye. + +Jordan’s party were calling impatiently to her from the porch, but she +lingered for a moment to shake hands. + +“I’ve just heard the most amazing thing,” she whispered. “How long +were we in there?” + +“Why, about an hour.” + +“It was … simply amazing,” she repeated abstractedly. “But I swore I +wouldn’t tell it and here I am tantalizing you.” She yawned gracefully +in my face. “Please come and see me … Phone book … Under the name of +Mrs. Sigourney Howard … My aunt …” She was hurrying off as she +talked—her brown hand waved a jaunty salute as she melted into her +party at the door. + +Rather ashamed that on my first appearance I had stayed so late, I +joined the last of Gatsby’s guests, who were clustered around him. I +wanted to explain that I’d hunted for him early in the evening and to +apologize for not having known him in the garden. + +“Don’t mention it,” he enjoined me eagerly. “Don’t give it another +thought, old sport.” The familiar expression held no more familiarity +than the hand which reassuringly brushed my shoulder. “And don’t +forget we’re going up in the hydroplane tomorrow morning, at nine +o’clock.” + +Then the butler, behind his shoulder: + +“Philadelphia wants you on the phone, sir.” + +“All right, in a minute. Tell them I’ll be right there … Good night.” + +“Good night.” + +“Good night.” He smiled—and suddenly there seemed to be a pleasant +significance in having been among the last to go, as if he had desired +it all the time. “Good night, old sport … Good night.” + +But as I walked down the steps I saw that the evening was not quite +over. Fifty feet from the door a dozen headlights illuminated a +bizarre and tumultuous scene. In the ditch beside the road, right side +up, but violently shorn of one wheel, rested a new coupé which had +left Gatsby’s drive not two minutes before. The sharp jut of a wall +accounted for the detachment of the wheel, which was now getting +considerable attention from half a dozen curious chauffeurs. However, +as they had left their cars blocking the road, a harsh, discordant din +from those in the rear had been audible for some time, and added to +the already violent confusion of the scene. + +A man in a long duster had dismounted from the wreck and now stood in +the middle of the road, looking from the car to the tyre and from the +tyre to the observers in a pleasant, puzzled way. + +“See!” he explained. “It went in the ditch.” + +The fact was infinitely astonishing to him, and I recognized first the +unusual quality of wonder, and then the man—it was the late patron of +Gatsby’s library. + +“How’d it happen?” + +He shrugged his shoulders. + +“I know nothing whatever about mechanics,” he said decisively. + +“But how did it happen? Did you run into the wall?” + +“Don’t ask me,” said Owl Eyes, washing his hands of the whole +matter. “I know very little about driving—next to nothing. It +happened, and that’s all I know.” + +“Well, if you’re a poor driver you oughtn’t to try driving at night.” + +“But I wasn’t even trying,” he explained indignantly, “I wasn’t even +trying.” + +An awed hush fell upon the bystanders. + +“Do you want to commit suicide?” + +“You’re lucky it was just a wheel! A bad driver and not even trying!” + +“You don’t understand,” explained the criminal. “I wasn’t driving. +There’s another man in the car.” + +The shock that followed this declaration found voice in a sustained +“Ah-h-h!” as the door of the coupé swung slowly open. The crowd—it was +now a crowd—stepped back involuntarily, and when the door had opened +wide there was a ghostly pause. Then, very gradually, part by part, a +pale, dangling individual stepped out of the wreck, pawing tentatively +at the ground with a large uncertain dancing shoe. + +Blinded by the glare of the headlights and confused by the incessant +groaning of the horns, the apparition stood swaying for a moment +before he perceived the man in the duster. + +“Wha’s matter?” he inquired calmly. “Did we run outa gas?” + +“Look!” + +Half a dozen fingers pointed at the amputated wheel—he stared at it +for a moment, and then looked upward as though he suspected that it +had dropped from the sky. + +“It came off,” someone explained. + +He nodded. + +“At first I din’ notice we’d stopped.” + +A pause. Then, taking a long breath and straightening his shoulders, +he remarked in a determined voice: + +“Wonder’ff tell me where there’s a gas’line station?” + +At least a dozen men, some of them a little better off than he was, +explained to him that wheel and car were no longer joined by any +physical bond. + +“Back out,” he suggested after a moment. “Put her in reverse.” + +“But the wheel’s off!” + +He hesitated. + +“No harm in trying,” he said. + +The caterwauling horns had reached a crescendo and I turned away and +cut across the lawn toward home. I glanced back once. A wafer of a +moon was shining over Gatsby’s house, making the night fine as before, +and surviving the laughter and the sound of his still glowing garden. +A sudden emptiness seemed to flow now from the windows and the great +doors, endowing with complete isolation the figure of the host, who +stood on the porch, his hand up in a formal gesture of farewell. + +------------------------------------------------------------------------ + +Reading over what I have written so far, I see I have given the +impression that the events of three nights several weeks apart were +all that absorbed me. On the contrary, they were merely casual events +in a crowded summer, and, until much later, they absorbed me +infinitely less than my personal affairs. + +Most of the time I worked. In the early morning the sun threw my +shadow westward as I hurried down the white chasms of lower New York +to the Probity Trust. I knew the other clerks and young bond-salesmen +by their first names, and lunched with them in dark, crowded +restaurants on little pig sausages and mashed potatoes and coffee. I +even had a short affair with a girl who lived in Jersey City and +worked in the accounting department, but her brother began throwing +mean looks in my direction, so when she went on her vacation in July I +let it blow quietly away. + +I took dinner usually at the Yale Club—for some reason it was the +gloomiest event of my day—and then I went upstairs to the library and +studied investments and securities for a conscientious hour. There +were generally a few rioters around, but they never came into the +library, so it was a good place to work. After that, if the night was +mellow, I strolled down Madison Avenue past the old Murray Hill Hotel, +and over 33rd Street to the Pennsylvania Station. + +I began to like New York, the racy, adventurous feel of it at night, +and the satisfaction that the constant flicker of men and women and +machines gives to the restless eye. I liked to walk up Fifth Avenue +and pick out romantic women from the crowd and imagine that in a few +minutes I was going to enter into their lives, and no one would ever +know or disapprove. Sometimes, in my mind, I followed them to their +apartments on the corners of hidden streets, and they turned and +smiled back at me before they faded through a door into warm +darkness. At the enchanted metropolitan twilight I felt a haunting +loneliness sometimes, and felt it in others—poor young clerks who +loitered in front of windows waiting until it was time for a solitary +restaurant dinner—young clerks in the dusk, wasting the most poignant +moments of night and life. + +Again at eight o’clock, when the dark lanes of the Forties were lined +five deep with throbbing taxicabs, bound for the theatre district, I +felt a sinking in my heart. Forms leaned together in the taxis as they +waited, and voices sang, and there was laughter from unheard jokes, +and lighted cigarettes made unintelligible circles inside. Imagining +that I, too, was hurrying towards gaiety and sharing their intimate +excitement, I wished them well. + +For a while I lost sight of Jordan Baker, and then in midsummer I +found her again. At first I was flattered to go places with her, +because she was a golf champion, and everyone knew her name. Then it +was something more. I wasn’t actually in love, but I felt a sort of +tender curiosity. The bored haughty face that she turned to the world +concealed something—most affectations conceal something eventually, +even though they don’t in the beginning—and one day I found what it +was. When we were on a house-party together up in Warwick, she left a +borrowed car out in the rain with the top down, and then lied about +it—and suddenly I remembered the story about her that had eluded me +that night at Daisy’s. At her first big golf tournament there was a +row that nearly reached the newspapers—a suggestion that she had moved +her ball from a bad lie in the semifinal round. The thing approached +the proportions of a scandal—then died away. A caddy retracted his +statement, and the only other witness admitted that he might have been +mistaken. The incident and the name had remained together in my mind. + +Jordan Baker instinctively avoided clever, shrewd men, and now I saw +that this was because she felt safer on a plane where any divergence +from a code would be thought impossible. She was incurably dishonest. +She wasn’t able to endure being at a disadvantage and, given this +unwillingness, I suppose she had begun dealing in subterfuges when she +was very young in order to keep that cool, insolent smile turned to +the world and yet satisfy the demands of her hard, jaunty body. + +It made no difference to me. Dishonesty in a woman is a thing you +never blame deeply—I was casually sorry, and then I forgot. It was on +that same house-party that we had a curious conversation about driving +a car. It started because she passed so close to some workmen that our +fender flicked a button on one man’s coat. + +“You’re a rotten driver,” I protested. “Either you ought to be more +careful, or you oughtn’t to drive at all.” + +“I am careful.” + +“No, you’re not.” + +“Well, other people are,” she said lightly. + +“What’s that got to do with it?” + +“They’ll keep out of my way,” she insisted. “It takes two to make an +accident.” + +“Suppose you met somebody just as careless as yourself.” + +“I hope I never will,” she answered. “I hate careless people. That’s +why I like you.” + +Her grey, sun-strained eyes stared straight ahead, but she had +deliberately shifted our relations, and for a moment I thought I loved +her. But I am slow-thinking and full of interior rules that act as +brakes on my desires, and I knew that first I had to get myself +definitely out of that tangle back home. I’d been writing letters once +a week and signing them: “Love, Nick,” and all I could think of was +how, when that certain girl played tennis, a faint moustache of +perspiration appeared on her upper lip. Nevertheless there was a vague +understanding that had to be tactfully broken off before I was free. + +Everyone suspects himself of at least one of the cardinal virtues, and +this is mine: I am one of the few honest people that I have ever +known. + + + IV + +On Sunday morning while church bells rang in the villages alongshore, +the world and its mistress returned to Gatsby’s house and twinkled +hilariously on his lawn. + +“He’s a bootlegger,” said the young ladies, moving somewhere between +his cocktails and his flowers. “One time he killed a man who had found +out that he was nephew to Von Hindenburg and second cousin to the +devil. Reach me a rose, honey, and pour me a last drop into that there +crystal glass.” + +Once I wrote down on the empty spaces of a timetable the names of +those who came to Gatsby’s house that summer. It is an old timetable +now, disintegrating at its folds, and headed “This schedule in effect +July 5th, 1922.” But I can still read the grey names, and they will +give you a better impression than my generalities of those who +accepted Gatsby’s hospitality and paid him the subtle tribute of +knowing nothing whatever about him. + +From East Egg, then, came the Chester Beckers and the Leeches, and a +man named Bunsen, whom I knew at Yale, and Doctor Webster Civet, who +was drowned last summer up in Maine. And the Hornbeams and the Willie +Voltaires, and a whole clan named Blackbuck, who always gathered in a +corner and flipped up their noses like goats at whosoever came +near. And the Ismays and the Chrysties (or rather Hubert Auerbach and +Mr. Chrystie’s wife), and Edgar Beaver, whose hair, they say, turned +cotton-white one winter afternoon for no good reason at all. + +Clarence Endive was from East Egg, as I remember. He came only once, +in white knickerbockers, and had a fight with a bum named Etty in the +garden. From farther out on the Island came the Cheadles and the O. +R. P. Schraeders, and the Stonewall Jackson Abrams of Georgia, and the +Fishguards and the Ripley Snells. Snell was there three days before he +went to the penitentiary, so drunk out on the gravel drive that +Mrs. Ulysses Swett’s automobile ran over his right hand. The Dancies +came, too, and S. B. Whitebait, who was well over sixty, and Maurice +A. Flink, and the Hammerheads, and Beluga the tobacco importer, and +Beluga’s girls. + +From West Egg came the Poles and the Mulreadys and Cecil Roebuck and +Cecil Schoen and Gulick the State senator and Newton Orchid, who +controlled Films Par Excellence, and Eckhaust and Clyde Cohen and Don +S. Schwartz (the son) and Arthur McCarty, all connected with the +movies in one way or another. And the Catlips and the Bembergs and G. +Earl Muldoon, brother to that Muldoon who afterward strangled his +wife. Da Fontano the promoter came there, and Ed Legros and James B. +(“Rot-Gut”) Ferret and the De Jongs and Ernest Lilly—they came to +gamble, and when Ferret wandered into the garden it meant he was +cleaned out and Associated Traction would have to fluctuate profitably +next day. + +A man named Klipspringer was there so often that he became known as +“the boarder”—I doubt if he had any other home. Of theatrical people +there were Gus Waize and Horace O’Donavan and Lester Myer and George +Duckweed and Francis Bull. Also from New York were the Chromes and the +Backhyssons and the Dennickers and Russel Betty and the Corrigans and +the Kellehers and the Dewars and the Scullys and S. W. Belcher and the +Smirkes and the young Quinns, divorced now, and Henry L. Palmetto, who +killed himself by jumping in front of a subway train in Times Square. + +Benny McClenahan arrived always with four girls. They were never quite +the same ones in physical person, but they were so identical one with +another that it inevitably seemed they had been there before. I have +forgotten their names—Jaqueline, I think, or else Consuela, or Gloria +or Judy or June, and their last names were either the melodious names +of flowers and months or the sterner ones of the great American +capitalists whose cousins, if pressed, they would confess themselves +to be. + +In addition to all these I can remember that Faustina O’Brien came +there at least once and the Baedeker girls and young Brewer, who had +his nose shot off in the war, and Mr. Albrucksburger and Miss Haag, +his fiancée, and Ardita Fitz-Peters and Mr. P. Jewett, once head of +the American Legion, and Miss Claudia Hip, with a man reputed to be +her chauffeur, and a prince of something, whom we called Duke, and +whose name, if I ever knew it, I have forgotten. + +All these people came to Gatsby’s house in the summer. + +------------------------------------------------------------------------ + +At nine o’clock, one morning late in July, Gatsby’s gorgeous car +lurched up the rocky drive to my door and gave out a burst of melody +from its three-noted horn. + +It was the first time he had called on me, though I had gone to two of +his parties, mounted in his hydroplane, and, at his urgent invitation, +made frequent use of his beach. + +“Good morning, old sport. You’re having lunch with me today and I +thought we’d ride up together.” + +He was balancing himself on the dashboard of his car with that +resourcefulness of movement that is so peculiarly American—that comes, +I suppose, with the absence of lifting work in youth and, even more, +with the formless grace of our nervous, sporadic games. This quality +was continually breaking through his punctilious manner in the shape +of restlessness. He was never quite still; there was always a tapping +foot somewhere or the impatient opening and closing of a hand. + +He saw me looking with admiration at his car. + +“It’s pretty, isn’t it, old sport?” He jumped off to give me a better +view. “Haven’t you ever seen it before?” + +I’d seen it. Everybody had seen it. It was a rich cream colour, bright +with nickel, swollen here and there in its monstrous length with +triumphant hatboxes and supper-boxes and toolboxes, and terraced with +a labyrinth of windshields that mirrored a dozen suns. Sitting down +behind many layers of glass in a sort of green leather conservatory, +we started to town. + +I had talked with him perhaps half a dozen times in the past month and +found, to my disappointment, that he had little to say. So my first +impression, that he was a person of some undefined consequence, had +gradually faded and he had become simply the proprietor of an +elaborate roadhouse next door. + +And then came that disconcerting ride. We hadn’t reached West Egg +village before Gatsby began leaving his elegant sentences unfinished +and slapping himself indecisively on the knee of his caramel-coloured +suit. + +“Look here, old sport,” he broke out surprisingly, “what’s your +opinion of me, anyhow?” + +A little overwhelmed, I began the generalized evasions which that +question deserves. + +“Well, I’m going to tell you something about my life,” he interrupted. +“I don’t want you to get a wrong idea of me from all these stories you +hear.” + +So he was aware of the bizarre accusations that flavoured conversation +in his halls. + +“I’ll tell you God’s truth.” His right hand suddenly ordered divine +retribution to stand by. “I am the son of some wealthy people in the +Middle West—all dead now. I was brought up in America but educated at +Oxford, because all my ancestors have been educated there for many +years. It is a family tradition.” + +He looked at me sideways—and I knew why Jordan Baker had believed he +was lying. He hurried the phrase “educated at Oxford,” or swallowed +it, or choked on it, as though it had bothered him before. And with +this doubt, his whole statement fell to pieces, and I wondered if +there wasn’t something a little sinister about him, after all. + +“What part of the Middle West?” I inquired casually. + +“San Francisco.” + +“I see.” + +“My family all died and I came into a good deal of money.” + +His voice was solemn, as if the memory of that sudden extinction of a +clan still haunted him. For a moment I suspected that he was pulling +my leg, but a glance at him convinced me otherwise. + +“After that I lived like a young rajah in all the capitals of +Europe—Paris, Venice, Rome—collecting jewels, chiefly rubies, hunting +big game, painting a little, things for myself only, and trying to +forget something very sad that had happened to me long ago.” + +With an effort I managed to restrain my incredulous laughter. The very +phrases were worn so threadbare that they evoked no image except that +of a turbaned “character” leaking sawdust at every pore as he pursued +a tiger through the Bois de Boulogne. + +“Then came the war, old sport. It was a great relief, and I tried very +hard to die, but I seemed to bear an enchanted life. I accepted a +commission as first lieutenant when it began. In the Argonne Forest I +took the remains of my machine-gun battalion so far forward that there +was a half mile gap on either side of us where the infantry couldn’t +advance. We stayed there two days and two nights, a hundred and thirty +men with sixteen Lewis guns, and when the infantry came up at last +they found the insignia of three German divisions among the piles of +dead. I was promoted to be a major, and every Allied government gave +me a decoration—even Montenegro, little Montenegro down on the +Adriatic Sea!” + +Little Montenegro! He lifted up the words and nodded at them—with his +smile. The smile comprehended Montenegro’s troubled history and +sympathized with the brave struggles of the Montenegrin people. It +appreciated fully the chain of national circumstances which had +elicited this tribute from Montenegro’s warm little heart. My +incredulity was submerged in fascination now; it was like skimming +hastily through a dozen magazines. + +He reached in his pocket, and a piece of metal, slung on a ribbon, +fell into my palm. + +“That’s the one from Montenegro.” + +To my astonishment, the thing had an authentic look. “Orderi di +Danilo,” ran the circular legend, “Montenegro, Nicolas Rex.” + +“Turn it.” + +“Major Jay Gatsby,” I read, “For Valour Extraordinary.” + +“Here’s another thing I always carry. A souvenir of Oxford days. It +was taken in Trinity Quad—the man on my left is now the Earl of +Doncaster.” + +It was a photograph of half a dozen young men in blazers loafing in an +archway through which were visible a host of spires. There was Gatsby, +looking a little, not much, younger—with a cricket bat in his hand. + +Then it was all true. I saw the skins of tigers flaming in his palace +on the Grand Canal; I saw him opening a chest of rubies to ease, with +their crimson-lighted depths, the gnawings of his broken heart. + +“I’m going to make a big request of you today,” he said, pocketing his +souvenirs with satisfaction, “so I thought you ought to know something +about me. I didn’t want you to think I was just some nobody. You see, +I usually find myself among strangers because I drift here and there +trying to forget the sad things that happened to me.” He hesitated. +“You’ll hear about it this afternoon.” + +“At lunch?” + +“No, this afternoon. I happened to find out that you’re taking Miss +Baker to tea.” + +“Do you mean you’re in love with Miss Baker?” + +“No, old sport, I’m not. But Miss Baker has kindly consented to speak +to you about this matter.” + +I hadn’t the faintest idea what “this matter” was, but I was more +annoyed than interested. I hadn’t asked Jordan to tea in order to +discuss Mr. Jay Gatsby. I was sure the request would be something +utterly fantastic, and for a moment I was sorry I’d ever set foot upon +his overpopulated lawn. + +He wouldn’t say another word. His correctness grew on him as we neared +the city. We passed Port Roosevelt, where there was a glimpse of +red-belted oceangoing ships, and sped along a cobbled slum lined with +the dark, undeserted saloons of the faded-gilt nineteen-hundreds. +Then the valley of ashes opened out on both sides of us, and I had a +glimpse of Mrs. Wilson straining at the garage pump with panting +vitality as we went by. + +With fenders spread like wings we scattered light through half +Astoria—only half, for as we twisted among the pillars of the elevated +I heard the familiar “jug-jug-spat!” of a motorcycle, and a frantic +policeman rode alongside. + +“All right, old sport,” called Gatsby. We slowed down. Taking a white +card from his wallet, he waved it before the man’s eyes. + +“Right you are,” agreed the policeman, tipping his cap. “Know you next +time, Mr. Gatsby. Excuse me!” + +“What was that?” I inquired. “The picture of Oxford?” + +“I was able to do the commissioner a favour once, and he sends me a +Christmas card every year.” + +Over the great bridge, with the sunlight through the girders making a +constant flicker upon the moving cars, with the city rising up across +the river in white heaps and sugar lumps all built with a wish out of +nonolfactory money. The city seen from the Queensboro Bridge is always +the city seen for the first time, in its first wild promise of all the +mystery and the beauty in the world. + +A dead man passed us in a hearse heaped with blooms, followed by two +carriages with drawn blinds, and by more cheerful carriages for +friends. The friends looked out at us with the tragic eyes and short +upper lips of southeastern Europe, and I was glad that the sight of +Gatsby’s splendid car was included in their sombre holiday. As we +crossed Blackwell’s Island a limousine passed us, driven by a white +chauffeur, in which sat three modish negroes, two bucks and a girl. I +laughed aloud as the yolks of their eyeballs rolled toward us in +haughty rivalry. + +“Anything can happen now that we’ve slid over this bridge,” I thought; +“anything at all …” + +Even Gatsby could happen, without any particular wonder. + +------------------------------------------------------------------------ + +Roaring noon. In a well-fanned Forty-second Street cellar I met Gatsby +for lunch. Blinking away the brightness of the street outside, my eyes +picked him out obscurely in the anteroom, talking to another man. + +“Mr. Carraway, this is my friend Mr. Wolfshiem.” + +A small, flat-nosed Jew raised his large head and regarded me with two +fine growths of hair which luxuriated in either nostril. After a +moment I discovered his tiny eyes in the half-darkness. + +“—So I took one look at him,” said Mr. Wolfshiem, shaking my hand +earnestly, “and what do you think I did?” + +“What?” I inquired politely. + +But evidently he was not addressing me, for he dropped my hand and +covered Gatsby with his expressive nose. + +“I handed the money to Katspaugh and I said: ‘All right, Katspaugh, +don’t pay him a penny till he shuts his mouth.’ He shut it then and +there.” + +Gatsby took an arm of each of us and moved forward into the +restaurant, whereupon Mr. Wolfshiem swallowed a new sentence he was +starting and lapsed into a somnambulatory abstraction. + +“Highballs?” asked the head waiter. + +“This is a nice restaurant here,” said Mr. Wolfshiem, looking at the +presbyterian nymphs on the ceiling. “But I like across the street +better!” + +“Yes, highballs,” agreed Gatsby, and then to Mr. Wolfshiem: “It’s too +hot over there.” + +“Hot and small—yes,” said Mr. Wolfshiem, “but full of memories.” + +“What place is that?” I asked. + +“The old Metropole.” + +“The old Metropole,” brooded Mr. Wolfshiem gloomily. “Filled with +faces dead and gone. Filled with friends gone now forever. I can’t +forget so long as I live the night they shot Rosy Rosenthal there. It +was six of us at the table, and Rosy had eat and drunk a lot all +evening. When it was almost morning the waiter came up to him with a +funny look and says somebody wants to speak to him outside. ‘All +right,’ says Rosy, and begins to get up, and I pulled him down in his +chair. + +“ ‘Let the bastards come in here if they want you, Rosy, but don’t +you, so help me, move outside this room.’ + +“It was four o’clock in the morning then, and if we’d of raised the +blinds we’d of seen daylight.” + +“Did he go?” I asked innocently. + +“Sure he went.” Mr. Wolfshiem’s nose flashed at me indignantly. “He +turned around in the door and says: ‘Don’t let that waiter take away +my coffee!’ Then he went out on the sidewalk, and they shot him three +times in his full belly and drove away.” + +“Four of them were electrocuted,” I said, remembering. + +“Five, with Becker.” His nostrils turned to me in an interested way. +“I understand you’re looking for a business gonnegtion.” + +The juxtaposition of these two remarks was startling. Gatsby answered +for me: + +“Oh, no,” he exclaimed, “this isn’t the man.” + +“No?” Mr. Wolfshiem seemed disappointed. + +“This is just a friend. I told you we’d talk about that some other +time.” + +“I beg your pardon,” said Mr. Wolfshiem, “I had a wrong man.” + +A succulent hash arrived, and Mr. Wolfshiem, forgetting the more +sentimental atmosphere of the old Metropole, began to eat with +ferocious delicacy. His eyes, meanwhile, roved very slowly all around +the room—he completed the arc by turning to inspect the people +directly behind. I think that, except for my presence, he would have +taken one short glance beneath our own table. + +“Look here, old sport,” said Gatsby, leaning toward me, “I’m afraid I +made you a little angry this morning in the car.” + +There was the smile again, but this time I held out against it. + +“I don’t like mysteries,” I answered, “and I don’t understand why you +won’t come out frankly and tell me what you want. Why has it all got +to come through Miss Baker?” + +“Oh, it’s nothing underhand,” he assured me. “Miss Baker’s a great +sportswoman, you know, and she’d never do anything that wasn’t all +right.” + +Suddenly he looked at his watch, jumped up, and hurried from the room, +leaving me with Mr. Wolfshiem at the table. + +“He has to telephone,” said Mr. Wolfshiem, following him with his +eyes. “Fine fellow, isn’t he? Handsome to look at and a perfect +gentleman.” + +“Yes.” + +“He’s an Oggsford man.” + +“Oh!” + +“He went to Oggsford College in England. You know Oggsford College?” + +“I’ve heard of it.” + +“It’s one of the most famous colleges in the world.” + +“Have you known Gatsby for a long time?” I inquired. + +“Several years,” he answered in a gratified way. “I made the pleasure +of his acquaintance just after the war. But I knew I had discovered a +man of fine breeding after I talked with him an hour. I said to +myself: ‘There’s the kind of man you’d like to take home and introduce +to your mother and sister.’ ” He paused. “I see you’re looking at my +cuff buttons.” + +I hadn’t been looking at them, but I did now. They were composed of +oddly familiar pieces of ivory. + +“Finest specimens of human molars,” he informed me. + +“Well!” I inspected them. “That’s a very interesting idea.” + +“Yeah.” He flipped his sleeves up under his coat. “Yeah, Gatsby’s very +careful about women. He would never so much as look at a friend’s +wife.” + +When the subject of this instinctive trust returned to the table and +sat down Mr. Wolfshiem drank his coffee with a jerk and got to his +feet. + +“I have enjoyed my lunch,” he said, “and I’m going to run off from you +two young men before I outstay my welcome.” + +“Don’t hurry Meyer,” said Gatsby, without enthusiasm. Mr. Wolfshiem +raised his hand in a sort of benediction. + +“You’re very polite, but I belong to another generation,” he announced +solemnly. “You sit here and discuss your sports and your young ladies +and your—” He supplied an imaginary noun with another wave of his +hand. “As for me, I am fifty years old, and I won’t impose myself on +you any longer.” + +As he shook hands and turned away his tragic nose was trembling. I +wondered if I had said anything to offend him. + +“He becomes very sentimental sometimes,” explained Gatsby. “This is +one of his sentimental days. He’s quite a character around New York—a +denizen of Broadway.” + +“Who is he, anyhow, an actor?” + +“No.” + +“A dentist?” + +“Meyer Wolfshiem? No, he’s a gambler.” Gatsby hesitated, then added, +coolly: “He’s the man who fixed the World’s Series back in 1919.” + +“Fixed the World’s Series?” I repeated. + +The idea staggered me. I remembered, of course, that the World’s +Series had been fixed in 1919, but if I had thought of it at all I +would have thought of it as a thing that merely happened, the end of +some inevitable chain. It never occurred to me that one man could +start to play with the faith of fifty million people—with the +single-mindedness of a burglar blowing a safe. + +“How did he happen to do that?” I asked after a minute. + +“He just saw the opportunity.” + +“Why isn’t he in jail?” + +“They can’t get him, old sport. He’s a smart man.” + +I insisted on paying the check. As the waiter brought my change I +caught sight of Tom Buchanan across the crowded room. + +“Come along with me for a minute,” I said; “I’ve got to say hello to +someone.” + +When he saw us Tom jumped up and took half a dozen steps in our +direction. + +“Where’ve you been?” he demanded eagerly. “Daisy’s furious because you +haven’t called up.” + +“This is Mr. Gatsby, Mr. Buchanan.” + +They shook hands briefly, and a strained, unfamiliar look of +embarrassment came over Gatsby’s face. + +“How’ve you been, anyhow?” demanded Tom of me. “How’d you happen to +come up this far to eat?” + +“I’ve been having lunch with Mr. Gatsby.” + +I turned toward Mr. Gatsby, but he was no longer there. + +------------------------------------------------------------------------ + +One October day in nineteen-seventeen— + +(said Jordan Baker that afternoon, sitting up very straight on a +straight chair in the tea-garden at the Plaza Hotel) + +—I was walking along from one place to another, half on the sidewalks +and half on the lawns. I was happier on the lawns because I had on +shoes from England with rubber knobs on the soles that bit into the +soft ground. I had on a new plaid skirt also that blew a little in the +wind, and whenever this happened the red, white, and blue banners in +front of all the houses stretched out stiff and said tut-tut-tut-tut, +in a disapproving way. + +The largest of the banners and the largest of the lawns belonged to +Daisy Fay’s house. She was just eighteen, two years older than me, and +by far the most popular of all the young girls in Louisville. She +dressed in white, and had a little white roadster, and all day long +the telephone rang in her house and excited young officers from Camp +Taylor demanded the privilege of monopolizing her that +night. “Anyways, for an hour!” + +When I came opposite her house that morning her white roadster was +beside the kerb, and she was sitting in it with a lieutenant I had +never seen before. They were so engrossed in each other that she +didn’t see me until I was five feet away. + +“Hello, Jordan,” she called unexpectedly. “Please come here.” + +I was flattered that she wanted to speak to me, because of all the +older girls I admired her most. She asked me if I was going to the Red +Cross to make bandages. I was. Well, then, would I tell them that she +couldn’t come that day? The officer looked at Daisy while she was +speaking, in a way that every young girl wants to be looked at +sometime, and because it seemed romantic to me I have remembered the +incident ever since. His name was Jay Gatsby, and I didn’t lay eyes on +him again for over four years—even after I’d met him on Long Island I +didn’t realize it was the same man. + +That was nineteen-seventeen. By the next year I had a few beaux +myself, and I began to play in tournaments, so I didn’t see Daisy very +often. She went with a slightly older crowd—when she went with anyone +at all. Wild rumours were circulating about her—how her mother had +found her packing her bag one winter night to go to New York and say +goodbye to a soldier who was going overseas. She was effectually +prevented, but she wasn’t on speaking terms with her family for +several weeks. After that she didn’t play around with the soldiers any +more, but only with a few flat-footed, shortsighted young men in town, +who couldn’t get into the army at all. + +By the next autumn she was gay again, gay as ever. She had a début +after the armistice, and in February she was presumably engaged to a +man from New Orleans. In June she married Tom Buchanan of Chicago, +with more pomp and circumstance than Louisville ever knew before. He +came down with a hundred people in four private cars, and hired a +whole floor of the Muhlbach Hotel, and the day before the wedding he +gave her a string of pearls valued at three hundred and fifty thousand +dollars. + +I was a bridesmaid. I came into her room half an hour before the +bridal dinner, and found her lying on her bed as lovely as the June +night in her flowered dress—and as drunk as a monkey. She had a bottle +of Sauterne in one hand and a letter in the other. + +“ ’Gratulate me,” she muttered. “Never had a drink before, but oh how +I do enjoy it.” + +“What’s the matter, Daisy?” + +I was scared, I can tell you; I’d never seen a girl like that before. + +“Here, dearies.” She groped around in a wastebasket she had with her +on the bed and pulled out the string of pearls. “Take ’em downstairs +and give ’em back to whoever they belong to. Tell ’em all Daisy’s +change’ her mine. Say: ‘Daisy’s change’ her mine!’ ” + +She began to cry—she cried and cried. I rushed out and found her +mother’s maid, and we locked the door and got her into a cold bath. +She wouldn’t let go of the letter. She took it into the tub with her +and squeezed it up in a wet ball, and only let me leave it in the +soap-dish when she saw that it was coming to pieces like snow. + +But she didn’t say another word. We gave her spirits of ammonia and +put ice on her forehead and hooked her back into her dress, and half +an hour later, when we walked out of the room, the pearls were around +her neck and the incident was over. Next day at five o’clock she +married Tom Buchanan without so much as a shiver, and started off on a +three months’ trip to the South Seas. + +I saw them in Santa Barbara when they came back, and I thought I’d +never seen a girl so mad about her husband. If he left the room for a +minute she’d look around uneasily, and say: “Where’s Tom gone?” and +wear the most abstracted expression until she saw him coming in the +door. She used to sit on the sand with his head in her lap by the +hour, rubbing her fingers over his eyes and looking at him with +unfathomable delight. It was touching to see them together—it made you +laugh in a hushed, fascinated way. That was in August. A week after I +left Santa Barbara Tom ran into a wagon on the Ventura road one night, +and ripped a front wheel off his car. The girl who was with him got +into the papers, too, because her arm was broken—she was one of the +chambermaids in the Santa Barbara Hotel. + +The next April Daisy had her little girl, and they went to France for +a year. I saw them one spring in Cannes, and later in Deauville, and +then they came back to Chicago to settle down. Daisy was popular in +Chicago, as you know. They moved with a fast crowd, all of them young +and rich and wild, but she came out with an absolutely perfect +reputation. Perhaps because she doesn’t drink. It’s a great advantage +not to drink among hard-drinking people. You can hold your tongue and, +moreover, you can time any little irregularity of your own so that +everybody else is so blind that they don’t see or care. Perhaps Daisy +never went in for amour at all—and yet there’s something in that voice +of hers … + +Well, about six weeks ago, she heard the name Gatsby for the first +time in years. It was when I asked you—do you remember?—if you knew +Gatsby in West Egg. After you had gone home she came into my room and +woke me up, and said: “What Gatsby?” and when I described him—I was +half asleep—she said in the strangest voice that it must be the man +she used to know. It wasn’t until then that I connected this Gatsby +with the officer in her white car. + +------------------------------------------------------------------------ + +When Jordan Baker had finished telling all this we had left the Plaza +for half an hour and were driving in a victoria through Central Park. +The sun had gone down behind the tall apartments of the movie stars in +the West Fifties, and the clear voices of children, already gathered +like crickets on the grass, rose through the hot twilight: + + “I’m the Sheik of Araby. Your love belongs to me. At night when + you’re asleep Into your tent I’ll creep—” + +“It was a strange coincidence,” I said. + +“But it wasn’t a coincidence at all.” + +“Why not?” + +“Gatsby bought that house so that Daisy would be just across the bay.” + +Then it had not been merely the stars to which he had aspired on that +June night. He came alive to me, delivered suddenly from the womb of +his purposeless splendour. + +“He wants to know,” continued Jordan, “if you’ll invite Daisy to your +house some afternoon and then let him come over.” + +The modesty of the demand shook me. He had waited five years and +bought a mansion where he dispensed starlight to casual moths—so that +he could “come over” some afternoon to a stranger’s garden. + +“Did I have to know all this before he could ask such a little thing?” + +“He’s afraid, he’s waited so long. He thought you might be +offended. You see, he’s regular tough underneath it all.” + +Something worried me. + +“Why didn’t he ask you to arrange a meeting?” + +“He wants her to see his house,” she explained. “And your house is +right next door.” + +“Oh!” + +“I think he half expected her to wander into one of his parties, some +night,” went on Jordan, “but she never did. Then he began asking +people casually if they knew her, and I was the first one he found. It +was that night he sent for me at his dance, and you should have heard +the elaborate way he worked up to it. Of course, I immediately +suggested a luncheon in New York—and I thought he’d go mad: + +“ ‘I don’t want to do anything out of the way!’ he kept saying. ‘I +want to see her right next door.’ + +“When I said you were a particular friend of Tom’s, he started to +abandon the whole idea. He doesn’t know very much about Tom, though he +says he’s read a Chicago paper for years just on the chance of +catching a glimpse of Daisy’s name.” + +It was dark now, and as we dipped under a little bridge I put my arm +around Jordan’s golden shoulder and drew her toward me and asked her +to dinner. Suddenly I wasn’t thinking of Daisy and Gatsby any more, +but of this clean, hard, limited person, who dealt in universal +scepticism, and who leaned back jauntily just within the circle of my +arm. A phrase began to beat in my ears with a sort of heady +excitement: “There are only the pursued, the pursuing, the busy, and +the tired.” + +“And Daisy ought to have something in her life,” murmured Jordan to +me. + +“Does she want to see Gatsby?” + +“She’s not to know about it. Gatsby doesn’t want her to know. You’re +just supposed to invite her to tea.” + +We passed a barrier of dark trees, and then the façade of Fifty-Ninth +Street, a block of delicate pale light, beamed down into the park. +Unlike Gatsby and Tom Buchanan, I had no girl whose disembodied face +floated along the dark cornices and blinding signs, and so I drew up +the girl beside me, tightening my arms. Her wan, scornful mouth +smiled, and so I drew her up again closer, this time to my face. + + + V + +When I came home to West Egg that night I was afraid for a moment that +my house was on fire. Two o’clock and the whole corner of the +peninsula was blazing with light, which fell unreal on the shrubbery +and made thin elongating glints upon the roadside wires. Turning a +corner, I saw that it was Gatsby’s house, lit from tower to cellar. + +At first I thought it was another party, a wild rout that had resolved +itself into “hide-and-go-seek” or “sardines-in-the-box” with all the +house thrown open to the game. But there wasn’t a sound. Only wind in +the trees, which blew the wires and made the lights go off and on +again as if the house had winked into the darkness. As my taxi groaned +away I saw Gatsby walking toward me across his lawn. + +“Your place looks like the World’s Fair,” I said. + +“Does it?” He turned his eyes toward it absently. “I have been +glancing into some of the rooms. Let’s go to Coney Island, old +sport. In my car.” + +“It’s too late.” + +“Well, suppose we take a plunge in the swimming pool? I haven’t made +use of it all summer.” + +“I’ve got to go to bed.” + +“All right.” + +He waited, looking at me with suppressed eagerness. + +“I talked with Miss Baker,” I said after a moment. “I’m going to call +up Daisy tomorrow and invite her over here to tea.” + +“Oh, that’s all right,” he said carelessly. “I don’t want to put you +to any trouble.” + +“What day would suit you?” + +“What day would suit you?” he corrected me quickly. “I don’t want to +put you to any trouble, you see.” + +“How about the day after tomorrow?” + +He considered for a moment. Then, with reluctance: “I want to get the +grass cut,” he said. + +We both looked down at the grass—there was a sharp line where my +ragged lawn ended and the darker, well-kept expanse of his began. I +suspected that he meant my grass. + +“There’s another little thing,” he said uncertainly, and hesitated. + +“Would you rather put it off for a few days?” I asked. + +“Oh, it isn’t about that. At least—” He fumbled with a series of +beginnings. “Why, I thought—why, look here, old sport, you don’t make +much money, do you?” + +“Not very much.” + +This seemed to reassure him and he continued more confidently. + +“I thought you didn’t, if you’ll pardon my—you see, I carry on a +little business on the side, a sort of side line, you understand. And +I thought that if you don’t make very much—You’re selling bonds, +aren’t you, old sport?” + +“Trying to.” + +“Well, this would interest you. It wouldn’t take up much of your time +and you might pick up a nice bit of money. It happens to be a rather +confidential sort of thing.” + +I realize now that under different circumstances that conversation +might have been one of the crises of my life. But, because the offer +was obviously and tactlessly for a service to be rendered, I had no +choice except to cut him off there. + +“I’ve got my hands full,” I said. “I’m much obliged but I couldn’t +take on any more work.” + +“You wouldn’t have to do any business with Wolfshiem.” Evidently he +thought that I was shying away from the “gonnegtion” mentioned at +lunch, but I assured him he was wrong. He waited a moment longer, +hoping I’d begin a conversation, but I was too absorbed to be +responsive, so he went unwillingly home. + +The evening had made me lightheaded and happy; I think I walked into a +deep sleep as I entered my front door. So I don’t know whether or not +Gatsby went to Coney Island, or for how many hours he “glanced into +rooms” while his house blazed gaudily on. I called up Daisy from the +office next morning, and invited her to come to tea. + +“Don’t bring Tom,” I warned her. + +“What?” + +“Don’t bring Tom.” + +“Who is ‘Tom’?” she asked innocently. + +The day agreed upon was pouring rain. At eleven o’clock a man in a +raincoat, dragging a lawn-mower, tapped at my front door and said that +Mr. Gatsby had sent him over to cut my grass. This reminded me that I +had forgotten to tell my Finn to come back, so I drove into West Egg +Village to search for her among soggy whitewashed alleys and to buy +some cups and lemons and flowers. + +The flowers were unnecessary, for at two o’clock a greenhouse arrived +from Gatsby’s, with innumerable receptacles to contain it. An hour +later the front door opened nervously, and Gatsby in a white flannel +suit, silver shirt, and gold-coloured tie, hurried in. He was pale, +and there were dark signs of sleeplessness beneath his eyes. + +“Is everything all right?” he asked immediately. + +“The grass looks fine, if that’s what you mean.” + +“What grass?” he inquired blankly. “Oh, the grass in the yard.” He +looked out the window at it, but, judging from his expression, I don’t +believe he saw a thing. + +“Looks very good,” he remarked vaguely. “One of the papers said they +thought the rain would stop about four. I think it was The +Journal. Have you got everything you need in the shape of—of tea?” + +I took him into the pantry, where he looked a little reproachfully at +the Finn. Together we scrutinized the twelve lemon cakes from the +delicatessen shop. + +“Will they do?” I asked. + +“Of course, of course! They’re fine!” and he added hollowly, “… old +sport.” + +The rain cooled about half-past three to a damp mist, through which +occasional thin drops swam like dew. Gatsby looked with vacant eyes +through a copy of Clay’s Economics, starting at the Finnish tread that +shook the kitchen floor, and peering towards the bleared windows from +time to time as if a series of invisible but alarming happenings were +taking place outside. Finally he got up and informed me, in an +uncertain voice, that he was going home. + +“Why’s that?” + +“Nobody’s coming to tea. It’s too late!” He looked at his watch as if +there was some pressing demand on his time elsewhere. “I can’t wait +all day.” + +“Don’t be silly; it’s just two minutes to four.” + +He sat down miserably, as if I had pushed him, and simultaneously +there was the sound of a motor turning into my lane. We both jumped +up, and, a little harrowed myself, I went out into the yard. + +Under the dripping bare lilac-trees a large open car was coming up the +drive. It stopped. Daisy’s face, tipped sideways beneath a +three-cornered lavender hat, looked out at me with a bright ecstatic +smile. + +“Is this absolutely where you live, my dearest one?” + +The exhilarating ripple of her voice was a wild tonic in the rain. I +had to follow the sound of it for a moment, up and down, with my ear +alone, before any words came through. A damp streak of hair lay like a +dash of blue paint across her cheek, and her hand was wet with +glistening drops as I took it to help her from the car. + +“Are you in love with me,” she said low in my ear, “or why did I have +to come alone?” + +“That’s the secret of Castle Rackrent. Tell your chauffeur to go far +away and spend an hour.” + +“Come back in an hour, Ferdie.” Then in a grave murmur: “His name is +Ferdie.” + +“Does the gasoline affect his nose?” + +“I don’t think so,” she said innocently. “Why?” + +We went in. To my overwhelming surprise the living-room was deserted. + +“Well, that’s funny,” I exclaimed. + +“What’s funny?” + +She turned her head as there was a light dignified knocking at the +front door. I went out and opened it. Gatsby, pale as death, with his +hands plunged like weights in his coat pockets, was standing in a +puddle of water glaring tragically into my eyes. + +With his hands still in his coat pockets he stalked by me into the +hall, turned sharply as if he were on a wire, and disappeared into the +living-room. It wasn’t a bit funny. Aware of the loud beating of my +own heart I pulled the door to against the increasing rain. + +For half a minute there wasn’t a sound. Then from the living-room I +heard a sort of choking murmur and part of a laugh, followed by +Daisy’s voice on a clear artificial note: + +“I certainly am awfully glad to see you again.” + +A pause; it endured horribly. I had nothing to do in the hall, so I +went into the room. + +Gatsby, his hands still in his pockets, was reclining against the +mantelpiece in a strained counterfeit of perfect ease, even of +boredom. His head leaned back so far that it rested against the face +of a defunct mantelpiece clock, and from this position his distraught +eyes stared down at Daisy, who was sitting, frightened but graceful, +on the edge of a stiff chair. + +“We’ve met before,” muttered Gatsby. His eyes glanced momentarily at +me, and his lips parted with an abortive attempt at a laugh. Luckily +the clock took this moment to tilt dangerously at the pressure of his +head, whereupon he turned and caught it with trembling fingers, and +set it back in place. Then he sat down, rigidly, his elbow on the arm +of the sofa and his chin in his hand. + +“I’m sorry about the clock,” he said. + +My own face had now assumed a deep tropical burn. I couldn’t muster up +a single commonplace out of the thousand in my head. + +“It’s an old clock,” I told them idiotically. + +I think we all believed for a moment that it had smashed in pieces on +the floor. + +“We haven’t met for many years,” said Daisy, her voice as +matter-of-fact as it could ever be. + +“Five years next November.” + +The automatic quality of Gatsby’s answer set us all back at least +another minute. I had them both on their feet with the desperate +suggestion that they help me make tea in the kitchen when the demoniac +Finn brought it in on a tray. + +Amid the welcome confusion of cups and cakes a certain physical +decency established itself. Gatsby got himself into a shadow and, +while Daisy and I talked, looked conscientiously from one to the other +of us with tense, unhappy eyes. However, as calmness wasn’t an end in +itself, I made an excuse at the first possible moment, and got to my +feet. + +“Where are you going?” demanded Gatsby in immediate alarm. + +“I’ll be back.” + +“I’ve got to speak to you about something before you go.” + +He followed me wildly into the kitchen, closed the door, and +whispered: “Oh, God!” in a miserable way. + +“What’s the matter?” + +“This is a terrible mistake,” he said, shaking his head from side to +side, “a terrible, terrible mistake.” + +“You’re just embarrassed, that’s all,” and luckily I added: “Daisy’s +embarrassed too.” + +“She’s embarrassed?” he repeated incredulously. + +“Just as much as you are.” + +“Don’t talk so loud.” + +“You’re acting like a little boy,” I broke out impatiently. “Not only +that, but you’re rude. Daisy’s sitting in there all alone.” + +He raised his hand to stop my words, looked at me with unforgettable +reproach, and, opening the door cautiously, went back into the other +room. + +I walked out the back way—just as Gatsby had when he had made his +nervous circuit of the house half an hour before—and ran for a huge +black knotted tree, whose massed leaves made a fabric against the +rain. Once more it was pouring, and my irregular lawn, well-shaved by +Gatsby’s gardener, abounded in small muddy swamps and prehistoric +marshes. There was nothing to look at from under the tree except +Gatsby’s enormous house, so I stared at it, like Kant at his church +steeple, for half an hour. A brewer had built it early in the “period” +craze, a decade before, and there was a story that he’d agreed to pay +five years’ taxes on all the neighbouring cottages if the owners would +have their roofs thatched with straw. Perhaps their refusal took the +heart out of his plan to Found a Family—he went into an immediate +decline. His children sold his house with the black wreath still on +the door. Americans, while willing, even eager, to be serfs, have +always been obstinate about being + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_4096.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_4096.txt new file mode 100644 index 0000000000..d8cb857cb4 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_4096.txt @@ -0,0 +1,365 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I decided to go East and learn the bond +business. Everybody I knew was in the bond business, so I supposed it +could support one more single man. All my aunts and uncles talked it +over as if they were choosing a prep school for me, and finally said, +“Why—ye-es,” with very grave, hesitant faces. Father agreed to finance +me for a year, and after various delays I came East, permanently, I +thought, in the spring of twenty-two. + +The practical thing was to find rooms in the city, but it was a warm +season, and I had just left a country of wide lawns and friendly +trees, so when a young man at the office suggested that we take a +house together in a commuting town, it sounded like a great idea. He +found the house, a weather-beaten cardboard bungalow at eighty a +month, but at the last minute the firm ordered him to Washington, and +I went out to the country alone. I had a dog—at least I had him for a +few days until he ran away—and an old Dodge and a Finnish woman, who +made my bed and cooked breakfast and muttered Finnish wisdom to +herself over the electric stove. + +It was lonely for a day or so until one morning some man, more +recently arrived than I, stopped me on the road. + +“How do you get to West Egg village?” he asked helplessly. + +I told him. And as I walked on I was lonely no longer. I was a guide, +a pathfinder, an original settler. He had casually conferred on me the +freedom of the neighbourhood. + +And so with the sunshine and the great bursts of leaves growing on the +trees, just as things grow in fast movies, I had that familiar +conviction that life was beginning over again with the summer. + +There was so much to read, for one thing, and so much fine health to +be pulled down out of the young breath-giving air. I bought a dozen +volumes on banking and credit and investment securities, and they +stood on my shelf in red and gold like new money from the mint, +promising to unfold the shining secrets that only Midas and Morgan and +Maecenas knew. And I had the high intention of reading many other +books besides. I was rather literary in college—one year I wrote a +series of very solemn and obvious editorials for the Yale News—and now +I was going to bring back all such things into my life and become +again that most limited of all specialists, the “well-rounded man.” +This isn’t just an epigram—life is much more successfully looked at +from a single window, after all. + +It was a matter of chance that I should have rented a house in one of +the strangest communities in North America. It was on that slender +riotous island which extends itself due east of New York—and where +there are, among other natural curiosities, two unusual formations of +land. Twenty miles from the city a pair of enormous eggs, identical in +contour and separated only by a courtesy bay, jut out into the most +domesticated body of salt water in the Western hemisphere, the great +wet barnyard of Long Island Sound. They are not perfect ovals—like the +egg in the Columbus story, they are both crushed flat at the contact +end—but their physical resemblance must be a source of perpetual +wonder to the gulls that fly overhead. To the wingless a more +interesting phenomenon is their dissimilarity in every particular +except shape and size. + +I lived at West Egg, the—well, the less fashionable of the two, though +this is a most superficial tag to express the bizarre and not a little +sinister contrast between them. My house was at the very tip of the +egg, only fifty yards from the Sound, and squeezed between two huge +places that rented for twelve or fifteen thousand a season. The one on +my right was a colossal affair by any standard—it was a factual +imitation of some Hôtel de Ville in Normandy, with a tower on one +side, spanking new under a thin beard of raw ivy, and a marble +swimming pool, and more than forty acres of lawn and garden. It was +Gatsby’s mansion. Or, rather, as I didn’t know Mr. Gatsby, it was a +mansion inhabited by a gentleman of that name. My own house was an +eyesore, but it was a small eyesore, and it had been overlooked, so I +had a view of the water, a partial view of my neighbour’s lawn, and +the consoling proximity of millionaires—all for eighty dollars a +month. + +Across the courtesy bay the white palaces of fashionable East Egg +glittered along the water, and the history of the summer really begins +on the evening I drove over there to have dinner with the Tom +Buchanans. Daisy was my second cousin once removed, and I’d known Tom +in college. And just after the war I spent two days with them in +Chicago. + +Her husband, among various physical accomplishments, had been one of +the most powerful ends that ever played football at New Haven—a +national figure in a way, one of those men who reach such an acute +limited excellence at twenty-one that everything afterward savours of +anticlimax. His family were enormously wealthy—even in college his +freedom with money was a matter for reproach—but now he’d left Chicago +and come East in a fashion that rather took your breath away: for +instance, he’d brought down a string of polo ponies from Lake +Forest. It was hard to realize that a man in my own generation was +wealthy enough to do that. + +Why they came East I don’t know. They had spent a year in France for +no particular reason, and then drifted here and there unrestfully +wherever people played polo and were rich together. This was a +permanent move, said Daisy over the telephone, but I didn’t believe +it—I had no sight into Daisy’s heart, but I felt that Tom would drift +on forever seeking, a little wistfully, for the dramatic turbulence of +some irrecoverable football game. + +And so it happened that on a warm windy evening I drove over to East +Egg to see two old friends whom I scarcely knew at all. Their house +was even more elaborate than I expected, a cheerful red-and-white +Georgian Colonial mansion, overlooking the bay. The lawn started at +the beach and ran towards the front door for a quarter of a mile, +jumping over sundials and brick walks and burning gardens—finally when +it reached the house drifting up the side in bright vines as though +from the momentum of its run. The front was broken by a line of French +windows, glowing now with reflected gold and wide open to the warm +windy afternoon, and Tom Buchanan in riding clothes was standing with +his legs apart on the front porch. + +He had changed since his New Haven years. Now he was a sturdy +straw-haired man of thirty, with a rather hard mouth and a +supercilious manner. Two shining arrogant eyes had established +dominance over his face and gave him the appearance of always leaning +aggressively forward. Not even the effeminate swank of his riding +clothes could hide the enormous power of that body—he seemed to fill +those glistening boots until he strained the top lacing, and you could +see a great pack of muscle shifting when his shoulder moved under his +thin coat. It was a body capable of enormous leverage—a cruel body. + +His speaking voice, a gruff husky tenor, added to the impression of +fractiousness he conveyed. There was a touch of paternal contempt in +it, even toward people he liked—and there were men at New Haven who +had hated his guts. + +“Now, don’t think my opinion on these matters is final,” he seemed to +say, “just because I’m stronger and more of a man than you are.” We +were in the same senior society, and while we were never intimate I +always had the impression that he approved of me and wanted me to like +him with some harsh, defiant wistfulness of his own. + +We talked for a few minutes on the sunny porch. + +“I’ve got a nice place here,” he said, his eyes flashing about +restlessly. + +Turning me around by one arm, he moved a broad flat hand along the +front vista, including in its sweep a sunken Italian garden, a half +acre of deep, pungent roses, and a snub-nosed motorboat that bumped +the tide offshore. + +“It belonged to Demaine, the oil man.” He turned me around again, +politely and abruptly. “We’ll go inside.” + +We walked through a high hallway into a bright rosy-coloured space, +fragilely bound into the house by French windows at either end. The +windows were ajar and gleaming white against the fresh grass outside +that seemed to grow a little way into the house. A breeze blew through +the room, blew curtains in at one end and out the other like pale +flags, twisting them up toward the frosted wedding-cake of the +ceiling, and then rippled over the wine-coloured rug, making a shadow +on it as wind does on the sea. + +The only completely stationary object in the room was an enormous +couch on which two young women were buoyed up as though upon an +anchored balloon. They were both in white, and their dresses were +rippling and fluttering as if they had just been blown back in after a +short flight around the house. I must have stood for a few moments +listening to the whip and snap of the curtains and the groan of a +picture on the wall. Then there was a boom as Tom Buchanan shut the +rear windows and the caught wind died out about the room, and the +curtains and the rugs and the two young women ballooned slowly to the +floor. + +The younger of the two was a stranger to me. She was extended full +length at her end of the divan, completely motionless, and with her +chin raised a little, as if she were balancing something on it which +was quite likely to fall. If she saw me out of the corner of her eyes +she gave no hint of it—indeed, I was almost surprised into murmuring +an apology for having disturbed her by coming in. + +The other girl, Daisy, made an attempt to rise—she leaned slightly +forward with a conscientious expression—then she laughed, an absurd, +charming little laugh, and I laughed too and came forward into the +room. + +“I’m p-paralysed with happiness.” + +She laughed again, as if she said something very witty, and held my +hand for a moment, looking up into my face, promising that there was +no one in the world she so much wanted to see. That was a way she +had. She hinted in a murmur that the surname of the balancing girl was +Baker. (I’ve heard it said that Daisy’s murmur was only to make people +lean toward her; an irrelevant criticism that made it no less +charming.) + +At any rate, Miss Baker’s lips fluttered, she nodded at me almost +imperceptibly, and then quickly tipped her head back again—the object +she was balancing had obviously tottered a little and given her +something of a fright. Again a sort of apology arose to my lips. +Almost any exhibition of complete self-sufficiency draws a stunned +tribute from me. + +I looked back at my cousin, who began to ask me questions in her low, +thrilling voice. It was the kind of voice that the ear follows up and +down, as if each speech is an arrangement of notes that will never be +played again. Her face was sad and lovely with bright things in it, +bright eyes and a bright passionate mouth, but there was an excitement +in her voice that men who had cared for her found difficult to forget: +a singing compulsion, a whispered “Listen,” a promise that she had +done gay, exciting things just a while since and that there were gay, +exciting things hovering in the next hour. + +I told her how I had stopped off in Chicago for a day on my way East, +and how a dozen people had sent their love through me. + +“Do they miss me?” she cried ecstatically. + +“The whole town is desolate. All the cars have the left rear wheel +painted black as a mourning wreath, and there’s a persistent wail all +night along the north shore.” + +“How gorgeous! Let’s go back, Tom. Tomorrow!” Then she added +irrelevantly: “You ought to see the baby.” + +“I’d like to.” + +“She’s asleep. She’s three years old. Haven’t you ever seen her?” + +“Never.” + +“Well, you ought to see her. She’s—” + +Tom Buchanan, who had been hovering restlessly about the room, stopped +and rested his hand on my shoulder. + +“What you doing, Nick?” + +“I’m a bond man.” + +“Who with?” + +I told him. + +“Never heard of them,” he remarked decisively. + +This annoyed me. + +“You will,” I answered shortly. “You will if you stay in the East.” + +“Oh, I’ll stay in the East, don’t you worry,” he said, glancing at +Daisy and then back at me, as if he were alert for something +more. “I’d be a God damned fool to live anywhere else.” + +At this point Miss Baker said: “Absolutely!” with such suddenness that +I started—it was the first word she had uttered since I came into the +room. Evidently it surprised her as much as it did me, for she yawned +and with a series of rapid, deft movements stood up into the room. + +“I’m stiff,” she complained, “I’ve been lying on that sofa for as long +as I can remember.” + +“Don’t look at me,” Daisy retorted, “I’ve been trying to get you to +New York all afternoon.” + +“No, thanks,” said Miss Baker to the four cocktails just in from the +pantry. “I’m absolutely in training.” + +Her host looked at her incredulously. + +“You are!” He took down his drink as if it were a drop in the + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_512.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_512.txt new file mode 100644 index 0000000000..16a2df2eb0 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_512.txt @@ -0,0 +1,65 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_65536.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_65536.txt new file mode 100644 index 0000000000..60ba030a72 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_65536.txt @@ -0,0 +1,6256 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I decided to go East and learn the bond +business. Everybody I knew was in the bond business, so I supposed it +could support one more single man. All my aunts and uncles talked it +over as if they were choosing a prep school for me, and finally said, +“Why—ye-es,” with very grave, hesitant faces. Father agreed to finance +me for a year, and after various delays I came East, permanently, I +thought, in the spring of twenty-two. + +The practical thing was to find rooms in the city, but it was a warm +season, and I had just left a country of wide lawns and friendly +trees, so when a young man at the office suggested that we take a +house together in a commuting town, it sounded like a great idea. He +found the house, a weather-beaten cardboard bungalow at eighty a +month, but at the last minute the firm ordered him to Washington, and +I went out to the country alone. I had a dog—at least I had him for a +few days until he ran away—and an old Dodge and a Finnish woman, who +made my bed and cooked breakfast and muttered Finnish wisdom to +herself over the electric stove. + +It was lonely for a day or so until one morning some man, more +recently arrived than I, stopped me on the road. + +“How do you get to West Egg village?” he asked helplessly. + +I told him. And as I walked on I was lonely no longer. I was a guide, +a pathfinder, an original settler. He had casually conferred on me the +freedom of the neighbourhood. + +And so with the sunshine and the great bursts of leaves growing on the +trees, just as things grow in fast movies, I had that familiar +conviction that life was beginning over again with the summer. + +There was so much to read, for one thing, and so much fine health to +be pulled down out of the young breath-giving air. I bought a dozen +volumes on banking and credit and investment securities, and they +stood on my shelf in red and gold like new money from the mint, +promising to unfold the shining secrets that only Midas and Morgan and +Maecenas knew. And I had the high intention of reading many other +books besides. I was rather literary in college—one year I wrote a +series of very solemn and obvious editorials for the Yale News—and now +I was going to bring back all such things into my life and become +again that most limited of all specialists, the “well-rounded man.” +This isn’t just an epigram—life is much more successfully looked at +from a single window, after all. + +It was a matter of chance that I should have rented a house in one of +the strangest communities in North America. It was on that slender +riotous island which extends itself due east of New York—and where +there are, among other natural curiosities, two unusual formations of +land. Twenty miles from the city a pair of enormous eggs, identical in +contour and separated only by a courtesy bay, jut out into the most +domesticated body of salt water in the Western hemisphere, the great +wet barnyard of Long Island Sound. They are not perfect ovals—like the +egg in the Columbus story, they are both crushed flat at the contact +end—but their physical resemblance must be a source of perpetual +wonder to the gulls that fly overhead. To the wingless a more +interesting phenomenon is their dissimilarity in every particular +except shape and size. + +I lived at West Egg, the—well, the less fashionable of the two, though +this is a most superficial tag to express the bizarre and not a little +sinister contrast between them. My house was at the very tip of the +egg, only fifty yards from the Sound, and squeezed between two huge +places that rented for twelve or fifteen thousand a season. The one on +my right was a colossal affair by any standard—it was a factual +imitation of some Hôtel de Ville in Normandy, with a tower on one +side, spanking new under a thin beard of raw ivy, and a marble +swimming pool, and more than forty acres of lawn and garden. It was +Gatsby’s mansion. Or, rather, as I didn’t know Mr. Gatsby, it was a +mansion inhabited by a gentleman of that name. My own house was an +eyesore, but it was a small eyesore, and it had been overlooked, so I +had a view of the water, a partial view of my neighbour’s lawn, and +the consoling proximity of millionaires—all for eighty dollars a +month. + +Across the courtesy bay the white palaces of fashionable East Egg +glittered along the water, and the history of the summer really begins +on the evening I drove over there to have dinner with the Tom +Buchanans. Daisy was my second cousin once removed, and I’d known Tom +in college. And just after the war I spent two days with them in +Chicago. + +Her husband, among various physical accomplishments, had been one of +the most powerful ends that ever played football at New Haven—a +national figure in a way, one of those men who reach such an acute +limited excellence at twenty-one that everything afterward savours of +anticlimax. His family were enormously wealthy—even in college his +freedom with money was a matter for reproach—but now he’d left Chicago +and come East in a fashion that rather took your breath away: for +instance, he’d brought down a string of polo ponies from Lake +Forest. It was hard to realize that a man in my own generation was +wealthy enough to do that. + +Why they came East I don’t know. They had spent a year in France for +no particular reason, and then drifted here and there unrestfully +wherever people played polo and were rich together. This was a +permanent move, said Daisy over the telephone, but I didn’t believe +it—I had no sight into Daisy’s heart, but I felt that Tom would drift +on forever seeking, a little wistfully, for the dramatic turbulence of +some irrecoverable football game. + +And so it happened that on a warm windy evening I drove over to East +Egg to see two old friends whom I scarcely knew at all. Their house +was even more elaborate than I expected, a cheerful red-and-white +Georgian Colonial mansion, overlooking the bay. The lawn started at +the beach and ran towards the front door for a quarter of a mile, +jumping over sundials and brick walks and burning gardens—finally when +it reached the house drifting up the side in bright vines as though +from the momentum of its run. The front was broken by a line of French +windows, glowing now with reflected gold and wide open to the warm +windy afternoon, and Tom Buchanan in riding clothes was standing with +his legs apart on the front porch. + +He had changed since his New Haven years. Now he was a sturdy +straw-haired man of thirty, with a rather hard mouth and a +supercilious manner. Two shining arrogant eyes had established +dominance over his face and gave him the appearance of always leaning +aggressively forward. Not even the effeminate swank of his riding +clothes could hide the enormous power of that body—he seemed to fill +those glistening boots until he strained the top lacing, and you could +see a great pack of muscle shifting when his shoulder moved under his +thin coat. It was a body capable of enormous leverage—a cruel body. + +His speaking voice, a gruff husky tenor, added to the impression of +fractiousness he conveyed. There was a touch of paternal contempt in +it, even toward people he liked—and there were men at New Haven who +had hated his guts. + +“Now, don’t think my opinion on these matters is final,” he seemed to +say, “just because I’m stronger and more of a man than you are.” We +were in the same senior society, and while we were never intimate I +always had the impression that he approved of me and wanted me to like +him with some harsh, defiant wistfulness of his own. + +We talked for a few minutes on the sunny porch. + +“I’ve got a nice place here,” he said, his eyes flashing about +restlessly. + +Turning me around by one arm, he moved a broad flat hand along the +front vista, including in its sweep a sunken Italian garden, a half +acre of deep, pungent roses, and a snub-nosed motorboat that bumped +the tide offshore. + +“It belonged to Demaine, the oil man.” He turned me around again, +politely and abruptly. “We’ll go inside.” + +We walked through a high hallway into a bright rosy-coloured space, +fragilely bound into the house by French windows at either end. The +windows were ajar and gleaming white against the fresh grass outside +that seemed to grow a little way into the house. A breeze blew through +the room, blew curtains in at one end and out the other like pale +flags, twisting them up toward the frosted wedding-cake of the +ceiling, and then rippled over the wine-coloured rug, making a shadow +on it as wind does on the sea. + +The only completely stationary object in the room was an enormous +couch on which two young women were buoyed up as though upon an +anchored balloon. They were both in white, and their dresses were +rippling and fluttering as if they had just been blown back in after a +short flight around the house. I must have stood for a few moments +listening to the whip and snap of the curtains and the groan of a +picture on the wall. Then there was a boom as Tom Buchanan shut the +rear windows and the caught wind died out about the room, and the +curtains and the rugs and the two young women ballooned slowly to the +floor. + +The younger of the two was a stranger to me. She was extended full +length at her end of the divan, completely motionless, and with her +chin raised a little, as if she were balancing something on it which +was quite likely to fall. If she saw me out of the corner of her eyes +she gave no hint of it—indeed, I was almost surprised into murmuring +an apology for having disturbed her by coming in. + +The other girl, Daisy, made an attempt to rise—she leaned slightly +forward with a conscientious expression—then she laughed, an absurd, +charming little laugh, and I laughed too and came forward into the +room. + +“I’m p-paralysed with happiness.” + +She laughed again, as if she said something very witty, and held my +hand for a moment, looking up into my face, promising that there was +no one in the world she so much wanted to see. That was a way she +had. She hinted in a murmur that the surname of the balancing girl was +Baker. (I’ve heard it said that Daisy’s murmur was only to make people +lean toward her; an irrelevant criticism that made it no less +charming.) + +At any rate, Miss Baker’s lips fluttered, she nodded at me almost +imperceptibly, and then quickly tipped her head back again—the object +she was balancing had obviously tottered a little and given her +something of a fright. Again a sort of apology arose to my lips. +Almost any exhibition of complete self-sufficiency draws a stunned +tribute from me. + +I looked back at my cousin, who began to ask me questions in her low, +thrilling voice. It was the kind of voice that the ear follows up and +down, as if each speech is an arrangement of notes that will never be +played again. Her face was sad and lovely with bright things in it, +bright eyes and a bright passionate mouth, but there was an excitement +in her voice that men who had cared for her found difficult to forget: +a singing compulsion, a whispered “Listen,” a promise that she had +done gay, exciting things just a while since and that there were gay, +exciting things hovering in the next hour. + +I told her how I had stopped off in Chicago for a day on my way East, +and how a dozen people had sent their love through me. + +“Do they miss me?” she cried ecstatically. + +“The whole town is desolate. All the cars have the left rear wheel +painted black as a mourning wreath, and there’s a persistent wail all +night along the north shore.” + +“How gorgeous! Let’s go back, Tom. Tomorrow!” Then she added +irrelevantly: “You ought to see the baby.” + +“I’d like to.” + +“She’s asleep. She’s three years old. Haven’t you ever seen her?” + +“Never.” + +“Well, you ought to see her. She’s—” + +Tom Buchanan, who had been hovering restlessly about the room, stopped +and rested his hand on my shoulder. + +“What you doing, Nick?” + +“I’m a bond man.” + +“Who with?” + +I told him. + +“Never heard of them,” he remarked decisively. + +This annoyed me. + +“You will,” I answered shortly. “You will if you stay in the East.” + +“Oh, I’ll stay in the East, don’t you worry,” he said, glancing at +Daisy and then back at me, as if he were alert for something +more. “I’d be a God damned fool to live anywhere else.” + +At this point Miss Baker said: “Absolutely!” with such suddenness that +I started—it was the first word she had uttered since I came into the +room. Evidently it surprised her as much as it did me, for she yawned +and with a series of rapid, deft movements stood up into the room. + +“I’m stiff,” she complained, “I’ve been lying on that sofa for as long +as I can remember.” + +“Don’t look at me,” Daisy retorted, “I’ve been trying to get you to +New York all afternoon.” + +“No, thanks,” said Miss Baker to the four cocktails just in from the +pantry. “I’m absolutely in training.” + +Her host looked at her incredulously. + +“You are!” He took down his drink as if it were a drop in the bottom +of a glass. “How you ever get anything done is beyond me.” + +I looked at Miss Baker, wondering what it was she “got done.” I +enjoyed looking at her. She was a slender, small-breasted girl, with +an erect carriage, which she accentuated by throwing her body backward +at the shoulders like a young cadet. Her grey sun-strained eyes looked +back at me with polite reciprocal curiosity out of a wan, charming, +discontented face. It occurred to me now that I had seen her, or a +picture of her, somewhere before. + +“You live in West Egg,” she remarked contemptuously. “I know somebody +there.” + +“I don’t know a single—” + +“You must know Gatsby.” + +“Gatsby?” demanded Daisy. “What Gatsby?” + +Before I could reply that he was my neighbour dinner was announced; +wedging his tense arm imperatively under mine, Tom Buchanan compelled +me from the room as though he were moving a checker to another square. + +Slenderly, languidly, their hands set lightly on their hips, the two +young women preceded us out on to a rosy-coloured porch, open toward +the sunset, where four candles flickered on the table in the +diminished wind. + +“Why candles?” objected Daisy, frowning. She snapped them out with her +fingers. “In two weeks it’ll be the longest day in the year.” She +looked at us all radiantly. “Do you always watch for the longest day +of the year and then miss it? I always watch for the longest day in +the year and then miss it.” + +“We ought to plan something,” yawned Miss Baker, sitting down at the +table as if she were getting into bed. + +“All right,” said Daisy. “What’ll we plan?” She turned to me +helplessly: “What do people plan?” + +Before I could answer her eyes fastened with an awed expression on her +little finger. + +“Look!” she complained; “I hurt it.” + +We all looked—the knuckle was black and blue. + +“You did it, Tom,” she said accusingly. “I know you didn’t mean to, +but you did do it. That’s what I get for marrying a brute of a man, a +great, big, hulking physical specimen of a—” + +“I hate that word ‘hulking,’ ” objected Tom crossly, “even in +kidding.” + +“Hulking,” insisted Daisy. + +Sometimes she and Miss Baker talked at once, unobtrusively and with a +bantering inconsequence that was never quite chatter, that was as cool +as their white dresses and their impersonal eyes in the absence of all +desire. They were here, and they accepted Tom and me, making only a +polite pleasant effort to entertain or to be entertained. They knew +that presently dinner would be over and a little later the evening too +would be over and casually put away. It was sharply different from the +West, where an evening was hurried from phase to phase towards its +close, in a continually disappointed anticipation or else in sheer +nervous dread of the moment itself. + +“You make me feel uncivilized, Daisy,” I confessed on my second glass +of corky but rather impressive claret. “Can’t you talk about crops or +something?” + +I meant nothing in particular by this remark, but it was taken up in +an unexpected way. + +“Civilization’s going to pieces,” broke out Tom violently. “I’ve +gotten to be a terrible pessimist about things. Have you read The Rise +of the Coloured Empires by this man Goddard?” + +“Why, no,” I answered, rather surprised by his tone. + +“Well, it’s a fine book, and everybody ought to read it. The idea is +if we don’t look out the white race will be—will be utterly +submerged. It’s all scientific stuff; it’s been proved.” + +“Tom’s getting very profound,” said Daisy, with an expression of +unthoughtful sadness. “He reads deep books with long words in +them. What was that word we—” + +“Well, these books are all scientific,” insisted Tom, glancing at her +impatiently. “This fellow has worked out the whole thing. It’s up to +us, who are the dominant race, to watch out or these other races will +have control of things.” + +“We’ve got to beat them down,” whispered Daisy, winking ferociously +toward the fervent sun. + +“You ought to live in California—” began Miss Baker, but Tom +interrupted her by shifting heavily in his chair. + +“This idea is that we’re Nordics. I am, and you are, and you are, +and—” After an infinitesimal hesitation he included Daisy with a +slight nod, and she winked at me again. “—And we’ve produced all the +things that go to make civilization—oh, science and art, and all +that. Do you see?” + +There was something pathetic in his concentration, as if his +complacency, more acute than of old, was not enough to him any more. +When, almost immediately, the telephone rang inside and the butler +left the porch Daisy seized upon the momentary interruption and leaned +towards me. + +“I’ll tell you a family secret,” she whispered enthusiastically. +“It’s about the butler’s nose. Do you want to hear about the butler’s +nose?” + +“That’s why I came over tonight.” + +“Well, he wasn’t always a butler; he used to be the silver polisher +for some people in New York that had a silver service for two hundred +people. He had to polish it from morning till night, until finally it +began to affect his nose—” + +“Things went from bad to worse,” suggested Miss Baker. + +“Yes. Things went from bad to worse, until finally he had to give up +his position.” + +For a moment the last sunshine fell with romantic affection upon her +glowing face; her voice compelled me forward breathlessly as I +listened—then the glow faded, each light deserting her with lingering +regret, like children leaving a pleasant street at dusk. + +The butler came back and murmured something close to Tom’s ear, +whereupon Tom frowned, pushed back his chair, and without a word went +inside. As if his absence quickened something within her, Daisy leaned +forward again, her voice glowing and singing. + +“I love to see you at my table, Nick. You remind me of a—of a rose, an +absolute rose. Doesn’t he?” She turned to Miss Baker for confirmation: +“An absolute rose?” + +This was untrue. I am not even faintly like a rose. She was only +extemporizing, but a stirring warmth flowed from her, as if her heart +was trying to come out to you concealed in one of those breathless, +thrilling words. Then suddenly she threw her napkin on the table and +excused herself and went into the house. + +Miss Baker and I exchanged a short glance consciously devoid of +meaning. I was about to speak when she sat up alertly and said “Sh!” +in a warning voice. A subdued impassioned murmur was audible in the +room beyond, and Miss Baker leaned forward unashamed, trying to +hear. The murmur trembled on the verge of coherence, sank down, +mounted excitedly, and then ceased altogether. + +“This Mr. Gatsby you spoke of is my neighbour—” I began. + +“Don’t talk. I want to hear what happens.” + +“Is something happening?” I inquired innocently. + +“You mean to say you don’t know?” said Miss Baker, honestly surprised. +“I thought everybody knew.” + +“I don’t.” + +“Why—” she said hesitantly. “Tom’s got some woman in New York.” + +“Got some woman?” I repeated blankly. + +Miss Baker nodded. + +“She might have the decency not to telephone him at dinner time. +Don’t you think?” + +Almost before I had grasped her meaning there was the flutter of a +dress and the crunch of leather boots, and Tom and Daisy were back at +the table. + +“It couldn’t be helped!” cried Daisy with tense gaiety. + +She sat down, glanced searchingly at Miss Baker and then at me, and +continued: “I looked outdoors for a minute, and it’s very romantic +outdoors. There’s a bird on the lawn that I think must be a +nightingale come over on the Cunard or White Star Line. He’s singing +away—” Her voice sang: “It’s romantic, isn’t it, Tom?” + +“Very romantic,” he said, and then miserably to me: “If it’s light +enough after dinner, I want to take you down to the stables.” + +The telephone rang inside, startlingly, and as Daisy shook her head +decisively at Tom the subject of the stables, in fact all subjects, +vanished into air. Among the broken fragments of the last five minutes +at table I remember the candles being lit again, pointlessly, and I +was conscious of wanting to look squarely at everyone, and yet to +avoid all eyes. I couldn’t guess what Daisy and Tom were thinking, but +I doubt if even Miss Baker, who seemed to have mastered a certain +hardy scepticism, was able utterly to put this fifth guest’s shrill +metallic urgency out of mind. To a certain temperament the situation +might have seemed intriguing—my own instinct was to telephone +immediately for the police. + +The horses, needless to say, were not mentioned again. Tom and Miss +Baker, with several feet of twilight between them, strolled back into +the library, as if to a vigil beside a perfectly tangible body, while, +trying to look pleasantly interested and a little deaf, I followed +Daisy around a chain of connecting verandas to the porch in front. In +its deep gloom we sat down side by side on a wicker settee. + +Daisy took her face in her hands as if feeling its lovely shape, and +her eyes moved gradually out into the velvet dusk. I saw that +turbulent emotions possessed her, so I asked what I thought would be +some sedative questions about her little girl. + +“We don’t know each other very well, Nick,” she said suddenly. “Even +if we are cousins. You didn’t come to my wedding.” + +“I wasn’t back from the war.” + +“That’s true.” She hesitated. “Well, I’ve had a very bad time, Nick, +and I’m pretty cynical about everything.” + +Evidently she had reason to be. I waited but she didn’t say any more, +and after a moment I returned rather feebly to the subject of her +daughter. + +“I suppose she talks, and—eats, and everything.” + +“Oh, yes.” She looked at me absently. “Listen, Nick; let me tell you +what I said when she was born. Would you like to hear?” + +“Very much.” + +“It’ll show you how I’ve gotten to feel about—things. Well, she was +less than an hour old and Tom was God knows where. I woke up out of +the ether with an utterly abandoned feeling, and asked the nurse right +away if it was a boy or a girl. She told me it was a girl, and so I +turned my head away and wept. ‘All right,’ I said, ‘I’m glad it’s a +girl. And I hope she’ll be a fool—that’s the best thing a girl can be +in this world, a beautiful little fool.’ + +“You see I think everything’s terrible anyhow,” she went on in a +convinced way. “Everybody thinks so—the most advanced people. And I +know. I’ve been everywhere and seen everything and done everything.” +Her eyes flashed around her in a defiant way, rather like Tom’s, and +she laughed with thrilling scorn. “Sophisticated—God, I’m +sophisticated!” + +The instant her voice broke off, ceasing to compel my attention, my +belief, I felt the basic insincerity of what she had said. It made me +uneasy, as though the whole evening had been a trick of some sort to +exact a contributory emotion from me. I waited, and sure enough, in a +moment she looked at me with an absolute smirk on her lovely face, as +if she had asserted her membership in a rather distinguished secret +society to which she and Tom belonged. + +------------------------------------------------------------------------ + +Inside, the crimson room bloomed with light. Tom and Miss Baker sat at +either end of the long couch and she read aloud to him from the +Saturday Evening Post—the words, murmurous and uninflected, running +together in a soothing tune. The lamplight, bright on his boots and +dull on the autumn-leaf yellow of her hair, glinted along the paper as +she turned a page with a flutter of slender muscles in her arms. + +When we came in she held us silent for a moment with a lifted hand. + +“To be continued,” she said, tossing the magazine on the table, “in +our very next issue.” + +Her body asserted itself with a restless movement of her knee, and she +stood up. + +“Ten o’clock,” she remarked, apparently finding the time on the +ceiling. “Time for this good girl to go to bed.” + +“Jordan’s going to play in the tournament tomorrow,” explained Daisy, +“over at Westchester.” + +“Oh—you’re Jordan Baker.” + +I knew now why her face was familiar—its pleasing contemptuous +expression had looked out at me from many rotogravure pictures of the +sporting life at Asheville and Hot Springs and Palm Beach. I had heard +some story of her too, a critical, unpleasant story, but what it was I +had forgotten long ago. + +“Good night,” she said softly. “Wake me at eight, won’t you.” + +“If you’ll get up.” + +“I will. Good night, Mr. Carraway. See you anon.” + +“Of course you will,” confirmed Daisy. “In fact I think I’ll arrange a +marriage. Come over often, Nick, and I’ll sort of—oh—fling you +together. You know—lock you up accidentally in linen closets and push +you out to sea in a boat, and all that sort of thing—” + +“Good night,” called Miss Baker from the stairs. “I haven’t heard a +word.” + +“She’s a nice girl,” said Tom after a moment. “They oughtn’t to let +her run around the country this way.” + +“Who oughtn’t to?” inquired Daisy coldly. + +“Her family.” + +“Her family is one aunt about a thousand years old. Besides, Nick’s +going to look after her, aren’t you, Nick? She’s going to spend lots +of weekends out here this summer. I think the home influence will be +very good for her.” + +Daisy and Tom looked at each other for a moment in silence. + +“Is she from New York?” I asked quickly. + +“From Louisville. Our white girlhood was passed together there. Our +beautiful white—” + +“Did you give Nick a little heart to heart talk on the veranda?” +demanded Tom suddenly. + +“Did I?” She looked at me. “I can’t seem to remember, but I think we +talked about the Nordic race. Yes, I’m sure we did. It sort of crept +up on us and first thing you know—” + +“Don’t believe everything you hear, Nick,” he advised me. + +I said lightly that I had heard nothing at all, and a few minutes +later I got up to go home. They came to the door with me and stood +side by side in a cheerful square of light. As I started my motor +Daisy peremptorily called: “Wait! + +“I forgot to ask you something, and it’s important. We heard you were +engaged to a girl out West.” + +“That’s right,” corroborated Tom kindly. “We heard that you were +engaged.” + +“It’s a libel. I’m too poor.” + +“But we heard it,” insisted Daisy, surprising me by opening up again +in a flower-like way. “We heard it from three people, so it must be +true.” + +Of course I knew what they were referring to, but I wasn’t even +vaguely engaged. The fact that gossip had published the banns was one +of the reasons I had come East. You can’t stop going with an old +friend on account of rumours, and on the other hand I had no intention +of being rumoured into marriage. + +Their interest rather touched me and made them less remotely +rich—nevertheless, I was confused and a little disgusted as I drove +away. It seemed to me that the thing for Daisy to do was to rush out +of the house, child in arms—but apparently there were no such +intentions in her head. As for Tom, the fact that he “had some woman +in New York” was really less surprising than that he had been +depressed by a book. Something was making him nibble at the edge of +stale ideas as if his sturdy physical egotism no longer nourished his +peremptory heart. + +Already it was deep summer on roadhouse roofs and in front of wayside +garages, where new red petrol-pumps sat out in pools of light, and +when I reached my estate at West Egg I ran the car under its shed and +sat for a while on an abandoned grass roller in the yard. The wind had +blown off, leaving a loud, bright night, with wings beating in the +trees and a persistent organ sound as the full bellows of the earth +blew the frogs full of life. The silhouette of a moving cat wavered +across the moonlight, and, turning my head to watch it, I saw that I +was not alone—fifty feet away a figure had emerged from the shadow of +my neighbour’s mansion and was standing with his hands in his pockets +regarding the silver pepper of the stars. Something in his leisurely +movements and the secure position of his feet upon the lawn suggested +that it was Mr. Gatsby himself, come out to determine what share was +his of our local heavens. + +I decided to call to him. Miss Baker had mentioned him at dinner, and +that would do for an introduction. But I didn’t call to him, for he +gave a sudden intimation that he was content to be alone—he stretched +out his arms toward the dark water in a curious way, and, far as I was +from him, I could have sworn he was trembling. Involuntarily I glanced +seaward—and distinguished nothing except a single green light, minute +and far away, that might have been the end of a dock. When I looked +once more for Gatsby he had vanished, and I was alone again in the +unquiet darkness. + + + II + +About halfway between West Egg and New York the motor road hastily +joins the railroad and runs beside it for a quarter of a mile, so as +to shrink away from a certain desolate area of land. This is a valley +of ashes—a fantastic farm where ashes grow like wheat into ridges and +hills and grotesque gardens; where ashes take the forms of houses and +chimneys and rising smoke and, finally, with a transcendent effort, of +ash-grey men, who move dimly and already crumbling through the powdery +air. Occasionally a line of grey cars crawls along an invisible track, +gives out a ghastly creak, and comes to rest, and immediately the +ash-grey men swarm up with leaden spades and stir up an impenetrable +cloud, which screens their obscure operations from your sight. + +But above the grey land and the spasms of bleak dust which drift +endlessly over it, you perceive, after a moment, the eyes of Doctor T. +J. Eckleburg. The eyes of Doctor T. J. Eckleburg are blue and +gigantic—their retinas are one yard high. They look out of no face, +but, instead, from a pair of enormous yellow spectacles which pass +over a nonexistent nose. Evidently some wild wag of an oculist set +them there to fatten his practice in the borough of Queens, and then +sank down himself into eternal blindness, or forgot them and moved +away. But his eyes, dimmed a little by many paintless days, under sun +and rain, brood on over the solemn dumping ground. + +The valley of ashes is bounded on one side by a small foul river, and, +when the drawbridge is up to let barges through, the passengers on +waiting trains can stare at the dismal scene for as long as half an +hour. There is always a halt there of at least a minute, and it was +because of this that I first met Tom Buchanan’s mistress. + +The fact that he had one was insisted upon wherever he was known. His +acquaintances resented the fact that he turned up in popular cafés +with her and, leaving her at a table, sauntered about, chatting with +whomsoever he knew. Though I was curious to see her, I had no desire +to meet her—but I did. I went up to New York with Tom on the train one +afternoon, and when we stopped by the ash-heaps he jumped to his feet +and, taking hold of my elbow, literally forced me from the car. + +“We’re getting off,” he insisted. “I want you to meet my girl.” + +I think he’d tanked up a good deal at luncheon, and his determination +to have my company bordered on violence. The supercilious assumption +was that on Sunday afternoon I had nothing better to do. + +I followed him over a low whitewashed railroad fence, and we walked +back a hundred yards along the road under Doctor Eckleburg’s +persistent stare. The only building in sight was a small block of +yellow brick sitting on the edge of the waste land, a sort of compact +Main Street ministering to it, and contiguous to absolutely nothing. +One of the three shops it contained was for rent and another was an +all-night restaurant, approached by a trail of ashes; the third was a +garage—Repairs. George B. Wilson. Cars bought and sold.—and I followed +Tom inside. + +The interior was unprosperous and bare; the only car visible was the +dust-covered wreck of a Ford which crouched in a dim corner. It had +occurred to me that this shadow of a garage must be a blind, and that +sumptuous and romantic apartments were concealed overhead, when the +proprietor himself appeared in the door of an office, wiping his hands +on a piece of waste. He was a blond, spiritless man, anaemic, and +faintly handsome. When he saw us a damp gleam of hope sprang into his +light blue eyes. + +“Hello, Wilson, old man,” said Tom, slapping him jovially on the +shoulder. “How’s business?” + +“I can’t complain,” answered Wilson unconvincingly. “When are you +going to sell me that car?” + +“Next week; I’ve got my man working on it now.” + +“Works pretty slow, don’t he?” + +“No, he doesn’t,” said Tom coldly. “And if you feel that way about it, +maybe I’d better sell it somewhere else after all.” + +“I don’t mean that,” explained Wilson quickly. “I just meant—” + +His voice faded off and Tom glanced impatiently around the garage. +Then I heard footsteps on a stairs, and in a moment the thickish +figure of a woman blocked out the light from the office door. She was +in the middle thirties, and faintly stout, but she carried her flesh +sensuously as some women can. Her face, above a spotted dress of dark +blue crêpe-de-chine, contained no facet or gleam of beauty, but there +was an immediately perceptible vitality about her as if the nerves of +her body were continually smouldering. She smiled slowly and, walking +through her husband as if he were a ghost, shook hands with Tom, +looking him flush in the eye. Then she wet her lips, and without +turning around spoke to her husband in a soft, coarse voice: + +“Get some chairs, why don’t you, so somebody can sit down.” + +“Oh, sure,” agreed Wilson hurriedly, and went toward the little +office, mingling immediately with the cement colour of the walls. A +white ashen dust veiled his dark suit and his pale hair as it veiled +everything in the vicinity—except his wife, who moved close to Tom. + +“I want to see you,” said Tom intently. “Get on the next train.” + +“All right.” + +“I’ll meet you by the newsstand on the lower level.” + +She nodded and moved away from him just as George Wilson emerged with +two chairs from his office door. + +We waited for her down the road and out of sight. It was a few days +before the Fourth of July, and a grey, scrawny Italian child was +setting torpedoes in a row along the railroad track. + +“Terrible place, isn’t it,” said Tom, exchanging a frown with Doctor +Eckleburg. + +“Awful.” + +“It does her good to get away.” + +“Doesn’t her husband object?” + +“Wilson? He thinks she goes to see her sister in New York. He’s so +dumb he doesn’t know he’s alive.” + +So Tom Buchanan and his girl and I went up together to New York—or not +quite together, for Mrs. Wilson sat discreetly in another car. Tom +deferred that much to the sensibilities of those East Eggers who might +be on the train. + +She had changed her dress to a brown figured muslin, which stretched +tight over her rather wide hips as Tom helped her to the platform in +New York. At the newsstand she bought a copy of Town Tattle and a +moving-picture magazine, and in the station drugstore some cold cream +and a small flask of perfume. Upstairs, in the solemn echoing drive +she let four taxicabs drive away before she selected a new one, +lavender-coloured with grey upholstery, and in this we slid out from +the mass of the station into the glowing sunshine. But immediately she +turned sharply from the window and, leaning forward, tapped on the +front glass. + +“I want to get one of those dogs,” she said earnestly. “I want to get +one for the apartment. They’re nice to have—a dog.” + +We backed up to a grey old man who bore an absurd resemblance to John +D. Rockefeller. In a basket swung from his neck cowered a dozen very +recent puppies of an indeterminate breed. + +“What kind are they?” asked Mrs. Wilson eagerly, as he came to the +taxi-window. + +“All kinds. What kind do you want, lady?” + +“I’d like to get one of those police dogs; I don’t suppose you got +that kind?” + +The man peered doubtfully into the basket, plunged in his hand and +drew one up, wriggling, by the back of the neck. + +“That’s no police dog,” said Tom. + +“No, it’s not exactly a police dog,” said the man with disappointment +in his voice. “It’s more of an Airedale.” He passed his hand over the +brown washrag of a back. “Look at that coat. Some coat. That’s a dog +that’ll never bother you with catching cold.” + +“I think it’s cute,” said Mrs. Wilson enthusiastically. “How much is +it?” + +“That dog?” He looked at it admiringly. “That dog will cost you ten +dollars.” + +The Airedale—undoubtedly there was an Airedale concerned in it +somewhere, though its feet were startlingly white—changed hands and +settled down into Mrs. Wilson’s lap, where she fondled the +weatherproof coat with rapture. + +“Is it a boy or a girl?” she asked delicately. + +“That dog? That dog’s a boy.” + +“It’s a bitch,” said Tom decisively. “Here’s your money. Go and buy +ten more dogs with it.” + +We drove over to Fifth Avenue, warm and soft, almost pastoral, on the +summer Sunday afternoon. I wouldn’t have been surprised to see a great +flock of white sheep turn the corner. + +“Hold on,” I said, “I have to leave you here.” + +“No you don’t,” interposed Tom quickly. “Myrtle’ll be hurt if you +don’t come up to the apartment. Won’t you, Myrtle?” + +“Come on,” she urged. “I’ll telephone my sister Catherine. She’s said +to be very beautiful by people who ought to know.” + +“Well, I’d like to, but—” + +We went on, cutting back again over the Park toward the West Hundreds. +At 158th Street the cab stopped at one slice in a long white cake of +apartment-houses. Throwing a regal homecoming glance around the +neighbourhood, Mrs. Wilson gathered up her dog and her other +purchases, and went haughtily in. + +“I’m going to have the McKees come up,” she announced as we rose in +the elevator. “And, of course, I got to call up my sister, too.” + +The apartment was on the top floor—a small living-room, a small +dining-room, a small bedroom, and a bath. The living-room was crowded +to the doors with a set of tapestried furniture entirely too large for +it, so that to move about was to stumble continually over scenes of +ladies swinging in the gardens of Versailles. The only picture was an +over-enlarged photograph, apparently a hen sitting on a blurred rock. +Looked at from a distance, however, the hen resolved itself into a +bonnet, and the countenance of a stout old lady beamed down into the +room. Several old copies of Town Tattle lay on the table together with +a copy of Simon Called Peter, and some of the small scandal magazines +of Broadway. Mrs. Wilson was first concerned with the dog. A reluctant +elevator boy went for a box full of straw and some milk, to which he +added on his own initiative a tin of large, hard dog biscuits—one of +which decomposed apathetically in the saucer of milk all +afternoon. Meanwhile Tom brought out a bottle of whisky from a locked +bureau door. + +I have been drunk just twice in my life, and the second time was that +afternoon; so everything that happened has a dim, hazy cast over it, +although until after eight o’clock the apartment was full of cheerful +sun. Sitting on Tom’s lap Mrs. Wilson called up several people on the +telephone; then there were no cigarettes, and I went out to buy some +at the drugstore on the corner. When I came back they had both +disappeared, so I sat down discreetly in the living-room and read a +chapter of Simon Called Peter—either it was terrible stuff or the +whisky distorted things, because it didn’t make any sense to me. + +Just as Tom and Myrtle (after the first drink Mrs. Wilson and I called +each other by our first names) reappeared, company commenced to arrive +at the apartment door. + +The sister, Catherine, was a slender, worldly girl of about thirty, +with a solid, sticky bob of red hair, and a complexion powdered milky +white. Her eyebrows had been plucked and then drawn on again at a more +rakish angle, but the efforts of nature toward the restoration of the +old alignment gave a blurred air to her face. When she moved about +there was an incessant clicking as innumerable pottery bracelets +jingled up and down upon her arms. She came in with such a proprietary +haste, and looked around so possessively at the furniture that I +wondered if she lived here. But when I asked her she laughed +immoderately, repeated my question aloud, and told me she lived with a +girl friend at a hotel. + +Mr. McKee was a pale, feminine man from the flat below. He had just +shaved, for there was a white spot of lather on his cheekbone, and he +was most respectful in his greeting to everyone in the room. He +informed me that he was in the “artistic game,” and I gathered later +that he was a photographer and had made the dim enlargement of +Mrs. Wilson’s mother which hovered like an ectoplasm on the wall. His +wife was shrill, languid, handsome, and horrible. She told me with +pride that her husband had photographed her a hundred and twenty-seven +times since they had been married. + +Mrs. Wilson had changed her costume some time before, and was now +attired in an elaborate afternoon dress of cream-coloured chiffon, +which gave out a continual rustle as she swept about the room. With +the influence of the dress her personality had also undergone a +change. The intense vitality that had been so remarkable in the garage +was converted into impressive hauteur. Her laughter, her gestures, her +assertions became more violently affected moment by moment, and as she +expanded the room grew smaller around her, until she seemed to be +revolving on a noisy, creaking pivot through the smoky air. + +“My dear,” she told her sister in a high, mincing shout, “most of +these fellas will cheat you every time. All they think of is money. I +had a woman up here last week to look at my feet, and when she gave me +the bill you’d of thought she had my appendicitis out.” + +“What was the name of the woman?” asked Mrs. McKee. + +“Mrs. Eberhardt. She goes around looking at people’s feet in their own +homes.” + +“I like your dress,” remarked Mrs. McKee, “I think it’s adorable.” + +Mrs. Wilson rejected the compliment by raising her eyebrow in disdain. + +“It’s just a crazy old thing,” she said. “I just slip it on sometimes +when I don’t care what I look like.” + +“But it looks wonderful on you, if you know what I mean,” pursued Mrs. +McKee. “If Chester could only get you in that pose I think he could +make something of it.” + +We all looked in silence at Mrs. Wilson, who removed a strand of hair +from over her eyes and looked back at us with a brilliant smile. Mr. +McKee regarded her intently with his head on one side, and then moved +his hand back and forth slowly in front of his face. + +“I should change the light,” he said after a moment. “I’d like to +bring out the modelling of the features. And I’d try to get hold of +all the back hair.” + +“I wouldn’t think of changing the light,” cried Mrs. McKee. “I think +it’s—” + +Her husband said “Sh!” and we all looked at the subject again, +whereupon Tom Buchanan yawned audibly and got to his feet. + +“You McKees have something to drink,” he said. “Get some more ice and +mineral water, Myrtle, before everybody goes to sleep.” + +“I told that boy about the ice.” Myrtle raised her eyebrows in despair +at the shiftlessness of the lower orders. “These people! You have to +keep after them all the time.” + +She looked at me and laughed pointlessly. Then she flounced over to +the dog, kissed it with ecstasy, and swept into the kitchen, implying +that a dozen chefs awaited her orders there. + +“I’ve done some nice things out on Long Island,” asserted Mr. McKee. + +Tom looked at him blankly. + +“Two of them we have framed downstairs.” + +“Two what?” demanded Tom. + +“Two studies. One of them I call Montauk Point—The Gulls, and the +other I call Montauk Point—The Sea.” + +The sister Catherine sat down beside me on the couch. + +“Do you live down on Long Island, too?” she inquired. + +“I live at West Egg.” + +“Really? I was down there at a party about a month ago. At a man named +Gatsby’s. Do you know him?” + +“I live next door to him.” + +“Well, they say he’s a nephew or a cousin of Kaiser Wilhelm’s. That’s +where all his money comes from.” + +“Really?” + +She nodded. + +“I’m scared of him. I’d hate to have him get anything on me.” + +This absorbing information about my neighbour was interrupted by Mrs. +McKee’s pointing suddenly at Catherine: + +“Chester, I think you could do something with her,” she broke out, but +Mr. McKee only nodded in a bored way, and turned his attention to Tom. + +“I’d like to do more work on Long Island, if I could get the entry. +All I ask is that they should give me a start.” + +“Ask Myrtle,” said Tom, breaking into a short shout of laughter as +Mrs. Wilson entered with a tray. “She’ll give you a letter of +introduction, won’t you, Myrtle?” + +“Do what?” she asked, startled. + +“You’ll give McKee a letter of introduction to your husband, so he can +do some studies of him.” His lips moved silently for a moment as he +invented, “ ‘George B. Wilson at the Gasoline Pump,’ or something like +that.” + +Catherine leaned close to me and whispered in my ear: + +“Neither of them can stand the person they’re married to.” + +“Can’t they?” + +“Can’t stand them.” She looked at Myrtle and then at Tom. “What I say +is, why go on living with them if they can’t stand them? If I was them +I’d get a divorce and get married to each other right away.” + +“Doesn’t she like Wilson either?” + +The answer to this was unexpected. It came from Myrtle, who had +overheard the question, and it was violent and obscene. + +“You see,” cried Catherine triumphantly. She lowered her voice again. +“It’s really his wife that’s keeping them apart. She’s a Catholic, and +they don’t believe in divorce.” + +Daisy was not a Catholic, and I was a little shocked at the +elaborateness of the lie. + +“When they do get married,” continued Catherine, “they’re going West +to live for a while until it blows over.” + +“It’d be more discreet to go to Europe.” + +“Oh, do you like Europe?” she exclaimed surprisingly. “I just got back +from Monte Carlo.” + +“Really.” + +“Just last year. I went over there with another girl.” + +“Stay long?” + +“No, we just went to Monte Carlo and back. We went by way of +Marseilles. We had over twelve hundred dollars when we started, but we +got gyped out of it all in two days in the private rooms. We had an +awful time getting back, I can tell you. God, how I hated that town!” + +The late afternoon sky bloomed in the window for a moment like the +blue honey of the Mediterranean—then the shrill voice of Mrs. McKee +called me back into the room. + +“I almost made a mistake, too,” she declared vigorously. “I almost +married a little kike who’d been after me for years. I knew he was +below me. Everybody kept saying to me: ‘Lucille, that man’s way below +you!’ But if I hadn’t met Chester, he’d of got me sure.” + +“Yes, but listen,” said Myrtle Wilson, nodding her head up and down, +“at least you didn’t marry him.” + +“I know I didn’t.” + +“Well, I married him,” said Myrtle, ambiguously. “And that’s the +difference between your case and mine.” + +“Why did you, Myrtle?” demanded Catherine. “Nobody forced you to.” + +Myrtle considered. + +“I married him because I thought he was a gentleman,” she said +finally. “I thought he knew something about breeding, but he wasn’t +fit to lick my shoe.” + +“You were crazy about him for a while,” said Catherine. + +“Crazy about him!” cried Myrtle incredulously. “Who said I was crazy +about him? I never was any more crazy about him than I was about that +man there.” + +She pointed suddenly at me, and everyone looked at me accusingly. I +tried to show by my expression that I expected no affection. + +“The only crazy I was was when I married him. I knew right away I made +a mistake. He borrowed somebody’s best suit to get married in, and +never even told me about it, and the man came after it one day when he +was out: ‘Oh, is that your suit?’ I said. ‘This is the first I ever +heard about it.’ But I gave it to him and then I lay down and cried to +beat the band all afternoon.” + +“She really ought to get away from him,” resumed Catherine to me. +“They’ve been living over that garage for eleven years. And Tom’s the +first sweetie she ever had.” + +The bottle of whisky—a second one—was now in constant demand by all +present, excepting Catherine, who “felt just as good on nothing at +all.” Tom rang for the janitor and sent him for some celebrated +sandwiches, which were a complete supper in themselves. I wanted to +get out and walk eastward toward the park through the soft twilight, +but each time I tried to go I became entangled in some wild, strident +argument which pulled me back, as if with ropes, into my chair. Yet +high over the city our line of yellow windows must have contributed +their share of human secrecy to the casual watcher in the darkening +streets, and I saw him too, looking up and wondering. I was within and +without, simultaneously enchanted and repelled by the inexhaustible +variety of life. + +Myrtle pulled her chair close to mine, and suddenly her warm breath +poured over me the story of her first meeting with Tom. + +“It was on the two little seats facing each other that are always the +last ones left on the train. I was going up to New York to see my +sister and spend the night. He had on a dress suit and patent leather +shoes, and I couldn’t keep my eyes off him, but every time he looked +at me I had to pretend to be looking at the advertisement over his +head. When we came into the station he was next to me, and his white +shirtfront pressed against my arm, and so I told him I’d have to call +a policeman, but he knew I lied. I was so excited that when I got into +a taxi with him I didn’t hardly know I wasn’t getting into a subway +train. All I kept thinking about, over and over, was ‘You can’t live +forever; you can’t live forever.’ ” + +She turned to Mrs. McKee and the room rang full of her artificial +laughter. + +“My dear,” she cried, “I’m going to give you this dress as soon as I’m +through with it. I’ve got to get another one tomorrow. I’m going to +make a list of all the things I’ve got to get. A massage and a wave, +and a collar for the dog, and one of those cute little ashtrays where +you touch a spring, and a wreath with a black silk bow for mother’s +grave that’ll last all summer. I got to write down a list so I won’t +forget all the things I got to do.” + +It was nine o’clock—almost immediately afterward I looked at my watch +and found it was ten. Mr. McKee was asleep on a chair with his fists +clenched in his lap, like a photograph of a man of action. Taking out +my handkerchief I wiped from his cheek the spot of dried lather that +had worried me all the afternoon. + +The little dog was sitting on the table looking with blind eyes +through the smoke, and from time to time groaning faintly. People +disappeared, reappeared, made plans to go somewhere, and then lost +each other, searched for each other, found each other a few feet +away. Some time toward midnight Tom Buchanan and Mrs. Wilson stood +face to face discussing, in impassioned voices, whether Mrs. Wilson +had any right to mention Daisy’s name. + +“Daisy! Daisy! Daisy!” shouted Mrs. Wilson. “I’ll say it whenever I +want to! Daisy! Dai—” + +Making a short deft movement, Tom Buchanan broke her nose with his +open hand. + +Then there were bloody towels upon the bathroom floor, and women’s +voices scolding, and high over the confusion a long broken wail of +pain. Mr. McKee awoke from his doze and started in a daze toward the +door. When he had gone halfway he turned around and stared at the +scene—his wife and Catherine scolding and consoling as they stumbled +here and there among the crowded furniture with articles of aid, and +the despairing figure on the couch, bleeding fluently, and trying to +spread a copy of Town Tattle over the tapestry scenes of +Versailles. Then Mr. McKee turned and continued on out the door. +Taking my hat from the chandelier, I followed. + +“Come to lunch some day,” he suggested, as we groaned down in the +elevator. + +“Where?” + +“Anywhere.” + +“Keep your hands off the lever,” snapped the elevator boy. + +“I beg your pardon,” said Mr. McKee with dignity, “I didn’t know I was +touching it.” + +“All right,” I agreed, “I’ll be glad to.” + +… I was standing beside his bed and he was sitting up between the +sheets, clad in his underwear, with a great portfolio in his hands. + +“Beauty and the Beast … Loneliness … Old Grocery Horse … Brook’n +Bridge …” + +Then I was lying half asleep in the cold lower level of the +Pennsylvania Station, staring at the morning Tribune, and waiting for +the four o’clock train. + + + III + +There was music from my neighbour’s house through the summer nights. +In his blue gardens men and girls came and went like moths among the +whisperings and the champagne and the stars. At high tide in the +afternoon I watched his guests diving from the tower of his raft, or +taking the sun on the hot sand of his beach while his two motorboats +slit the waters of the Sound, drawing aquaplanes over cataracts of +foam. On weekends his Rolls-Royce became an omnibus, bearing parties +to and from the city between nine in the morning and long past +midnight, while his station wagon scampered like a brisk yellow bug to +meet all trains. And on Mondays eight servants, including an extra +gardener, toiled all day with mops and scrubbing-brushes and hammers +and garden-shears, repairing the ravages of the night before. + +Every Friday five crates of oranges and lemons arrived from a +fruiterer in New York—every Monday these same oranges and lemons left +his back door in a pyramid of pulpless halves. There was a machine in +the kitchen which could extract the juice of two hundred oranges in +half an hour if a little button was pressed two hundred times by a +butler’s thumb. + +At least once a fortnight a corps of caterers came down with several +hundred feet of canvas and enough coloured lights to make a Christmas +tree of Gatsby’s enormous garden. On buffet tables, garnished with +glistening hors-d’oeuvre, spiced baked hams crowded against salads of +harlequin designs and pastry pigs and turkeys bewitched to a dark +gold. In the main hall a bar with a real brass rail was set up, and +stocked with gins and liquors and with cordials so long forgotten that +most of his female guests were too young to know one from another. + +By seven o’clock the orchestra has arrived, no thin five-piece affair, +but a whole pitful of oboes and trombones and saxophones and viols and +cornets and piccolos, and low and high drums. The last swimmers have +come in from the beach now and are dressing upstairs; the cars from +New York are parked five deep in the drive, and already the halls and +salons and verandas are gaudy with primary colours, and hair bobbed in +strange new ways, and shawls beyond the dreams of Castile. The bar is +in full swing, and floating rounds of cocktails permeate the garden +outside, until the air is alive with chatter and laughter, and casual +innuendo and introductions forgotten on the spot, and enthusiastic +meetings between women who never knew each other’s names. + +The lights grow brighter as the earth lurches away from the sun, and +now the orchestra is playing yellow cocktail music, and the opera of +voices pitches a key higher. Laughter is easier minute by minute, +spilled with prodigality, tipped out at a cheerful word. The groups +change more swiftly, swell with new arrivals, dissolve and form in the +same breath; already there are wanderers, confident girls who weave +here and there among the stouter and more stable, become for a sharp, +joyous moment the centre of a group, and then, excited with triumph, +glide on through the sea-change of faces and voices and colour under +the constantly changing light. + +Suddenly one of these gypsies, in trembling opal, seizes a cocktail +out of the air, dumps it down for courage and, moving her hands like +Frisco, dances out alone on the canvas platform. A momentary hush; the +orchestra leader varies his rhythm obligingly for her, and there is a +burst of chatter as the erroneous news goes around that she is Gilda +Gray’s understudy from the Follies. The party has begun. + +I believe that on the first night I went to Gatsby’s house I was one +of the few guests who had actually been invited. People were not +invited—they went there. They got into automobiles which bore them out +to Long Island, and somehow they ended up at Gatsby’s door. Once there +they were introduced by somebody who knew Gatsby, and after that they +conducted themselves according to the rules of behaviour associated +with an amusement park. Sometimes they came and went without having +met Gatsby at all, came for the party with a simplicity of heart that +was its own ticket of admission. + +I had been actually invited. A chauffeur in a uniform of robin’s-egg +blue crossed my lawn early that Saturday morning with a surprisingly +formal note from his employer: the honour would be entirely Gatsby’s, +it said, if I would attend his “little party” that night. He had seen +me several times, and had intended to call on me long before, but a +peculiar combination of circumstances had prevented it—signed Jay +Gatsby, in a majestic hand. + +Dressed up in white flannels I went over to his lawn a little after +seven, and wandered around rather ill at ease among swirls and eddies +of people I didn’t know—though here and there was a face I had noticed +on the commuting train. I was immediately struck by the number of +young Englishmen dotted about; all well dressed, all looking a little +hungry, and all talking in low, earnest voices to solid and prosperous +Americans. I was sure that they were selling something: bonds or +insurance or automobiles. They were at least agonizingly aware of the +easy money in the vicinity and convinced that it was theirs for a few +words in the right key. + +As soon as I arrived I made an attempt to find my host, but the two or +three people of whom I asked his whereabouts stared at me in such an +amazed way, and denied so vehemently any knowledge of his movements, +that I slunk off in the direction of the cocktail table—the only place +in the garden where a single man could linger without looking +purposeless and alone. + +I was on my way to get roaring drunk from sheer embarrassment when +Jordan Baker came out of the house and stood at the head of the marble +steps, leaning a little backward and looking with contemptuous +interest down into the garden. + +Welcome or not, I found it necessary to attach myself to someone +before I should begin to address cordial remarks to the passersby. + +“Hello!” I roared, advancing toward her. My voice seemed unnaturally +loud across the garden. + +“I thought you might be here,” she responded absently as I came up. +“I remembered you lived next door to—” + +She held my hand impersonally, as a promise that she’d take care of me +in a minute, and gave ear to two girls in twin yellow dresses, who +stopped at the foot of the steps. + +“Hello!” they cried together. “Sorry you didn’t win.” + +That was for the golf tournament. She had lost in the finals the week +before. + +“You don’t know who we are,” said one of the girls in yellow, “but we +met you here about a month ago.” + +“You’ve dyed your hair since then,” remarked Jordan, and I started, +but the girls had moved casually on and her remark was addressed to +the premature moon, produced like the supper, no doubt, out of a +caterer’s basket. With Jordan’s slender golden arm resting in mine, we +descended the steps and sauntered about the garden. A tray of +cocktails floated at us through the twilight, and we sat down at a +table with the two girls in yellow and three men, each one introduced +to us as Mr. Mumble. + +“Do you come to these parties often?” inquired Jordan of the girl +beside her. + +“The last one was the one I met you at,” answered the girl, in an +alert confident voice. She turned to her companion: “Wasn’t it for +you, Lucille?” + +It was for Lucille, too. + +“I like to come,” Lucille said. “I never care what I do, so I always +have a good time. When I was here last I tore my gown on a chair, and +he asked me my name and address—inside of a week I got a package from +Croirier’s with a new evening gown in it.” + +“Did you keep it?” asked Jordan. + +“Sure I did. I was going to wear it tonight, but it was too big in the +bust and had to be altered. It was gas blue with lavender beads. Two +hundred and sixty-five dollars.” + +“There’s something funny about a fellow that’ll do a thing like that,” +said the other girl eagerly. “He doesn’t want any trouble with +anybody.” + +“Who doesn’t?” I inquired. + +“Gatsby. Somebody told me—” + +The two girls and Jordan leaned together confidentially. + +“Somebody told me they thought he killed a man once.” + +A thrill passed over all of us. The three Mr. Mumbles bent forward and +listened eagerly. + +“I don’t think it’s so much that,” argued Lucille sceptically; “It’s +more that he was a German spy during the war.” + +One of the men nodded in confirmation. + +“I heard that from a man who knew all about him, grew up with him in +Germany,” he assured us positively. + +“Oh, no,” said the first girl, “it couldn’t be that, because he was in +the American army during the war.” As our credulity switched back to +her she leaned forward with enthusiasm. “You look at him sometimes +when he thinks nobody’s looking at him. I’ll bet he killed a man.” + +She narrowed her eyes and shivered. Lucille shivered. We all turned +and looked around for Gatsby. It was testimony to the romantic +speculation he inspired that there were whispers about him from those +who had found little that it was necessary to whisper about in this +world. + +The first supper—there would be another one after midnight—was now +being served, and Jordan invited me to join her own party, who were +spread around a table on the other side of the garden. There were +three married couples and Jordan’s escort, a persistent undergraduate +given to violent innuendo, and obviously under the impression that +sooner or later Jordan was going to yield him up her person to a +greater or lesser degree. Instead of rambling, this party had +preserved a dignified homogeneity, and assumed to itself the function +of representing the staid nobility of the countryside—East Egg +condescending to West Egg and carefully on guard against its +spectroscopic gaiety. + +“Let’s get out,” whispered Jordan, after a somehow wasteful and +inappropriate half-hour; “this is much too polite for me.” + +We got up, and she explained that we were going to find the host: I +had never met him, she said, and it was making me uneasy. The +undergraduate nodded in a cynical, melancholy way. + +The bar, where we glanced first, was crowded, but Gatsby was not +there. She couldn’t find him from the top of the steps, and he wasn’t +on the veranda. On a chance we tried an important-looking door, and +walked into a high Gothic library, panelled with carved English oak, +and probably transported complete from some ruin overseas. + +A stout, middle-aged man, with enormous owl-eyed spectacles, was +sitting somewhat drunk on the edge of a great table, staring with +unsteady concentration at the shelves of books. As we entered he +wheeled excitedly around and examined Jordan from head to foot. + +“What do you think?” he demanded impetuously. + +“About what?” + +He waved his hand toward the bookshelves. + +“About that. As a matter of fact you needn’t bother to ascertain. I +ascertained. They’re real.” + +“The books?” + +He nodded. + +“Absolutely real—have pages and everything. I thought they’d be a nice +durable cardboard. Matter of fact, they’re absolutely real. Pages +and—Here! Lemme show you.” + +Taking our scepticism for granted, he rushed to the bookcases and +returned with Volume One of the Stoddard Lectures. + +“See!” he cried triumphantly. “It’s a bona-fide piece of printed +matter. It fooled me. This fella’s a regular Belasco. It’s a +triumph. What thoroughness! What realism! Knew when to stop, +too—didn’t cut the pages. But what do you want? What do you expect?” + +He snatched the book from me and replaced it hastily on its shelf, +muttering that if one brick was removed the whole library was liable +to collapse. + +“Who brought you?” he demanded. “Or did you just come? I was brought. +Most people were brought.” + +Jordan looked at him alertly, cheerfully, without answering. + +“I was brought by a woman named Roosevelt,” he continued. “Mrs. Claud +Roosevelt. Do you know her? I met her somewhere last night. I’ve been +drunk for about a week now, and I thought it might sober me up to sit +in a library.” + +“Has it?” + +“A little bit, I think. I can’t tell yet. I’ve only been here an hour. +Did I tell you about the books? They’re real. They’re—” + +“You told us.” + +We shook hands with him gravely and went back outdoors. + +There was dancing now on the canvas in the garden; old men pushing +young girls backward in eternal graceless circles, superior couples +holding each other tortuously, fashionably, and keeping in the +corners—and a great number of single girls dancing individually or +relieving the orchestra for a moment of the burden of the banjo or the +traps. By midnight the hilarity had increased. A celebrated tenor had +sung in Italian, and a notorious contralto had sung in jazz, and +between the numbers people were doing “stunts” all over the garden, +while happy, vacuous bursts of laughter rose toward the summer sky. A +pair of stage twins, who turned out to be the girls in yellow, did a +baby act in costume, and champagne was served in glasses bigger than +finger-bowls. The moon had risen higher, and floating in the Sound was +a triangle of silver scales, trembling a little to the stiff, tinny +drip of the banjoes on the lawn. + +I was still with Jordan Baker. We were sitting at a table with a man +of about my age and a rowdy little girl, who gave way upon the +slightest provocation to uncontrollable laughter. I was enjoying +myself now. I had taken two finger-bowls of champagne, and the scene +had changed before my eyes into something significant, elemental, and +profound. + +At a lull in the entertainment the man looked at me and smiled. + +“Your face is familiar,” he said politely. “Weren’t you in the First +Division during the war?” + +“Why yes. I was in the Twenty-eighth Infantry.” + +“I was in the Sixteenth until June nineteen-eighteen. I knew I’d seen +you somewhere before.” + +We talked for a moment about some wet, grey little villages in France. +Evidently he lived in this vicinity, for he told me that he had just +bought a hydroplane, and was going to try it out in the morning. + +“Want to go with me, old sport? Just near the shore along the Sound.” + +“What time?” + +“Any time that suits you best.” + +It was on the tip of my tongue to ask his name when Jordan looked +around and smiled. + +“Having a gay time now?” she inquired. + +“Much better.” I turned again to my new acquaintance. “This is an +unusual party for me. I haven’t even seen the host. I live over +there—” I waved my hand at the invisible hedge in the distance, “and +this man Gatsby sent over his chauffeur with an invitation.” + +For a moment he looked at me as if he failed to understand. + +“I’m Gatsby,” he said suddenly. + +“What!” I exclaimed. “Oh, I beg your pardon.” + +“I thought you knew, old sport. I’m afraid I’m not a very good host.” + +He smiled understandingly—much more than understandingly. It was one +of those rare smiles with a quality of eternal reassurance in it, that +you may come across four or five times in life. It faced—or seemed to +face—the whole eternal world for an instant, and then concentrated on +you with an irresistible prejudice in your favour. It understood you +just so far as you wanted to be understood, believed in you as you +would like to believe in yourself, and assured you that it had +precisely the impression of you that, at your best, you hoped to +convey. Precisely at that point it vanished—and I was looking at an +elegant young roughneck, a year or two over thirty, whose elaborate +formality of speech just missed being absurd. Some time before he +introduced himself I’d got a strong impression that he was picking his +words with care. + +Almost at the moment when Mr. Gatsby identified himself a butler +hurried toward him with the information that Chicago was calling him +on the wire. He excused himself with a small bow that included each of +us in turn. + +“If you want anything just ask for it, old sport,” he urged me. +“Excuse me. I will rejoin you later.” + +When he was gone I turned immediately to Jordan—constrained to assure +her of my surprise. I had expected that Mr. Gatsby would be a florid +and corpulent person in his middle years. + +“Who is he?” I demanded. “Do you know?” + +“He’s just a man named Gatsby.” + +“Where is he from, I mean? And what does he do?” + +“Now you’re started on the subject,” she answered with a wan smile. +“Well, he told me once he was an Oxford man.” + +A dim background started to take shape behind him, but at her next +remark it faded away. + +“However, I don’t believe it.” + +“Why not?” + +“I don’t know,” she insisted, “I just don’t think he went there.” + +Something in her tone reminded me of the other girl’s “I think he +killed a man,” and had the effect of stimulating my curiosity. I would +have accepted without question the information that Gatsby sprang from +the swamps of Louisiana or from the lower East Side of New York. That +was comprehensible. But young men didn’t—at least in my provincial +inexperience I believed they didn’t—drift coolly out of nowhere and +buy a palace on Long Island Sound. + +“Anyhow, he gives large parties,” said Jordan, changing the subject +with an urban distaste for the concrete. “And I like large parties. +They’re so intimate. At small parties there isn’t any privacy.” + +There was the boom of a bass drum, and the voice of the orchestra +leader rang out suddenly above the echolalia of the garden. + +“Ladies and gentlemen,” he cried. “At the request of Mr. Gatsby we are +going to play for you Mr. Vladmir Tostoff’s latest work, which +attracted so much attention at Carnegie Hall last May. If you read the +papers you know there was a big sensation.” He smiled with jovial +condescension, and added: “Some sensation!” Whereupon everybody +laughed. + +“The piece is known,” he concluded lustily, “as ‘Vladmir Tostoff’s +Jazz History of the World!’ ” + +The nature of Mr. Tostoff’s composition eluded me, because just as it +began my eyes fell on Gatsby, standing alone on the marble steps and +looking from one group to another with approving eyes. His tanned skin +was drawn attractively tight on his face and his short hair looked as +though it were trimmed every day. I could see nothing sinister about +him. I wondered if the fact that he was not drinking helped to set him +off from his guests, for it seemed to me that he grew more correct as +the fraternal hilarity increased. When the “Jazz History of the World” +was over, girls were putting their heads on men’s shoulders in a +puppyish, convivial way, girls were swooning backward playfully into +men’s arms, even into groups, knowing that someone would arrest their +falls—but no one swooned backward on Gatsby, and no French bob touched +Gatsby’s shoulder, and no singing quartets were formed with Gatsby’s +head for one link. + +“I beg your pardon.” + +Gatsby’s butler was suddenly standing beside us. + +“Miss Baker?” he inquired. “I beg your pardon, but Mr. Gatsby would +like to speak to you alone.” + +“With me?” she exclaimed in surprise. + +“Yes, madame.” + +She got up slowly, raising her eyebrows at me in astonishment, and +followed the butler toward the house. I noticed that she wore her +evening-dress, all her dresses, like sports clothes—there was a +jauntiness about her movements as if she had first learned to walk +upon golf courses on clean, crisp mornings. + +I was alone and it was almost two. For some time confused and +intriguing sounds had issued from a long, many-windowed room which +overhung the terrace. Eluding Jordan’s undergraduate, who was now +engaged in an obstetrical conversation with two chorus girls, and who +implored me to join him, I went inside. + +The large room was full of people. One of the girls in yellow was +playing the piano, and beside her stood a tall, red-haired young lady +from a famous chorus, engaged in song. She had drunk a quantity of +champagne, and during the course of her song she had decided, ineptly, +that everything was very, very sad—she was not only singing, she was +weeping too. Whenever there was a pause in the song she filled it with +gasping, broken sobs, and then took up the lyric again in a quavering +soprano. The tears coursed down her cheeks—not freely, however, for +when they came into contact with her heavily beaded eyelashes they +assumed an inky colour, and pursued the rest of their way in slow +black rivulets. A humorous suggestion was made that she sing the notes +on her face, whereupon she threw up her hands, sank into a chair, and +went off into a deep vinous sleep. + +“She had a fight with a man who says he’s her husband,” explained a +girl at my elbow. + +I looked around. Most of the remaining women were now having fights +with men said to be their husbands. Even Jordan’s party, the quartet +from East Egg, were rent asunder by dissension. One of the men was +talking with curious intensity to a young actress, and his wife, after +attempting to laugh at the situation in a dignified and indifferent +way, broke down entirely and resorted to flank attacks—at intervals +she appeared suddenly at his side like an angry diamond, and hissed: +“You promised!” into his ear. + +The reluctance to go home was not confined to wayward men. The hall +was at present occupied by two deplorably sober men and their highly +indignant wives. The wives were sympathizing with each other in +slightly raised voices. + +“Whenever he sees I’m having a good time he wants to go home.” + +“Never heard anything so selfish in my life.” + +“We’re always the first ones to leave.” + +“So are we.” + +“Well, we’re almost the last tonight,” said one of the men sheepishly. +“The orchestra left half an hour ago.” + +In spite of the wives’ agreement that such malevolence was beyond +credibility, the dispute ended in a short struggle, and both wives +were lifted, kicking, into the night. + +As I waited for my hat in the hall the door of the library opened and +Jordan Baker and Gatsby came out together. He was saying some last +word to her, but the eagerness in his manner tightened abruptly into +formality as several people approached him to say goodbye. + +Jordan’s party were calling impatiently to her from the porch, but she +lingered for a moment to shake hands. + +“I’ve just heard the most amazing thing,” she whispered. “How long +were we in there?” + +“Why, about an hour.” + +“It was … simply amazing,” she repeated abstractedly. “But I swore I +wouldn’t tell it and here I am tantalizing you.” She yawned gracefully +in my face. “Please come and see me … Phone book … Under the name of +Mrs. Sigourney Howard … My aunt …” She was hurrying off as she +talked—her brown hand waved a jaunty salute as she melted into her +party at the door. + +Rather ashamed that on my first appearance I had stayed so late, I +joined the last of Gatsby’s guests, who were clustered around him. I +wanted to explain that I’d hunted for him early in the evening and to +apologize for not having known him in the garden. + +“Don’t mention it,” he enjoined me eagerly. “Don’t give it another +thought, old sport.” The familiar expression held no more familiarity +than the hand which reassuringly brushed my shoulder. “And don’t +forget we’re going up in the hydroplane tomorrow morning, at nine +o’clock.” + +Then the butler, behind his shoulder: + +“Philadelphia wants you on the phone, sir.” + +“All right, in a minute. Tell them I’ll be right there … Good night.” + +“Good night.” + +“Good night.” He smiled—and suddenly there seemed to be a pleasant +significance in having been among the last to go, as if he had desired +it all the time. “Good night, old sport … Good night.” + +But as I walked down the steps I saw that the evening was not quite +over. Fifty feet from the door a dozen headlights illuminated a +bizarre and tumultuous scene. In the ditch beside the road, right side +up, but violently shorn of one wheel, rested a new coupé which had +left Gatsby’s drive not two minutes before. The sharp jut of a wall +accounted for the detachment of the wheel, which was now getting +considerable attention from half a dozen curious chauffeurs. However, +as they had left their cars blocking the road, a harsh, discordant din +from those in the rear had been audible for some time, and added to +the already violent confusion of the scene. + +A man in a long duster had dismounted from the wreck and now stood in +the middle of the road, looking from the car to the tyre and from the +tyre to the observers in a pleasant, puzzled way. + +“See!” he explained. “It went in the ditch.” + +The fact was infinitely astonishing to him, and I recognized first the +unusual quality of wonder, and then the man—it was the late patron of +Gatsby’s library. + +“How’d it happen?” + +He shrugged his shoulders. + +“I know nothing whatever about mechanics,” he said decisively. + +“But how did it happen? Did you run into the wall?” + +“Don’t ask me,” said Owl Eyes, washing his hands of the whole +matter. “I know very little about driving—next to nothing. It +happened, and that’s all I know.” + +“Well, if you’re a poor driver you oughtn’t to try driving at night.” + +“But I wasn’t even trying,” he explained indignantly, “I wasn’t even +trying.” + +An awed hush fell upon the bystanders. + +“Do you want to commit suicide?” + +“You’re lucky it was just a wheel! A bad driver and not even trying!” + +“You don’t understand,” explained the criminal. “I wasn’t driving. +There’s another man in the car.” + +The shock that followed this declaration found voice in a sustained +“Ah-h-h!” as the door of the coupé swung slowly open. The crowd—it was +now a crowd—stepped back involuntarily, and when the door had opened +wide there was a ghostly pause. Then, very gradually, part by part, a +pale, dangling individual stepped out of the wreck, pawing tentatively +at the ground with a large uncertain dancing shoe. + +Blinded by the glare of the headlights and confused by the incessant +groaning of the horns, the apparition stood swaying for a moment +before he perceived the man in the duster. + +“Wha’s matter?” he inquired calmly. “Did we run outa gas?” + +“Look!” + +Half a dozen fingers pointed at the amputated wheel—he stared at it +for a moment, and then looked upward as though he suspected that it +had dropped from the sky. + +“It came off,” someone explained. + +He nodded. + +“At first I din’ notice we’d stopped.” + +A pause. Then, taking a long breath and straightening his shoulders, +he remarked in a determined voice: + +“Wonder’ff tell me where there’s a gas’line station?” + +At least a dozen men, some of them a little better off than he was, +explained to him that wheel and car were no longer joined by any +physical bond. + +“Back out,” he suggested after a moment. “Put her in reverse.” + +“But the wheel’s off!” + +He hesitated. + +“No harm in trying,” he said. + +The caterwauling horns had reached a crescendo and I turned away and +cut across the lawn toward home. I glanced back once. A wafer of a +moon was shining over Gatsby’s house, making the night fine as before, +and surviving the laughter and the sound of his still glowing garden. +A sudden emptiness seemed to flow now from the windows and the great +doors, endowing with complete isolation the figure of the host, who +stood on the porch, his hand up in a formal gesture of farewell. + +------------------------------------------------------------------------ + +Reading over what I have written so far, I see I have given the +impression that the events of three nights several weeks apart were +all that absorbed me. On the contrary, they were merely casual events +in a crowded summer, and, until much later, they absorbed me +infinitely less than my personal affairs. + +Most of the time I worked. In the early morning the sun threw my +shadow westward as I hurried down the white chasms of lower New York +to the Probity Trust. I knew the other clerks and young bond-salesmen +by their first names, and lunched with them in dark, crowded +restaurants on little pig sausages and mashed potatoes and coffee. I +even had a short affair with a girl who lived in Jersey City and +worked in the accounting department, but her brother began throwing +mean looks in my direction, so when she went on her vacation in July I +let it blow quietly away. + +I took dinner usually at the Yale Club—for some reason it was the +gloomiest event of my day—and then I went upstairs to the library and +studied investments and securities for a conscientious hour. There +were generally a few rioters around, but they never came into the +library, so it was a good place to work. After that, if the night was +mellow, I strolled down Madison Avenue past the old Murray Hill Hotel, +and over 33rd Street to the Pennsylvania Station. + +I began to like New York, the racy, adventurous feel of it at night, +and the satisfaction that the constant flicker of men and women and +machines gives to the restless eye. I liked to walk up Fifth Avenue +and pick out romantic women from the crowd and imagine that in a few +minutes I was going to enter into their lives, and no one would ever +know or disapprove. Sometimes, in my mind, I followed them to their +apartments on the corners of hidden streets, and they turned and +smiled back at me before they faded through a door into warm +darkness. At the enchanted metropolitan twilight I felt a haunting +loneliness sometimes, and felt it in others—poor young clerks who +loitered in front of windows waiting until it was time for a solitary +restaurant dinner—young clerks in the dusk, wasting the most poignant +moments of night and life. + +Again at eight o’clock, when the dark lanes of the Forties were lined +five deep with throbbing taxicabs, bound for the theatre district, I +felt a sinking in my heart. Forms leaned together in the taxis as they +waited, and voices sang, and there was laughter from unheard jokes, +and lighted cigarettes made unintelligible circles inside. Imagining +that I, too, was hurrying towards gaiety and sharing their intimate +excitement, I wished them well. + +For a while I lost sight of Jordan Baker, and then in midsummer I +found her again. At first I was flattered to go places with her, +because she was a golf champion, and everyone knew her name. Then it +was something more. I wasn’t actually in love, but I felt a sort of +tender curiosity. The bored haughty face that she turned to the world +concealed something—most affectations conceal something eventually, +even though they don’t in the beginning—and one day I found what it +was. When we were on a house-party together up in Warwick, she left a +borrowed car out in the rain with the top down, and then lied about +it—and suddenly I remembered the story about her that had eluded me +that night at Daisy’s. At her first big golf tournament there was a +row that nearly reached the newspapers—a suggestion that she had moved +her ball from a bad lie in the semifinal round. The thing approached +the proportions of a scandal—then died away. A caddy retracted his +statement, and the only other witness admitted that he might have been +mistaken. The incident and the name had remained together in my mind. + +Jordan Baker instinctively avoided clever, shrewd men, and now I saw +that this was because she felt safer on a plane where any divergence +from a code would be thought impossible. She was incurably dishonest. +She wasn’t able to endure being at a disadvantage and, given this +unwillingness, I suppose she had begun dealing in subterfuges when she +was very young in order to keep that cool, insolent smile turned to +the world and yet satisfy the demands of her hard, jaunty body. + +It made no difference to me. Dishonesty in a woman is a thing you +never blame deeply—I was casually sorry, and then I forgot. It was on +that same house-party that we had a curious conversation about driving +a car. It started because she passed so close to some workmen that our +fender flicked a button on one man’s coat. + +“You’re a rotten driver,” I protested. “Either you ought to be more +careful, or you oughtn’t to drive at all.” + +“I am careful.” + +“No, you’re not.” + +“Well, other people are,” she said lightly. + +“What’s that got to do with it?” + +“They’ll keep out of my way,” she insisted. “It takes two to make an +accident.” + +“Suppose you met somebody just as careless as yourself.” + +“I hope I never will,” she answered. “I hate careless people. That’s +why I like you.” + +Her grey, sun-strained eyes stared straight ahead, but she had +deliberately shifted our relations, and for a moment I thought I loved +her. But I am slow-thinking and full of interior rules that act as +brakes on my desires, and I knew that first I had to get myself +definitely out of that tangle back home. I’d been writing letters once +a week and signing them: “Love, Nick,” and all I could think of was +how, when that certain girl played tennis, a faint moustache of +perspiration appeared on her upper lip. Nevertheless there was a vague +understanding that had to be tactfully broken off before I was free. + +Everyone suspects himself of at least one of the cardinal virtues, and +this is mine: I am one of the few honest people that I have ever +known. + + + IV + +On Sunday morning while church bells rang in the villages alongshore, +the world and its mistress returned to Gatsby’s house and twinkled +hilariously on his lawn. + +“He’s a bootlegger,” said the young ladies, moving somewhere between +his cocktails and his flowers. “One time he killed a man who had found +out that he was nephew to Von Hindenburg and second cousin to the +devil. Reach me a rose, honey, and pour me a last drop into that there +crystal glass.” + +Once I wrote down on the empty spaces of a timetable the names of +those who came to Gatsby’s house that summer. It is an old timetable +now, disintegrating at its folds, and headed “This schedule in effect +July 5th, 1922.” But I can still read the grey names, and they will +give you a better impression than my generalities of those who +accepted Gatsby’s hospitality and paid him the subtle tribute of +knowing nothing whatever about him. + +From East Egg, then, came the Chester Beckers and the Leeches, and a +man named Bunsen, whom I knew at Yale, and Doctor Webster Civet, who +was drowned last summer up in Maine. And the Hornbeams and the Willie +Voltaires, and a whole clan named Blackbuck, who always gathered in a +corner and flipped up their noses like goats at whosoever came +near. And the Ismays and the Chrysties (or rather Hubert Auerbach and +Mr. Chrystie’s wife), and Edgar Beaver, whose hair, they say, turned +cotton-white one winter afternoon for no good reason at all. + +Clarence Endive was from East Egg, as I remember. He came only once, +in white knickerbockers, and had a fight with a bum named Etty in the +garden. From farther out on the Island came the Cheadles and the O. +R. P. Schraeders, and the Stonewall Jackson Abrams of Georgia, and the +Fishguards and the Ripley Snells. Snell was there three days before he +went to the penitentiary, so drunk out on the gravel drive that +Mrs. Ulysses Swett’s automobile ran over his right hand. The Dancies +came, too, and S. B. Whitebait, who was well over sixty, and Maurice +A. Flink, and the Hammerheads, and Beluga the tobacco importer, and +Beluga’s girls. + +From West Egg came the Poles and the Mulreadys and Cecil Roebuck and +Cecil Schoen and Gulick the State senator and Newton Orchid, who +controlled Films Par Excellence, and Eckhaust and Clyde Cohen and Don +S. Schwartz (the son) and Arthur McCarty, all connected with the +movies in one way or another. And the Catlips and the Bembergs and G. +Earl Muldoon, brother to that Muldoon who afterward strangled his +wife. Da Fontano the promoter came there, and Ed Legros and James B. +(“Rot-Gut”) Ferret and the De Jongs and Ernest Lilly—they came to +gamble, and when Ferret wandered into the garden it meant he was +cleaned out and Associated Traction would have to fluctuate profitably +next day. + +A man named Klipspringer was there so often that he became known as +“the boarder”—I doubt if he had any other home. Of theatrical people +there were Gus Waize and Horace O’Donavan and Lester Myer and George +Duckweed and Francis Bull. Also from New York were the Chromes and the +Backhyssons and the Dennickers and Russel Betty and the Corrigans and +the Kellehers and the Dewars and the Scullys and S. W. Belcher and the +Smirkes and the young Quinns, divorced now, and Henry L. Palmetto, who +killed himself by jumping in front of a subway train in Times Square. + +Benny McClenahan arrived always with four girls. They were never quite +the same ones in physical person, but they were so identical one with +another that it inevitably seemed they had been there before. I have +forgotten their names—Jaqueline, I think, or else Consuela, or Gloria +or Judy or June, and their last names were either the melodious names +of flowers and months or the sterner ones of the great American +capitalists whose cousins, if pressed, they would confess themselves +to be. + +In addition to all these I can remember that Faustina O’Brien came +there at least once and the Baedeker girls and young Brewer, who had +his nose shot off in the war, and Mr. Albrucksburger and Miss Haag, +his fiancée, and Ardita Fitz-Peters and Mr. P. Jewett, once head of +the American Legion, and Miss Claudia Hip, with a man reputed to be +her chauffeur, and a prince of something, whom we called Duke, and +whose name, if I ever knew it, I have forgotten. + +All these people came to Gatsby’s house in the summer. + +------------------------------------------------------------------------ + +At nine o’clock, one morning late in July, Gatsby’s gorgeous car +lurched up the rocky drive to my door and gave out a burst of melody +from its three-noted horn. + +It was the first time he had called on me, though I had gone to two of +his parties, mounted in his hydroplane, and, at his urgent invitation, +made frequent use of his beach. + +“Good morning, old sport. You’re having lunch with me today and I +thought we’d ride up together.” + +He was balancing himself on the dashboard of his car with that +resourcefulness of movement that is so peculiarly American—that comes, +I suppose, with the absence of lifting work in youth and, even more, +with the formless grace of our nervous, sporadic games. This quality +was continually breaking through his punctilious manner in the shape +of restlessness. He was never quite still; there was always a tapping +foot somewhere or the impatient opening and closing of a hand. + +He saw me looking with admiration at his car. + +“It’s pretty, isn’t it, old sport?” He jumped off to give me a better +view. “Haven’t you ever seen it before?” + +I’d seen it. Everybody had seen it. It was a rich cream colour, bright +with nickel, swollen here and there in its monstrous length with +triumphant hatboxes and supper-boxes and toolboxes, and terraced with +a labyrinth of windshields that mirrored a dozen suns. Sitting down +behind many layers of glass in a sort of green leather conservatory, +we started to town. + +I had talked with him perhaps half a dozen times in the past month and +found, to my disappointment, that he had little to say. So my first +impression, that he was a person of some undefined consequence, had +gradually faded and he had become simply the proprietor of an +elaborate roadhouse next door. + +And then came that disconcerting ride. We hadn’t reached West Egg +village before Gatsby began leaving his elegant sentences unfinished +and slapping himself indecisively on the knee of his caramel-coloured +suit. + +“Look here, old sport,” he broke out surprisingly, “what’s your +opinion of me, anyhow?” + +A little overwhelmed, I began the generalized evasions which that +question deserves. + +“Well, I’m going to tell you something about my life,” he interrupted. +“I don’t want you to get a wrong idea of me from all these stories you +hear.” + +So he was aware of the bizarre accusations that flavoured conversation +in his halls. + +“I’ll tell you God’s truth.” His right hand suddenly ordered divine +retribution to stand by. “I am the son of some wealthy people in the +Middle West—all dead now. I was brought up in America but educated at +Oxford, because all my ancestors have been educated there for many +years. It is a family tradition.” + +He looked at me sideways—and I knew why Jordan Baker had believed he +was lying. He hurried the phrase “educated at Oxford,” or swallowed +it, or choked on it, as though it had bothered him before. And with +this doubt, his whole statement fell to pieces, and I wondered if +there wasn’t something a little sinister about him, after all. + +“What part of the Middle West?” I inquired casually. + +“San Francisco.” + +“I see.” + +“My family all died and I came into a good deal of money.” + +His voice was solemn, as if the memory of that sudden extinction of a +clan still haunted him. For a moment I suspected that he was pulling +my leg, but a glance at him convinced me otherwise. + +“After that I lived like a young rajah in all the capitals of +Europe—Paris, Venice, Rome—collecting jewels, chiefly rubies, hunting +big game, painting a little, things for myself only, and trying to +forget something very sad that had happened to me long ago.” + +With an effort I managed to restrain my incredulous laughter. The very +phrases were worn so threadbare that they evoked no image except that +of a turbaned “character” leaking sawdust at every pore as he pursued +a tiger through the Bois de Boulogne. + +“Then came the war, old sport. It was a great relief, and I tried very +hard to die, but I seemed to bear an enchanted life. I accepted a +commission as first lieutenant when it began. In the Argonne Forest I +took the remains of my machine-gun battalion so far forward that there +was a half mile gap on either side of us where the infantry couldn’t +advance. We stayed there two days and two nights, a hundred and thirty +men with sixteen Lewis guns, and when the infantry came up at last +they found the insignia of three German divisions among the piles of +dead. I was promoted to be a major, and every Allied government gave +me a decoration—even Montenegro, little Montenegro down on the +Adriatic Sea!” + +Little Montenegro! He lifted up the words and nodded at them—with his +smile. The smile comprehended Montenegro’s troubled history and +sympathized with the brave struggles of the Montenegrin people. It +appreciated fully the chain of national circumstances which had +elicited this tribute from Montenegro’s warm little heart. My +incredulity was submerged in fascination now; it was like skimming +hastily through a dozen magazines. + +He reached in his pocket, and a piece of metal, slung on a ribbon, +fell into my palm. + +“That’s the one from Montenegro.” + +To my astonishment, the thing had an authentic look. “Orderi di +Danilo,” ran the circular legend, “Montenegro, Nicolas Rex.” + +“Turn it.” + +“Major Jay Gatsby,” I read, “For Valour Extraordinary.” + +“Here’s another thing I always carry. A souvenir of Oxford days. It +was taken in Trinity Quad—the man on my left is now the Earl of +Doncaster.” + +It was a photograph of half a dozen young men in blazers loafing in an +archway through which were visible a host of spires. There was Gatsby, +looking a little, not much, younger—with a cricket bat in his hand. + +Then it was all true. I saw the skins of tigers flaming in his palace +on the Grand Canal; I saw him opening a chest of rubies to ease, with +their crimson-lighted depths, the gnawings of his broken heart. + +“I’m going to make a big request of you today,” he said, pocketing his +souvenirs with satisfaction, “so I thought you ought to know something +about me. I didn’t want you to think I was just some nobody. You see, +I usually find myself among strangers because I drift here and there +trying to forget the sad things that happened to me.” He hesitated. +“You’ll hear about it this afternoon.” + +“At lunch?” + +“No, this afternoon. I happened to find out that you’re taking Miss +Baker to tea.” + +“Do you mean you’re in love with Miss Baker?” + +“No, old sport, I’m not. But Miss Baker has kindly consented to speak +to you about this matter.” + +I hadn’t the faintest idea what “this matter” was, but I was more +annoyed than interested. I hadn’t asked Jordan to tea in order to +discuss Mr. Jay Gatsby. I was sure the request would be something +utterly fantastic, and for a moment I was sorry I’d ever set foot upon +his overpopulated lawn. + +He wouldn’t say another word. His correctness grew on him as we neared +the city. We passed Port Roosevelt, where there was a glimpse of +red-belted oceangoing ships, and sped along a cobbled slum lined with +the dark, undeserted saloons of the faded-gilt nineteen-hundreds. +Then the valley of ashes opened out on both sides of us, and I had a +glimpse of Mrs. Wilson straining at the garage pump with panting +vitality as we went by. + +With fenders spread like wings we scattered light through half +Astoria—only half, for as we twisted among the pillars of the elevated +I heard the familiar “jug-jug-spat!” of a motorcycle, and a frantic +policeman rode alongside. + +“All right, old sport,” called Gatsby. We slowed down. Taking a white +card from his wallet, he waved it before the man’s eyes. + +“Right you are,” agreed the policeman, tipping his cap. “Know you next +time, Mr. Gatsby. Excuse me!” + +“What was that?” I inquired. “The picture of Oxford?” + +“I was able to do the commissioner a favour once, and he sends me a +Christmas card every year.” + +Over the great bridge, with the sunlight through the girders making a +constant flicker upon the moving cars, with the city rising up across +the river in white heaps and sugar lumps all built with a wish out of +nonolfactory money. The city seen from the Queensboro Bridge is always +the city seen for the first time, in its first wild promise of all the +mystery and the beauty in the world. + +A dead man passed us in a hearse heaped with blooms, followed by two +carriages with drawn blinds, and by more cheerful carriages for +friends. The friends looked out at us with the tragic eyes and short +upper lips of southeastern Europe, and I was glad that the sight of +Gatsby’s splendid car was included in their sombre holiday. As we +crossed Blackwell’s Island a limousine passed us, driven by a white +chauffeur, in which sat three modish negroes, two bucks and a girl. I +laughed aloud as the yolks of their eyeballs rolled toward us in +haughty rivalry. + +“Anything can happen now that we’ve slid over this bridge,” I thought; +“anything at all …” + +Even Gatsby could happen, without any particular wonder. + +------------------------------------------------------------------------ + +Roaring noon. In a well-fanned Forty-second Street cellar I met Gatsby +for lunch. Blinking away the brightness of the street outside, my eyes +picked him out obscurely in the anteroom, talking to another man. + +“Mr. Carraway, this is my friend Mr. Wolfshiem.” + +A small, flat-nosed Jew raised his large head and regarded me with two +fine growths of hair which luxuriated in either nostril. After a +moment I discovered his tiny eyes in the half-darkness. + +“—So I took one look at him,” said Mr. Wolfshiem, shaking my hand +earnestly, “and what do you think I did?” + +“What?” I inquired politely. + +But evidently he was not addressing me, for he dropped my hand and +covered Gatsby with his expressive nose. + +“I handed the money to Katspaugh and I said: ‘All right, Katspaugh, +don’t pay him a penny till he shuts his mouth.’ He shut it then and +there.” + +Gatsby took an arm of each of us and moved forward into the +restaurant, whereupon Mr. Wolfshiem swallowed a new sentence he was +starting and lapsed into a somnambulatory abstraction. + +“Highballs?” asked the head waiter. + +“This is a nice restaurant here,” said Mr. Wolfshiem, looking at the +presbyterian nymphs on the ceiling. “But I like across the street +better!” + +“Yes, highballs,” agreed Gatsby, and then to Mr. Wolfshiem: “It’s too +hot over there.” + +“Hot and small—yes,” said Mr. Wolfshiem, “but full of memories.” + +“What place is that?” I asked. + +“The old Metropole.” + +“The old Metropole,” brooded Mr. Wolfshiem gloomily. “Filled with +faces dead and gone. Filled with friends gone now forever. I can’t +forget so long as I live the night they shot Rosy Rosenthal there. It +was six of us at the table, and Rosy had eat and drunk a lot all +evening. When it was almost morning the waiter came up to him with a +funny look and says somebody wants to speak to him outside. ‘All +right,’ says Rosy, and begins to get up, and I pulled him down in his +chair. + +“ ‘Let the bastards come in here if they want you, Rosy, but don’t +you, so help me, move outside this room.’ + +“It was four o’clock in the morning then, and if we’d of raised the +blinds we’d of seen daylight.” + +“Did he go?” I asked innocently. + +“Sure he went.” Mr. Wolfshiem’s nose flashed at me indignantly. “He +turned around in the door and says: ‘Don’t let that waiter take away +my coffee!’ Then he went out on the sidewalk, and they shot him three +times in his full belly and drove away.” + +“Four of them were electrocuted,” I said, remembering. + +“Five, with Becker.” His nostrils turned to me in an interested way. +“I understand you’re looking for a business gonnegtion.” + +The juxtaposition of these two remarks was startling. Gatsby answered +for me: + +“Oh, no,” he exclaimed, “this isn’t the man.” + +“No?” Mr. Wolfshiem seemed disappointed. + +“This is just a friend. I told you we’d talk about that some other +time.” + +“I beg your pardon,” said Mr. Wolfshiem, “I had a wrong man.” + +A succulent hash arrived, and Mr. Wolfshiem, forgetting the more +sentimental atmosphere of the old Metropole, began to eat with +ferocious delicacy. His eyes, meanwhile, roved very slowly all around +the room—he completed the arc by turning to inspect the people +directly behind. I think that, except for my presence, he would have +taken one short glance beneath our own table. + +“Look here, old sport,” said Gatsby, leaning toward me, “I’m afraid I +made you a little angry this morning in the car.” + +There was the smile again, but this time I held out against it. + +“I don’t like mysteries,” I answered, “and I don’t understand why you +won’t come out frankly and tell me what you want. Why has it all got +to come through Miss Baker?” + +“Oh, it’s nothing underhand,” he assured me. “Miss Baker’s a great +sportswoman, you know, and she’d never do anything that wasn’t all +right.” + +Suddenly he looked at his watch, jumped up, and hurried from the room, +leaving me with Mr. Wolfshiem at the table. + +“He has to telephone,” said Mr. Wolfshiem, following him with his +eyes. “Fine fellow, isn’t he? Handsome to look at and a perfect +gentleman.” + +“Yes.” + +“He’s an Oggsford man.” + +“Oh!” + +“He went to Oggsford College in England. You know Oggsford College?” + +“I’ve heard of it.” + +“It’s one of the most famous colleges in the world.” + +“Have you known Gatsby for a long time?” I inquired. + +“Several years,” he answered in a gratified way. “I made the pleasure +of his acquaintance just after the war. But I knew I had discovered a +man of fine breeding after I talked with him an hour. I said to +myself: ‘There’s the kind of man you’d like to take home and introduce +to your mother and sister.’ ” He paused. “I see you’re looking at my +cuff buttons.” + +I hadn’t been looking at them, but I did now. They were composed of +oddly familiar pieces of ivory. + +“Finest specimens of human molars,” he informed me. + +“Well!” I inspected them. “That’s a very interesting idea.” + +“Yeah.” He flipped his sleeves up under his coat. “Yeah, Gatsby’s very +careful about women. He would never so much as look at a friend’s +wife.” + +When the subject of this instinctive trust returned to the table and +sat down Mr. Wolfshiem drank his coffee with a jerk and got to his +feet. + +“I have enjoyed my lunch,” he said, “and I’m going to run off from you +two young men before I outstay my welcome.” + +“Don’t hurry Meyer,” said Gatsby, without enthusiasm. Mr. Wolfshiem +raised his hand in a sort of benediction. + +“You’re very polite, but I belong to another generation,” he announced +solemnly. “You sit here and discuss your sports and your young ladies +and your—” He supplied an imaginary noun with another wave of his +hand. “As for me, I am fifty years old, and I won’t impose myself on +you any longer.” + +As he shook hands and turned away his tragic nose was trembling. I +wondered if I had said anything to offend him. + +“He becomes very sentimental sometimes,” explained Gatsby. “This is +one of his sentimental days. He’s quite a character around New York—a +denizen of Broadway.” + +“Who is he, anyhow, an actor?” + +“No.” + +“A dentist?” + +“Meyer Wolfshiem? No, he’s a gambler.” Gatsby hesitated, then added, +coolly: “He’s the man who fixed the World’s Series back in 1919.” + +“Fixed the World’s Series?” I repeated. + +The idea staggered me. I remembered, of course, that the World’s +Series had been fixed in 1919, but if I had thought of it at all I +would have thought of it as a thing that merely happened, the end of +some inevitable chain. It never occurred to me that one man could +start to play with the faith of fifty million people—with the +single-mindedness of a burglar blowing a safe. + +“How did he happen to do that?” I asked after a minute. + +“He just saw the opportunity.” + +“Why isn’t he in jail?” + +“They can’t get him, old sport. He’s a smart man.” + +I insisted on paying the check. As the waiter brought my change I +caught sight of Tom Buchanan across the crowded room. + +“Come along with me for a minute,” I said; “I’ve got to say hello to +someone.” + +When he saw us Tom jumped up and took half a dozen steps in our +direction. + +“Where’ve you been?” he demanded eagerly. “Daisy’s furious because you +haven’t called up.” + +“This is Mr. Gatsby, Mr. Buchanan.” + +They shook hands briefly, and a strained, unfamiliar look of +embarrassment came over Gatsby’s face. + +“How’ve you been, anyhow?” demanded Tom of me. “How’d you happen to +come up this far to eat?” + +“I’ve been having lunch with Mr. Gatsby.” + +I turned toward Mr. Gatsby, but he was no longer there. + +------------------------------------------------------------------------ + +One October day in nineteen-seventeen— + +(said Jordan Baker that afternoon, sitting up very straight on a +straight chair in the tea-garden at the Plaza Hotel) + +—I was walking along from one place to another, half on the sidewalks +and half on the lawns. I was happier on the lawns because I had on +shoes from England with rubber knobs on the soles that bit into the +soft ground. I had on a new plaid skirt also that blew a little in the +wind, and whenever this happened the red, white, and blue banners in +front of all the houses stretched out stiff and said tut-tut-tut-tut, +in a disapproving way. + +The largest of the banners and the largest of the lawns belonged to +Daisy Fay’s house. She was just eighteen, two years older than me, and +by far the most popular of all the young girls in Louisville. She +dressed in white, and had a little white roadster, and all day long +the telephone rang in her house and excited young officers from Camp +Taylor demanded the privilege of monopolizing her that +night. “Anyways, for an hour!” + +When I came opposite her house that morning her white roadster was +beside the kerb, and she was sitting in it with a lieutenant I had +never seen before. They were so engrossed in each other that she +didn’t see me until I was five feet away. + +“Hello, Jordan,” she called unexpectedly. “Please come here.” + +I was flattered that she wanted to speak to me, because of all the +older girls I admired her most. She asked me if I was going to the Red +Cross to make bandages. I was. Well, then, would I tell them that she +couldn’t come that day? The officer looked at Daisy while she was +speaking, in a way that every young girl wants to be looked at +sometime, and because it seemed romantic to me I have remembered the +incident ever since. His name was Jay Gatsby, and I didn’t lay eyes on +him again for over four years—even after I’d met him on Long Island I +didn’t realize it was the same man. + +That was nineteen-seventeen. By the next year I had a few beaux +myself, and I began to play in tournaments, so I didn’t see Daisy very +often. She went with a slightly older crowd—when she went with anyone +at all. Wild rumours were circulating about her—how her mother had +found her packing her bag one winter night to go to New York and say +goodbye to a soldier who was going overseas. She was effectually +prevented, but she wasn’t on speaking terms with her family for +several weeks. After that she didn’t play around with the soldiers any +more, but only with a few flat-footed, shortsighted young men in town, +who couldn’t get into the army at all. + +By the next autumn she was gay again, gay as ever. She had a début +after the armistice, and in February she was presumably engaged to a +man from New Orleans. In June she married Tom Buchanan of Chicago, +with more pomp and circumstance than Louisville ever knew before. He +came down with a hundred people in four private cars, and hired a +whole floor of the Muhlbach Hotel, and the day before the wedding he +gave her a string of pearls valued at three hundred and fifty thousand +dollars. + +I was a bridesmaid. I came into her room half an hour before the +bridal dinner, and found her lying on her bed as lovely as the June +night in her flowered dress—and as drunk as a monkey. She had a bottle +of Sauterne in one hand and a letter in the other. + +“ ’Gratulate me,” she muttered. “Never had a drink before, but oh how +I do enjoy it.” + +“What’s the matter, Daisy?” + +I was scared, I can tell you; I’d never seen a girl like that before. + +“Here, dearies.” She groped around in a wastebasket she had with her +on the bed and pulled out the string of pearls. “Take ’em downstairs +and give ’em back to whoever they belong to. Tell ’em all Daisy’s +change’ her mine. Say: ‘Daisy’s change’ her mine!’ ” + +She began to cry—she cried and cried. I rushed out and found her +mother’s maid, and we locked the door and got her into a cold bath. +She wouldn’t let go of the letter. She took it into the tub with her +and squeezed it up in a wet ball, and only let me leave it in the +soap-dish when she saw that it was coming to pieces like snow. + +But she didn’t say another word. We gave her spirits of ammonia and +put ice on her forehead and hooked her back into her dress, and half +an hour later, when we walked out of the room, the pearls were around +her neck and the incident was over. Next day at five o’clock she +married Tom Buchanan without so much as a shiver, and started off on a +three months’ trip to the South Seas. + +I saw them in Santa Barbara when they came back, and I thought I’d +never seen a girl so mad about her husband. If he left the room for a +minute she’d look around uneasily, and say: “Where’s Tom gone?” and +wear the most abstracted expression until she saw him coming in the +door. She used to sit on the sand with his head in her lap by the +hour, rubbing her fingers over his eyes and looking at him with +unfathomable delight. It was touching to see them together—it made you +laugh in a hushed, fascinated way. That was in August. A week after I +left Santa Barbara Tom ran into a wagon on the Ventura road one night, +and ripped a front wheel off his car. The girl who was with him got +into the papers, too, because her arm was broken—she was one of the +chambermaids in the Santa Barbara Hotel. + +The next April Daisy had her little girl, and they went to France for +a year. I saw them one spring in Cannes, and later in Deauville, and +then they came back to Chicago to settle down. Daisy was popular in +Chicago, as you know. They moved with a fast crowd, all of them young +and rich and wild, but she came out with an absolutely perfect +reputation. Perhaps because she doesn’t drink. It’s a great advantage +not to drink among hard-drinking people. You can hold your tongue and, +moreover, you can time any little irregularity of your own so that +everybody else is so blind that they don’t see or care. Perhaps Daisy +never went in for amour at all—and yet there’s something in that voice +of hers … + +Well, about six weeks ago, she heard the name Gatsby for the first +time in years. It was when I asked you—do you remember?—if you knew +Gatsby in West Egg. After you had gone home she came into my room and +woke me up, and said: “What Gatsby?” and when I described him—I was +half asleep—she said in the strangest voice that it must be the man +she used to know. It wasn’t until then that I connected this Gatsby +with the officer in her white car. + +------------------------------------------------------------------------ + +When Jordan Baker had finished telling all this we had left the Plaza +for half an hour and were driving in a victoria through Central Park. +The sun had gone down behind the tall apartments of the movie stars in +the West Fifties, and the clear voices of children, already gathered +like crickets on the grass, rose through the hot twilight: + + “I’m the Sheik of Araby. Your love belongs to me. At night when + you’re asleep Into your tent I’ll creep—” + +“It was a strange coincidence,” I said. + +“But it wasn’t a coincidence at all.” + +“Why not?” + +“Gatsby bought that house so that Daisy would be just across the bay.” + +Then it had not been merely the stars to which he had aspired on that +June night. He came alive to me, delivered suddenly from the womb of +his purposeless splendour. + +“He wants to know,” continued Jordan, “if you’ll invite Daisy to your +house some afternoon and then let him come over.” + +The modesty of the demand shook me. He had waited five years and +bought a mansion where he dispensed starlight to casual moths—so that +he could “come over” some afternoon to a stranger’s garden. + +“Did I have to know all this before he could ask such a little thing?” + +“He’s afraid, he’s waited so long. He thought you might be +offended. You see, he’s regular tough underneath it all.” + +Something worried me. + +“Why didn’t he ask you to arrange a meeting?” + +“He wants her to see his house,” she explained. “And your house is +right next door.” + +“Oh!” + +“I think he half expected her to wander into one of his parties, some +night,” went on Jordan, “but she never did. Then he began asking +people casually if they knew her, and I was the first one he found. It +was that night he sent for me at his dance, and you should have heard +the elaborate way he worked up to it. Of course, I immediately +suggested a luncheon in New York—and I thought he’d go mad: + +“ ‘I don’t want to do anything out of the way!’ he kept saying. ‘I +want to see her right next door.’ + +“When I said you were a particular friend of Tom’s, he started to +abandon the whole idea. He doesn’t know very much about Tom, though he +says he’s read a Chicago paper for years just on the chance of +catching a glimpse of Daisy’s name.” + +It was dark now, and as we dipped under a little bridge I put my arm +around Jordan’s golden shoulder and drew her toward me and asked her +to dinner. Suddenly I wasn’t thinking of Daisy and Gatsby any more, +but of this clean, hard, limited person, who dealt in universal +scepticism, and who leaned back jauntily just within the circle of my +arm. A phrase began to beat in my ears with a sort of heady +excitement: “There are only the pursued, the pursuing, the busy, and +the tired.” + +“And Daisy ought to have something in her life,” murmured Jordan to +me. + +“Does she want to see Gatsby?” + +“She’s not to know about it. Gatsby doesn’t want her to know. You’re +just supposed to invite her to tea.” + +We passed a barrier of dark trees, and then the façade of Fifty-Ninth +Street, a block of delicate pale light, beamed down into the park. +Unlike Gatsby and Tom Buchanan, I had no girl whose disembodied face +floated along the dark cornices and blinding signs, and so I drew up +the girl beside me, tightening my arms. Her wan, scornful mouth +smiled, and so I drew her up again closer, this time to my face. + + + V + +When I came home to West Egg that night I was afraid for a moment that +my house was on fire. Two o’clock and the whole corner of the +peninsula was blazing with light, which fell unreal on the shrubbery +and made thin elongating glints upon the roadside wires. Turning a +corner, I saw that it was Gatsby’s house, lit from tower to cellar. + +At first I thought it was another party, a wild rout that had resolved +itself into “hide-and-go-seek” or “sardines-in-the-box” with all the +house thrown open to the game. But there wasn’t a sound. Only wind in +the trees, which blew the wires and made the lights go off and on +again as if the house had winked into the darkness. As my taxi groaned +away I saw Gatsby walking toward me across his lawn. + +“Your place looks like the World’s Fair,” I said. + +“Does it?” He turned his eyes toward it absently. “I have been +glancing into some of the rooms. Let’s go to Coney Island, old +sport. In my car.” + +“It’s too late.” + +“Well, suppose we take a plunge in the swimming pool? I haven’t made +use of it all summer.” + +“I’ve got to go to bed.” + +“All right.” + +He waited, looking at me with suppressed eagerness. + +“I talked with Miss Baker,” I said after a moment. “I’m going to call +up Daisy tomorrow and invite her over here to tea.” + +“Oh, that’s all right,” he said carelessly. “I don’t want to put you +to any trouble.” + +“What day would suit you?” + +“What day would suit you?” he corrected me quickly. “I don’t want to +put you to any trouble, you see.” + +“How about the day after tomorrow?” + +He considered for a moment. Then, with reluctance: “I want to get the +grass cut,” he said. + +We both looked down at the grass—there was a sharp line where my +ragged lawn ended and the darker, well-kept expanse of his began. I +suspected that he meant my grass. + +“There’s another little thing,” he said uncertainly, and hesitated. + +“Would you rather put it off for a few days?” I asked. + +“Oh, it isn’t about that. At least—” He fumbled with a series of +beginnings. “Why, I thought—why, look here, old sport, you don’t make +much money, do you?” + +“Not very much.” + +This seemed to reassure him and he continued more confidently. + +“I thought you didn’t, if you’ll pardon my—you see, I carry on a +little business on the side, a sort of side line, you understand. And +I thought that if you don’t make very much—You’re selling bonds, +aren’t you, old sport?” + +“Trying to.” + +“Well, this would interest you. It wouldn’t take up much of your time +and you might pick up a nice bit of money. It happens to be a rather +confidential sort of thing.” + +I realize now that under different circumstances that conversation +might have been one of the crises of my life. But, because the offer +was obviously and tactlessly for a service to be rendered, I had no +choice except to cut him off there. + +“I’ve got my hands full,” I said. “I’m much obliged but I couldn’t +take on any more work.” + +“You wouldn’t have to do any business with Wolfshiem.” Evidently he +thought that I was shying away from the “gonnegtion” mentioned at +lunch, but I assured him he was wrong. He waited a moment longer, +hoping I’d begin a conversation, but I was too absorbed to be +responsive, so he went unwillingly home. + +The evening had made me lightheaded and happy; I think I walked into a +deep sleep as I entered my front door. So I don’t know whether or not +Gatsby went to Coney Island, or for how many hours he “glanced into +rooms” while his house blazed gaudily on. I called up Daisy from the +office next morning, and invited her to come to tea. + +“Don’t bring Tom,” I warned her. + +“What?” + +“Don’t bring Tom.” + +“Who is ‘Tom’?” she asked innocently. + +The day agreed upon was pouring rain. At eleven o’clock a man in a +raincoat, dragging a lawn-mower, tapped at my front door and said that +Mr. Gatsby had sent him over to cut my grass. This reminded me that I +had forgotten to tell my Finn to come back, so I drove into West Egg +Village to search for her among soggy whitewashed alleys and to buy +some cups and lemons and flowers. + +The flowers were unnecessary, for at two o’clock a greenhouse arrived +from Gatsby’s, with innumerable receptacles to contain it. An hour +later the front door opened nervously, and Gatsby in a white flannel +suit, silver shirt, and gold-coloured tie, hurried in. He was pale, +and there were dark signs of sleeplessness beneath his eyes. + +“Is everything all right?” he asked immediately. + +“The grass looks fine, if that’s what you mean.” + +“What grass?” he inquired blankly. “Oh, the grass in the yard.” He +looked out the window at it, but, judging from his expression, I don’t +believe he saw a thing. + +“Looks very good,” he remarked vaguely. “One of the papers said they +thought the rain would stop about four. I think it was The +Journal. Have you got everything you need in the shape of—of tea?” + +I took him into the pantry, where he looked a little reproachfully at +the Finn. Together we scrutinized the twelve lemon cakes from the +delicatessen shop. + +“Will they do?” I asked. + +“Of course, of course! They’re fine!” and he added hollowly, “… old +sport.” + +The rain cooled about half-past three to a damp mist, through which +occasional thin drops swam like dew. Gatsby looked with vacant eyes +through a copy of Clay’s Economics, starting at the Finnish tread that +shook the kitchen floor, and peering towards the bleared windows from +time to time as if a series of invisible but alarming happenings were +taking place outside. Finally he got up and informed me, in an +uncertain voice, that he was going home. + +“Why’s that?” + +“Nobody’s coming to tea. It’s too late!” He looked at his watch as if +there was some pressing demand on his time elsewhere. “I can’t wait +all day.” + +“Don’t be silly; it’s just two minutes to four.” + +He sat down miserably, as if I had pushed him, and simultaneously +there was the sound of a motor turning into my lane. We both jumped +up, and, a little harrowed myself, I went out into the yard. + +Under the dripping bare lilac-trees a large open car was coming up the +drive. It stopped. Daisy’s face, tipped sideways beneath a +three-cornered lavender hat, looked out at me with a bright ecstatic +smile. + +“Is this absolutely where you live, my dearest one?” + +The exhilarating ripple of her voice was a wild tonic in the rain. I +had to follow the sound of it for a moment, up and down, with my ear +alone, before any words came through. A damp streak of hair lay like a +dash of blue paint across her cheek, and her hand was wet with +glistening drops as I took it to help her from the car. + +“Are you in love with me,” she said low in my ear, “or why did I have +to come alone?” + +“That’s the secret of Castle Rackrent. Tell your chauffeur to go far +away and spend an hour.” + +“Come back in an hour, Ferdie.” Then in a grave murmur: “His name is +Ferdie.” + +“Does the gasoline affect his nose?” + +“I don’t think so,” she said innocently. “Why?” + +We went in. To my overwhelming surprise the living-room was deserted. + +“Well, that’s funny,” I exclaimed. + +“What’s funny?” + +She turned her head as there was a light dignified knocking at the +front door. I went out and opened it. Gatsby, pale as death, with his +hands plunged like weights in his coat pockets, was standing in a +puddle of water glaring tragically into my eyes. + +With his hands still in his coat pockets he stalked by me into the +hall, turned sharply as if he were on a wire, and disappeared into the +living-room. It wasn’t a bit funny. Aware of the loud beating of my +own heart I pulled the door to against the increasing rain. + +For half a minute there wasn’t a sound. Then from the living-room I +heard a sort of choking murmur and part of a laugh, followed by +Daisy’s voice on a clear artificial note: + +“I certainly am awfully glad to see you again.” + +A pause; it endured horribly. I had nothing to do in the hall, so I +went into the room. + +Gatsby, his hands still in his pockets, was reclining against the +mantelpiece in a strained counterfeit of perfect ease, even of +boredom. His head leaned back so far that it rested against the face +of a defunct mantelpiece clock, and from this position his distraught +eyes stared down at Daisy, who was sitting, frightened but graceful, +on the edge of a stiff chair. + +“We’ve met before,” muttered Gatsby. His eyes glanced momentarily at +me, and his lips parted with an abortive attempt at a laugh. Luckily +the clock took this moment to tilt dangerously at the pressure of his +head, whereupon he turned and caught it with trembling fingers, and +set it back in place. Then he sat down, rigidly, his elbow on the arm +of the sofa and his chin in his hand. + +“I’m sorry about the clock,” he said. + +My own face had now assumed a deep tropical burn. I couldn’t muster up +a single commonplace out of the thousand in my head. + +“It’s an old clock,” I told them idiotically. + +I think we all believed for a moment that it had smashed in pieces on +the floor. + +“We haven’t met for many years,” said Daisy, her voice as +matter-of-fact as it could ever be. + +“Five years next November.” + +The automatic quality of Gatsby’s answer set us all back at least +another minute. I had them both on their feet with the desperate +suggestion that they help me make tea in the kitchen when the demoniac +Finn brought it in on a tray. + +Amid the welcome confusion of cups and cakes a certain physical +decency established itself. Gatsby got himself into a shadow and, +while Daisy and I talked, looked conscientiously from one to the other +of us with tense, unhappy eyes. However, as calmness wasn’t an end in +itself, I made an excuse at the first possible moment, and got to my +feet. + +“Where are you going?” demanded Gatsby in immediate alarm. + +“I’ll be back.” + +“I’ve got to speak to you about something before you go.” + +He followed me wildly into the kitchen, closed the door, and +whispered: “Oh, God!” in a miserable way. + +“What’s the matter?” + +“This is a terrible mistake,” he said, shaking his head from side to +side, “a terrible, terrible mistake.” + +“You’re just embarrassed, that’s all,” and luckily I added: “Daisy’s +embarrassed too.” + +“She’s embarrassed?” he repeated incredulously. + +“Just as much as you are.” + +“Don’t talk so loud.” + +“You’re acting like a little boy,” I broke out impatiently. “Not only +that, but you’re rude. Daisy’s sitting in there all alone.” + +He raised his hand to stop my words, looked at me with unforgettable +reproach, and, opening the door cautiously, went back into the other +room. + +I walked out the back way—just as Gatsby had when he had made his +nervous circuit of the house half an hour before—and ran for a huge +black knotted tree, whose massed leaves made a fabric against the +rain. Once more it was pouring, and my irregular lawn, well-shaved by +Gatsby’s gardener, abounded in small muddy swamps and prehistoric +marshes. There was nothing to look at from under the tree except +Gatsby’s enormous house, so I stared at it, like Kant at his church +steeple, for half an hour. A brewer had built it early in the “period” +craze, a decade before, and there was a story that he’d agreed to pay +five years’ taxes on all the neighbouring cottages if the owners would +have their roofs thatched with straw. Perhaps their refusal took the +heart out of his plan to Found a Family—he went into an immediate +decline. His children sold his house with the black wreath still on +the door. Americans, while willing, even eager, to be serfs, have +always been obstinate about being peasantry. + +After half an hour, the sun shone again, and the grocer’s automobile +rounded Gatsby’s drive with the raw material for his servants’ +dinner—I felt sure he wouldn’t eat a spoonful. A maid began opening +the upper windows of his house, appeared momentarily in each, and, +leaning from the large central bay, spat meditatively into the +garden. It was time I went back. While the rain continued it had +seemed like the murmur of their voices, rising and swelling a little +now and then with gusts of emotion. But in the new silence I felt that +silence had fallen within the house too. + +I went in—after making every possible noise in the kitchen, short of +pushing over the stove—but I don’t believe they heard a sound. They +were sitting at either end of the couch, looking at each other as if +some question had been asked, or was in the air, and every vestige of +embarrassment was gone. Daisy’s face was smeared with tears, and when +I came in she jumped up and began wiping at it with her handkerchief +before a mirror. But there was a change in Gatsby that was simply +confounding. He literally glowed; without a word or a gesture of +exultation a new well-being radiated from him and filled the little +room. + +“Oh, hello, old sport,” he said, as if he hadn’t seen me for years. I +thought for a moment he was going to shake hands. + +“It’s stopped raining.” + +“Has it?” When he realized what I was talking about, that there were +twinkle-bells of sunshine in the room, he smiled like a weather man, +like an ecstatic patron of recurrent light, and repeated the news to +Daisy. “What do you think of that? It’s stopped raining.” + +“I’m glad, Jay.” Her throat, full of aching, grieving beauty, told +only of her unexpected joy. + +“I want you and Daisy to come over to my house,” he said, “I’d like to +show her around.” + +“You’re sure you want me to come?” + +“Absolutely, old sport.” + +Daisy went upstairs to wash her face—too late I thought with +humiliation of my towels—while Gatsby and I waited on the lawn. + +“My house looks well, doesn’t it?” he demanded. “See how the whole +front of it catches the light.” + +I agreed that it was splendid. + +“Yes.” His eyes went over it, every arched door and square tower. “It +took me just three years to earn the money that bought it.” + +“I thought you inherited your money.” + +“I did, old sport,” he said automatically, “but I lost most of it in +the big panic—the panic of the war.” + +I think he hardly knew what he was saying, for when I asked him what +business he was in he answered: “That’s my affair,” before he realized +that it wasn’t an appropriate reply. + +“Oh, I’ve been in several things,” he corrected himself. “I was in the +drug business and then I was in the oil business. But I’m not in +either one now.” He looked at me with more attention. “Do you mean +you’ve been thinking over what I proposed the other night?” + +Before I could answer, Daisy came out of the house and two rows of +brass buttons on her dress gleamed in the sunlight. + +“That huge place there?” she cried pointing. + +“Do you like it?” + +“I love it, but I don’t see how you live there all alone.” + +“I keep it always full of interesting people, night and day. People +who do interesting things. Celebrated people.” + +Instead of taking the shortcut along the Sound we went down to the +road and entered by the big postern. With enchanting murmurs Daisy +admired this aspect or that of the feudal silhouette against the sky, +admired the gardens, the sparkling odour of jonquils and the frothy +odour of hawthorn and plum blossoms and the pale gold odour of +kiss-me-at-the-gate. It was strange to reach the marble steps and find +no stir of bright dresses in and out the door, and hear no sound but +bird voices in the trees. + +And inside, as we wandered through Marie Antoinette music-rooms and +Restoration Salons, I felt that there were guests concealed behind +every couch and table, under orders to be breathlessly silent until we +had passed through. As Gatsby closed the door of “the Merton College +Library” I could have sworn I heard the owl-eyed man break into +ghostly laughter. + +We went upstairs, through period bedrooms swathed in rose and lavender +silk and vivid with new flowers, through dressing-rooms and poolrooms, +and bathrooms with sunken baths—intruding into one chamber where a +dishevelled man in pyjamas was doing liver exercises on the floor. It +was Mr. Klipspringer, the “boarder.” I had seen him wandering hungrily +about the beach that morning. Finally we came to Gatsby’s own +apartment, a bedroom and a bath, and an Adam’s study, where we sat +down and drank a glass of some Chartreuse he took from a cupboard in +the wall. + +He hadn’t once ceased looking at Daisy, and I think he revalued +everything in his house according to the measure of response it drew +from her well-loved eyes. Sometimes too, he stared around at his +possessions in a dazed way, as though in her actual and astounding +presence none of it was any longer real. Once he nearly toppled down a +flight of stairs. + +His bedroom was the simplest room of all—except where the dresser was +garnished with a toilet set of pure dull gold. Daisy took the brush +with delight, and smoothed her hair, whereupon Gatsby sat down and +shaded his eyes and began to laugh. + +“It’s the funniest thing, old sport,” he said hilariously. “I +can’t—When I try to—” + +He had passed visibly through two states and was entering upon a +third. After his embarrassment and his unreasoning joy he was consumed +with wonder at her presence. He had been full of the idea so long, +dreamed it right through to the end, waited with his teeth set, so to +speak, at an inconceivable pitch of intensity. Now, in the reaction, +he was running down like an over-wound clock. + +Recovering himself in a minute he opened for us two hulking patent +cabinets which held his massed suits and dressing-gowns and ties, and +his shirts, piled like bricks in stacks a dozen high. + +“I’ve got a man in England who buys me clothes. He sends over a +selection of things at the beginning of each season, spring and fall.” + +He took out a pile of shirts and began throwing them, one by one, +before us, shirts of sheer linen and thick silk and fine flannel, +which lost their folds as they fell and covered the table in +many-coloured disarray. While we admired he brought more and the soft +rich heap mounted higher—shirts with stripes and scrolls and plaids in +coral and apple-green and lavender and faint orange, with monograms of +indian blue. Suddenly, with a strained sound, Daisy bent her head into +the shirts and began to cry stormily. + +“They’re such beautiful shirts,” she sobbed, her voice muffled in the +thick folds. “It makes me sad because I’ve never seen such—such +beautiful shirts before.” + +------------------------------------------------------------------------ + +After the house, we were to see the grounds and the swimming pool, and +the hydroplane, and the midsummer flowers—but outside Gatsby’s window +it began to rain again, so we stood in a row looking at the corrugated +surface of the Sound. + +“If it wasn’t for the mist we could see your home across the bay,” +said Gatsby. “You always have a green light that burns all night at +the end of your dock.” + +Daisy put her arm through his abruptly, but he seemed absorbed in what +he had just said. Possibly it had occurred to him that the colossal +significance of that light had now vanished forever. Compared to the +great distance that had separated him from Daisy it had seemed very +near to her, almost touching her. It had seemed as close as a star to +the moon. Now it was again a green light on a dock. His count of +enchanted objects had diminished by one. + +I began to walk about the room, examining various indefinite objects +in the half darkness. A large photograph of an elderly man in yachting +costume attracted me, hung on the wall over his desk. + +“Who’s this?” + +“That? That’s Mr. Dan Cody, old sport.” + +The name sounded faintly familiar. + +“He’s dead now. He used to be my best friend years ago.” + +There was a small picture of Gatsby, also in yachting costume, on the +bureau—Gatsby with his head thrown back defiantly—taken apparently +when he was about eighteen. + +“I adore it,” exclaimed Daisy. “The pompadour! You never told me you +had a pompadour—or a yacht.” + +“Look at this,” said Gatsby quickly. “Here’s a lot of clippings—about +you.” + +They stood side by side examining it. I was going to ask to see the +rubies when the phone rang, and Gatsby took up the receiver. + +“Yes … Well, I can’t talk now … I can’t talk now, old sport … I said a +small town … He must know what a small town is … Well, he’s no use to +us if Detroit is his idea of a small town …” + +He rang off. + +“Come here quick!” cried Daisy at the window. + +The rain was still falling, but the darkness had parted in the west, +and there was a pink and golden billow of foamy clouds above the sea. + +“Look at that,” she whispered, and then after a moment: “I’d like to +just get one of those pink clouds and put you in it and push you +around.” + +I tried to go then, but they wouldn’t hear of it; perhaps my presence +made them feel more satisfactorily alone. + +“I know what we’ll do,” said Gatsby, “we’ll have Klipspringer play the +piano.” + +He went out of the room calling “Ewing!” and returned in a few minutes +accompanied by an embarrassed, slightly worn young man, with +shell-rimmed glasses and scanty blond hair. He was now decently +clothed in a “sport shirt,” open at the neck, sneakers, and duck +trousers of a nebulous hue. + +“Did we interrupt your exercise?” inquired Daisy politely. + +“I was asleep,” cried Mr. Klipspringer, in a spasm of embarrassment. +“That is, I’d been asleep. Then I got up …” + +“Klipspringer plays the piano,” said Gatsby, cutting him off. “Don’t +you, Ewing, old sport?” + +“I don’t play well. I don’t—hardly play at all. I’m all out of prac—” + +“We’ll go downstairs,” interrupted Gatsby. He flipped a switch. The +grey windows disappeared as the house glowed full of light. + +In the music-room Gatsby turned on a solitary lamp beside the piano. +He lit Daisy’s cigarette from a trembling match, and sat down with her +on a couch far across the room, where there was no light save what the +gleaming floor bounced in from the hall. + +When Klipspringer had played “The Love Nest” he turned around on the +bench and searched unhappily for Gatsby in the gloom. + +“I’m all out of practice, you see. I told you I couldn’t play. I’m all +out of prac—” + +“Don’t talk so much, old sport,” commanded Gatsby. “Play!” + + “In the morning, In the evening, Ain’t we got fun—” + +Outside the wind was loud and there was a faint flow of thunder along +the Sound. All the lights were going on in West Egg now; the electric +trains, men-carrying, were plunging home through the rain from New +York. It was the hour of a profound human change, and excitement was +generating on the air. + + “One thing’s sure and nothing’s surer The rich get richer and the + poor get—children. In the meantime, In between time—” + +As I went over to say goodbye I saw that the expression of +bewilderment had come back into Gatsby’s face, as though a faint doubt +had occurred to him as to the quality of his present happiness. Almost +five years! There must have been moments even that afternoon when +Daisy tumbled short of his dreams—not through her own fault, but +because of the colossal vitality of his illusion. It had gone beyond +her, beyond everything. He had thrown himself into it with a creative +passion, adding to it all the time, decking it out with every bright +feather that drifted his way. No amount of fire or freshness can +challenge what a man can store up in his ghostly heart. + +As I watched him he adjusted himself a little, visibly. His hand took +hold of hers, and as she said something low in his ear he turned +toward her with a rush of emotion. I think that voice held him most, +with its fluctuating, feverish warmth, because it couldn’t be +over-dreamed—that voice was a deathless song. + +They had forgotten me, but Daisy glanced up and held out her hand; +Gatsby didn’t know me now at all. I looked once more at them and they +looked back at me, remotely, possessed by intense life. Then I went +out of the room and down the marble steps into the rain, leaving them +there together. + + + VI + +About this time an ambitious young reporter from New York arrived one +morning at Gatsby’s door and asked him if he had anything to say. + +“Anything to say about what?” inquired Gatsby politely. + +“Why—any statement to give out.” + +It transpired after a confused five minutes that the man had heard +Gatsby’s name around his office in a connection which he either +wouldn’t reveal or didn’t fully understand. This was his day off and +with laudable initiative he had hurried out “to see.” + +It was a random shot, and yet the reporter’s instinct was right. +Gatsby’s notoriety, spread about by the hundreds who had accepted his +hospitality and so become authorities upon his past, had increased all +summer until he fell just short of being news. Contemporary legends +such as the “underground pipeline to Canada” attached themselves to +him, and there was one persistent story that he didn’t live in a house +at all, but in a boat that looked like a house and was moved secretly +up and down the Long Island shore. Just why these inventions were a +source of satisfaction to James Gatz of North Dakota, isn’t easy to +say. + +James Gatz—that was really, or at least legally, his name. He had +changed it at the age of seventeen and at the specific moment that +witnessed the beginning of his career—when he saw Dan Cody’s yacht +drop anchor over the most insidious flat on Lake Superior. It was +James Gatz who had been loafing along the beach that afternoon in a +torn green jersey and a pair of canvas pants, but it was already Jay +Gatsby who borrowed a rowboat, pulled out to the Tuolomee, and +informed Cody that a wind might catch him and break him up in half an +hour. + +I suppose he’d had the name ready for a long time, even then. His +parents were shiftless and unsuccessful farm people—his imagination +had never really accepted them as his parents at all. The truth was +that Jay Gatsby of West Egg, Long Island, sprang from his Platonic +conception of himself. He was a son of God—a phrase which, if it means +anything, means just that—and he must be about His Father’s business, +the service of a vast, vulgar, and meretricious beauty. So he invented +just the sort of Jay Gatsby that a seventeen-year-old boy would be +likely to invent, and to this conception he was faithful to the end. + +For over a year he had been beating his way along the south shore of +Lake Superior as a clam-digger and a salmon-fisher or in any other +capacity that brought him food and bed. His brown, hardening body +lived naturally through the half-fierce, half-lazy work of the bracing +days. He knew women early, and since they spoiled him he became +contemptuous of them, of young virgins because they were ignorant, of +the others because they were hysterical about things which in his +overwhelming self-absorption he took for granted. + +But his heart was in a constant, turbulent riot. The most grotesque +and fantastic conceits haunted him in his bed at night. A universe of +ineffable gaudiness spun itself out in his brain while the clock +ticked on the washstand and the moon soaked with wet light his tangled +clothes upon the floor. Each night he added to the pattern of his +fancies until drowsiness closed down upon some vivid scene with an +oblivious embrace. For a while these reveries provided an outlet for +his imagination; they were a satisfactory hint of the unreality of +reality, a promise that the rock of the world was founded securely on +a fairy’s wing. + +An instinct toward his future glory had led him, some months before, +to the small Lutheran College of St. Olaf’s in southern Minnesota. He +stayed there two weeks, dismayed at its ferocious indifference to the +drums of his destiny, to destiny itself, and despising the janitor’s +work with which he was to pay his way through. Then he drifted back to +Lake Superior, and he was still searching for something to do on the +day that Dan Cody’s yacht dropped anchor in the shallows alongshore. + +Cody was fifty years old then, a product of the Nevada silver fields, +of the Yukon, of every rush for metal since seventy-five. The +transactions in Montana copper that made him many times a millionaire +found him physically robust but on the verge of soft-mindedness, and, +suspecting this, an infinite number of women tried to separate him +from his money. The none too savoury ramifications by which Ella Kaye, +the newspaper woman, played Madame de Maintenon to his weakness and +sent him to sea in a yacht, were common property of the turgid +journalism in 1902. He had been coasting along all too hospitable +shores for five years when he turned up as James Gatz’s destiny in +Little Girl Bay. + +To young Gatz, resting on his oars and looking up at the railed deck, +that yacht represented all the beauty and glamour in the world. I +suppose he smiled at Cody—he had probably discovered that people liked +him when he smiled. At any rate Cody asked him a few questions (one of +them elicited the brand new name) and found that he was quick and +extravagantly ambitious. A few days later he took him to Duluth and +bought him a blue coat, six pairs of white duck trousers, and a +yachting cap. And when the Tuolomee left for the West Indies and the +Barbary Coast, Gatsby left too. + +He was employed in a vague personal capacity—while he remained with +Cody he was in turn steward, mate, skipper, secretary, and even +jailor, for Dan Cody sober knew what lavish doings Dan Cody drunk +might soon be about, and he provided for such contingencies by +reposing more and more trust in Gatsby. The arrangement lasted five +years, during which the boat went three times around the Continent. +It might have lasted indefinitely except for the fact that Ella Kaye +came on board one night in Boston and a week later Dan Cody +inhospitably died. + +I remember the portrait of him up in Gatsby’s bedroom, a grey, florid +man with a hard, empty face—the pioneer debauchee, who during one +phase of American life brought back to the Eastern seaboard the savage +violence of the frontier brothel and saloon. It was indirectly due to +Cody that Gatsby drank so little. Sometimes in the course of gay +parties women used to rub champagne into his hair; for himself he +formed the habit of letting liquor alone. + +And it was from Cody that he inherited money—a legacy of twenty-five +thousand dollars. He didn’t get it. He never understood the legal +device that was used against him, but what remained of the millions +went intact to Ella Kaye. He was left with his singularly appropriate +education; the vague contour of Jay Gatsby had filled out to the +substantiality of a man. + +------------------------------------------------------------------------ + +He told me all this very much later, but I’ve put it down here with +the idea of exploding those first wild rumours about his antecedents, +which weren’t even faintly true. Moreover he told it to me at a time +of confusion, when I had reached the point of believing everything and +nothing about him. So I take advantage of this short halt, while +Gatsby, so to speak, caught his breath, to clear this set of +misconceptions away. + +It was a halt, too, in my association with his affairs. For several +weeks I didn’t see him or hear his voice on the phone—mostly I was in +New York, trotting around with Jordan and trying to ingratiate myself +with her senile aunt—but finally I went over to his house one Sunday +afternoon. I hadn’t been there two minutes when somebody brought Tom +Buchanan in for a drink. I was startled, naturally, but the really +surprising thing was that it hadn’t happened before. + +They were a party of three on horseback—Tom and a man named Sloane and +a pretty woman in a brown riding-habit, who had been there previously. + +“I’m delighted to see you,” said Gatsby, standing on his porch. “I’m +delighted that you dropped in.” + +As though they cared! + +“Sit right down. Have a cigarette or a cigar.” He walked around the +room quickly, ringing bells. “I’ll have something to drink for you in +just a minute.” + +He was profoundly affected by the fact that Tom was there. But he +would be uneasy anyhow until he had given them something, realizing in +a vague way that that was all they came for. Mr. Sloane wanted +nothing. A lemonade? No, thanks. A little champagne? Nothing at all, +thanks … I’m sorry— + +“Did you have a nice ride?” + +“Very good roads around here.” + +“I suppose the automobiles—” + +“Yeah.” + +Moved by an irresistible impulse, Gatsby turned to Tom, who had +accepted the introduction as a stranger. + +“I believe we’ve met somewhere before, Mr. Buchanan.” + +“Oh, yes,” said Tom, gruffly polite, but obviously not remembering. +“So we did. I remember very well.” + +“About two weeks ago.” + +“That’s right. You were with Nick here.” + +“I know your wife,” continued Gatsby, almost aggressively. + +“That so?” + +Tom turned to me. + +“You live near here, Nick?” + +“Next door.” + +“That so?” + +Mr. Sloane didn’t enter into the conversation, but lounged back +haughtily in his chair; the woman said nothing either—until +unexpectedly, after two highballs, she became cordial. + +“We’ll all come over to your next party, Mr. Gatsby,” she suggested. +“What do you say?” + +“Certainly; I’d be delighted to have you.” + +“Be ver’ nice,” said Mr. Sloane, without gratitude. “Well—think ought +to be starting home.” + +“Please don’t hurry,” Gatsby urged them. He had control of himself +now, and he wanted to see more of Tom. “Why don’t you—why don’t you +stay for supper? I wouldn’t be surprised if some other people dropped +in from New York.” + +“You come to supper with me,” said the lady enthusiastically. “Both of +you.” + +This included me. Mr. Sloane got to his feet. + +“Come along,” he said—but to her only. + +“I mean it,” she insisted. “I’d love to have you. Lots of room.” + +Gatsby looked at me questioningly. He wanted to go and he didn’t see +that Mr. Sloane had determined he shouldn’t. + +“I’m afraid I won’t be able to,” I said. + +“Well, you come,” she urged, concentrating on Gatsby. + +Mr. Sloane murmured something close to her ear. + +“We won’t be late if we start now,” she insisted aloud. + +“I haven’t got a horse,” said Gatsby. “I used to ride in the army, but +I’ve never bought a horse. I’ll have to follow you in my car. Excuse +me for just a minute.” + +The rest of us walked out on the porch, where Sloane and the lady +began an impassioned conversation aside. + +“My God, I believe the man’s coming,” said Tom. “Doesn’t he know she +doesn’t want him?” + +“She says she does want him.” + +“She has a big dinner party and he won’t know a soul there.” He +frowned. “I wonder where in the devil he met Daisy. By God, I may be +old-fashioned in my ideas, but women run around too much these days to +suit me. They meet all kinds of crazy fish.” + +Suddenly Mr. Sloane and the lady walked down the steps and mounted +their horses. + +“Come on,” said Mr. Sloane to Tom, “we’re late. We’ve got to go.” And +then to me: “Tell him we couldn’t wait, will you?” + +Tom and I shook hands, the rest of us exchanged a cool nod, and they +trotted quickly down the drive, disappearing under the August foliage +just as Gatsby, with hat and light overcoat in hand, came out the +front door. + +Tom was evidently perturbed at Daisy’s running around alone, for on +the following Saturday night he came with her to Gatsby’s +party. Perhaps his presence gave the evening its peculiar quality of +oppressiveness—it stands out in my memory from Gatsby’s other parties +that summer. There were the same people, or at least the same sort of +people, the same profusion of champagne, the same many-coloured, +many-keyed commotion, but I felt an unpleasantness in the air, a +pervading harshness that hadn’t been there before. Or perhaps I had +merely grown used to it, grown to accept West Egg as a world complete +in itself, with its own standards and its own great figures, second to +nothing because it had no consciousness of being so, and now I was +looking at it again, through Daisy’s eyes. It is invariably saddening +to look through new eyes at things upon which you have expended your +own powers of adjustment. + +They arrived at twilight, and, as we strolled out among the sparkling +hundreds, Daisy’s voice was playing murmurous tricks in her throat. + +“These things excite me so,” she whispered. “If you want to kiss me +any time during the evening, Nick, just let me know and I’ll be glad +to arrange it for you. Just mention my name. Or present a green card. +I’m giving out green—” + +“Look around,” suggested Gatsby. + +“I’m looking around. I’m having a marvellous—” + +“You must see the faces of many people you’ve heard about.” + +Tom’s arrogant eyes roamed the crowd. + +“We don’t go around very much,” he said; “in fact, I was just thinking +I don’t know a soul here.” + +“Perhaps you know that lady.” Gatsby indicated a gorgeous, scarcely +human orchid of a woman who sat in state under a white-plum tree. Tom +and Daisy stared, with that peculiarly unreal feeling that accompanies +the recognition of a hitherto ghostly celebrity of the movies. + +“She’s lovely,” said Daisy. + +“The man bending over her is her director.” + +He took them ceremoniously from group to group: + +“Mrs. Buchanan … and Mr. Buchanan—” After an instant’s hesitation he +added: “the polo player.” + +“Oh no,” objected Tom quickly, “not me.” + +But evidently the sound of it pleased Gatsby for Tom remained “the +polo player” for the rest of the evening. + +“I’ve never met so many celebrities,” Daisy exclaimed. “I liked that +man—what was his name?—with the sort of blue nose.” + +Gatsby identified him, adding that he was a small producer. + +“Well, I liked him anyhow.” + +“I’d a little rather not be the polo player,” said Tom pleasantly, +“I’d rather look at all these famous people in—in oblivion.” + +Daisy and Gatsby danced. I remember being surprised by his graceful, +conservative foxtrot—I had never seen him dance before. Then they +sauntered over to my house and sat on the steps for half an hour, +while at her request I remained watchfully in the garden. “In case +there’s a fire or a flood,” she explained, “or any act of God.” + +Tom appeared from his oblivion as we were sitting down to supper +together. “Do you mind if I eat with some people over here?” he +said. “A fellow’s getting off some funny stuff.” + +“Go ahead,” answered Daisy genially, “and if you want to take down any +addresses here’s my little gold pencil.” … She looked around after a +moment and told me the girl was “common but pretty,” and I knew that +except for the half-hour she’d been alone with Gatsby she wasn’t +having a good time. + +We were at a particularly tipsy table. That was my fault—Gatsby had +been called to the phone, and I’d enjoyed these same people only two +weeks before. But what had amused me then turned septic on the air +now. + +“How do you feel, Miss Baedeker?” + +The girl addressed was trying, unsuccessfully, to slump against my +shoulder. At this inquiry she sat up and opened her eyes. + +“Wha’?” + +A massive and lethargic woman, who had been urging Daisy to play golf +with her at the local club tomorrow, spoke in Miss Baedeker’s defence: + +“Oh, she’s all right now. When she’s had five or six cocktails she +always starts screaming like that. I tell her she ought to leave it +alone.” + +“I do leave it alone,” affirmed the accused hollowly. + +“We heard you yelling, so I said to Doc Civet here: ‘There’s somebody +that needs your help, Doc.’ ” + +“She’s much obliged, I’m sure,” said another friend, without +gratitude, “but you got her dress all wet when you stuck her head in +the pool.” + +“Anything I hate is to get my head stuck in a pool,” mumbled Miss +Baedeker. “They almost drowned me once over in New Jersey.” + +“Then you ought to leave it alone,” countered Doctor Civet. + +“Speak for yourself!” cried Miss Baedeker violently. “Your hand +shakes. I wouldn’t let you operate on me!” + +It was like that. Almost the last thing I remember was standing with +Daisy and watching the moving-picture director and his Star. They were +still under the white-plum tree and their faces were touching except +for a pale, thin ray of moonlight between. It occurred to me that he +had been very slowly bending toward her all evening to attain this +proximity, and even while I watched I saw him stoop one ultimate +degree and kiss at her cheek. + +“I like her,” said Daisy, “I think she’s lovely.” + +But the rest offended her—and inarguably because it wasn’t a gesture +but an emotion. She was appalled by West Egg, this unprecedented +“place” that Broadway had begotten upon a Long Island fishing +village—appalled by its raw vigour that chafed under the old +euphemisms and by the too obtrusive fate that herded its inhabitants +along a shortcut from nothing to nothing. She saw something awful in +the very simplicity she failed to understand. + +I sat on the front steps with them while they waited for their car. +It was dark here in front; only the bright door sent ten square feet +of light volleying out into the soft black morning. Sometimes a shadow +moved against a dressing-room blind above, gave way to another shadow, +an indefinite procession of shadows, who rouged and powdered in an +invisible glass. + +“Who is this Gatsby anyhow?” demanded Tom suddenly. “Some big +bootlegger?” + +“Where’d you hear that?” I inquired. + +“I didn’t hear it. I imagined it. A lot of these newly rich people are +just big bootleggers, you know.” + +“Not Gatsby,” I said shortly. + +He was silent for a moment. The pebbles of the drive crunched under +his feet. + +“Well, he certainly must have strained himself to get this menagerie +together.” + +A breeze stirred the grey haze of Daisy’s fur collar. + +“At least they are more interesting than the people we know,” she said +with an effort. + +“You didn’t look so interested.” + +“Well, I was.” + +Tom laughed and turned to me. + +“Did you notice Daisy’s face when that girl asked her to put her under +a cold shower?” + +Daisy began to sing with the music in a husky, rhythmic whisper, +bringing out a meaning in each word that it had never had before and +would never have again. When the melody rose her voice broke up +sweetly, following it, in a way contralto voices have, and each change +tipped out a little of her warm human magic upon the air. + +“Lots of people come who haven’t been invited,” she said +suddenly. “That girl hadn’t been invited. They simply force their way +in and he’s too polite to object.” + +“I’d like to know who he is and what he does,” insisted Tom. “And I +think I’ll make a point of finding out.” + +“I can tell you right now,” she answered. “He owned some drugstores, a +lot of drugstores. He built them up himself.” + +The dilatory limousine came rolling up the drive. + +“Good night, Nick,” said Daisy. + +Her glance left me and sought the lighted top of the steps, where +“Three O’Clock in the Morning,” a neat, sad little waltz of that year, +was drifting out the open door. After all, in the very casualness of +Gatsby’s party there were romantic possibilities totally absent from +her world. What was it up there in the song that seemed to be calling +her back inside? What would happen now in the dim, incalculable hours? +Perhaps some unbelievable guest would arrive, a person infinitely rare +and to be marvelled at, some authentically radiant young girl who with +one fresh glance at Gatsby, one moment of magical encounter, would +blot out those five years of unwavering devotion. + +I stayed late that night. Gatsby asked me to wait until he was free, +and I lingered in the garden until the inevitable swimming party had +run up, chilled and exalted, from the black beach, until the lights +were extinguished in the guestrooms overhead. When he came down the +steps at last the tanned skin was drawn unusually tight on his face, +and his eyes were bright and tired. + +“She didn’t like it,” he said immediately. + +“Of course she did.” + +“She didn’t like it,” he insisted. “She didn’t have a good time.” + +He was silent, and I guessed at his unutterable depression. + +“I feel far away from her,” he said. “It’s hard to make her +understand.” + +“You mean about the dance?” + +“The dance?” He dismissed all the dances he had given with a snap of +his fingers. “Old sport, the dance is unimportant.” + +He wanted nothing less of Daisy than that she should go to Tom and +say: “I never loved you.” After she had obliterated four years with +that sentence they could decide upon the more practical measures to be +taken. One of them was that, after she was free, they were to go back +to Louisville and be married from her house—just as if it were five +years ago. + +“And she doesn’t understand,” he said. “She used to be able to +understand. We’d sit for hours—” + +He broke off and began to walk up and down a desolate path of fruit +rinds and discarded favours and crushed flowers. + +“I wouldn’t ask too much of her,” I ventured. “You can’t repeat the +past.” + +“Can’t repeat the past?” he cried incredulously. “Why of course you +can!” + +He looked around him wildly, as if the past were lurking here in the +shadow of his house, just out of reach of his hand. + +“I’m going to fix everything just the way it was before,” he said, +nodding determinedly. “She’ll see.” + +He talked a lot about the past, and I gathered that he wanted to +recover something, some idea of himself perhaps, that had gone into +loving Daisy. His life had been confused and disordered since then, +but if he could once return to a certain starting place and go over it +all slowly, he could find out what that thing was … + +… One autumn night, five years before, they had been walking down the +street when the leaves were falling, and they came to a place where +there were no trees and the sidewalk was white with moonlight. They +stopped here and turned toward each other. Now it was a cool night +with that mysterious excitement in it which comes at the two changes +of the year. The quiet lights in the houses were humming out into the +darkness and there was a stir and bustle among the stars. Out of the +corner of his eye Gatsby saw that the blocks of the sidewalks really +formed a ladder and mounted to a secret place above the trees—he could +climb to it, if he climbed alone, and once there he could suck on the +pap of life, gulp down the incomparable milk of wonder. + +His heart beat faster as Daisy’s white face came up to his own. He +knew that when he kissed this girl, and forever wed his unutterable +visions to her perishable breath, his mind would never romp again like +the mind of God. So he waited, listening for a moment longer to the +tuning-fork that had been struck upon a star. Then he kissed her. At +his lips’ touch she blossomed for him like a flower and the +incarnation was complete. + +Through all he said, even through his appalling sentimentality, I was +reminded of something—an elusive rhythm, a fragment of lost words, +that I had heard somewhere a long time ago. For a moment a phrase +tried to take shape in my mouth and my lips parted like a dumb man’s, +as though there was more struggling upon them than a wisp of startled +air. But they made no sound, and what I had almost remembered was +uncommunicable forever. + + + VII + +It was when curiosity about Gatsby was at its highest that the lights +in his house failed to go on one Saturday night—and, as obscurely as +it had begun, his career as Trimalchio was over. Only gradually did I +become aware that the automobiles which turned expectantly into his +drive stayed for just a minute and then drove sulkily away. Wondering +if he were sick I went over to find out—an unfamiliar butler with a +villainous face squinted at me suspiciously from the door. + +“Is Mr. Gatsby sick?” + +“Nope.” After a pause he added “sir” in a dilatory, grudging way. + +“I hadn’t seen him around, and I was rather worried. Tell him Mr. +Carraway came over.” + +“Who?” he demanded rudely. + +“Carraway.” + +“Carraway. All right, I’ll tell him.” + +Abruptly he slammed the door. + +My Finn informed me that Gatsby had dismissed every servant in his +house a week ago and replaced them with half a dozen others, who never +went into West Egg village to be bribed by the tradesmen, but ordered +moderate supplies over the telephone. The grocery boy reported that +the kitchen looked like a pigsty, and the general opinion in the +village was that the new people weren’t servants at all. + +Next day Gatsby called me on the phone. + +“Going away?” I inquired. + +“No, old sport.” + +“I hear you fired all your servants.” + +“I wanted somebody who wouldn’t gossip. Daisy comes over quite +often—in the afternoons.” + +So the whole caravansary had fallen in like a card house at the +disapproval in her eyes. + +“They’re some people Wolfshiem wanted to do something for. They’re all +brothers and sisters. They used to run a small hotel.” + +“I see.” + +He was calling up at Daisy’s request—would I come to lunch at her +house tomorrow? Miss Baker would be there. Half an hour later Daisy +herself telephoned and seemed relieved to find that I was +coming. Something was up. And yet I couldn’t believe that they would +choose this occasion for a scene—especially for the rather harrowing +scene that Gatsby had outlined in the garden. + +The next day was broiling, almost the last, certainly the warmest, of +the summer. As my train emerged from the tunnel into sunlight, only +the hot whistles of the National Biscuit Company broke the simmering +hush at noon. The straw seats of the car hovered on the edge of +combustion; the woman next to me perspired delicately for a while into +her white shirtwaist, and then, as her newspaper dampened under her +fingers, lapsed despairingly into deep heat with a desolate cry. Her +pocketbook slapped to the floor. + +“Oh, my!” she gasped. + +I picked it up with a weary bend and handed it back to her, holding it +at arm’s length and by the extreme tip of the corners to indicate that +I had no designs upon it—but everyone near by, including the woman, +suspected me just the same. + +“Hot!” said the conductor to familiar faces. “Some weather! … Hot! … +Hot! … Hot! … Is it hot enough for you? Is it hot? Is it … ?” + +My commutation ticket came back to me with a dark stain from his hand. +That anyone should care in this heat whose flushed lips he kissed, +whose head made damp the pyjama pocket over his heart! + +… Through the hall of the Buchanans’ house blew a faint wind, carrying +the sound of the telephone bell out to Gatsby and me as we waited at +the door. + +“The master’s body?” roared the butler into the mouthpiece. “I’m +sorry, madame, but we can’t furnish it—it’s far too hot to touch this +noon!” + +What he really said was: “Yes … Yes … I’ll see.” + +He set down the receiver and came toward us, glistening slightly, to +take our stiff straw hats. + +“Madame expects you in the salon!” he cried, needlessly indicating the +direction. In this heat every extra gesture was an affront to the +common store of life. + +The room, shadowed well with awnings, was dark and cool. Daisy and +Jordan lay upon an enormous couch, like silver idols weighing down +their own white dresses against the singing breeze of the fans. + +“We can’t move,” they said together. + +Jordan’s fingers, powdered white over their tan, rested for a moment +in mine. + +“And Mr. Thomas Buchanan, the athlete?” I inquired. + +Simultaneously I heard his voice, gruff, muffled, husky, at the hall +telephone. + +Gatsby stood in the centre of the crimson carpet and gazed around with +fascinated eyes. Daisy watched him and laughed, her sweet, exciting +laugh; a tiny gust of powder rose from her bosom into the air. + +“The rumour is,” whispered Jordan, “that that’s Tom’s girl on the +telephone.” + +We were silent. The voice in the hall rose high with annoyance: “Very +well, then, I won’t sell you the car at all … I’m under no obligations +to you at all … and as for your bothering me about it at lunch time, I +won’t stand that at all!” + +“Holding down the receiver,” said Daisy cynically. + +“No, he’s not,” I assured her. “It’s a bona-fide deal. I happen to +know about it.” + +Tom flung open the door, blocked out its space for a moment with his +thick body, and hurried into the room. + +“Mr. Gatsby!” He put out his broad, flat hand with well-concealed +dislike. “I’m glad to see you, sir … Nick …” + +“Make us a cold drink,” cried Daisy. + +As he left the room again she got up and went over to Gatsby and +pulled his face down, kissing him on the mouth. + +“You know I love you,” she murmured. + +“You forget there’s a lady present,” said Jordan. + +Daisy looked around doubtfully. + +“You kiss Nick too.” + +“What a low, vulgar girl!” + +“I don’t care!” cried Daisy, and began to clog on the brick fireplace. +Then she remembered the heat and sat down guiltily on the couch just +as a freshly laundered nurse leading a little girl came into the room. + +“Bles-sed pre-cious,” she crooned, holding out her arms. “Come to your +own mother that loves you.” + +The child, relinquished by the nurse, rushed across the room and +rooted shyly into her mother’s dress. + +“The bles-sed pre-cious! Did mother get powder on your old yellowy +hair? Stand up now, and say—How-de-do.” + +Gatsby and I in turn leaned down and took the small reluctant hand. +Afterward he kept looking at the child with surprise. I don’t think he +had ever really believed in its existence before. + +“I got dressed before luncheon,” said the child, turning eagerly to +Daisy. + +“That’s because your mother wanted to show you off.” Her face bent +into the single wrinkle of the small white neck. “You dream, you. You +absolute little dream.” + +“Yes,” admitted the child calmly. “Aunt Jordan’s got on a white dress +too.” + +“How do you like mother’s friends?” Daisy turned her around so that +she faced Gatsby. “Do you think they’re pretty?” + +“Where’s Daddy?” + +“She doesn’t look like her father,” explained Daisy. “She looks like +me. She’s got my hair and shape of the face.” + +Daisy sat back upon the couch. The nurse took a step forward and held +out her hand. + +“Come, Pammy.” + +“Goodbye, sweetheart!” + +With a reluctant backward glance the well-disciplined child held to +her nurse’s hand and was pulled out the door, just as Tom came back, +preceding four gin rickeys that clicked full of ice. + +Gatsby took up his drink. + +“They certainly look cool,” he said, with visible tension. + +We drank in long, greedy swallows. + +“I read somewhere that the sun’s getting hotter every year,” said Tom +genially. “It seems that pretty soon the earth’s going to fall into +the sun—or wait a minute—it’s just the opposite—the sun’s getting +colder every year. + +“Come outside,” he suggested to Gatsby, “I’d like you to have a look +at the place.” + +I went with them out to the veranda. On the green Sound, stagnant in +the heat, one small sail crawled slowly toward the fresher sea. +Gatsby’s eyes followed it momentarily; he raised his hand and pointed +across the bay. + +“I’m right across from you.” + +“So you are.” + +Our eyes lifted over the rose-beds and the hot lawn and the weedy +refuse of the dog-days alongshore. Slowly the white wings of the boat +moved against the blue cool limit of the sky. Ahead lay the scalloped +ocean and the abounding blessed isles. + +“There’s sport for you,” said Tom, nodding. “I’d like to be out there +with him for about an hour.” + +We had luncheon in the dining-room, darkened too against the heat, and +drank down nervous gaiety with the cold ale. + +“What’ll we do with ourselves this afternoon?” cried Daisy, “and the +day after that, and the next thirty years?” + +“Don’t be morbid,” Jordan said. “Life starts all over again when it +gets crisp in the fall.” + +“But it’s so hot,” insisted Daisy, on the verge of tears, “and +everything’s so confused. Let’s all go to town!” + +Her voice struggled on through the heat, beating against it, moulding +its senselessness into forms. + +“I’ve heard of making a garage out of a stable,” Tom was saying to +Gatsby, “but I’m the first man who ever made a stable out of a +garage.” + +“Who wants to go to town?” demanded Daisy insistently. Gatsby’s eyes +floated toward her. “Ah,” she cried, “you look so cool.” + +Their eyes met, and they stared together at each other, alone in +space. With an effort she glanced down at the table. + +“You always look so cool,” she repeated. + +She had told him that she loved him, and Tom Buchanan saw. He was +astounded. His mouth opened a little, and he looked at Gatsby, and +then back at Daisy as if he had just recognized her as someone he knew +a long time ago. + +“You resemble the advertisement of the man,” she went on innocently. +“You know the advertisement of the man—” + +“All right,” broke in Tom quickly, “I’m perfectly willing to go to +town. Come on—we’re all going to town.” + +He got up, his eyes still flashing between Gatsby and his wife. No one +moved. + +“Come on!” His temper cracked a little. “What’s the matter, anyhow? +If we’re going to town, let’s start.” + +His hand, trembling with his effort at self-control, bore to his lips +the last of his glass of ale. Daisy’s voice got us to our feet and out +on to the blazing gravel drive. + +“Are we just going to go?” she objected. “Like this? Aren’t we going +to let anyone smoke a cigarette first?” + +“Everybody smoked all through lunch.” + +“Oh, let’s have fun,” she begged him. “It’s too hot to fuss.” + +He didn’t answer. + +“Have it your own way,” she said. “Come on, Jordan.” + +They went upstairs to get ready while we three men stood there +shuffling the hot pebbles with our feet. A silver curve of the moon +hovered already in the western sky. Gatsby started to speak, changed +his mind, but not before Tom wheeled and faced him expectantly. + +“Have you got your stables here?” asked Gatsby with an effort. + +“About a quarter of a mile down the road.” + +“Oh.” + +A pause. + +“I don’t see the idea of going to town,” broke out Tom savagely. +“Women get these notions in their heads—” + +“Shall we take anything to drink?” called Daisy from an upper window. + +“I’ll get some whisky,” answered Tom. He went inside. + +Gatsby turned to me rigidly: + +“I can’t say anything in his house, old sport.” + +“She’s got an indiscreet voice,” I remarked. “It’s full of—” I +hesitated. + +“Her voice is full of money,” he said suddenly. + +That was it. I’d never understood before. It was full of money—that +was the inexhaustible charm that rose and fell in it, the jingle of +it, the cymbals’ song of it … High in a white palace the king’s +daughter, the golden girl … + +Tom came out of the house wrapping a quart bottle in a towel, followed +by Daisy and Jordan wearing small tight hats of metallic cloth and +carrying light capes over their arms. + +“Shall we all go in my car?” suggested Gatsby. He felt the hot, green +leather of the seat. “I ought to have left it in the shade.” + +“Is it standard shift?” demanded Tom. + +“Yes.” + +“Well, you take my coupé and let me drive your car to town.” + +The suggestion was distasteful to Gatsby. + +“I don’t think there’s much gas,” he objected. + +“Plenty of gas,” said Tom boisterously. He looked at the gauge. “And +if it runs out I can stop at a drugstore. You can buy anything at a +drugstore nowadays.” + +A pause followed this apparently pointless remark. Daisy looked at Tom +frowning, and an indefinable expression, at once definitely unfamiliar +and vaguely recognizable, as if I had only heard it described in +words, passed over Gatsby’s face. + +“Come on, Daisy,” said Tom, pressing her with his hand toward Gatsby’s +car. “I’ll take you in this circus wagon.” + +He opened the door, but she moved out from the circle of his arm. + +“You take Nick and Jordan. We’ll follow you in the coupé.” + +She walked close to Gatsby, touching his coat with her hand. Jordan +and Tom and I got into the front seat of Gatsby’s car, Tom pushed the +unfamiliar gears tentatively, and we shot off into the oppressive +heat, leaving them out of sight behind. + +“Did you see that?” demanded Tom. + +“See what?” + +He looked at me keenly, realizing that Jordan and I must have known +all along. + +“You think I’m pretty dumb, don’t you?” he suggested. “Perhaps I am, +but I have a—almost a second sight, sometimes, that tells me what to +do. Maybe you don’t believe that, but science—” + +He paused. The immediate contingency overtook him, pulled him back +from the edge of theoretical abyss. + +“I’ve made a small investigation of this fellow,” he continued. “I +could have gone deeper if I’d known—” + +“Do you mean you’ve been to a medium?” inquired Jordan humorously. + +“What?” Confused, he stared at us as we laughed. “A medium?” + +“About Gatsby.” + +“About Gatsby! No, I haven’t. I said I’d been making a small +investigation of his past.” + +“And you found he was an Oxford man,” said Jordan helpfully. + +“An Oxford man!” He was incredulous. “Like hell he is! He wears a pink +suit.” + +“Nevertheless he’s an Oxford man.” + +“Oxford, New Mexico,” snorted Tom contemptuously, “or something like +that.” + +“Listen, Tom. If you’re such a snob, why did you invite him to lunch?” +demanded Jordan crossly. + +“Daisy invited him; she knew him before we were married—God knows +where!” + +We were all irritable now with the fading ale, and aware of it we +drove for a while in silence. Then as Doctor T. J. Eckleburg’s faded +eyes came into sight down the road, I remembered Gatsby’s caution +about gasoline. + +“We’ve got enough to get us to town,” said Tom. + +“But there’s a garage right here,” objected Jordan. “I don’t want to +get stalled in this baking heat.” + +Tom threw on both brakes impatiently, and we slid to an abrupt dusty +stop under Wilson’s sign. After a moment the proprietor emerged from +the interior of his establishment and gazed hollow-eyed at the car. + +“Let’s have some gas!” cried Tom roughly. “What do you think we +stopped for—to admire the view?” + +“I’m sick,” said Wilson without moving. “Been sick all day.” + +“What’s the matter?” + +“I’m all run down.” + +“Well, shall I help myself?” Tom demanded. “You sounded well enough on +the phone.” + +With an effort Wilson left the shade and support of the doorway and, +breathing hard, unscrewed the cap of the tank. In the sunlight his +face was green. + +“I didn’t mean to interrupt your lunch,” he said. “But I need money +pretty bad, and I was wondering what you were going to do with your +old car.” + +“How do you like this one?” inquired Tom. “I bought it last week.” + +“It’s a nice yellow one,” said Wilson, as he strained at the handle. + +“Like to buy it?” + +“Big chance,” Wilson smiled faintly. “No, but I could make some money +on the other.” + +“What do you want money for, all of a sudden?” + +“I’ve been here too long. I want to get away. My wife and I want to go +West.” + +“Your wife does,” exclaimed Tom, startled. + +“She’s been talking about it for ten years.” He rested for a moment +against the pump, shading his eyes. “And now she’s going whether she +wants to or not. I’m going to get her away.” + +The coupé flashed by us with a flurry of dust and the flash of a +waving hand. + +“What do I owe you?” demanded Tom harshly. + +“I just got wised up to something funny the last two days,” remarked +Wilson. “That’s why I want to get away. That’s why I been bothering +you about the car.” + +“What do I owe you?” + +“Dollar twenty.” + +The relentless beating heat was beginning to confuse me and I had a +bad moment there before I realized that so far his suspicions hadn’t +alighted on Tom. He had discovered that Myrtle had some sort of life +apart from him in another world, and the shock had made him physically +sick. I stared at him and then at Tom, who had made a parallel +discovery less than an hour before—and it occurred to me that there +was no difference between men, in intelligence or race, so profound as +the difference between the sick and the well. Wilson was so sick that +he looked guilty, unforgivably guilty—as if he had just got some poor +girl with child. + +“I’ll let you have that car,” said Tom. “I’ll send it over tomorrow +afternoon.” + +That locality was always vaguely disquieting, even in the broad glare +of afternoon, and now I turned my head as though I had been warned of +something behind. Over the ash-heaps the giant eyes of Doctor T. J. +Eckleburg kept their vigil, but I perceived, after a moment, that +other eyes were regarding us with peculiar intensity from less than +twenty feet away. + +In one of the windows over the garage the curtains had been moved +aside a little, and Myrtle Wilson was peering down at the car. So +engrossed was she that she had no consciousness of being observed, and +one emotion after another crept into her face like objects into a +slowly developing picture. Her expression was curiously familiar—it +was an expression I had often seen on women’s faces, but on Myrtle +Wilson’s face it seemed purposeless and inexplicable until I realized +that her eyes, wide with jealous terror, were fixed not on Tom, but on +Jordan Baker, whom she took to be his wife. + +------------------------------------------------------------------------ + +There is no confusion like the confusion of a simple mind, and as we +drove away Tom was feeling the hot whips of panic. His wife and his +mistress, until an hour ago secure and inviolate, were slipping +precipitately from his control. Instinct made him step on the +accelerator with the double purpose of overtaking Daisy and leaving +Wilson behind, and we sped along toward Astoria at fifty miles an +hour, until, among the spidery girders of the elevated, we came in +sight of the easygoing blue coupé. + +“Those big movies around Fiftieth Street are cool,” suggested +Jordan. “I love New York on summer afternoons when everyone’s away. +There’s something very sensuous about it—overripe, as if all sorts of +funny fruits were going to fall into your hands.” + +The word “sensuous” had the effect of further disquieting Tom, but +before he could invent a protest the coupé came to a stop, and Daisy +signalled us to draw up alongside. + +“Where are we going?” she cried. + +“How about the movies?” + +“It’s so hot,” she complained. “You go. We’ll ride around and meet you +after.” With an effort her wit rose faintly. “We’ll meet you on some +corner. I’ll be the man smoking two cigarettes.” + +“We can’t argue about it here,” Tom said impatiently, as a truck gave +out a cursing whistle behind us. “You follow me to the south side of +Central Park, in front of the Plaza.” + +Several times he turned his head and looked back for their car, and if +the traffic delayed them he slowed up until they came into sight. I +think he was afraid they would dart down a side-street and out of his +life forever. + +But they didn’t. And we all took the less explicable step of engaging +the parlour of a suite in the Plaza Hotel. + +The prolonged and tumultuous argument that ended by herding us into +that room eludes me, though I have a sharp physical memory that, in +the course of it, my underwear kept climbing like a damp snake around +my legs and intermittent beads of sweat raced cool across my back. +The notion originated with Daisy’s suggestion that we hire five +bathrooms and take cold baths, and then assumed more tangible form as +“a place to have a mint julep.” Each of us said over and over that it +was a “crazy idea”—we all talked at once to a baffled clerk and +thought, or pretended to think, that we were being very funny … + +The room was large and stifling, and, though it was already four +o’clock, opening the windows admitted only a gust of hot shrubbery +from the Park. Daisy went to the mirror and stood with her back to us, +fixing her hair. + +“It’s a swell suite,” whispered Jordan respectfully, and everyone +laughed. + +“Open another window,” commanded Daisy, without turning around. + +“There aren’t any more.” + +“Well, we’d better telephone for an axe—” + +“The thing to do is to forget about the heat,” said Tom impatiently. +“You make it ten times worse by crabbing about it.” + +He unrolled the bottle of whisky from the towel and put it on the +table. + +“Why not let her alone, old sport?” remarked Gatsby. “You’re the one +that wanted to come to town.” + +There was a moment of silence. The telephone book slipped from its +nail and splashed to the floor, whereupon Jordan whispered, “Excuse +me”—but this time no one laughed. + +“I’ll pick it up,” I offered. + +“I’ve got it.” Gatsby examined the parted string, muttered “Hum!” in +an interested way, and tossed the book on a chair. + +“That’s a great expression of yours, isn’t it?” said Tom sharply. + +“What is?” + +“All this ‘old sport’ business. Where’d you pick that up?” + +“Now see here, Tom,” said Daisy, turning around from the mirror, “if +you’re going to make personal remarks I won’t stay here a minute. +Call up and order some ice for the mint julep.” + +As Tom took up the receiver the compressed heat exploded into sound +and we were listening to the portentous chords of Mendelssohn’s +Wedding March from the ballroom below. + +“Imagine marrying anybody in this heat!” cried Jordan dismally. + +“Still—I was married in the middle of June,” Daisy remembered. +“Louisville in June! Somebody fainted. Who was it fainted, Tom?” + +“Biloxi,” he answered shortly. + +“A man named Biloxi. ‘Blocks’ Biloxi, and he made boxes—that’s a +fact—and he was from Biloxi, Tennessee.” + +“They carried him into my house,” appended Jordan, “because we lived +just two doors from the church. And he stayed three weeks, until Daddy +told him he had to get out. The day after he left Daddy died.” After +a moment she added as if she might have sounded irreverent, “There +wasn’t any connection.” + +“I used to know a Bill Biloxi from Memphis,” I remarked. + +“That was his cousin. I knew his whole family history before he +left. He gave me an aluminium putter that I use today.” + +The music had died down as the ceremony began and now a long cheer +floated in at the window, followed by intermittent cries of +“Yea—ea—ea!” and finally by a burst of jazz as the dancing began. + +“We’re getting old,” said Daisy. “If we were young we’d rise and +dance.” + +“Remember Biloxi,” Jordan warned her. “Where’d you know him, Tom?” + +“Biloxi?” He concentrated with an effort. “I didn’t know him. He was a +friend of Daisy’s.” + +“He was not,” she denied. “I’d never seen him before. He came down in +the private car.” + +“Well, he said he knew you. He said he was raised in Louisville. Asa +Bird brought him around at the last minute and asked if we had room +for him.” + +Jordan smiled. + +“He was probably bumming his way home. He told me he was president of +your class at Yale.” + +Tom and I looked at each other blankly. + +“Biloxi?” + +“First place, we didn’t have any president—” + +Gatsby’s foot beat a short, restless tattoo and Tom eyed him suddenly. + +“By the way, Mr. Gatsby, I understand you’re an Oxford man.” + +“Not exactly.” + +“Oh, yes, I understand you went to Oxford.” + +“Yes—I went there.” + +A pause. Then Tom’s voice, incredulous and insulting: + +“You must have gone there about the time Biloxi went to New Haven.” + +Another pause. A waiter knocked and came in with crushed mint and ice +but the silence was unbroken by his “thank you” and the soft closing +of the door. This tremendous detail was to be cleared up at last. + +“I told you I went there,” said Gatsby. + +“I heard you, but I’d like to know when.” + +“It was in nineteen-nineteen, I only stayed five months. That’s why I +can’t really call myself an Oxford man.” + +Tom glanced around to see if we mirrored his unbelief. But we were all +looking at Gatsby. + +“It was an opportunity they gave to some of the officers after the +armistice,” he continued. “We could go to any of the universities in +England or France.” + +I wanted to get up and slap him on the back. I had one of those +renewals of complete faith in him that I’d experienced before. + +Daisy rose, smiling faintly, and went to the table. + +“Open the whisky, Tom,” she ordered, “and I’ll make you a mint julep. +Then you won’t seem so stupid to yourself … Look at the mint!” + +“Wait a minute,” snapped Tom, “I want to ask Mr. Gatsby one more +question.” + +“Go on,” Gatsby said politely. + +“What kind of a row are you trying to cause in my house anyhow?” + +They were out in the open at last and Gatsby was content. + +“He isn’t causing a row,” Daisy looked desperately from one to the +other. “You’re causing a row. Please have a little self-control.” + +“Self-control!” repeated Tom incredulously. “I suppose the latest +thing is to sit back and let Mr. Nobody from Nowhere make love to your +wife. Well, if that’s the idea you can count me out … Nowadays people +begin by sneering at family life and family institutions, and next +they’ll throw everything overboard and have intermarriage between +black and white.” + +Flushed with his impassioned gibberish, he saw himself standing alone +on the last barrier of civilization. + +“We’re all white here,” murmured Jordan. + +“I know I’m not very popular. I don’t give big parties. I suppose +you’ve got to make your house into a pigsty in order to have any +friends—in the modern world.” + +Angry as I was, as we all were, I was tempted to laugh whenever he +opened his mouth. The transition from libertine to prig was so +complete. + +“I’ve got something to tell you, old sport—” began Gatsby. But Daisy +guessed at his intention. + +“Please don’t!” she interrupted helplessly. “Please let’s all go +home. Why don’t we all go home?” + +“That’s a good idea,” I got up. “Come on, Tom. Nobody wants a drink.” + +“I want to know what Mr. Gatsby has to tell me.” + +“Your wife doesn’t love you,” said Gatsby. “She’s never loved you. +She loves me.” + +“You must be crazy!” exclaimed Tom automatically. + +Gatsby sprang to his feet, vivid with excitement. + +“She never loved you, do you hear?” he cried. “She only married you +because I was poor and she was tired of waiting for me. It was a +terrible mistake, but in her heart she never loved anyone except me!” + +At this point Jordan and I tried to go, but Tom and Gatsby insisted +with competitive firmness that we remain—as though neither of them had +anything to conceal and it would be a privilege to partake vicariously +of their emotions. + +“Sit down, Daisy,” Tom’s voice groped unsuccessfully for the paternal +note. “What’s been going on? I want to hear all about it.” + +“I told you what’s been going on,” said Gatsby. “Going on for five +years—and you didn’t know.” + +Tom turned to Daisy sharply. + +“You’ve been seeing this fellow for five years?” + +“Not seeing,” said Gatsby. “No, we couldn’t meet. But both of us loved +each other all that time, old sport, and you didn’t know. I used to +laugh sometimes”—but there was no laughter in his eyes—“to think that +you didn’t know.” + +“Oh—that’s all.” Tom tapped his thick fingers together like a +clergyman and leaned back in his chair. + +“You’re crazy!” he exploded. “I can’t speak about what happened five +years ago, because I didn’t know Daisy then—and I’ll be damned if I +see how you got within a mile of her unless you brought the groceries +to the back door. But all the rest of that’s a God damned lie. Daisy +loved me when she married me and she loves me now.” + +“No,” said Gatsby, shaking his head. + +“She does, though. The trouble is that sometimes she gets foolish +ideas in her head and doesn’t know what she’s doing.” He nodded +sagely. “And what’s more, I love Daisy too. Once in a while I go off +on a spree and make a fool of myself, but I always come back, and in +my heart I love her all the time.” + +“You’re revolting,” said Daisy. She turned to me, and her voice, +dropping an octave lower, filled the room with thrilling scorn: “Do +you know why we left Chicago? I’m surprised that they didn’t treat you +to the story of that little spree.” + +Gatsby walked over and stood beside her. + +“Daisy, that’s all over now,” he said earnestly. “It doesn’t matter +any more. Just tell him the truth—that you never loved him—and it’s +all wiped out forever.” + +She looked at him blindly. “Why—how could I love him—possibly?” + +“You never loved him.” + +She hesitated. Her eyes fell on Jordan and me with a sort of appeal, +as though she realized at last what she was doing—and as though she +had never, all along, intended doing anything at all. But it was done +now. It was too late. + +“I never loved him,” she said, with perceptible reluctance. + +“Not at Kapiolani?” demanded Tom suddenly. + +“No.” + +From the ballroom beneath, muffled and suffocating chords were +drifting up on hot waves of air. + +“Not that day I carried you down from the Punch Bowl to keep your +shoes dry?” There was a husky tenderness in his tone … “Daisy?” + +“Please don’t.” Her voice was cold, but the rancour was gone from it. +She looked at Gatsby. “There, Jay,” she said—but her hand as she tried +to light a cigarette was trembling. Suddenly she threw the cigarette +and the burning match on the carpet. + +“Oh, you want too much!” she cried to Gatsby. “I love you now—isn’t +that enough? I can’t help what’s past.” She began to sob +helplessly. “I did love him once—but I loved you too.” + +Gatsby’s eyes opened and closed. + +“You loved me too?” he repeated. + +“Even that’s a lie,” said Tom savagely. “She didn’t know you were +alive. Why—there’s things between Daisy and me that you’ll never know, +things that neither of us can ever forget.” + +The words seemed to bite physically into Gatsby. + +“I want to speak to Daisy alone,” he insisted. “She’s all excited +now—” + +“Even alone I can’t say I never loved Tom,” she admitted in a pitiful +voice. “It wouldn’t be true.” + +“Of course it wouldn’t,” agreed Tom. + +She turned to her husband. + +“As if it mattered to you,” she said. + +“Of course it matters. I’m going to take better care of you from now +on.” + +“You don’t understand,” said Gatsby, with a touch of panic. “You’re +not going to take care of her any more.” + +“I’m not?” Tom opened his eyes wide and laughed. He could afford to +control himself now. “Why’s that?” + +“Daisy’s leaving you.” + +“Nonsense.” + +“I am, though,” she said with a visible effort. + +“She’s not leaving me!” Tom’s words suddenly leaned down over Gatsby. +“Certainly not for a common swindler who’d have to steal the ring he +put on her finger.” + +“I won’t stand this!” cried Daisy. “Oh, please let’s get out.” + +“Who are you, anyhow?” broke out Tom. “You’re one of that bunch that +hangs around with Meyer Wolfshiem—that much I happen to know. I’ve +made a little investigation into your affairs—and I’ll carry it +further tomorrow.” + +“You can suit yourself about that, old sport,” said Gatsby steadily. + +“I found out what your ‘drugstores’ were.” He turned to us and spoke +rapidly. “He and this Wolfshiem bought up a lot of side-street +drugstores here and in Chicago and sold grain alcohol over the +counter. That’s one of his little stunts. I picked him for a +bootlegger the first time I saw him, and I wasn’t far wrong.” + +“What about it?” said Gatsby politely. “I guess your friend Walter +Chase wasn’t too proud to come in on it.” + +“And you left him in the lurch, didn’t you? You let him go to jail for +a month over in New Jersey. God! You ought to hear Walter on the +subject of you.” + +“He came to us dead broke. He was very glad to pick up some money, old +sport.” + +“Don’t you call me ‘old sport’!” cried Tom. Gatsby said +nothing. “Walter could have you up on the betting laws too, but +Wolfshiem scared him into shutting his mouth.” + +That unfamiliar yet recognizable look was back again in Gatsby’s face. + +“That drugstore business was just small change,” continued Tom slowly, +“but you’ve got something on now that Walter’s afraid to tell me +about.” + +I glanced at Daisy, who was staring terrified between Gatsby and her +husband, and at Jordan, who had begun to balance an invisible but +absorbing object on the tip of her chin. Then I turned back to +Gatsby—and was startled at his expression. He looked—and this is said +in all contempt for the babbled slander of his garden—as if he had +“killed a man.” For a moment the set of his face could be described in +just that fantastic way. + +It passed, and he began to talk excitedly to Daisy, denying +everything, defending his name against accusations that had not been +made. But with every word she was drawing further and further into +herself, so he gave that up, and only the dead dream fought on as the +afternoon slipped away, trying to touch what was no longer tangible, +struggling unhappily, undespairingly, toward that lost voice across +the room. + +The voice begged again to go. + +“Please, Tom! I can’t stand this any more.” + +Her frightened eyes told that whatever intentions, whatever courage +she had had, were definitely gone. + +“You two start on home, Daisy,” said Tom. “In Mr. Gatsby’s car.” + +She looked at Tom, alarmed now, but he insisted with magnanimous +scorn. + +“Go on. He won’t annoy you. I think he realizes that his presumptuous +little flirtation is over.” + +They were gone, without a word, snapped out, made accidental, +isolated, like ghosts, even from our pity. + +After a moment Tom got up and began wrapping the unopened bottle of +whisky in the towel. + +“Want any of this stuff? Jordan? … Nick?” + +I didn’t answer. + +“Nick?” He asked again. + +“What?” + +“Want any?” + +“No … I just remembered that today’s my birthday.” + +I was thirty. Before me stretched the portentous, menacing road of a +new decade. + +It was seven o’clock when we got into the coupé with him and started +for Long Island. Tom talked incessantly, exulting and laughing, but +his voice was as remote from Jordan and me as the foreign clamour on +the sidewalk or the tumult of the elevated overhead. Human sympathy +has its limits, and we were content to let all their tragic arguments +fade with the city lights behind. Thirty—the promise of a decade of +loneliness, a thinning list of single men to know, a thinning +briefcase of enthusiasm, thinning hair. But there was Jordan beside +me, who, unlike Daisy, was too wise ever to carry well-forgotten +dreams from age to age. As we passed over the dark bridge her wan face +fell lazily against my coat’s shoulder and the formidable stroke of +thirty died away with the reassuring pressure of her hand. + +So we drove on toward death through the cooling twilight. + +------------------------------------------------------------------------ + +The young Greek, Michaelis, who ran the coffee joint beside the +ash-heaps was the principal witness at the inquest. He had slept +through the heat until after five, when he strolled over to the +garage, and found George Wilson sick in his office—really sick, pale +as his own pale hair and shaking all over. Michaelis advised him to go +to bed, but Wilson refused, saying that he’d miss a lot of business if +he did. While his neighbour was trying to persuade him a violent +racket broke out overhead. + +“I’ve got my wife locked in up there,” explained Wilson calmly. +“She’s going to stay there till the day after tomorrow, and then we’re +going to move away.” + +Michaelis was astonished; they had been neighbours for four years, and +Wilson had never seemed faintly capable of such a statement. +Generally he was one of these worn-out men: when he wasn’t working, he +sat on a chair in the doorway and stared at the people and the cars +that passed along the road. When anyone spoke to him he invariably +laughed in an agreeable, colourless way. He was his wife’s man and not +his own. + +So naturally Michaelis tried to find out what had happened, but Wilson +wouldn’t say a word—instead he began to throw curious, suspicious +glances at his visitor and ask him what he’d been doing at certain +times on certain days. Just as the latter was getting uneasy, some +workmen came past the door bound for his restaurant, and Michaelis +took the opportunity to get away, intending to come back later. But he +didn’t. He supposed he forgot to, that’s all. When he came outside +again, a little after seven, he was reminded of the conversation +because he heard Mrs. Wilson’s voice, loud and scolding, downstairs in +the garage. + +“Beat me!” he heard her cry. “Throw me down and beat me, you dirty +little coward!” + +A moment later she rushed out into the dusk, waving her hands and +shouting—before he could move from his door the business was over. + +The “death car” as the newspapers called it, didn’t stop; it came out +of the gathering darkness, wavered tragically for a moment, and then +disappeared around the next bend. Mavro Michaelis wasn’t even sure of +its colour—he told the first policeman that it was light green. The +other car, the one going toward New York, came to rest a hundred yards +beyond, and its driver hurried back to where Myrtle Wilson, her life +violently extinguished, knelt in the road and mingled her thick dark +blood with the dust. + +Michaelis and this man reached her first, but when they had torn open +her shirtwaist, still damp with perspiration, they saw that her left +breast was swinging loose like a flap, and there was no need to listen +for the heart beneath. The mouth was wide open and ripped a little at +the corners, as though she had choked a little in giving up the +tremendous vitality she had stored so long. + +------------------------------------------------------------------------ + +We saw the three or four automobiles and the crowd when we were still +some distance away. + +“Wreck!” said Tom. “That’s good. Wilson’ll have a little business at +last.” + +He slowed down, but still without any intention of stopping, until, as +we came nearer, the hushed, intent faces of the people at the garage +door made him automatically put on the brakes. + +“We’ll take a look,” he said doubtfully, “just a look.” + +I became aware now of a hollow, wailing sound which issued incessantly +from the garage, a sound which as we got out of the coupé and walked +toward the door resolved itself into the words “Oh, my God!” uttered +over and over in a gasping moan. + +“There’s some bad trouble here,” said Tom excitedly. + +He reached up on tiptoes and peered over a circle of heads into the +garage, which was lit only by a yellow light in a swinging metal +basket overhead. Then he made a harsh sound in his throat, and with a +violent thrusting movement of his powerful arms pushed his way +through. + +The circle closed up again with a running murmur of expostulation; it +was a minute before I could see anything at all. Then new arrivals +deranged the line, and Jordan and I were pushed suddenly inside. + +Myrtle Wilson’s body, wrapped in a blanket, and then in another +blanket, as though she suffered from a chill in the hot night, lay on +a worktable by the wall, and Tom, with his back to us, was bending +over it, motionless. Next to him stood a motorcycle policeman taking +down names with much sweat and correction in a little book. At first I +couldn’t find the source of the high, groaning words that echoed +clamorously through the bare garage—then I saw Wilson standing on the +raised threshold of his office, swaying back and forth and holding to +the doorposts with both hands. Some man was talking to him in a low +voice and attempting, from time to time, to lay a hand on his +shoulder, but Wilson neither heard nor saw. His eyes would drop slowly +from the swinging light to the laden table by the wall, and then jerk +back to the light again, and he gave out incessantly his high, +horrible call: + +“Oh, my Ga-od! Oh, my Ga-od! Oh, Ga-od! Oh, my Ga-od!” + +Presently Tom lifted his head with a jerk and, after staring around +the garage with glazed eyes, addressed a mumbled incoherent remark to +the policeman. + +“M-a-v—” the policeman was saying, “—o—” + +“No, r—” corrected the man, “M-a-v-r-o—” + +“Listen to me!” muttered Tom fiercely. + +“r—” said the policeman, “o—” + +“g—” + +“g—” He looked up as Tom’s broad hand fell sharply on his shoulder. +“What you want, fella?” + +“What happened?—that’s what I want to know.” + +“Auto hit her. Ins’antly killed.” + +“Instantly killed,” repeated Tom, staring. + +“She ran out ina road. Son-of-a-bitch didn’t even stopus car.” + +“There was two cars,” said Michaelis, “one comin’, one goin’, see?” + +“Going where?” asked the policeman keenly. + +“One goin’ each way. Well, she”—his hand rose toward the blankets but +stopped halfway and fell to his side—“she ran out there an’ the one +comin’ from N’York knock right into her, goin’ thirty or forty miles +an hour.” + +“What’s the name of this place here?” demanded the officer. + +“Hasn’t got any name.” + +A pale well-dressed negro stepped near. + +“It was a yellow car,” he said, “big yellow car. New.” + +“See the accident?” asked the policeman. + +“No, but the car passed me down the road, going faster’n forty. Going +fifty, sixty.” + +“Come here and let’s have your name. Look out now. I want to get his +name.” + +Some words of this conversation must have reached Wilson, swaying in +the office door, for suddenly a new theme found voice among his +grasping cries: + +“You don’t have to tell me what kind of car it was! I know what kind +of car it was!” + +Watching Tom, I saw the wad of muscle back of his shoulder tighten +under his coat. He walked quickly over to Wilson and, standing in +front of him, seized him firmly by the upper arms. + +“You’ve got to pull yourself together,” he said with soothing +gruffness. + +Wilson’s eyes fell upon Tom; he started up on his tiptoes and then +would have collapsed to his knees had not Tom held him upright. + +“Listen,” said Tom, shaking him a little. “I just got here a minute +ago, from New York. I was bringing you that coupé we’ve been talking +about. That yellow car I was driving this afternoon wasn’t mine—do you +hear? I haven’t seen it all afternoon.” + +Only the negro and I were near enough to hear what he said, but the +policeman caught something in the tone and looked over with truculent +eyes. + +“What’s all that?” he demanded. + +“I’m a friend of his.” Tom turned his head but kept his hands firm on +Wilson’s body. “He says he knows the car that did it … It was a yellow +car.” + +Some dim impulse moved the policeman to look suspiciously at Tom. + +“And what colour’s your car?” + +“It’s a blue car, a coupé.” + +“We’ve come straight from New York,” I said. + +Someone who had been driving a little behind us confirmed this, and +the policeman turned away. + +“Now, if you’ll let me have that name again correct—” + +Picking up Wilson like a doll, Tom carried him into the office, set +him down in a chair, and came back. + +“If somebody’ll come here and sit with him,” he snapped +authoritatively. He watched while the two men standing closest glanced +at each other and went unwillingly into the room. Then Tom shut the +door on them and came down the single step, his eyes avoiding the +table. As he passed close to me he whispered: “Let’s get out.” + +Self-consciously, with his authoritative arms breaking the way, we +pushed through the still gathering crowd, passing a hurried doctor, +case in hand, who had been sent for in wild hope half an hour ago. + +Tom drove slowly until we were beyond the bend—then his foot came down +hard, and the coupé raced along through the night. In a little while I +heard a low husky sob, and saw that the tears were overflowing down +his face. + +“The God damned coward!” he whimpered. “He didn’t even stop his car.” + +------------------------------------------------------------------------ + +The Buchanans’ house floated suddenly toward us through the dark +rustling trees. Tom stopped beside the porch and looked up at the +second floor, where two windows bloomed with light among the vines. + +“Daisy’s home,” he said. As we got out of the car he glanced at me and +frowned slightly. + +“I ought to have dropped you in West Egg, Nick. There’s nothing we can +do tonight.” + +A change had come over him, and he spoke gravely, and with decision. +As we walked across the moonlight gravel to the porch he disposed of +the situation in a few brisk phrases. + +“I’ll telephone for a taxi to take you home, and while you’re waiting +you and Jordan better go in the kitchen and have them get you some +supper—if you want any.” He opened the door. “Come in.” + +“No, thanks. But I’d be glad if you’d order me the taxi. I’ll wait +outside.” + +Jordan put her hand on my arm. + +“Won’t you come in, Nick?” + +“No, thanks.” + +I was feeling a little sick and I wanted to be alone. But Jordan +lingered for a moment more. + +“It’s only half-past nine,” she said. + +I’d be damned if I’d go in; I’d had enough of all of them for one day, +and suddenly that included Jordan too. She must have seen something of +this in my expression, for she turned abruptly away and ran up the +porch steps into the house. I sat down for a few minutes with my head +in my hands, until I heard the phone taken up inside and the butler’s +voice calling a taxi. Then I walked slowly down the drive away from +the house, intending to wait by the gate. + +I hadn’t gone twenty yards when I heard my name and Gatsby stepped +from between two bushes into the path. I must have felt pretty weird +by that time, because I could think of nothing except the luminosity +of his pink suit under the moon. + +“What are you doing?” I inquired. + +“Just standing here, old sport.” + +Somehow, that seemed a despicable occupation. For all I knew he was +going to rob the house in a moment; I wouldn’t have been surprised to +see sinister faces, the faces of “Wolfshiem’s people,” behind him in +the dark shrubbery. + +“Did you see any trouble on the road?” he asked after a minute. + +“Yes.” + +He hesitated. + +“Was she killed?” + +“Yes.” + +“I thought so; I told Daisy I thought so. It’s better that the shock +should all come at once. She stood it pretty well.” + +He spoke as if Daisy’s reaction was the only thing that mattered. + +“I got to West Egg by a side road,” he went on, “and left the car in +my garage. I don’t think anybody saw us, but of course I can’t be +sure.” + +I disliked him so much by this time that I didn’t find it necessary to +tell him he was wrong. + +“Who was the woman?” he inquired. + +“Her name was Wilson. Her husband owns the garage. How the devil did +it happen?” + +“Well, I tried to swing the wheel—” He broke off, and suddenly I +guessed at the truth. + +“Was Daisy driving?” + +“Yes,” he said after a moment, “but of course I’ll say I was. You see, +when we left New York she was very nervous and she thought it would +steady her to drive—and this woman rushed out at us just as we were +passing a car coming the other way. It all happened in a minute, but +it seemed to me that she wanted to speak to us, thought we were +somebody she knew. Well, first Daisy turned away from the woman toward +the other car, and then she lost her nerve and turned back. The second +my hand reached the wheel I felt the shock—it must have killed her +instantly.” + +“It ripped her open—” + +“Don’t tell me, old sport.” He winced. “Anyhow—Daisy stepped on it. I +tried to make her stop, but she couldn’t, so I pulled on the emergency +brake. Then she fell over into my lap and I drove on. + +“She’ll be all right tomorrow,” he said presently. “I’m just going to +wait here and see if he tries to bother her about that unpleasantness +this afternoon. She’s locked herself into her room, and if he tries +any brutality she’s going to turn the light out and on again.” + +“He won’t touch her,” I said. “He’s not thinking about her.” + +“I don’t trust him, old sport.” + +“How long are you going to wait?” + +“All night, if necessary. Anyhow, till they all go to bed.” + +A new point of view occurred to me. Suppose Tom found out that Daisy +had been driving. He might think he saw a connection in it—he might +think anything. I looked at the house; there were two or three bright +windows downstairs and the pink glow from Daisy’s room on the ground +floor. + +“You wait here,” I said. “I’ll see if there’s any sign of a +commotion.” + +I walked back along the border of the lawn, traversed the gravel +softly, and tiptoed up the veranda steps. The drawing-room curtains +were open, and I saw that the room was empty. Crossing the porch where +we had dined that June night three months before, I came to a small +rectangle of light which I guessed was the pantry window. The blind +was drawn, but I found a rift at the sill. + +Daisy and Tom were sitting opposite each other at the kitchen table, +with a plate of cold fried chicken between them, and two bottles of +ale. He was talking intently across the table at her, and in his +earnestness his hand had fallen upon and covered her own. Once in a +while she looked up at him and nodded in agreement. + +They weren’t happy, and neither of them had touched the chicken or the +ale—and yet they weren’t unhappy either. There was an unmistakable air +of natural intimacy about the picture, and anybody would have said +that they were conspiring together. + +As I tiptoed from the porch I heard my taxi feeling its way along the +dark road toward the house. Gatsby was waiting where I had left him in +the drive. + +“Is it all quiet up there?” he asked anxiously. + +“Yes, it’s all quiet.” I hesitated. “You’d better come home and get +some sleep.” + +He shook his head. + +“I want to wait here till Daisy goes to bed. Good night, old sport.” + +He put his hands in his coat pockets and turned back eagerly to his +scrutiny of the house, as though my presence marred the sacredness of +the vigil. So I walked away and left him standing there in the +moonlight—watching over nothing. + + + VIII + +I couldn’t sleep all night; a foghorn was groaning incessantly on the +Sound, and I tossed half-sick between grotesque reality and savage, +frightening dreams. Toward dawn I heard a taxi go up Gatsby’s drive, +and immediately I jumped out of bed and began to dress—I felt that I +had something to tell him, something to warn him about, and morning +would be too late. + +Crossing his lawn, I saw that his front door was still open and he was +leaning against a table in the hall, heavy with dejection or sleep. + +“Nothing happened,” he said wanly. “I waited, and about four o’clock +she came to the window and stood there for a minute and then turned +out the light.” + +His house had never seemed so enormous to me as it did that night when +we hunted through the great rooms for cigarettes. We pushed aside +curtains that were like pavilions, and felt over innumerable feet of +dark wall for electric light switches—once I tumbled with a sort of +splash upon the keys of a ghostly piano. There was an inexplicable +amount of dust everywhere, and the rooms were musty, as though they +hadn’t been aired for many days. I found the humidor on an unfamiliar +table, with two stale, dry cigarettes inside. Throwing open the French +windows of the drawing-room, we sat smoking out into the darkness. + +“You ought to go away,” I said. “It’s pretty certain they’ll trace +your car.” + +“Go away now, old sport?” + +“Go to Atlantic City for a week, or up to Montreal.” + +He wouldn’t consider it. He couldn’t possibly leave Daisy until he +knew what she was going to do. He was clutching at some last hope and +I couldn’t bear to shake him free. + +It was this night that he told me the strange story of his youth with +Dan Cody—told it to me because “Jay Gatsby” had broken up like glass +against Tom’s hard malice, and the long secret extravaganza was played +out. I think that he would have acknowledged anything now, without +reserve, but he wanted to talk about Daisy. + +She was the first “nice” girl he had ever known. In various unrevealed +capacities he had come in contact with such people, but always with +indiscernible barbed wire between. He found her excitingly +desirable. He went to her house, at first with other officers from +Camp Taylor, then alone. It amazed him—he had never been in such a +beautiful house before. But what gave it an air of breathless +intensity, was that Daisy lived there—it was as casual a thing to her +as his tent out at camp was to him. There was a ripe mystery about it, +a hint of bedrooms upstairs more beautiful and cool than other +bedrooms, of gay and radiant activities taking place through its +corridors, and of romances that were not musty and laid away already +in lavender but fresh and breathing and redolent of this year’s +shining motorcars and of dances whose flowers were scarcely +withered. It excited him, too, that many men had already loved +Daisy—it increased her value in his eyes. He felt their presence all +about the house, pervading the air with the shades and echoes of still +vibrant emotions. + +But he knew that he was in Daisy’s house by a colossal +accident. However glorious might be his future as Jay Gatsby, he was +at present a penniless young man without a past, and at any moment the +invisible cloak of his uniform might slip from his shoulders. So he +made the most of his time. He took what he could get, ravenously and +unscrupulously—eventually he took Daisy one still October night, took +her because he had no real right to touch her hand. + +He might have despised himself, for he had certainly taken her under +false pretences. I don’t mean that he had traded on his phantom +millions, but he had deliberately given Daisy a sense of security; he +let her believe that he was a person from much the same strata as +herself—that he was fully able to take care of her. As a matter of +fact, he had no such facilities—he had no comfortable family standing +behind him, and he was liable at the whim of an impersonal government +to be blown anywhere about the world. + +But he didn’t despise himself and it didn’t turn out as he had +imagined. He had intended, probably, to take what he could and go—but +now he found that he had committed himself to the following of a +grail. He knew that Daisy was extraordinary, but he didn’t realize +just how extraordinary a “nice” girl could be. She vanished into her +rich house, into her rich, full life, leaving Gatsby—nothing. He felt +married to her, that was all. + +When they met again, two days later, it was Gatsby who was breathless, +who was, somehow, betrayed. Her porch was bright with the bought +luxury of star-shine; the wicker of the settee squeaked fashionably as +she turned toward him and he kissed her curious and lovely mouth. She +had caught a cold, and it made her voice huskier and more charming +than ever, and Gatsby was overwhelmingly aware of the youth and +mystery that wealth imprisons and preserves, of the freshness of many +clothes, and of Daisy, gleaming like silver, safe and proud above the +hot struggles of the poor. + +------------------------------------------------------------------------ + +“I can’t describe to you how surprised I was to find out I loved her, +old sport. I even hoped for a while that she’d throw me over, but she +didn’t, because she was in love with me too. She thought I knew a lot +because I knew different things from her … Well, there I was, way off +my ambitions, getting deeper in love every minute, and all of a sudden +I didn’t care. What was the use of doing great things if I could have +a better time telling her what I was going to do?” + +On the last afternoon before he went abroad, he sat with Daisy in his +arms for a long, silent time. It was a cold fall day, with fire in the +room and her cheeks flushed. Now and then she moved and he changed his +arm a little, and once he kissed her dark shining hair. The afternoon +had made them tranquil for a while, as if to give them a deep memory +for the long parting the next day promised. They had never been closer +in their month of love, nor communicated more profoundly one with +another, than when she brushed silent lips against his coat’s shoulder +or when he touched the end of her fingers, gently, as though she were +asleep. + +------------------------------------------------------------------------ + +He did extraordinarily well in the war. He was a captain before he +went to the front, and following the Argonne battles he got his +majority and the command of the divisional machine-guns. After the +armistice he tried frantically to get home, but some complication or +misunderstanding sent him to Oxford instead. He was worried now—there +was a quality of nervous despair in Daisy’s letters. She didn’t see +why he couldn’t come. She was feeling the pressure of the world +outside, and she wanted to see him and feel his presence beside her +and be reassured that she was doing the right thing after all. + +For Daisy was young and her artificial world was redolent of orchids +and pleasant, cheerful snobbery and orchestras which set the rhythm of +the year, summing up the sadness and suggestiveness of life in new +tunes. All night the saxophones wailed the hopeless comment of the +“Beale Street Blues” while a hundred pairs of golden and silver +slippers shuffled the shining dust. At the grey tea hour there were +always rooms that throbbed incessantly with this low, sweet fever, +while fresh faces drifted here and there like rose petals blown by the +sad horns around the floor. + +Through this twilight universe Daisy began to move again with the +season; suddenly she was again keeping half a dozen dates a day with +half a dozen men, and drowsing asleep at dawn with the beads and +chiffon of an evening-dress tangled among dying orchids on the floor +beside her bed. And all the time something within her was crying for a +decision. She wanted her life shaped now, immediately—and the decision +must be made by some force—of love, of money, of unquestionable +practicality—that was close at hand. + +That force took shape in the middle of spring with the arrival of Tom +Buchanan. There was a wholesome bulkiness about his person and his +position, and Daisy was flattered. Doubtless there was a certain +struggle and a certain relief. The letter reached Gatsby while he was +still at Oxford. + +------------------------------------------------------------------------ + +It was dawn now on Long Island and we went about opening the rest of +the windows downstairs, filling the house with grey-turning, +gold-turning light. The shadow of a tree fell abruptly across the dew +and ghostly birds began to sing among the blue leaves. There was a +slow, pleasant movement in the air, scarcely a wind, promising a cool, +lovely day. + +“I don’t think she ever loved him.” Gatsby turned around from a window +and looked at me challengingly. “You must remember, old sport, she was +very excited this afternoon. He told her those things in a way that +frightened her—that made it look as if I was some kind of cheap +sharper. And the result was she hardly knew what she was saying.” + +He sat down gloomily. + +“Of course she might have loved him just for a minute, when they were +first married—and loved me more even then, do you see?” + +Suddenly he came out with a curious remark. + +“In any case,” he said, “it was just personal.” + +What could you make of that, except to suspect some intensity in his +conception of the affair that couldn’t be measured? + +He came back from France when Tom and Daisy were still on their +wedding trip, and made a miserable but irresistible journey to +Louisville on the last of his army pay. He stayed there a week, +walking the streets where their footsteps had clicked together through +the November night and revisiting the out-of-the-way places to which +they had driven in her white car. Just as Daisy’s house had always +seemed to him more mysterious and gay than other houses, so his idea +of the city itself, even though she was gone from it, was pervaded +with a melancholy beauty. + +He left feeling that if he had searched harder, he might have found +her—that he was leaving her behind. The day-coach—he was penniless +now—was hot. He went out to the open vestibule and sat down on a +folding-chair, and the station slid away and the backs of unfamiliar +buildings moved by. Then out into the spring fields, where a yellow +trolley raced them for a minute with people in it who might once have +seen the pale magic of her face along the casual street. + +The track curved and now it was going away from the sun, which, as it +sank lower, seemed to spread itself in benediction over the vanishing +city where she had drawn her breath. He stretched out his hand +desperately as if to snatch only a wisp of air, to save a fragment of +the spot that she had made lovely for him. But it was all going by too +fast now for his blurred eyes and he knew that he had lost that part +of it, the freshest and the best, forever. + +It was nine o’clock when we finished breakfast and went out on the +porch. The night had made a sharp difference in the weather and there +was an autumn flavour in the air. The gardener, the last one of +Gatsby’s former servants, came to the foot of the steps. + +“I’m going to drain the pool today, Mr. Gatsby. Leaves’ll start +falling pretty soon, and then there’s always trouble with the pipes.” + +“Don’t do it today,” Gatsby answered. He turned to me apologetically. +“You know, old sport, I’ve never used that pool all summer?” + +I looked at my watch and stood up. + +“Twelve minutes to my train.” + +I didn’t want to go to the city. I wasn’t worth a decent stroke of +work, but it was more than that—I didn’t want to leave Gatsby. I +missed that train, and then another, before I could get myself away. + +“I’ll call you up,” I said finally. + +“Do, old sport.” + +“I’ll call you about noon.” + +We walked slowly down the steps. + +“I suppose Daisy’ll call too.” He looked at me anxiously, as if he +hoped I’d corroborate this. + +“I suppose so.” + +“Well, goodbye.” + +We shook hands and I started away. Just before I reached the hedge I +remembered something and turned around. + +“They’re a rotten crowd,” I shouted across the lawn. “You’re worth the +whole damn bunch put together.” + +I’ve always been glad I said that. It was the only compliment I ever +gave him, because I disapproved of him from beginning to end. First he +nodded politely, and then his face broke into that radiant and +understanding smile, as if we’d been in ecstatic cahoots on that fact +all the time. His gorgeous pink rag of a suit made a bright spot of +colour against the white steps, and I thought of the night when I +first came to his ancestral home, three months before. The lawn and +drive had been crowded with the faces of those who guessed at his +corruption—and he had stood on those steps, concealing his +incorruptible dream, as he waved them goodbye. + +I thanked him for his hospitality. We were always thanking him for +that—I and the others. + +“Goodbye,” I called. “I enjoyed breakfast, Gatsby.” + +------------------------------------------------------------------------ + +Up in the city, I tried for a while to list the quotations on an +interminable amount of stock, then I fell asleep in my swivel-chair. +Just before noon the phone woke me, and I started up with sweat +breaking out on my forehead. It was Jordan Baker; she often called me +up at this hour because the uncertainty of her own movements between +hotels and clubs and private houses made her hard to find in any other +way. Usually her voice came over the wire as something fresh and cool, +as if a divot from a green golf-links had come sailing in at the +office window, but this morning it seemed harsh and dry. + +“I’ve left Daisy’s house,” she said. “I’m at Hempstead, and I’m going +down to Southampton this afternoon.” + +Probably it had been tactful to leave Daisy’s house, but the act +annoyed me, and her next remark made me rigid. + +“You weren’t so nice to me last night.” + +“How could it have mattered then?” + +Silence for a moment. Then: + +“However—I want to see you.” + +“I want to see you, too.” + +“Suppose I don’t go to Southampton, and come into town this +afternoon?” + +“No—I don’t think this afternoon.” + +“Very well.” + +“It’s impossible this afternoon. Various—” + +We talked like that for a while, and then abruptly we weren’t talking +any longer. I don’t know which of us hung up with a sharp click, but I +know I didn’t care. I couldn’t have talked to her across a tea-table +that day if I never talked to her again in this world. + +I called Gatsby’s house a few minutes later, but the line was busy. I +tried four times; finally an exasperated central told me the wire was +being kept open for long distance from Detroit. Taking out my +timetable, I drew a small circle around the three-fifty train. Then I +leaned back in my chair and tried to think. It was just noon. + +------------------------------------------------------------------------ + +When I passed the ash-heaps on the train that morning I had crossed +deliberately to the other side of the car. I supposed there’d be a +curious crowd around there all day with little boys searching for dark +spots in the dust, and some garrulous man telling over and over what +had happened, until it became less and less real even to him and he +could tell it no longer, and Myrtle Wilson’s tragic achievement was +forgotten. Now I want to go back a little and tell what happened at +the garage after we left there the night before. + +They had difficulty in locating the sister, Catherine. She must have +broken her rule against drinking that night, for when she arrived she +was stupid with liquor and unable to understand that the ambulance had +already gone to Flushing. When they convinced her of this, she +immediately fainted, as if that was the intolerable part of the +affair. Someone, kind or curious, took her in his car and drove her in +the wake of her sister’s body. + +Until long after midnight a changing crowd lapped up against the front +of the garage, while George Wilson rocked himself back and forth on +the couch inside. For a while the door of the office was open, and +everyone who came into the garage glanced irresistibly through it. +Finally someone said it was a shame, and closed the door. Michaelis +and several other men were with him; first, four or five men, later +two or three men. Still later Michaelis had to ask the last stranger +to wait there fifteen minutes longer, while he went back to his own +place and made a pot of coffee. After that, he stayed there alone with +Wilson until dawn. + +About three o’clock the quality of Wilson’s incoherent muttering +changed—he grew quieter and began to talk about the yellow car. He +announced that he had a way of finding out whom the yellow car +belonged to, and then he blurted out that a couple of months ago his +wife had come from the city with her face bruised and her nose +swollen. + +But when he heard himself say this, he flinched and began to cry “Oh, +my God!” again in his groaning voice. Michaelis made a clumsy attempt +to distract him. + +“How long have you been married, George? Come on there, try and sit +still a minute, and answer my question. How long have you been +married?” + +“Twelve years.” + +“Ever had any children? Come on, George, sit still—I asked you a +question. Did you ever have any children?” + +The hard brown beetles kept thudding against the dull light, and +whenever Michaelis heard a car go tearing along the road outside it +sounded to him like the car that hadn’t stopped a few hours before. +He didn’t like to go into the garage, because the work bench was +stained where the body had been lying, so he moved uncomfortably +around the office—he knew every object in it before morning—and from +time to time sat down beside Wilson trying to keep him more quiet. + +“Have you got a church you go to sometimes, George? Maybe even if you +haven’t been there for a long time? Maybe I could call up the church +and get a priest to come over and he could talk to you, see?” + +“Don’t belong to any.” + +“You ought to have a church, George, for times like this. You must +have gone to church once. Didn’t you get married in a church? Listen, +George, listen to me. Didn’t you get married in a church?” + +“That was a long time ago.” + +The effort of answering broke the rhythm of his rocking—for a moment +he was silent. Then the same half-knowing, half-bewildered look came +back into his faded eyes. + +“Look in the drawer there,” he said, pointing at the desk. + +“Which drawer?” + +“That drawer—that one.” + +Michaelis opened the drawer nearest his hand. There was nothing in it +but a small, expensive dog-leash, made of leather and braided +silver. It was apparently new. + +“This?” he inquired, holding it up. + +Wilson stared and nodded. + +“I found it yesterday afternoon. She tried to tell me about it, but I +knew it was something funny.” + +“You mean your wife bought it?” + +“She had it wrapped in tissue paper on her bureau.” + +Michaelis didn’t see anything odd in that, and he gave Wilson a dozen +reasons why his wife might have bought the dog-leash. But conceivably +Wilson had heard some of these same explanations before, from Myrtle, +because he began saying “Oh, my God!” again in a whisper—his comforter +left several explanations in the air. + +“Then he killed her,” said Wilson. His mouth dropped open suddenly. + +“Who did?” + +“I have a way of finding out.” + +“You’re morbid, George,” said his friend. “This has been a strain to +you and you don’t know what you’re saying. You’d better try and sit +quiet till morning.” + +“He murdered her.” + +“It was an accident, George.” + +Wilson shook his head. His eyes narrowed and his mouth widened +slightly with the ghost of a superior “Hm!” + +“I know,” he said definitely. “I’m one of these trusting fellas and I +don’t think any harm to nobody, but when I get to know a thing I know +it. It was the man in that car. She ran out to speak to him and he +wouldn’t stop.” + +Michaelis had seen this too, but it hadn’t occurred to him that there +was any special significance in it. He believed that Mrs. Wilson had +been running away from her husband, rather than trying to stop any +particular car. + +“How could she of been like that?” + +“She’s a deep one,” said Wilson, as if that answered the question. +“Ah-h-h—” + +He began to rock again, and Michaelis stood twisting the leash in his +hand. + +“Maybe you got some friend that I could telephone for, George?” + +This was a forlorn hope—he was almost sure that Wilson had no friend: +there was not enough of him for his wife. He was glad a little later +when he noticed a change in the room, a blue quickening by the window, +and realized that dawn wasn’t far off. About five o’clock it was blue +enough outside to snap off the light. + +Wilson’s glazed eyes turned out to the ash-heaps, where small grey +clouds took on fantastic shapes and scurried here and there in the +faint dawn wind. + +“I spoke to her,” he muttered, after a long silence. “I told her she +might fool me but she couldn’t fool God. I took her to the +window”—with an effort he got up and walked to the rear window and +leaned with his face pressed against it—“and I said ‘God knows what +you’ve been doing, everything you’ve been doing. You may fool me, but +you can’t fool God!’ ” + +Standing behind him, Michaelis saw with a shock that he was looking at +the eyes of Doctor T. J. Eckleburg, which had just emerged, pale and +enormous, from the dissolving night. + +“God sees everything,” repeated Wilson. + +“That’s an advertisement,” Michaelis assured him. Something made him +turn away from the window and look back into the room. But Wilson +stood there a long time, his face close to the window pane, nodding +into the twilight. + +------------------------------------------------------------------------ + +By six o’clock Michaelis was worn out, and grateful for the sound of a +car stopping outside. It was one of the watchers of the night before +who had promised to come back, so he cooked breakfast for three, which +he and the other man ate together. Wilson was quieter now, and +Michaelis went home to sleep; when he awoke four hours later and +hurried back to the garage, Wilson was gone. + +His movements—he was on foot all the time—were afterward traced to +Port Roosevelt and then to Gad’s Hill, where he bought a sandwich that +he didn’t eat, and a cup of coffee. He must have been tired and +walking slowly, for he didn’t reach Gad’s Hill until noon. Thus far +there was no difficulty in accounting for his time—there were boys who +had seen a man “acting sort of crazy,” and motorists at whom he stared +oddly from the side of the road. Then for three hours he disappeared +from view. The police, on the strength of what he said to Michaelis, +that he “had a way of finding out,” supposed that he spent that time +going from garage to garage thereabout, inquiring for a yellow car. On +the other hand, no garage man who had seen him ever came forward, and +perhaps he had an easier, surer way of finding out what he wanted to +know. By half-past two he was in West Egg, where he asked someone the +way to Gatsby’s house. So by that time he knew Gatsby’s name. + +------------------------------------------------------------------------ + +At two o’clock Gatsby put on his bathing-suit and left word with the +butler that if anyone phoned word was to be brought to him at the +pool. He stopped at the garage for a pneumatic mattress that had +amused his guests during the summer, and the chauffeur helped him to +pump it up. Then he gave instructions that the open car wasn’t to be +taken out under any circumstances—and this was strange, because the +front right fender needed repair. + +Gatsby shouldered the mattress and started for the pool. Once he +stopped and shifted it a little, and the chauffeur asked him if he +needed help, but he shook his head and in a moment disappeared among +the yellowing trees. + +No telephone message arrived, but the butler went without his sleep +and waited for it until four o’clock—until long after there was anyone +to give it to if it came. I have an idea that Gatsby himself didn’t +believe it would come, and perhaps he no longer cared. If that was +true he must have felt that he had lost the old warm world, paid a +high price for living too long with a single dream. He must have +looked up at an unfamiliar sky through frightening leaves and shivered +as he found what a grotesque thing a rose is and how raw the sunlight +was upon the scarcely created grass. A new world, material without +being real, where poor ghosts, breathing dreams like air, drifted +fortuitously about … like that ashen, fantastic figure gliding toward +him through the amorphous trees. + +The chauffeur—he was one of Wolfshiem’s protégés—heard the +shots—afterwards he could only say that he hadn’t thought anything +much about them. I drove from the station directly to Gatsby’s house +and my rushing anxiously up the front steps was the first thing that +alarmed anyone. But they knew then, I firmly believe. With scarcely a +word said, four of us, the chauffeur, butler, gardener, and I hurried +down to the pool. + +There was a faint, barely perceptible movement of the water as the +fresh flow from one end urged its way toward the drain at the other. +With little ripples that were hardly the shadows of waves, the laden +mattress moved irregularly down the pool. A small gust of wind that +scarcely corrugated the surface was enough to disturb its accidental +course with its accidental burden. The touch of a cluster of leaves +revolved it slowly, tracing, like the leg of transit, a thin red +circle in the water. + +It was after we started with Gatsby toward the house that the gardener +saw Wilson’s body a little way off in the grass, and the holocaust was +complete. + + + IX + +After two years I remember the rest of that day, and that night and +the next day, only as an endless drill of police and photographers and +newspaper men in and out of Gatsby’s front door. A rope stretched +across the main gate and a policeman by it kept out the curious, but +little boys soon discovered that they could enter through my yard, and +there were always a few of them clustered open-mouthed about the +pool. Someone with a positive manner, perhaps a detective, used the +expression “madman” as he bent over Wilson’s body that afternoon, and +the adventitious authority of his voice set the key for the newspaper +reports next morning. + +Most of those reports were a nightmare—grotesque, circumstantial, +eager, and untrue. When Michaelis’s testimony at the inquest brought +to light Wilson’s suspicions of his wife I thought the whole tale +would shortly be served up in racy pasquinade—but Catherine, who might +have said anything, didn’t say a word. She showed a surprising amount +of character about it too—looked at the coroner with determined eyes +under that corrected brow of hers, and swore that her sister had never +seen Gatsby, that her sister was completely happy with her husband, +that her sister had been into no mischief whatever. She convinced +herself of it, and cried into her handkerchief, as if the very +suggestion was more than she could endure. So Wilson was reduced to a +man “deranged by grief” in order that the case might remain in its +simplest form. And it rested there. + +But all this part of it seemed remote and unessential. I found myself +on Gatsby’s side, and alone. From the moment I telephoned news of the +catastrophe to West Egg village, every surmise about him, and every +practical question, was referred to me. At first I was surprised and +confused; then, as he lay in his house and didn’t move or breathe or +speak, hour upon hour, it grew upon me that I was responsible, because +no one else was interested—interested, I mean, with that intense +personal interest to which everyone has some vague right at the end. + +I called up Daisy half an hour after we found him, called her +instinctively and without hesitation. But she and Tom had gone away +early that afternoon, and taken baggage with them. + +“Left no address?” + +“No.” + +“Say when they’d be back?” + +“No.” + +“Any idea where they are? How I could reach them?” + +“I don’t know. Can’t say.” + +I wanted to get somebody for him. I wanted to go into the room where +he lay and reassure him: “I’ll get somebody for you, Gatsby. Don’t +worry. Just trust me and I’ll get somebody for you—” + +Meyer Wolfshiem’s name wasn’t in the phone book. The butler gave me +his office address on Broadway, and I called Information, but by the +time I had the number it was long after five, and no one answered the +phone. + +“Will you ring again?” + +“I’ve rung three times.” + +“It’s very important.” + +“Sorry. I’m afraid no one’s there.” + +I went back to the drawing-room and thought for an instant that they +were chance visitors, all these official people who suddenly filled +it. But, though they drew back the sheet and looked at Gatsby with +shocked eyes, his protest continued in my brain: + +“Look here, old sport, you’ve got to get somebody for me. You’ve got +to try hard. I can’t go through this alone.” + +Someone started to ask me questions, but I broke away and going +upstairs looked hastily through the unlocked parts of his desk—he’d +never told me definitely that his parents were dead. But there was +nothing—only the picture of Dan Cody, a token of forgotten violence, +staring down from the wall. + +Next morning I sent the butler to New York with a letter to Wolfshiem, +which asked for information and urged him to come out on the next +train. That request seemed superfluous when I wrote it. I was sure +he’d start when he saw the newspapers, just as I was sure there’d be a +wire from Daisy before noon—but neither a wire nor Mr. Wolfshiem +arrived; no one arrived except more police and photographers and +newspaper men. When the butler brought back Wolfshiem’s answer I began +to have a feeling of defiance, of scornful solidarity between Gatsby +and me against them all. + + Dear Mr. Carraway. This has been one of the most terrible shocks of + my life to me I hardly can believe it that it is true at all. Such a + mad act as that man did should make us all think. I cannot come down + now as I am tied up in some very important business and cannot get + mixed up in this thing now. If there is anything I can do a little + later let me know in a letter by Edgar. I hardly know where I am when + I hear about a thing like this and am completely knocked down and + out. + + Yours truly + + Meyer Wolfshiem + +and then hasty addenda beneath: + + Let me know about the funeral etc do not know his family at all. + +When the phone rang that afternoon and Long Distance said Chicago was +calling I thought this would be Daisy at last. But the connection came +through as a man’s voice, very thin and far away. + +“This is Slagle speaking …” + +“Yes?” The name was unfamiliar. + +“Hell of a note, isn’t it? Get my wire?” + +“There haven’t been any wires.” + +“Young Parke’s in trouble,” he said rapidly. “They picked him up when +he handed the bonds over the counter. They got a circular from New +York giving ’em the numbers just five minutes before. What d’you know +about that, hey? You never can tell in these hick towns—” + +“Hello!” I interrupted breathlessly. “Look here—this isn’t Mr. +Gatsby. Mr. Gatsby’s dead.” + +There was a long silence on the other end of the wire, followed by an +exclamation … then a quick squawk as the connection was broken. + +------------------------------------------------------------------------ + +I think it was on the third day that a telegram signed Henry C. Gatz +arrived from a town in Minnesota. It said only that the sender was +leaving immediately and to postpone the funeral until he came. + +It was Gatsby’s father, a solemn old man, very helpless and dismayed, +bundled up in a long cheap ulster against the warm September day. His +eyes leaked continuously with excitement, and when I took the bag and +umbrella from his hands he began to pull so incessantly at his sparse +grey beard that I had difficulty in getting off his coat. He was on +the point of collapse, so I took him into the music-room and made him +sit down while I sent for something to eat. But he wouldn’t eat, and +the glass of milk spilled from his trembling hand. + +“I saw it in the Chicago newspaper,” he said. “It was all in the +Chicago newspaper. I started right away.” + +“I didn’t know how to reach you.” + +His eyes, seeing nothing, moved ceaselessly about the room. + +“It was a madman,” he said. “He must have been mad.” + +“Wouldn’t you like some coffee?” I urged him. + +“I don’t want anything. I’m all right now, Mr.—” + +“Carraway.” + +“Well, I’m all right now. Where have they got Jimmy?” + +I took him into the drawing-room, where his son lay, and left him +there. Some little boys had come up on the steps and were looking into +the hall; when I told them who had arrived, they went reluctantly +away. + +After a little while Mr. Gatz opened the door and came out, his mouth +ajar, his face flushed slightly, his eyes leaking isolated and +unpunctual tears. He had reached an age where death no longer has the +quality of ghastly surprise, and when he looked around him now for the +first time and saw the height and splendour of the hall and the great +rooms opening out from it into other rooms, his grief began to be +mixed with an awed pride. I helped him to a bedroom upstairs; while he +took off his coat and vest I told him that all arrangements had been +deferred until he came. + +“I didn’t know what you’d want, Mr. Gatsby—” + +“Gatz is my name.” + +“—Mr. Gatz. I thought you might want to take the body West.” + +He shook his head. + +“Jimmy always liked it better down East. He rose up to his position in +the East. Were you a friend of my boy’s, Mr.—?” + +“We were close friends.” + +“He had a big future before him, you know. He was only a young man, +but he had a lot of brain power here.” + +He touched his head impressively, and I nodded. + +“If he’d of lived, he’d of been a great man. A man like James J. +Hill. He’d of helped build up the country.” + +“That’s true,” I said, uncomfortably. + +He fumbled at the embroidered coverlet, trying to take it from the +bed, and lay down stiffly—was instantly asleep. + +That night an obviously frightened person called up, and demanded to +know who I was before he would give his name. + +“This is Mr. Carraway,” I said. + +“Oh!” He sounded relieved. “This is Klipspringer.” + +I was relieved too, for that seemed to promise another friend at +Gatsby’s grave. I didn’t want it to be in the papers and draw a +sightseeing crowd, so I’d been calling up a few people myself. They +were hard to find. + +“The funeral’s tomorrow,” I said. “Three o’clock, here at the house. +I wish you’d tell anybody who’d be interested.” + +“Oh, I will,” he broke out hastily. “Of course I’m not likely to see +anybody, but if I do.” + +His tone made me suspicious. + +“Of course you’ll be there yourself.” + +“Well, I’ll certainly try. What I called up about is—” + +“Wait a minute,” I interrupted. “How about saying you’ll come?” + +“Well, the fact is—the truth of the matter is that I’m staying with +some people up here in Greenwich, and they rather expect me to be with +them tomorrow. In fact, there’s a sort of picnic or something. Of +course I’ll do my best to get away.” + +I ejaculated an unrestrained “Huh!” and he must have heard me, for he +went on nervously: + +“What I called up about was a pair of shoes I left there. I wonder if +it’d be too much trouble to have the butler send them on. You see, +they’re tennis shoes, and I’m sort of helpless without them. My +address is care of B. F.—” + +I didn’t hear the rest of the name, because I hung up the receiver. + +After that I felt a certain shame for Gatsby—one gentleman to whom I +telephoned implied that he had got what he deserved. However, that was +my fault, for he was one of those who used to sneer most bitterly at +Gatsby on the courage of Gatsby’s liquor, and I should have known +better than to call him. + +The morning of the funeral I went up to New York to see Meyer +Wolfshiem; I couldn’t seem to reach him any other way. The door that I +pushed open, on the advice of an elevator boy, was marked “The +Swastika Holding Company,” and at first there didn’t seem to be anyone +inside. But when I’d shouted “hello” several times in vain, an +argument broke out behind a partition, and presently a lovely Jewess +appeared at an interior door and scrutinized me with black hostile +eyes. + +“Nobody’s in,” she said. “Mr. Wolfshiem’s gone to Chicago.” + +The first part of this was obviously untrue, for someone had begun to +whistle “The Rosary,” tunelessly, inside. + +“Please say that Mr. Carraway wants to see him.” + +“I can’t get him back from Chicago, can I?” + +At this moment a voice, unmistakably Wolfshiem’s, called “Stella!” +from the other side of the door. + +“Leave your name on the desk,” she said quickly. “I’ll give it to him +when he gets back.” + +“But I know he’s there.” + +She took a step toward me and began to slide her hands indignantly up +and down her hips. + +“You young men think you can force your way in here any time,” she +scolded. “We’re getting sickantired of it. When I say he’s in Chicago, +he’s in Chicago.” + +I mentioned Gatsby. + +“Oh-h!” She looked at me over again. “Will you just—What was your +name?” + +She vanished. In a moment Meyer Wolfshiem stood solemnly in the +doorway, holding out both hands. He drew me into his office, remarking +in a reverent voice that it was a sad time for all of us, and offered +me a cigar. + +“My memory goes back to when first I met him,” he said. “A young major +just out of the army and covered over with medals he got in the war. +He was so hard up he had to keep on wearing his uniform because he +couldn’t buy some regular clothes. First time I saw him was when he +came into Winebrenner’s poolroom at Forty-third Street and asked for a +job. He hadn’t eat anything for a couple of days. ‘Come on have some +lunch with me,’ I said. He ate more than four dollars’ worth of food +in half an hour.” + +“Did you start him in business?” I inquired. + +“Start him! I made him.” + +“Oh.” + +“I raised him up out of nothing, right out of the gutter. I saw right +away he was a fine-appearing, gentlemanly young man, and when he told +me he was at Oggsford I knew I could use him good. I got him to join +the American Legion and he used to stand high there. Right off he did +some work for a client of mine up to Albany. We were so thick like +that in everything”—he held up two bulbous fingers—“always together.” + +I wondered if this partnership had included the World’s Series +transaction in 1919. + +“Now he’s dead,” I said after a moment. “You were his closest friend, +so I know you’ll want to come to his funeral this afternoon.” + +“I’d like to come.” + +“Well, come then.” + +The hair in his nostrils quivered slightly, and as he shook his head +his eyes filled with tears. + +“I can’t do it—I can’t get mixed up in it,” he said. + +“There’s nothing to get mixed up in. It’s all over now.” + +“When a man gets killed I never like to get mixed up in it in any +way. I keep out. When I was a young man it was different—if a friend +of mine died, no matter how, I stuck with them to the end. You may +think that’s sentimental, but I mean it—to the bitter end.” + +I saw that for some reason of his own he was determined not to come, +so I stood up. + +“Are you a college man?” he inquired suddenly. + +For a moment I thought he was going to suggest a “gonnegtion,” but he +only nodded and shook my hand. + +“Let us learn to show our friendship for a man when he is alive and +not after he is dead,” he suggested. “After that my own rule is to let +everything alone.” + +When I left his office the sky had turned dark and I got back to West +Egg in a drizzle. After changing my clothes I went next door and found +Mr. Gatz walking up and down excitedly in the hall. His pride in his +son and in his son’s possessions was continually increasing and now he +had something to show me. + +“Jimmy sent me this picture.” He took out his wallet with trembling +fingers. “Look there.” + +It was a photograph of the house, cracked in the corners and dirty +with many hands. He pointed out every detail to me eagerly. “Look +there!” and then sought admiration from my eyes. He had shown it so +often that I think it was more real to him now than the house itself. + +“Jimmy sent it to me. I think it’s a very pretty picture. It shows up +well.” + +“Very well. Had you seen him lately?” + +“He come out to see me two years ago and bought me the house I live in +now. Of course we was broke up when he run off from home, but I see +now there was a reason for it. He knew he had a big future in front of +him. And ever since he made a success he was very generous with me.” + +He seemed reluctant to put away the picture, held it for another +minute, lingeringly, before my eyes. Then he returned the wallet and +pulled from his pocket a ragged old copy of a book called Hopalong +Cassidy. + +“Look here, this is a book he had when he was a boy. It just shows +you.” + +He opened it at the back cover and turned it around for me to see. On +the last flyleaf was printed the word schedule, and the date September +12, 1906. And underneath: + + Rise from bed 6:00 a.m. + Dumbell exercise and wall-scaling 6:15-6:30 ” + Study electricity, etc. 7:15-8:15 ” + Work 8:30-4:30 p.m. + Baseball and sports 4:30-5:00 ” + Practise elocution, poise and how to attain it 5:00-6:00 ” + Study needed inventions 7:00-9:00 ” + + General Resolves + + * No wasting time at Shafters or [a name, indecipherable] + + * No more smokeing or chewing. + + * Bath every other day + + * Read one improving book or magazine per week + + * Save $5.00 [crossed out] $3.00 per week + + * Be better to parents + +“I came across this book by accident,” said the old man. “It just +shows you, don’t it?” + +“It just shows you.” + +“Jimmy was bound to get ahead. He always had some resolves like this +or something. Do you notice what he’s got about improving his mind? He +was always great for that. He told me I et like a hog once, and I beat +him for it.” + +He was reluctant to close the book, reading each item aloud and then +looking eagerly at me. I think he rather expected me to copy down the +list for my own use. + +A little before three the Lutheran minister arrived from Flushing, and +I began to look involuntarily out the windows for other cars. So did +Gatsby’s father. And as the time passed and the servants came in and +stood waiting in the hall, his eyes began to blink anxiously, and he +spoke of the rain in a worried, uncertain way. The minister glanced +several times at his watch, so I took him aside and asked him to wait +for half an hour. But it wasn’t any use. Nobody came. + +------------------------------------------------------------------------ + +About five o’clock our procession of three cars reached the cemetery +and stopped in a thick drizzle beside the gate—first a motor hearse, +horribly black and wet, then Mr. Gatz and the minister and me in the +limousine, and a little later four or five servants and the postman +from West Egg, in Gatsby’s station wagon, all wet to the skin. As we +started through the gate into the cemetery I heard a car stop and then +the sound of someone splashing after us over the soggy ground. I +looked around. It was the man with owl-eyed glasses whom I had found +marvelling over Gatsby’s books in the library one night three months +before. + +I’d never seen him since then. I don’t know how he knew about the +funeral, or even his name. The rain poured down his thick glasses, and +he took them off and wiped them to see the protecting canvas unrolled +from Gatsby’s grave. + +I tried to think about Gatsby then for a moment, but he was already +too far away, and I could only remember, without resentment, that +Daisy hadn’t sent a message or a flower. Dimly I heard someone murmur +“Blessed are the dead that the rain falls on,” and then the owl-eyed +man said “Amen to that,” in a brave voice. + +We straggled down quickly through the rain to the cars. Owl-eyes spoke +to me by the gate. + +“I couldn’t get to the house,” he remarked. + +“Neither could anybody else.” + +“Go on!” He started. “Why, my God! they used to go there by the +hundreds.” + +He took off his glasses and wiped them again, outside and in. + +“The poor son-of-a-bitch,” he said. + +------------------------------------------------------------------------ + +One of my most vivid memories is of coming back West from prep school +and later from college at Christmas time. Those who went farther than +Chicago would gather in the old dim Union Station at six o’clock of a +December evening, with a few Chicago friends, already caught up into +their own holiday gaieties, to bid them a hasty goodbye. I remember +the fur coats of the girls returning from Miss This-or-That’s and the +chatter of frozen breath and the hands waving overhead as we caught +sight of old acquaintances, and the matchings of invitations: “Are you +going to the Ordways’? the Herseys’? the Schultzes’?” and the long +green tickets clasped tight in our gloved hands. And last the murky +yellow cars of the Chicago, Milwaukee and St. Paul railroad looking +cheerful as Christmas itself on the tracks beside the gate. + +When we pulled out into the winter night and the real snow, our snow, +began to stretch out beside us and twinkle against the windows, and +the dim lights of small Wisconsin stations moved by, a sharp wild +brace came suddenly into the air. We drew in deep breaths of it as we +walked back from dinner through the cold vestibules, unutterably aware +of our identity with this country for one strange hour, before we +melted indistinguishably into it again. + +That’s my Middle West—not the wheat or the prairies or the lost Swede +towns, but the thrilling returning trains of my youth, and the street +lamps and sleigh bells in the frosty dark and the shadows of holly +wreaths thrown by lighted windows on the snow. I am part of that, a +little solemn with the feel of those long winters, a little complacent +from growing up in the Carraway house in a city where dwellings are +still called through decades by a family’s name. I see now that this +has been a story of the West, after all—Tom and Gatsby, Daisy and +Jordan and I, were all Westerners, and perhaps we possessed some +deficiency in common which made us subtly unadaptable to Eastern life. + +Even when the East excited me most, even when I was most keenly aware +of its superiority to the bored, sprawling, swollen towns beyond the +Ohio, with their interminable inquisitions which spared only the +children and the very old—even then it had always for me a quality of +distortion. West Egg, especially, still figures in my more fantastic +dreams. I see it as a night scene by El Greco: a hundred houses, at +once conventional and grotesque, crouching under a sullen, overhanging +sky and a lustreless moon. In the foreground four solemn men in dress +suits are walking along the sidewalk with a stretcher on which lies a +drunken woman in a white evening dress. Her hand, which dangles over +the side, sparkles cold with jewels. Gravely the men turn in at a +house—the wrong house. But no one knows the woman’s name, and no one +cares. + +After Gatsby’s death the East was haunted for me like that, distorted +beyond my eyes’ power of correction. So when the blue smoke of brittle + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Resources/llm-test-prompts/prompt_8192.txt b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_8192.txt new file mode 100644 index 0000000000..048fcefa69 --- /dev/null +++ b/Tests/Benchmarks/Resources/llm-test-prompts/prompt_8192.txt @@ -0,0 +1,750 @@ + The Great Gatsby + by + F. Scott Fitzgerald + + + Table of Contents + +I +II +III +IV +V +VI +VII +VIII +IX + + + Once again + to + Zelda + + + Then wear the gold hat, if that will move her; + If you can bounce high, bounce for her too, + Till she cry “Lover, gold-hatted, high-bouncing lover, + I must have you!” + + Thomas Parke d’Invilliers + + + I + +In my younger and more vulnerable years my father gave me some advice +that I’ve been turning over in my mind ever since. + +“Whenever you feel like criticizing anyone,” he told me, “just +remember that all the people in this world haven’t had the advantages +that you’ve had.” + +He didn’t say any more, but we’ve always been unusually communicative +in a reserved way, and I understood that he meant a great deal more +than that. In consequence, I’m inclined to reserve all judgements, a +habit that has opened up many curious natures to me and also made me +the victim of not a few veteran bores. The abnormal mind is quick to +detect and attach itself to this quality when it appears in a normal +person, and so it came about that in college I was unjustly accused of +being a politician, because I was privy to the secret griefs of wild, +unknown men. Most of the confidences were unsought—frequently I have +feigned sleep, preoccupation, or a hostile levity when I realized by +some unmistakable sign that an intimate revelation was quivering on +the horizon; for the intimate revelations of young men, or at least +the terms in which they express them, are usually plagiaristic and +marred by obvious suppressions. Reserving judgements is a matter of +infinite hope. I am still a little afraid of missing something if I +forget that, as my father snobbishly suggested, and I snobbishly +repeat, a sense of the fundamental decencies is parcelled out +unequally at birth. + +And, after boasting this way of my tolerance, I come to the admission +that it has a limit. Conduct may be founded on the hard rock or the +wet marshes, but after a certain point I don’t care what it’s founded +on. When I came back from the East last autumn I felt that I wanted +the world to be in uniform and at a sort of moral attention forever; I +wanted no more riotous excursions with privileged glimpses into the +human heart. Only Gatsby, the man who gives his name to this book, was +exempt from my reaction—Gatsby, who represented everything for which I +have an unaffected scorn. If personality is an unbroken series of +successful gestures, then there was something gorgeous about him, some +heightened sensitivity to the promises of life, as if he were related +to one of those intricate machines that register earthquakes ten +thousand miles away. This responsiveness had nothing to do with that +flabby impressionability which is dignified under the name of the +“creative temperament”—it was an extraordinary gift for hope, a +romantic readiness such as I have never found in any other person and +which it is not likely I shall ever find again. No—Gatsby turned out +all right at the end; it is what preyed on Gatsby, what foul dust +floated in the wake of his dreams that temporarily closed out my +interest in the abortive sorrows and short-winded elations of men. + +------------------------------------------------------------------------ + +My family have been prominent, well-to-do people in this Middle +Western city for three generations. The Carraways are something of a +clan, and we have a tradition that we’re descended from the Dukes of +Buccleuch, but the actual founder of my line was my grandfather’s +brother, who came here in fifty-one, sent a substitute to the Civil +War, and started the wholesale hardware business that my father +carries on today. + +I never saw this great-uncle, but I’m supposed to look like him—with +special reference to the rather hard-boiled painting that hangs in +father’s office. I graduated from New Haven in 1915, just a quarter of +a century after my father, and a little later I participated in that +delayed Teutonic migration known as the Great War. I enjoyed the +counter-raid so thoroughly that I came back restless. Instead of being +the warm centre of the world, the Middle West now seemed like the +ragged edge of the universe—so I decided to go East and learn the bond +business. Everybody I knew was in the bond business, so I supposed it +could support one more single man. All my aunts and uncles talked it +over as if they were choosing a prep school for me, and finally said, +“Why—ye-es,” with very grave, hesitant faces. Father agreed to finance +me for a year, and after various delays I came East, permanently, I +thought, in the spring of twenty-two. + +The practical thing was to find rooms in the city, but it was a warm +season, and I had just left a country of wide lawns and friendly +trees, so when a young man at the office suggested that we take a +house together in a commuting town, it sounded like a great idea. He +found the house, a weather-beaten cardboard bungalow at eighty a +month, but at the last minute the firm ordered him to Washington, and +I went out to the country alone. I had a dog—at least I had him for a +few days until he ran away—and an old Dodge and a Finnish woman, who +made my bed and cooked breakfast and muttered Finnish wisdom to +herself over the electric stove. + +It was lonely for a day or so until one morning some man, more +recently arrived than I, stopped me on the road. + +“How do you get to West Egg village?” he asked helplessly. + +I told him. And as I walked on I was lonely no longer. I was a guide, +a pathfinder, an original settler. He had casually conferred on me the +freedom of the neighbourhood. + +And so with the sunshine and the great bursts of leaves growing on the +trees, just as things grow in fast movies, I had that familiar +conviction that life was beginning over again with the summer. + +There was so much to read, for one thing, and so much fine health to +be pulled down out of the young breath-giving air. I bought a dozen +volumes on banking and credit and investment securities, and they +stood on my shelf in red and gold like new money from the mint, +promising to unfold the shining secrets that only Midas and Morgan and +Maecenas knew. And I had the high intention of reading many other +books besides. I was rather literary in college—one year I wrote a +series of very solemn and obvious editorials for the Yale News—and now +I was going to bring back all such things into my life and become +again that most limited of all specialists, the “well-rounded man.” +This isn’t just an epigram—life is much more successfully looked at +from a single window, after all. + +It was a matter of chance that I should have rented a house in one of +the strangest communities in North America. It was on that slender +riotous island which extends itself due east of New York—and where +there are, among other natural curiosities, two unusual formations of +land. Twenty miles from the city a pair of enormous eggs, identical in +contour and separated only by a courtesy bay, jut out into the most +domesticated body of salt water in the Western hemisphere, the great +wet barnyard of Long Island Sound. They are not perfect ovals—like the +egg in the Columbus story, they are both crushed flat at the contact +end—but their physical resemblance must be a source of perpetual +wonder to the gulls that fly overhead. To the wingless a more +interesting phenomenon is their dissimilarity in every particular +except shape and size. + +I lived at West Egg, the—well, the less fashionable of the two, though +this is a most superficial tag to express the bizarre and not a little +sinister contrast between them. My house was at the very tip of the +egg, only fifty yards from the Sound, and squeezed between two huge +places that rented for twelve or fifteen thousand a season. The one on +my right was a colossal affair by any standard—it was a factual +imitation of some Hôtel de Ville in Normandy, with a tower on one +side, spanking new under a thin beard of raw ivy, and a marble +swimming pool, and more than forty acres of lawn and garden. It was +Gatsby’s mansion. Or, rather, as I didn’t know Mr. Gatsby, it was a +mansion inhabited by a gentleman of that name. My own house was an +eyesore, but it was a small eyesore, and it had been overlooked, so I +had a view of the water, a partial view of my neighbour’s lawn, and +the consoling proximity of millionaires—all for eighty dollars a +month. + +Across the courtesy bay the white palaces of fashionable East Egg +glittered along the water, and the history of the summer really begins +on the evening I drove over there to have dinner with the Tom +Buchanans. Daisy was my second cousin once removed, and I’d known Tom +in college. And just after the war I spent two days with them in +Chicago. + +Her husband, among various physical accomplishments, had been one of +the most powerful ends that ever played football at New Haven—a +national figure in a way, one of those men who reach such an acute +limited excellence at twenty-one that everything afterward savours of +anticlimax. His family were enormously wealthy—even in college his +freedom with money was a matter for reproach—but now he’d left Chicago +and come East in a fashion that rather took your breath away: for +instance, he’d brought down a string of polo ponies from Lake +Forest. It was hard to realize that a man in my own generation was +wealthy enough to do that. + +Why they came East I don’t know. They had spent a year in France for +no particular reason, and then drifted here and there unrestfully +wherever people played polo and were rich together. This was a +permanent move, said Daisy over the telephone, but I didn’t believe +it—I had no sight into Daisy’s heart, but I felt that Tom would drift +on forever seeking, a little wistfully, for the dramatic turbulence of +some irrecoverable football game. + +And so it happened that on a warm windy evening I drove over to East +Egg to see two old friends whom I scarcely knew at all. Their house +was even more elaborate than I expected, a cheerful red-and-white +Georgian Colonial mansion, overlooking the bay. The lawn started at +the beach and ran towards the front door for a quarter of a mile, +jumping over sundials and brick walks and burning gardens—finally when +it reached the house drifting up the side in bright vines as though +from the momentum of its run. The front was broken by a line of French +windows, glowing now with reflected gold and wide open to the warm +windy afternoon, and Tom Buchanan in riding clothes was standing with +his legs apart on the front porch. + +He had changed since his New Haven years. Now he was a sturdy +straw-haired man of thirty, with a rather hard mouth and a +supercilious manner. Two shining arrogant eyes had established +dominance over his face and gave him the appearance of always leaning +aggressively forward. Not even the effeminate swank of his riding +clothes could hide the enormous power of that body—he seemed to fill +those glistening boots until he strained the top lacing, and you could +see a great pack of muscle shifting when his shoulder moved under his +thin coat. It was a body capable of enormous leverage—a cruel body. + +His speaking voice, a gruff husky tenor, added to the impression of +fractiousness he conveyed. There was a touch of paternal contempt in +it, even toward people he liked—and there were men at New Haven who +had hated his guts. + +“Now, don’t think my opinion on these matters is final,” he seemed to +say, “just because I’m stronger and more of a man than you are.” We +were in the same senior society, and while we were never intimate I +always had the impression that he approved of me and wanted me to like +him with some harsh, defiant wistfulness of his own. + +We talked for a few minutes on the sunny porch. + +“I’ve got a nice place here,” he said, his eyes flashing about +restlessly. + +Turning me around by one arm, he moved a broad flat hand along the +front vista, including in its sweep a sunken Italian garden, a half +acre of deep, pungent roses, and a snub-nosed motorboat that bumped +the tide offshore. + +“It belonged to Demaine, the oil man.” He turned me around again, +politely and abruptly. “We’ll go inside.” + +We walked through a high hallway into a bright rosy-coloured space, +fragilely bound into the house by French windows at either end. The +windows were ajar and gleaming white against the fresh grass outside +that seemed to grow a little way into the house. A breeze blew through +the room, blew curtains in at one end and out the other like pale +flags, twisting them up toward the frosted wedding-cake of the +ceiling, and then rippled over the wine-coloured rug, making a shadow +on it as wind does on the sea. + +The only completely stationary object in the room was an enormous +couch on which two young women were buoyed up as though upon an +anchored balloon. They were both in white, and their dresses were +rippling and fluttering as if they had just been blown back in after a +short flight around the house. I must have stood for a few moments +listening to the whip and snap of the curtains and the groan of a +picture on the wall. Then there was a boom as Tom Buchanan shut the +rear windows and the caught wind died out about the room, and the +curtains and the rugs and the two young women ballooned slowly to the +floor. + +The younger of the two was a stranger to me. She was extended full +length at her end of the divan, completely motionless, and with her +chin raised a little, as if she were balancing something on it which +was quite likely to fall. If she saw me out of the corner of her eyes +she gave no hint of it—indeed, I was almost surprised into murmuring +an apology for having disturbed her by coming in. + +The other girl, Daisy, made an attempt to rise—she leaned slightly +forward with a conscientious expression—then she laughed, an absurd, +charming little laugh, and I laughed too and came forward into the +room. + +“I’m p-paralysed with happiness.” + +She laughed again, as if she said something very witty, and held my +hand for a moment, looking up into my face, promising that there was +no one in the world she so much wanted to see. That was a way she +had. She hinted in a murmur that the surname of the balancing girl was +Baker. (I’ve heard it said that Daisy’s murmur was only to make people +lean toward her; an irrelevant criticism that made it no less +charming.) + +At any rate, Miss Baker’s lips fluttered, she nodded at me almost +imperceptibly, and then quickly tipped her head back again—the object +she was balancing had obviously tottered a little and given her +something of a fright. Again a sort of apology arose to my lips. +Almost any exhibition of complete self-sufficiency draws a stunned +tribute from me. + +I looked back at my cousin, who began to ask me questions in her low, +thrilling voice. It was the kind of voice that the ear follows up and +down, as if each speech is an arrangement of notes that will never be +played again. Her face was sad and lovely with bright things in it, +bright eyes and a bright passionate mouth, but there was an excitement +in her voice that men who had cared for her found difficult to forget: +a singing compulsion, a whispered “Listen,” a promise that she had +done gay, exciting things just a while since and that there were gay, +exciting things hovering in the next hour. + +I told her how I had stopped off in Chicago for a day on my way East, +and how a dozen people had sent their love through me. + +“Do they miss me?” she cried ecstatically. + +“The whole town is desolate. All the cars have the left rear wheel +painted black as a mourning wreath, and there’s a persistent wail all +night along the north shore.” + +“How gorgeous! Let’s go back, Tom. Tomorrow!” Then she added +irrelevantly: “You ought to see the baby.” + +“I’d like to.” + +“She’s asleep. She’s three years old. Haven’t you ever seen her?” + +“Never.” + +“Well, you ought to see her. She’s—” + +Tom Buchanan, who had been hovering restlessly about the room, stopped +and rested his hand on my shoulder. + +“What you doing, Nick?” + +“I’m a bond man.” + +“Who with?” + +I told him. + +“Never heard of them,” he remarked decisively. + +This annoyed me. + +“You will,” I answered shortly. “You will if you stay in the East.” + +“Oh, I’ll stay in the East, don’t you worry,” he said, glancing at +Daisy and then back at me, as if he were alert for something +more. “I’d be a God damned fool to live anywhere else.” + +At this point Miss Baker said: “Absolutely!” with such suddenness that +I started—it was the first word she had uttered since I came into the +room. Evidently it surprised her as much as it did me, for she yawned +and with a series of rapid, deft movements stood up into the room. + +“I’m stiff,” she complained, “I’ve been lying on that sofa for as long +as I can remember.” + +“Don’t look at me,” Daisy retorted, “I’ve been trying to get you to +New York all afternoon.” + +“No, thanks,” said Miss Baker to the four cocktails just in from the +pantry. “I’m absolutely in training.” + +Her host looked at her incredulously. + +“You are!” He took down his drink as if it were a drop in the bottom +of a glass. “How you ever get anything done is beyond me.” + +I looked at Miss Baker, wondering what it was she “got done.” I +enjoyed looking at her. She was a slender, small-breasted girl, with +an erect carriage, which she accentuated by throwing her body backward +at the shoulders like a young cadet. Her grey sun-strained eyes looked +back at me with polite reciprocal curiosity out of a wan, charming, +discontented face. It occurred to me now that I had seen her, or a +picture of her, somewhere before. + +“You live in West Egg,” she remarked contemptuously. “I know somebody +there.” + +“I don’t know a single—” + +“You must know Gatsby.” + +“Gatsby?” demanded Daisy. “What Gatsby?” + +Before I could reply that he was my neighbour dinner was announced; +wedging his tense arm imperatively under mine, Tom Buchanan compelled +me from the room as though he were moving a checker to another square. + +Slenderly, languidly, their hands set lightly on their hips, the two +young women preceded us out on to a rosy-coloured porch, open toward +the sunset, where four candles flickered on the table in the +diminished wind. + +“Why candles?” objected Daisy, frowning. She snapped them out with her +fingers. “In two weeks it’ll be the longest day in the year.” She +looked at us all radiantly. “Do you always watch for the longest day +of the year and then miss it? I always watch for the longest day in +the year and then miss it.” + +“We ought to plan something,” yawned Miss Baker, sitting down at the +table as if she were getting into bed. + +“All right,” said Daisy. “What’ll we plan?” She turned to me +helplessly: “What do people plan?” + +Before I could answer her eyes fastened with an awed expression on her +little finger. + +“Look!” she complained; “I hurt it.” + +We all looked—the knuckle was black and blue. + +“You did it, Tom,” she said accusingly. “I know you didn’t mean to, +but you did do it. That’s what I get for marrying a brute of a man, a +great, big, hulking physical specimen of a—” + +“I hate that word ‘hulking,’ ” objected Tom crossly, “even in +kidding.” + +“Hulking,” insisted Daisy. + +Sometimes she and Miss Baker talked at once, unobtrusively and with a +bantering inconsequence that was never quite chatter, that was as cool +as their white dresses and their impersonal eyes in the absence of all +desire. They were here, and they accepted Tom and me, making only a +polite pleasant effort to entertain or to be entertained. They knew +that presently dinner would be over and a little later the evening too +would be over and casually put away. It was sharply different from the +West, where an evening was hurried from phase to phase towards its +close, in a continually disappointed anticipation or else in sheer +nervous dread of the moment itself. + +“You make me feel uncivilized, Daisy,” I confessed on my second glass +of corky but rather impressive claret. “Can’t you talk about crops or +something?” + +I meant nothing in particular by this remark, but it was taken up in +an unexpected way. + +“Civilization’s going to pieces,” broke out Tom violently. “I’ve +gotten to be a terrible pessimist about things. Have you read The Rise +of the Coloured Empires by this man Goddard?” + +“Why, no,” I answered, rather surprised by his tone. + +“Well, it’s a fine book, and everybody ought to read it. The idea is +if we don’t look out the white race will be—will be utterly +submerged. It’s all scientific stuff; it’s been proved.” + +“Tom’s getting very profound,” said Daisy, with an expression of +unthoughtful sadness. “He reads deep books with long words in +them. What was that word we—” + +“Well, these books are all scientific,” insisted Tom, glancing at her +impatiently. “This fellow has worked out the whole thing. It’s up to +us, who are the dominant race, to watch out or these other races will +have control of things.” + +“We’ve got to beat them down,” whispered Daisy, winking ferociously +toward the fervent sun. + +“You ought to live in California—” began Miss Baker, but Tom +interrupted her by shifting heavily in his chair. + +“This idea is that we’re Nordics. I am, and you are, and you are, +and—” After an infinitesimal hesitation he included Daisy with a +slight nod, and she winked at me again. “—And we’ve produced all the +things that go to make civilization—oh, science and art, and all +that. Do you see?” + +There was something pathetic in his concentration, as if his +complacency, more acute than of old, was not enough to him any more. +When, almost immediately, the telephone rang inside and the butler +left the porch Daisy seized upon the momentary interruption and leaned +towards me. + +“I’ll tell you a family secret,” she whispered enthusiastically. +“It’s about the butler’s nose. Do you want to hear about the butler’s +nose?” + +“That’s why I came over tonight.” + +“Well, he wasn’t always a butler; he used to be the silver polisher +for some people in New York that had a silver service for two hundred +people. He had to polish it from morning till night, until finally it +began to affect his nose—” + +“Things went from bad to worse,” suggested Miss Baker. + +“Yes. Things went from bad to worse, until finally he had to give up +his position.” + +For a moment the last sunshine fell with romantic affection upon her +glowing face; her voice compelled me forward breathlessly as I +listened—then the glow faded, each light deserting her with lingering +regret, like children leaving a pleasant street at dusk. + +The butler came back and murmured something close to Tom’s ear, +whereupon Tom frowned, pushed back his chair, and without a word went +inside. As if his absence quickened something within her, Daisy leaned +forward again, her voice glowing and singing. + +“I love to see you at my table, Nick. You remind me of a—of a rose, an +absolute rose. Doesn’t he?” She turned to Miss Baker for confirmation: +“An absolute rose?” + +This was untrue. I am not even faintly like a rose. She was only +extemporizing, but a stirring warmth flowed from her, as if her heart +was trying to come out to you concealed in one of those breathless, +thrilling words. Then suddenly she threw her napkin on the table and +excused herself and went into the house. + +Miss Baker and I exchanged a short glance consciously devoid of +meaning. I was about to speak when she sat up alertly and said “Sh!” +in a warning voice. A subdued impassioned murmur was audible in the +room beyond, and Miss Baker leaned forward unashamed, trying to +hear. The murmur trembled on the verge of coherence, sank down, +mounted excitedly, and then ceased altogether. + +“This Mr. Gatsby you spoke of is my neighbour—” I began. + +“Don’t talk. I want to hear what happens.” + +“Is something happening?” I inquired innocently. + +“You mean to say you don’t know?” said Miss Baker, honestly surprised. +“I thought everybody knew.” + +“I don’t.” + +“Why—” she said hesitantly. “Tom’s got some woman in New York.” + +“Got some woman?” I repeated blankly. + +Miss Baker nodded. + +“She might have the decency not to telephone him at dinner time. +Don’t you think?” + +Almost before I had grasped her meaning there was the flutter of a +dress and the crunch of leather boots, and Tom and Daisy were back at +the table. + +“It couldn’t be helped!” cried Daisy with tense gaiety. + +She sat down, glanced searchingly at Miss Baker and then at me, and +continued: “I looked outdoors for a minute, and it’s very romantic +outdoors. There’s a bird on the lawn that I think must be a +nightingale come over on the Cunard or White Star Line. He’s singing +away—” Her voice sang: “It’s romantic, isn’t it, Tom?” + +“Very romantic,” he said, and then miserably to me: “If it’s light +enough after dinner, I want to take you down to the stables.” + +The telephone rang inside, startlingly, and as Daisy shook her head +decisively at Tom the subject of the stables, in fact all subjects, +vanished into air. Among the broken fragments of the last five minutes +at table I remember the candles being lit again, pointlessly, and I +was conscious of wanting to look squarely at everyone, and yet to +avoid all eyes. I couldn’t guess what Daisy and Tom were thinking, but +I doubt if even Miss Baker, who seemed to have mastered a certain +hardy scepticism, was able utterly to put this fifth guest’s shrill +metallic urgency out of mind. To a certain temperament the situation +might have seemed intriguing—my own instinct was to telephone +immediately for the police. + +The horses, needless to say, were not mentioned again. Tom and Miss +Baker, with several feet of twilight between them, strolled back into +the library, as if to a vigil beside a perfectly tangible body, while, +trying to look pleasantly interested and a little deaf, I followed +Daisy around a chain of connecting verandas to the porch in front. In +its deep gloom we sat down side by side on a wicker settee. + +Daisy took her face in her hands as if feeling its lovely shape, and +her eyes moved gradually out into the velvet dusk. I saw that +turbulent emotions possessed her, so I asked what I thought would be +some sedative questions about her little girl. + +“We don’t know each other very well, Nick,” she said suddenly. “Even +if we are cousins. You didn’t come to my wedding.” + +“I wasn’t back from the war.” + +“That’s true.” She hesitated. “Well, I’ve had a very bad time, Nick, +and I’m pretty cynical about everything.” + +Evidently she had reason to be. I waited but she didn’t say any more, +and after a moment I returned rather feebly to the subject of her +daughter. + +“I suppose she talks, and—eats, and everything.” + +“Oh, yes.” She looked at me absently. “Listen, Nick; let me tell you +what I said when she was born. Would you like to hear?” + +“Very much.” + +“It’ll show you how I’ve gotten to feel about—things. Well, she was +less than an hour old and Tom was God knows where. I woke up out of +the ether with an utterly abandoned feeling, and asked the nurse right +away if it was a boy or a girl. She told me it was a girl, and so I +turned my head away and wept. ‘All right,’ I said, ‘I’m glad it’s a +girl. And I hope she’ll be a fool—that’s the best thing a girl can be +in this world, a beautiful little fool.’ + +“You see I think everything’s terrible anyhow,” she went on in a +convinced way. “Everybody thinks so—the most advanced people. And I +know. I’ve been everywhere and seen everything and done everything.” +Her eyes flashed around her in a defiant way, rather like Tom’s, and +she laughed with thrilling scorn. “Sophisticated—God, I’m +sophisticated!” + +The instant her voice broke off, ceasing to compel my attention, my +belief, I felt the basic insincerity of what she had said. It made me +uneasy, as though the whole evening had been a trick of some sort to +exact a contributory emotion from me. I waited, and sure enough, in a +moment she looked at me with an absolute smirk on her lovely face, as +if she had asserted her membership in a rather distinguished secret +society to which she and Tom belonged. + +------------------------------------------------------------------------ + +Inside, the crimson room bloomed with light. Tom and Miss Baker sat at +either end of the long couch and she read aloud to him from the +Saturday Evening Post—the words, murmurous and uninflected, running +together in a soothing tune. The lamplight, bright on his boots and +dull on the autumn-leaf yellow of her hair, glinted along the paper as +she turned a page with a flutter of slender muscles in her arms. + +When we came in she held us silent for a moment with a lifted hand. + +“To be continued,” she said, tossing the magazine on the table, “in +our very next issue.” + +Her body asserted itself with a restless movement of her knee, and she +stood up. + +“Ten o’clock,” she remarked, apparently finding the time on the +ceiling. “Time for this good girl to go to bed.” + +“Jordan’s going to play in the tournament tomorrow,” explained Daisy, +“over at Westchester.” + +“Oh—you’re Jordan Baker.” + +I knew now why her face was familiar—its pleasing contemptuous +expression had looked out at me from many rotogravure pictures of the +sporting life at Asheville and Hot Springs and Palm Beach. I had heard +some story of her too, a critical, unpleasant story, but what it was I +had forgotten long ago. + +“Good night,” she said softly. “Wake me at eight, won’t you.” + +“If you’ll get up.” + +“I will. Good night, Mr. Carraway. See you anon.” + +“Of course you will,” confirmed Daisy. “In fact I think I’ll arrange a +marriage. Come over often, Nick, and I’ll sort of—oh—fling you +together. You know—lock you up accidentally in linen closets and push +you out to sea in a boat, and all that sort of thing—” + +“Good night,” called Miss Baker from the stairs. “I haven’t heard a +word.” + +“She’s a nice girl,” said Tom after a moment. “They oughtn’t to let +her run around the country this way.” + +“Who oughtn’t to?” inquired Daisy coldly. + +“Her family.” + +“Her family is one aunt about a thousand years old. Besides, Nick’s +going to look after her, aren’t you, Nick? She’s going to spend lots +of weekends out here this summer. I think the home influence will be +very good for her.” + +Daisy and Tom looked at each other for a moment in silence. + +“Is she from New York?” I asked quickly. + +“From Louisville. Our white girlhood was passed together there. Our +beautiful white—” + +“Did you give Nick a little heart to heart talk on the veranda?” +demanded Tom suddenly. + +“Did I?” She looked at me. “I can’t seem to remember, but I think we +talked about the Nordic race. Yes, I’m sure we did. It sort of crept +up on us and first thing you know—” + +“Don’t believe everything you hear, Nick,” he advised me. + +I said lightly that I had heard nothing at all, and a few minutes +later I got up to go home. They came to the door with me and stood +side by side in a cheerful square of light. As I started my motor +Daisy peremptorily called: “Wait! + +“I forgot to ask you something, and it’s important. We heard you were +engaged to a girl out West.” + +“That’s right,” corroborated Tom kindly. “We heard that you were +engaged.” + +“It’s a libel. I’m too poor.” + +“But we heard it,” insisted Daisy, surprising me by opening up again +in a flower-like way. “We heard it from three people, so it must be +true.” + +Of course I knew what they were referring to, but I wasn’t even +vaguely engaged. The fact that gossip had published the banns was one +of the reasons I had come East. You can’t stop going with an old +friend on account of rumours, and on the other hand I had no intention +of being rumoured into marriage. + +Their interest rather touched me and made them less remotely +rich—nevertheless, I was confused and a little disgusted as I drove +away. It seemed to me that the thing for Daisy to do was to rush out +of the house, child in arms—but apparently there were no such +intentions in her head. As for Tom, the fact that he “had some woman +in New York” was really less surprising than that he had been +depressed by a book. Something was making him nibble at the edge of +stale ideas as if his sturdy physical egotism no longer nourished his +peremptory heart. + +Already it was deep summer on roadhouse roofs and in front of wayside +garages, where new red petrol-pumps sat out in pools of light, and +when I reached my estate at West Egg I ran the car under its shed and +sat for a while on an abandoned grass roller in the yard. The wind had +blown off, leaving a loud, bright night, with wings beating in the +trees and a persistent organ sound as the full bellows of the earth +blew the frogs full of life. The silhouette of a moving cat wavered +across the moonlight, and, turning my head to watch it, I saw that I +was not alone—fifty feet away a figure had emerged from the shadow of +my neighbour’s mansion and was standing with his hands in his pockets +regarding the silver pepper of the stars. Something in his leisurely +movements and the secure position of his feet upon the lawn suggested +that it was Mr. Gatsby himself, come out to determine what share was +his of our local heavens. + +I decided to call to him. Miss Baker had mentioned him at dinner, and +that would do for an introduction. But I didn’t call to him, for he +gave a sudden intimation that he was content to be alone—he stretched +out his arms toward the dark water in a curious way, and, far as I was +from him, I could have sworn he was trembling. Involuntarily I glanced +seaward—and distinguished nothing except a single green light, minute +and far away, that might have been the end of a dock. When I looked +once more for Gatsby he had vanished, and I was alone again in the +unquiet darkness. + +--- + + Summarize the content above. \ No newline at end of file diff --git a/Tests/Benchmarks/Utils/BenchmarkWriter.swift b/Tests/Benchmarks/Utils/BenchmarkWriter.swift new file mode 100644 index 0000000000..2de9ee861e --- /dev/null +++ b/Tests/Benchmarks/Utils/BenchmarkWriter.swift @@ -0,0 +1,736 @@ +import Foundation +import MLX +import MLXLMCommon + +/// Writes benchmark results to a single hardware-dated markdown file under `benchmarks/`. +/// +/// File naming: `{chip-slug}-{ram}gb-{YYYY-MM-DD}.md` +/// Example: `m1-max-64gb-2026-04-16.md`, `m5-max-128gb-2026-04-16.md` +/// +/// Multiple runs (across models, quantizations, KV configs, methods) accumulate into the +/// same file, grouped by model. State lives in a `.{filename}.state.json` sidecar so the +/// markdown can be re-rendered deterministically and runs in separate `swift test` +/// invocations (as the CLI does for multi-model sweeps) continue to append into the +/// same file. +/// +/// See `benchmarks/README.md#output` for the on-disk layout. +enum BenchmarkWriter { + private static let lock = NSLock() + + // MARK: - Public append API (unchanged signature) + + /// Generation + runner metadata for the benchmark markdown header. + struct BenchmarkParameters { + let generate: GenerateParameters + let thinkingEnabled: Bool + let thinkingTokenBudget: Int? + let kldSummary: String + let maxOpsPerBuffer: String + let batchSize: Int + let speculativeDecoding: String + let systemPromptSummary: String + } + + /// Append a benchmark result row to the session's markdown file. + /// + /// Rows are grouped by model → config. The config identity is + /// `quantization / kvConfig / scenario` plus any non-empty `configKeyExtras` + /// appended as ` / key=value` pairs (e.g. `ngram=3`) so that two runs which + /// differ only on a dimension outside (quant, kv, method) — like `--ngram` + /// — land in separate config blocks with distinct Parameters tables. + static func append( + model: String, + repoId: String = "", + quantization: String, + kvConfig: String, + scenario: String, + configKeyExtras: [(String, String)] = [], + contextSize: Int, + promptTokens: Int, + prefillTokPerSec: Double, + genTokPerSec: Double, + genTokens: Int, + ttftMs: Double, + thinkingPerplexity: Double?, + generationPerplexity: Double?, + thinkingKLD: Double? = nil, + generationKLD: Double? = nil, + baselineGPU: Int, + peakGPU: Int, + kvDelta: Int, + kvCacheBytes: Int = 0, + outputPreview: String, + parameters: BenchmarkParameters? = nil + ) { + lock.lock() + defer { lock.unlock() } + + let hw = hardwareInfo() + let filename = sessionFilename(hw: hw) + let projectRoot = Self.projectRoot() + let markdownURL = projectRoot + .appendingPathComponent("benchmarks") + .appendingPathComponent(filename + ".md") + let sidecarURL = projectRoot + .appendingPathComponent("benchmarks") + .appendingPathComponent("." + filename + ".state.json") + + try? FileManager.default.createDirectory( + at: markdownURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + + var state = loadState(from: sidecarURL) ?? SessionState( + chip: hw.chip, + gpuArch: GPU.deviceInfo().architecture, + systemRAM: hw.systemRAM, + gpuLimit: hw.gpuLimit, + osVersion: hw.osVersion, + branch: gitBranch(), + commit: gitLastCommitLine(), + naxEnabled: detectNAX(), + createdAt: isoDateTime(Date()), + models: [] + ) + + let row = ResultRow( + contextSize: contextSize, + promptTokens: promptTokens, + prefillTokPerSec: prefillTokPerSec, + decodeTokPerSec: genTokPerSec, + genTokens: genTokens, + ttftMs: ttftMs, + thinkPPL: thinkingPerplexity, + genPPL: generationPerplexity, + thinkKLD: thinkingKLD, + genKLD: generationKLD, + baselineGPU: baselineGPU, + peakGPU: peakGPU, + kvDelta: kvDelta, + kvCacheBytes: kvCacheBytes + ) + + var configKey = "\(quantization) / \(kvConfig) / \(scenario)" + for (k, v) in configKeyExtras { + configKey += " / \(k)=\(v)" + } + var paramRows: [[String]] = [] + var systemPrompt = "" + if let p = parameters { + paramRows = buildParameterRows(p) + systemPrompt = p.systemPromptSummary + } + + // Locate or create model entry (preserves insertion order). + if let mi = state.models.firstIndex(where: { $0.displayName == model }) { + if let ci = state.models[mi].configs.firstIndex(where: { $0.key == configKey }) { + state.models[mi].configs[ci].rows.append(row) + if state.models[mi].configs[ci].outputSample.isEmpty { + state.models[mi].configs[ci].outputSample = outputPreview + } + } else { + state.models[mi].configs.append(ConfigEntry( + key: configKey, + quantization: quantization, + kvConfig: kvConfig, + method: scenario, + parameterRows: paramRows, + systemPromptSummary: systemPrompt, + rows: [row], + outputSample: outputPreview + )) + } + } else { + state.models.append(ModelEntry( + displayName: model, + repoId: repoId, + configs: [ConfigEntry( + key: configKey, + quantization: quantization, + kvConfig: kvConfig, + method: scenario, + parameterRows: paramRows, + systemPromptSummary: systemPrompt, + rows: [row], + outputSample: outputPreview + )] + )) + } + + saveState(state, to: sidecarURL) + let markdown = renderMarkdown(state: state) + try? markdown.write(to: markdownURL, atomically: true, encoding: .utf8) + } + + // MARK: - State types (JSON sidecar) + + private struct SessionState: Codable { + var chip: String + var gpuArch: String + var systemRAM: String + var gpuLimit: String + var osVersion: String + var branch: String + var commit: String + var naxEnabled: Bool + var createdAt: String + var models: [ModelEntry] + } + + private struct ModelEntry: Codable { + var displayName: String + var repoId: String + var configs: [ConfigEntry] + } + + private struct ConfigEntry: Codable { + var key: String + var quantization: String + var kvConfig: String + var method: String + var parameterRows: [[String]] + var systemPromptSummary: String + var rows: [ResultRow] + var outputSample: String + } + + private struct ResultRow: Codable { + var contextSize: Int + var promptTokens: Int + var prefillTokPerSec: Double + var decodeTokPerSec: Double + var genTokens: Int + var ttftMs: Double + var thinkPPL: Double? + var genPPL: Double? + var thinkKLD: Double? + var genKLD: Double? + var baselineGPU: Int + var peakGPU: Int + var kvDelta: Int + var kvCacheBytes: Int + } + + // MARK: - Sidecar I/O + + private static func loadState(from url: URL) -> SessionState? { + guard let data = try? Data(contentsOf: url) else { return nil } + return try? JSONDecoder().decode(SessionState.self, from: data) + } + + private static func saveState(_ state: SessionState, to url: URL) { + let enc = JSONEncoder() + enc.outputFormatting = [.prettyPrinted, .sortedKeys] + guard let data = try? enc.encode(state) else { return } + try? data.write(to: url, options: .atomic) + } + + // MARK: - Markdown rendering + + private static func renderMarkdown(state: SessionState) -> String { + var md = "" + md += "# Benchmark: \(state.chip) — \(datePortion(state.createdAt))\n\n" + + // Environment block + md += "**Hardware:** \(state.chip), \(state.systemRAM) unified memory" + md += " (GPU limit \(state.gpuLimit))\n" + md += "**OS:** macOS \(state.osVersion)\n" + md += "**Branch:** `\(state.branch)`\n" + md += "**Commit:** \(state.commit)\n" + md += "**NAX:** \(state.naxEnabled ? "ENABLED ✓" : "DISABLED ✗")\n" + md += "**Created:** \(state.createdAt)\n\n" + + if state.models.isEmpty { + md += "_No benchmark rows recorded yet._\n" + } else { + md += "## Models\n\n" + for m in state.models { + md += renderModelSection(m) + } + } + + // Methodology link + md += "## Methodology\n\n" + md += "See [benchmarks/README.md](README.md#methodology) for method definitions, " + md += "perplexity / KLD computation, and memory accounting.\n" + + return md + } + + private static func renderModelSection(_ model: ModelEntry) -> String { + var md = "### \(model.displayName)\n\n" + if !model.repoId.isEmpty { + md += "**Model:** `\(model.repoId)`\n\n" + } + + // Results table (shared across all configs for this model). + md += "#### Results\n\n" + md += "| Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak |\n" + md += "|--------|----:|-------:|--------------:|-------------:|-----:|----------:|--------:|----------:|--------:|---------:|---------:|\n" + for c in model.configs { + for r in c.rows { + let ctx = r.contextSize > 0 ? "\(r.contextSize)" : "—" + let thinkPPL = r.thinkPPL.map { String(format: "%.4f", $0) } ?? "—" + let genPPL = r.genPPL.map { String(format: "%.4f", $0) } ?? "—" + let thinkKLD = r.thinkKLD.map { String(format: "%.4f", $0) } ?? "—" + let genKLD = r.genKLD.map { String(format: "%.4f", $0) } ?? "—" + md += "| \(mdTableCell(c.key))" + md += " | \(ctx)" + md += " | \(r.promptTokens)" + md += " | \(String(format: "%.1f", r.prefillTokPerSec))" + md += " | \(String(format: "%.1f", r.decodeTokPerSec))" + md += " | \(String(format: "%.0f", r.ttftMs))ms" + md += " | \(thinkPPL) | \(genPPL)" + md += " | \(thinkKLD) | \(genKLD)" + md += " | \(formatBytes(r.baselineGPU))" + md += " | \(formatBytes(r.peakGPU)) |\n" + } + } + md += "\n" + + // Output samples (one per config) + md += "#### Output samples\n\n" + for c in model.configs { + md += "**\(c.key)**\n\n" + let sample = c.outputSample.isEmpty ? "_(no output captured)_" + : String(c.outputSample.prefix(400)) + .replacingOccurrences(of: "\n", with: " ") + md += "```\n\(sample)\n```\n\n" + } + + // Parameters (one block per config — placed BELOW results per user direction) + md += "#### Parameters\n\n" + for c in model.configs { + md += "**\(c.key)**\n\n" + md += "| Parameter | Value |\n" + md += "|-----------|-------|\n" + for row in c.parameterRows where row.count == 2 { + md += "| \(row[0]) | \(row[1]) |\n" + } + md += "\n" + if !c.systemPromptSummary.isEmpty { + md += "_System prompt:_ \(c.systemPromptSummary)\n\n" + } + } + + return md + } + + // MARK: - Parameters serialisation + + private static func buildParameterRows(_ p: BenchmarkParameters) -> [[String]] { + func optFloat(_ x: Float?) -> String { + guard let x else { return "nil" } + return String(format: "%g", x) + } + let gp = p.generate + let strat = mdTableCell(kvCacheStrategyLine(from: gp)) + let maxKV = gp.maxKVSize.map { "\($0) tokens (RotatingKVCache)" } ?? "unbounded (KVCacheSimple)" + + // Parameter table — ordered into semantic groups so readers can scan + // related knobs together. Groups in order: KV cache → generation → + // sampling → penalties → thinking → speculative decoding → + // telemetry/runtime. + var rows: [[String]] = [] + + // KV cache + rows.append(contentsOf: [ + ["KV cache strategy", strat], + ["Max KV size", mdTableCell(maxKV)], + ["KV bits", gp.kvBits.map(String.init) ?? "nil"], + ["KV scheme", mdTableCell(gp.kvScheme ?? "nil")], + ["KV group size", "\(gp.kvGroupSize)"], + ["Quantized KV start", "\(gp.quantizedKVStart)"], + ]) + + // Generation budget + rows.append(contentsOf: [ + ["Prefill step size", "\(gp.prefillStepSize)"], + ["Max tokens", gp.maxTokens.map(String.init) ?? "nil"], + ]) + + // Sampling + rows.append(contentsOf: [ + ["Temperature", "\(gp.temperature)"], + ["Top P", "\(gp.topP)"], + ["Top K", "\(gp.topK)"], + ["Min P", "\(gp.minP)"], + ]) + + // Penalties + rows.append(contentsOf: [ + ["Repetition penalty", optFloat(gp.repetitionPenalty)], + ["Repetition context size", "\(gp.repetitionContextSize)"], + ["Presence penalty", optFloat(gp.presencePenalty)], + ["Presence context size", "\(gp.presenceContextSize)"], + ["Frequency penalty", optFloat(gp.frequencyPenalty)], + ["Frequency context size", "\(gp.frequencyContextSize)"], + ]) + + // Thinking / reasoning + rows.append(contentsOf: [ + ["Reasoning effort", mdTableCell(gp.reasoningEffort ?? "nil")], + ["Think start token id", gp.thinkStartTokenId.map { "\($0)" } ?? "nil"], + ["Think end token id", gp.thinkEndTokenId.map { "\($0)" } ?? "nil"], + ["Thinking phase prefilled", gp.thinkingPhasePrefilled ? "true" : "false"], + ]) + if let budget = p.thinkingTokenBudget { + rows.append(["Thinking token budget (processor)", "\(budget)"]) + } + rows.append(["Thinking (effective)", p.thinkingEnabled ? "Yes" : "No"]) + + // Speculative decoding (n-gram + draft-model fields grouped together). + // A later row names the active strategy ("none", "ngram (size=N, …)", + // or "draft (repo-id)") so readers can see the strategy alongside its + // parameters without hopping around the table. + rows.append(contentsOf: [ + ["Speculative decoding", mdTableCell(p.speculativeDecoding)], + ["N-gram size", "\(gp.ngramSize)"], + ["Max n-gram draft tokens", "\(gp.maxNgramDraftTokens)"], + ]) + + // Telemetry / runtime + rows.append(contentsOf: [ + ["Collect per-token data", gp.collectPerTokenData ? "true" : "false"], + ["Track perplexity", gp.trackPerplexity ? "true" : "false"], + ["Perplexity tracking (MLX_BENCH_PPL)", gp.trackPerplexity ? "Yes" : "No"], + ["KL divergence (MLX_BENCH_KLD)", mdTableCell(p.kldSummary)], + ["Batch size (MLX_BENCH_BATCH)", "\(p.batchSize)"], + ["Additional processors count", "\(gp.additionalProcessors.count)"], + ["Max ops per buffer (MLX_MAX_OPS_PER_BUFFER)", mdTableCell(p.maxOpsPerBuffer)], + ]) + + return rows + } + + private static func kvCacheStrategyLine(from p: GenerateParameters) -> String { + if let s = p.kvScheme, !s.isEmpty { + return "TurboQuant (\(s))" + } + if let bits = p.kvBits { + return "Affine (\(bits)-bit, group \(p.kvGroupSize), start \(p.quantizedKVStart))" + } + return "None (FP16)" + } + + private static func mdTableCell(_ s: String) -> String { + s.replacingOccurrences(of: "|", with: "\\|") + } + + // MARK: - Filename helpers + + /// `{chip-slug}-{ram}gb-{YYYY-MM-DD}` — no extension. + static func sessionFilename(hw: HardwareInfo) -> String { + let chipSlug = chipSlug(from: hw.chip) + let ramSlug = hw.systemRAM.lowercased() // "64GB" → "64gb" + let date = sessionDatePortion + return "\(chipSlug)-\(ramSlug)-\(date)" + } + + /// "Apple M1 Max (applegpu_g13s)" → "m1-max". + private static func chipSlug(from chip: String) -> String { + // Strip trailing "(...)" annotation. + var s = chip + if let paren = s.firstIndex(of: "(") { + s = String(s[.. String { + String(iso.prefix(10)) + } + + private static func isoDateTime(_ d: Date) -> String { + let fmt = ISO8601DateFormatter() + fmt.formatOptions = [.withInternetDateTime] + return fmt.string(from: d) + } + + // MARK: - Project root / git + + static func projectRoot() -> URL { + var dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + for _ in 0..<5 { + if FileManager.default.fileExists(atPath: dir.appendingPathComponent("Package.swift").path) { + return dir + } + dir = dir.deletingLastPathComponent() + } + return URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + } + + static func gitBranch() -> String { + let root = projectRoot() + let headPath = root.appendingPathComponent(".git/HEAD").path + return (try? String(contentsOfFile: headPath, encoding: .utf8))? + .trimmingCharacters(in: .whitespacesAndNewlines) + .replacingOccurrences(of: "ref: refs/heads/", with: "") ?? "unknown" + } + + private static func gitLastCommitLine() -> String { + let root = projectRoot() + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/git") + process.arguments = ["-C", root.path, "log", "-1", "--format=%h %s"] + let out = Pipe() + process.standardOutput = out + process.standardError = FileHandle.nullDevice + do { + try process.run() + process.waitUntilExit() + let data = out.fileHandleForReading.readDataToEndOfFile() + guard process.terminationStatus == 0, + var line = String(data: data, encoding: .utf8)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !line.isEmpty + else { + return "`unknown`" + } + line = line.replacingOccurrences(of: "`", with: "'") + line = line.replacingOccurrences(of: "|", with: "\\|") + return "`\(line)`" + } catch { + return "`unknown`" + } + } + + // MARK: - Hardware + + struct HardwareInfo { + let chip: String + let systemRAM: String + let gpuLimit: String + let osVersion: String + } + + static func hardwareInfo() -> HardwareInfo { + let info = GPU.deviceInfo() + let ramGB = Double(info.memorySize) / 1_073_741_824 + let gpuGB = Double(info.maxRecommendedWorkingSetSize) / 1_073_741_824 + let os = ProcessInfo.processInfo.operatingSystemVersion + let chipName = humanReadableChipName(gpuArch: info.architecture) + return HardwareInfo( + chip: chipName, + systemRAM: String(format: "%.0fGB", ramGB), + gpuLimit: String(format: "%.0fGB", gpuGB), + osVersion: "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)" + ) + } + + private static func humanReadableChipName(gpuArch: String) -> String { + var size = 0 + sysctlbyname("machdep.cpu.brand_string", nil, &size, nil, 0) + var brand = [CChar](repeating: 0, count: size) + sysctlbyname("machdep.cpu.brand_string", &brand, &size, nil, 0) + let brandStr = String(cString: brand) + if !brandStr.isEmpty { + return "\(brandStr) (\(gpuArch))" + } + size = 0 + sysctlbyname("hw.model", nil, &size, nil, 0) + var model = [CChar](repeating: 0, count: size) + sysctlbyname("hw.model", &model, &size, nil, 0) + let modelStr = String(cString: model) + let marketingName = appleChipName(from: modelStr, gpuArch: gpuArch) + return "\(marketingName) (\(gpuArch))" + } + + private static func appleChipName(from model: String, gpuArch: String) -> String { + let archLower = gpuArch.lowercased() + let gen: String + if archLower.contains("g13") { gen = "M1" } + else if archLower.contains("g14") { gen = "M2" } + else if archLower.contains("g15") { gen = "M3" } + else if archLower.contains("g16") { gen = "M4" } + else if archLower.contains("g17") { gen = "M5" } + else { return model.isEmpty ? gpuArch : model } + + let variant: String + if archLower.hasSuffix("c") { variant = "Ultra" } + else if archLower.hasSuffix("x") { variant = "Max" } + else if archLower.hasSuffix("d") { variant = "Pro" } + else { variant = "" } + + return variant.isEmpty ? "Apple \(gen)" : "Apple \(gen) \(variant)" + } + + static func formatBytes(_ bytes: Int) -> String { + if bytes >= 1_073_741_824 { + return String(format: "%.2fGB", Double(bytes) / 1_073_741_824) + } else { + return String(format: "%.0fMB", Double(bytes) / 1_048_576) + } + } + + // MARK: - NAX detection (parity with InferenceBenchmark.printBuildEnvironment) + + private static func detectNAX() -> Bool { + let naxObj = FileManager.default.fileExists( + atPath: ".build/arm64-apple-macosx/release/Cmlx.build/mlx-generated/steel_attention_nax.cpp.o") + return naxObj + } + + // MARK: - MLX max ops per buffer (Metal backend defaults) + + /// Hard-coded fallback values. Only used when the parser at + /// ``hardwareDefaultMaxOpsPerBuffer(gpuArch:)`` cannot locate + /// `device.cpp` or the file's format has drifted from what the parser + /// expects. Kept in sync with the current committed defaults. + private static func hardcodedFallback(gpuArchSuffix: Character) -> Int { + switch gpuArchSuffix { + case "p": return 20 + case "g": return 40 + case "s": return 200 + case "d": return 200 + default: return 40 + } + } + + /// Hardware default for max ops per command buffer **before** + /// `MLX_MAX_OPS_PER_BUFFER` is applied. + /// + /// Resolved at runtime by parsing `mlx/backend/metal/device.cpp` from the + /// local mlx-swift dependency (sibling checkout or SPM-fetched path). + /// Reading the same source the library was compiled from eliminates the + /// staleness we otherwise get from duplicating the switch statement in + /// Swift. Falls back to a hardcoded table if the file can't be located or + /// parsed. + static func hardwareDefaultMaxOpsPerBuffer(gpuArch: String) -> Int { + guard let suffix = gpuArch.last else { return 40 } + if let parsed = parseMaxOpsPerBufferFromDeviceCpp(archSuffix: suffix) { + return parsed + } + return hardcodedFallback(gpuArchSuffix: suffix) + } + + /// Whether the last call to ``hardwareDefaultMaxOpsPerBuffer(gpuArch:)`` + /// resolved via the `device.cpp` parse (`true`) or fell back to the + /// hardcoded table (`false`). Surfaced in the Parameters row label so + /// readers can see which path produced the value. + nonisolated(unsafe) private static var lastParseSucceeded = false + + /// Parse the `max_ops_per_buffer_ = N;` line for the given GPU arch + /// suffix from `mlx/backend/metal/device.cpp`. Returns `nil` if the file + /// can't be found or the case isn't present / doesn't match the expected + /// shape. + private static func parseMaxOpsPerBufferFromDeviceCpp(archSuffix: Character) -> Int? { + guard let source = loadDeviceCppSource() else { + lastParseSucceeded = false + return nil + } + + // State machine: find the Device::Device() arch switch, advance to + // the case matching our suffix, then grab the first + // `max_ops_per_buffer_ = N;` inside that case block. + let caseNeedle = "case '\(archSuffix)'" + var inTargetCase = false + for rawLine in source.split(separator: "\n", omittingEmptySubsequences: false) { + let line = rawLine.trimmingCharacters(in: .whitespaces) + if !inTargetCase { + if line.hasPrefix(caseNeedle) { + inTargetCase = true + } + continue + } + // End of case block without finding the assignment — give up. + if line.hasPrefix("case ") || line.hasPrefix("default:") { + break + } + if let value = extractMaxOpsAssignment(line) { + lastParseSucceeded = true + return value + } + if line == "break;" { + break + } + } + lastParseSucceeded = false + return nil + } + + /// Extract `N` from a line like `max_ops_per_buffer_ = 200;`. + private static func extractMaxOpsAssignment(_ line: String) -> Int? { + let prefix = "max_ops_per_buffer_" + guard line.hasPrefix(prefix) else { return nil } + // Skip past `max_ops_per_buffer_`, whitespace, `=`, whitespace. + let afterKey = line.dropFirst(prefix.count) + .drop(while: { $0.isWhitespace }) + guard afterKey.first == "=" else { return nil } + let afterEq = afterKey.dropFirst().drop(while: { $0.isWhitespace }) + let digits = afterEq.prefix(while: { $0.isNumber }) + return Int(digits) + } + + /// Locate and read the mlx `device.cpp` source file. Searches, in order: + /// + /// 1. `$MLX_SWIFT_PATH/Source/Cmlx/mlx/mlx/backend/metal/device.cpp` + /// (explicit override, matches the Makefile's resolution). + /// 2. Sibling repository at `{projectRoot}/../mlx-swift/...` (our primary + /// dev layout; aligned with how `Makefile` finds mlx-swift). + /// 3. SPM checkout at `{projectRoot}/.build/checkouts/mlx-swift/...`. + /// + /// Returns the full file contents, or `nil` if no candidate exists. + private static func loadDeviceCppSource() -> String? { + let relative = "Source/Cmlx/mlx/mlx/backend/metal/device.cpp" + var candidates: [URL] = [] + if let override = ProcessInfo.processInfo.environment["MLX_SWIFT_PATH"], !override.isEmpty { + candidates.append(URL(fileURLWithPath: override).appendingPathComponent(relative)) + } + let root = projectRoot() + candidates.append(root.deletingLastPathComponent() + .appendingPathComponent("mlx-swift") + .appendingPathComponent(relative)) + candidates.append(root.appendingPathComponent(".build/checkouts/mlx-swift") + .appendingPathComponent(relative)) + + for url in candidates where FileManager.default.fileExists(atPath: url.path) { + if let text = try? String(contentsOf: url, encoding: .utf8) { + return text + } + } + return nil + } + + /// Value shown in the Parameters table. Three-state label: + /// - `N (env)` — `MLX_MAX_OPS_PER_BUFFER` was set. + /// - `N (from device.cpp, )` — parsed directly from the mlx source + /// that was built into the linked library. Authoritative. + /// - `N (fallback, )` — `device.cpp` not found or format drifted; + /// hardcoded table was used. A warning signal that the benchmark harness + /// may report stale values. + static func resolvedMaxOpsPerBufferReport() -> String { + let raw = ProcessInfo.processInfo.environment["MLX_MAX_OPS_PER_BUFFER"]? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !raw.isEmpty, let v = Int(raw) { + return "\(v) (env)" + } + let arch = GPU.deviceInfo().architecture + let d = hardwareDefaultMaxOpsPerBuffer(gpuArch: arch) + let safeArch = arch.replacingOccurrences(of: "|", with: "\\|") + let source = lastParseSucceeded ? "from device.cpp" : "fallback" + return "\(d) (\(source), \(safeArch))" + } +} diff --git a/Tests/Benchmarks/Utils/ModelRegistry.swift b/Tests/Benchmarks/Utils/ModelRegistry.swift new file mode 100644 index 0000000000..20ede42859 --- /dev/null +++ b/Tests/Benchmarks/Utils/ModelRegistry.swift @@ -0,0 +1,363 @@ +import Foundation +import MLXLMCommon + +/// A specific quantization variant of a model with its HuggingFace repo ID. +struct ModelVariant { + let quantization: String // "bf16", "8bit", "4bit", "nvfp4", "mxfp4" + let repoId: String +} + +/// A model family with multiple quantization variants and generation parameters. +/// Thinking token configuration for models that support reasoning traces. +/// +/// Two styles are represented: +/// - `bracket` — a single start token pairs with a single end token +/// (Qwen `…`, Gemma 4 `<|channel>…`). +/// - `harmonyChannel` — channel transitions via a marker token plus a +/// channel-name token (GPT-OSS `<|channel|>analysis<|message|>…`). +struct ThinkingConfig { + enum Style { + case bracket(start: String, end: String) + case harmonyChannel( + marker: String, + thinkingChannels: [String], + generationChannels: [String], + /// Token-string sequence forced into the output stream when the + /// harmony budget processor decides reasoning has run long enough. + /// For GPT-OSS: `<|end|>`, `<|start|>`, `assistant`, `<|channel|>`, + /// `final`, `<|message|>` — closing the analysis message and + /// opening the final-channel visible answer. All six are resolved + /// to token IDs at benchmark start-up and handed to the processor. + transitionSequence: [String] + ) + } + + let style: Style + + /// Assistant prefill to inject before generation to trigger thinking mode. + /// Qwen-style models use "\n" prefill; Gemma 4 and GPT-OSS use their + /// chat template's enable_thinking / reasoning_effort controls instead. + let assistantPrefill: String + + /// Qwen-style: ... + static let qwen = ThinkingConfig( + style: .bracket(start: "", end: ""), + assistantPrefill: "\n" + ) + + /// Gemma 4 style: <|channel>thought\n... + /// Thinking is triggered via enable_thinking=true in the chat template. + static let gemma4 = ThinkingConfig( + style: .bracket(start: "<|channel>", end: ""), + assistantPrefill: "" + ) + + /// GPT-OSS / harmony format: <|channel|>analysis<|message|>… for reasoning, + /// <|channel|>final<|message|>… for the visible answer. The model emits + /// the transitions itself; no assistant prefill is needed. `commentary` + /// channel is treated as a generation-phase channel (visible tool/meta + /// commentary rather than chain-of-thought). + static let harmony = ThinkingConfig( + style: .harmonyChannel( + marker: "<|channel|>", + thinkingChannels: ["analysis"], + generationChannels: ["final", "commentary"], + transitionSequence: [ + "<|end|>", "<|start|>", "assistant", + "<|channel|>", "final", "<|message|>" + ] + ), + assistantPrefill: "" + ) +} + +struct ModelFamily { + let name: String // Display name: "Qwen3.5 27B" + let shortName: String // CLI filter: "qwen35-27b" + let variants: [ModelVariant] + let temperature: Float + let topP: Float + let topK: Int + let minP: Float + let presencePenalty: Float? + let repetitionPenalty: Float? + let extraEOSTokens: [String] + /// Whether this model supports thinking mode. + /// When true, benchmarks will force thinking via assistant prefill and track + /// think/gen perplexity separately. + let supportsThinking: Bool + /// Thinking token configuration. Defaults to Qwen-style if not specified. + var thinkingConfig: ThinkingConfig = .qwen + /// Reasoning effort hint passed to GenerateParameters (e.g., "low", "medium", "high"). + /// Used by models like GPT-OSS that support configurable reasoning depth. + let reasoningEffort: String? + + /// Get the variant for a specific quantization, or nil if not available. + func variant(for quantization: String) -> ModelVariant? { + variants.first { $0.quantization == quantization } + } + + /// Ordered preference for baseline selection: bf16 → 8bit → 4bit + static let baselinePreference = ["bf16", "8bit", "4bit"] + + /// Select the highest-fidelity variant that fits in memory. + func selectBaseline(hardware: SystemInfo.Hardware) async throws -> ModelVariant { + for quant in Self.baselinePreference { + guard let v = variant(for: quant) else { continue } + do { + let size = try await SystemInfo.estimateModelSize(repo: v.repoId) + if SystemInfo.fitsInMemory(modelSizeBytes: size, hardware: hardware) { + return v + } + print("[BENCH] Skipping \(name) \(quant) (\(SystemInfo.formatGB(size))) — exceeds \(String(format: "%.0f", hardware.gpuMemoryLimitGB))GB GPU memory") + } catch { + print("[BENCH] Could not check size for \(v.repoId): \(error)") + } + } + + // Try all remaining variants as last resort + for v in variants where !Self.baselinePreference.contains(v.quantization) { + do { + let size = try await SystemInfo.estimateModelSize(repo: v.repoId) + if SystemInfo.fitsInMemory(modelSizeBytes: size, hardware: hardware) { + return v + } + } catch { + continue + } + } + + let smallest = variants.last! + let size = (try? await SystemInfo.estimateModelSize(repo: smallest.repoId)) ?? 0 + throw BenchmarkError( + "\(name) won't fit: smallest variant (\(smallest.quantization)) is \(SystemInfo.formatGB(size)) " + + "but system has \(String(format: "%.0f", hardware.gpuMemoryLimitGB))GB GPU memory" + ) + } +} + +struct BenchmarkError: Error, CustomStringConvertible { + let description: String + init(_ description: String) { self.description = description } +} + +/// Central registry of all benchmark model families and their quantization variants. +enum ModelRegistry { + + // MARK: - Qwen3.5 Family + + static let qwen35_08B = ModelFamily( + name: "Qwen3.5 0.8B", shortName: "qwen35-0.8b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/Qwen3.5-0.8B-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/Qwen3.5-0.8B-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/Qwen3.5-0.8B-4bit"), + .init(quantization: "nvfp4", repoId: "mlx-community/Qwen3.5-0.8B-nvfp4"), + .init(quantization: "mxfp4", repoId: "mlx-community/Qwen3.5-0.8B-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: 1.5, repetitionPenalty: 1.0, + extraEOSTokens: ["<|endoftext|>", "<|im_end|>"], + supportsThinking: true, reasoningEffort: nil + ) + + static let qwen35_2B = ModelFamily( + name: "Qwen3.5 2B", shortName: "qwen35-2b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/Qwen3.5-2B-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/Qwen3.5-2B-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/Qwen3.5-2B-4bit"), + .init(quantization: "nvfp4", repoId: "mlx-community/Qwen3.5-2B-nvfp4"), + .init(quantization: "mxfp4", repoId: "mlx-community/Qwen3.5-2B-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: 1.5, repetitionPenalty: 1.0, + extraEOSTokens: ["<|endoftext|>", "<|im_end|>"], + supportsThinking: true, reasoningEffort: nil + ) + + static let qwen35_4B = ModelFamily( + name: "Qwen3.5 4B", shortName: "qwen35-4b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/Qwen3.5-4B-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/Qwen3.5-4B-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/Qwen3.5-4B-4bit"), + .init(quantization: "nvfp4", repoId: "mlx-community/Qwen3.5-4B-nvfp4"), + .init(quantization: "mxfp4", repoId: "mlx-community/Qwen3.5-4B-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: 1.5, repetitionPenalty: 1.0, + extraEOSTokens: ["<|endoftext|>", "<|im_end|>"], + supportsThinking: true, reasoningEffort: nil + ) + + static let qwen35_9B = ModelFamily( + name: "Qwen3.5 9B", shortName: "qwen35-9b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/Qwen3.5-9B-MLX-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/Qwen3.5-9B-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/Qwen3.5-9B-4bit"), + .init(quantization: "nvfp4", repoId: "mlx-community/Qwen3.5-9B-nvfp4"), + .init(quantization: "mxfp4", repoId: "mlx-community/Qwen3.5-9B-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: 1.5, repetitionPenalty: 1.0, + extraEOSTokens: ["<|endoftext|>", "<|im_end|>"], + supportsThinking: true, reasoningEffort: nil + ) + + static let qwen35_27B = ModelFamily( + name: "Qwen3.5 27B", shortName: "qwen35-27b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/Qwen3.5-27B-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/Qwen3.5-27B-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/Qwen3.5-27B-4bit"), + .init(quantization: "nvfp4", repoId: "dumtjul/Qwen3.5-27B-mlx-nvfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: 1.5, repetitionPenalty: 1.0, + extraEOSTokens: ["<|endoftext|>", "<|im_end|>"], + supportsThinking: true, reasoningEffort: nil + ) + + static let qwen35_35B_A3B = ModelFamily( + name: "Qwen3.5 35B A3B", shortName: "qwen35-35b-a3b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/Qwen3.5-35B-A3B-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/Qwen3.5-35B-A3B-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/Qwen3.5-35B-A3B-4bit"), + .init(quantization: "nvfp4", repoId: "RepublicOfKorokke/Qwen3.5-35B-A3B-mlx-vlm-nvfp4"), + .init(quantization: "mxfp4", repoId: "RepublicOfKorokke/Qwen3.5-35B-A3B-mlx-vlm-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: 1.5, repetitionPenalty: 1.0, + extraEOSTokens: ["<|endoftext|>", "<|im_end|>"], + supportsThinking: true, reasoningEffort: nil + ) + + // MARK: - GPT-OSS + + static let gptOSS20B = ModelFamily( + name: "GPT-OSS 20B", shortName: "gpt-oss-20b", + variants: [ + .init(quantization: "bf16", repoId: "sjgdr/gpt-oss-20b-mlx-fp16"), + .init(quantization: "4bit", repoId: "loan-star/gpt-oss-20b-mlx-4Bit"), + .init(quantization: "mxfp4", repoId: "mlx-community/gpt-oss-20b-MXFP4-Q8"), + ], + temperature: 0.8, topP: 0.8, topK: 0, minP: 0.0, + presencePenalty: nil, repetitionPenalty: nil, + extraEOSTokens: [], + supportsThinking: true, thinkingConfig: .harmony, reasoningEffort: "medium" + ) + + // MARK: - Nemotron (Cascade 2) + + static let nemotron30B = ModelFamily( + name: "Nemotron 30B A3B", shortName: "nemotron-30b-a3b", + variants: [ + .init(quantization: "8bit", repoId: "mlx-community/Nemotron-Cascade-2-30B-A3B-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/Nemotron-Cascade-2-30B-A3B-4bit"), + .init(quantization: "nvfp4", repoId: "RepublicOfKorokke/Nemotron-Cascade-2-30B-A3B-mlx-nvfp4"), + .init(quantization: "mxfp4", repoId: "RepublicOfKorokke/Nemotron-Cascade-2-30B-A3B-mlx-mxfp4"), + ], + temperature: 0.6, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: nil, repetitionPenalty: nil, + extraEOSTokens: [], + supportsThinking: true, reasoningEffort: nil + ) + + // MARK: - Gemma 4 + + static let gemma4_E2B = ModelFamily( + name: "Gemma 4 E2B", shortName: "gemma4-e2b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/gemma-4-e2b-it-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/gemma-4-e2b-it-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/gemma-4-e2b-it-4bit"), + .init(quantization: "mxfp4", repoId: "mlx-community/gemma-4-e2b-it-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 64, minP: 0.0, + presencePenalty: nil, repetitionPenalty: nil, + extraEOSTokens: [], + supportsThinking: true, thinkingConfig: .gemma4, reasoningEffort: nil + ) + + static let gemma4_E4B = ModelFamily( + name: "Gemma 4 E4B", shortName: "gemma4-e4b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/gemma-4-e4b-it-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/gemma-4-e4b-it-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/gemma-4-e4b-it-4bit"), + .init(quantization: "mxfp4", repoId: "mlx-community/gemma-4-e4b-it-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 64, minP: 0.0, + presencePenalty: nil, repetitionPenalty: nil, + extraEOSTokens: [], + supportsThinking: true, thinkingConfig: .gemma4, reasoningEffort: nil + ) + + static let gemma4_26B_A4B = ModelFamily( + name: "Gemma 4 26B A4B", shortName: "gemma4-26b-a4b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/gemma-4-26b-a4b-it-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/gemma-4-26b-a4b-it-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/gemma-4-26b-a4b-it-4bit"), + .init(quantization: "mxfp4", repoId: "mlx-community/gemma-4-26b-a4b-it-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 64, minP: 0.0, + presencePenalty: nil, repetitionPenalty: nil, + extraEOSTokens: [], + supportsThinking: true, thinkingConfig: .gemma4, reasoningEffort: nil + ) + + static let gemma4_31B = ModelFamily( + name: "Gemma 4 31B", shortName: "gemma4-31b", + variants: [ + .init(quantization: "bf16", repoId: "mlx-community/gemma-4-31b-it-bf16"), + .init(quantization: "8bit", repoId: "mlx-community/gemma-4-31b-it-8bit"), + .init(quantization: "4bit", repoId: "mlx-community/gemma-4-31b-it-4bit"), + .init(quantization: "mxfp4", repoId: "mlx-community/gemma-4-31b-it-mxfp4"), + ], + temperature: 1.0, topP: 0.95, topK: 64, minP: 0.0, + presencePenalty: nil, repetitionPenalty: nil, + extraEOSTokens: [], + supportsThinking: true, thinkingConfig: .gemma4, reasoningEffort: nil + ) + + // MARK: - All Families + + static let allFamilies: [ModelFamily] = [ + qwen35_08B, qwen35_2B, qwen35_4B, qwen35_9B, qwen35_27B, qwen35_35B_A3B, + gptOSS20B, nemotron30B, + gemma4_E2B, gemma4_E4B, gemma4_26B_A4B, gemma4_31B, + ] + + /// Alternate `--model` names → registry `shortName` (keys lowercased). + private static let familyAliases: [String: String] = [ + // Nemotron Cascade 2 30B A3B (nemotron_h on MLX) + "nemotron-cascade-2": "nemotron-30b-a3b", + "nemotron-cascade2": "nemotron-30b-a3b", + "nemotron-cascade-2-30b": "nemotron-30b-a3b", + "nemotron-cascade-2-30b-a3b": "nemotron-30b-a3b", + "nemotron-cascade2-30b-a3b": "nemotron-30b-a3b", + ] + + /// Look up a model family by its short name (CLI filter) or a known alias. + static func family(named shortName: String) -> ModelFamily? { + let normalized = shortName.lowercased() + let key = familyAliases[normalized] ?? normalized + return allFamilies.first { $0.shortName == key } + } + + /// Create an ad-hoc family from a custom HuggingFace repo ID. + static func customFamily(repoId: String) -> ModelFamily { + ModelFamily( + name: repoId, shortName: repoId, + variants: [.init(quantization: "custom", repoId: repoId)], + temperature: 0.6, topP: 0.95, topK: 20, minP: 0.0, + presencePenalty: nil, repetitionPenalty: nil, + extraEOSTokens: [], + supportsThinking: false, reasoningEffort: nil + ) + } +} diff --git a/Tests/Benchmarks/Utils/SystemInfo.swift b/Tests/Benchmarks/Utils/SystemInfo.swift new file mode 100644 index 0000000000..2b00a9d8c8 --- /dev/null +++ b/Tests/Benchmarks/Utils/SystemInfo.swift @@ -0,0 +1,70 @@ +import Foundation +import MLX +import MLXHuggingFace + +/// Hardware detection and memory-aware model variant selection. +enum SystemInfo { + + struct Hardware: CustomStringConvertible { + let architecture: String + let systemMemoryGB: Double + let gpuMemoryLimitGB: Double + + var description: String { + "\(architecture), \(String(format: "%.0f", systemMemoryGB))GB RAM, \(String(format: "%.0f", gpuMemoryLimitGB))GB GPU limit" + } + } + + /// Query current hardware info via Metal / sysctl. + static func hardware() -> Hardware { + let info = GPU.deviceInfo() + return Hardware( + architecture: info.architecture, + systemMemoryGB: Double(info.memorySize) / 1_073_741_824, + gpuMemoryLimitGB: Double(info.maxRecommendedWorkingSetSize) / 1_073_741_824 + ) + } + + /// Estimate model weight size by summing .safetensors file sizes from HuggingFace Hub metadata. + /// Uses the HuggingFace API to list repo files, then sums safetensors sizes. + static func estimateModelSize(repo: String) async throws -> Int { + // Use the HF API to list files and their sizes + let urlString = "https://huggingface.co/api/models/\(repo)" + guard let url = URL(string: urlString) else { + throw URLError(.badURL) + } + let (data, _) = try await URLSession.shared.data(from: url) + // Parse the JSON response to extract sibling file sizes + guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], + let siblings = json["siblings"] as? [[String: Any]] + else { + return 0 + } + // Sum sizes of .safetensors files + return siblings + .filter { ($0["rfilename"] as? String)?.hasSuffix(".safetensors") == true } + .compactMap { $0["size"] as? Int } + .reduce(0, +) + } + + /// Check if a model fits in available GPU memory. + /// Adds a 2GB overhead estimate for KV cache, workspace, and framework buffers. + static func fitsInMemory(modelSizeBytes: Int, hardware: Hardware) -> Bool { + let overheadBytes = 2 * 1_073_741_824 // 2GB + let totalNeeded = Double(modelSizeBytes + overheadBytes) + return totalNeeded < hardware.gpuMemoryLimitGB * 1_073_741_824 + } + + /// Format bytes as a human-readable string. + static func formatGB(_ bytes: Int) -> String { + String(format: "%.1fGB", Double(bytes) / 1_073_741_824) + } + + /// Print hardware info as [BENCH] lines. + static func printHardwareInfo() { + let hw = hardware() + print("[BENCH] Hardware: \(hw.architecture)") + print("[BENCH] System RAM: \(String(format: "%.0f", hw.systemMemoryGB))GB") + print("[BENCH] GPU Memory Limit: \(String(format: "%.0f", hw.gpuMemoryLimitGB))GB") + } +} diff --git a/Tests/MLXLMTests/ToolTests.swift b/Tests/MLXLMTests/ToolTests.swift index 51cbc5ab14..2cc2b4cefb 100644 --- a/Tests/MLXLMTests/ToolTests.swift +++ b/Tests/MLXLMTests/ToolTests.swift @@ -196,6 +196,33 @@ struct ToolTests { #expect(toolCall.function.arguments.isEmpty) } + @Test("Test Pythonic Tool Call Parser - Multiple Tools via parseEOS") + func testPythonicParserMultipleToolsEOS() throws { + let parser = PythonicToolCallParser( + startTag: "<|tool_call_start|>", endTag: "<|tool_call_end|>") + + let content1 = + "<|tool_call_start|>[get_weather(location='Paris'), current_time(timezone=\"UTC\")]<|tool_call_end|>" + let toolCalls1 = parser.parseEOS(content1, tools: nil) + + #expect(toolCalls1.count == 2) + #expect(toolCalls1[0].function.name == "get_weather") + #expect(toolCalls1[0].function.arguments["location"] == .string("Paris")) + #expect(toolCalls1[1].function.name == "current_time") + #expect(toolCalls1[1].function.arguments["timezone"] == .string("UTC")) + + // Multiple distinct tool call blocks + let content2 = + "<|tool_call_start|>[get_weather(location='London')]<|tool_call_end|> <|tool_call_start|>[current_time(timezone='UTC')]<|tool_call_end|>" + let toolCalls2 = parser.parseEOS(content2, tools: nil) + + #expect(toolCalls2.count == 2) + #expect(toolCalls2[0].function.name == "get_weather") + #expect(toolCalls2[0].function.arguments["location"] == .string("London")) + #expect(toolCalls2[1].function.name == "current_time") + #expect(toolCalls2[1].function.arguments["timezone"] == .string("UTC")) + } + @Test("Test Pythonic Tool Call Parser - Type Conversion") func testPythonicParserTypeConversion() throws { let parser = PythonicToolCallParser( @@ -495,6 +522,73 @@ struct ToolTests { #expect(toolCall.function.arguments["query"] == .string("AI news")) } + // MARK: - Llama 3 Format Tests + + @Test("Test Llama 3 Tool Call Parser") + func testLlama3Parser() throws { + let parser = Llama3ToolCallParser() + + let content1 = """ + <|python_tag|>{"name": "knowledge_search", "parameters": {"query": "example"}} + """ + + let toolCall1 = try #require(parser.parse(content: content1, tools: nil)) + #expect(toolCall1.function.name == "knowledge_search") + #expect(toolCall1.function.arguments["query"] == .string("example")) + + let content2 = """ + {"name": "get_weather", "arguments": {"location": "Tokyo"}} + """ + + let toolCall2 = try #require(parser.parse(content: content2, tools: nil)) + #expect(toolCall2.function.name == "get_weather") + #expect(toolCall2.function.arguments["location"] == .string("Tokyo")) + + // Pythonic format + let content3 = """ + <|python_tag|>get_weather(location="San Francisco, CA") + """ + + let toolCall3 = try #require(parser.parse(content: content3, tools: nil)) + #expect(toolCall3.function.name == "get_weather") + #expect(toolCall3.function.arguments["location"] == .string("San Francisco, CA")) + + // Multiple arguments Pythonic + let content4 = """ + <|python_tag|>calculate(expression="2 + 2", precision=4) + """ + + let toolCall4 = try #require(parser.parse(content: content4, tools: nil)) + #expect(toolCall4.function.name == "calculate") + #expect(toolCall4.function.arguments["expression"] == .string("2 + 2")) + #expect(toolCall4.function.arguments["precision"] == .string("4")) + + // Multiple JSON list format via parseEOS + let content5 = """ + <|python_tag|>[ + {"name": "get_weather", "parameters": {"location": "New York"}}, + {"name": "get_time", "parameters": {"location": "London"}} + ] + """ + let toolCalls5 = parser.parseEOS(content5, tools: nil) + #expect(toolCalls5.count == 2) + #expect(toolCalls5[0].function.name == "get_weather") + #expect(toolCalls5[0].function.arguments["location"] == .string("New York")) + #expect(toolCalls5[1].function.name == "get_time") + #expect(toolCalls5[1].function.arguments["location"] == .string("London")) + + // Multiple pythonic format via parseEOS + let content6 = """ + <|python_tag|>[get_weather(location="New York"), get_time(location="London")] + """ + let toolCalls6 = parser.parseEOS(content6, tools: nil) + #expect(toolCalls6.count == 2) + #expect(toolCalls6[0].function.name == "get_weather") + #expect(toolCalls6[0].function.arguments["location"] == .string("New York")) + #expect(toolCalls6[1].function.name == "get_time") + #expect(toolCalls6[1].function.arguments["location"] == .string("London")) + } + // MARK: - ToolCallFormat Serialization Tests @Test("Test ToolCallFormat Raw Values for Serialization") @@ -552,8 +646,36 @@ struct ToolTests { #expect(ToolCallFormat.infer(from: "Mistral3") == .mistral) #expect(ToolCallFormat.infer(from: "mistral3_text") == .mistral) + // Llama models - require secondary signals from configData + #expect(ToolCallFormat.infer(from: "llama") == nil) // Should be nil without configData + + let llama3RopeConfig = """ + { + "model_type": "llama", + "rope_scaling": { + "rope_type": "llama3" + } + } + """.data(using: .utf8)! + #expect(ToolCallFormat.infer(from: "llama", configData: llama3RopeConfig) == .llama3) + + let llama3VocabConfig = """ + { + "model_type": "llama", + "vocab_size": 128256 + } + """.data(using: .utf8)! + #expect(ToolCallFormat.infer(from: "LLAMA", configData: llama3VocabConfig) == .llama3) + + let llama2Config = """ + { + "model_type": "llama", + "vocab_size": 32000 + } + """.data(using: .utf8)! + #expect(ToolCallFormat.infer(from: "llama", configData: llama2Config) == nil) + // Unknown models should return nil (use default JSON format) - #expect(ToolCallFormat.infer(from: "llama") == nil) #expect(ToolCallFormat.infer(from: "qwen2") == nil) #expect(ToolCallFormat.infer(from: "mistral") == nil) } diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 0000000000..6ea366591f --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,436 @@ +# Inference Benchmarks + +Automated benchmarks for MLX Swift LM inference across model families, weight quantizations, and KV cache compression strategies running on Apple Silicon. + +The CLI (`benchmark.sh`) is designed to be language-agnostic — all configuration is passed via environment variables, making it straightforward to add backends in other languages (Python, Java) for cross-platform benchmarking. + +Benchmark reports in this directory also serve as **baselines** — periodic full-matrix snapshots of prefill / decode tokens-per-second across the supported model range on a specific piece of hardware at a specific point in time. Use them when: + +- **Diagnosing a perf regression** — compare current numbers against the most recent baseline on matching hardware. +- **Landing a kernel or framework change** — re-run the affected rows and update the baseline if the delta is material. +- **Picking a model for a target device** — the TL;DR table shows prefill/decode at 1k context and whether 8k coherency holds. + +## Setup + +Run once after cloning (or after fetching new `mlx-swift` changes): + +```bash +./scripts/setup-dev.sh +``` + +This resolves Swift packages, compiles Metal shaders, builds the prefill bridge dylib, and does an initial release build. After setup, all benchmark commands work immediately. + +Internally, `setup-dev.sh` and `benchmark.sh` both call `make build-tests`, which handles the full build pipeline incrementally — only rebuilding what actually changed. See the [main README](../README.md#why-make-instead-of-swift-build) for details on why `make` is used. + +If you are iterating on C/C++ code in the `mlx` or `mlx-c` submodules and benchmarks are using stale artifacts, run: + +```bash +make clean-cmlx # Invalidate SPM's C/C++ cache +make status # Verify what's built +``` + +Then re-run your benchmark — it will recompile only the C/C++ target. + +## Quick Start + +```bash +# Simple chat evaluation (default method) +./scripts/benchmark.sh --model qwen35-0.8b + +# Simple eval with perplexity tracking +./scripts/benchmark.sh --model qwen35-0.8b --ppl + +# Context-scaling summarization (3 quick context sizes) +./scripts/benchmark.sh --model qwen35-9b --method summarization --quick + +# WikiText-2 perplexity at a specific context +./scripts/benchmark.sh --model qwen35-0.8b --method wikitext2 --context 1024 + +# Needle-in-a-haystack +./scripts/benchmark.sh --model qwen35-9b --method niah --context 4096 + +# With KLD quality metrics +./scripts/benchmark.sh --model qwen35-0.8b --method summarization --kv affine4 --kld + +# Full matrix: all quants × all KV configs +./scripts/benchmark.sh --model qwen35-0.8b --quant all --kv all --quick + +# Multi-model sweep: two models, two KV configs, quick contexts — one output file +./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 --quick + +# Two methods against the same model +./scripts/benchmark.sh --model qwen35-0.8b --method simple,summarization + +# GPT-OSS with high-effort reasoning, thinking + PPL tracking +./scripts/benchmark.sh --model gpt-oss-20b --reasoning high --think --ppl +``` + +## CLI Reference + +| Flag | Description | Default | +|------|-------------|---------| +| `--model MODELS` | **(required)** Model family / HF repo ID. Comma-separated for multi-model sweeps. | — | +| `--method METHODS` | Benchmark method(s), comma-separated (see [Methods](#methods)) | `simple` | +| `--quant QUANTS` | Weight quantization(s): `bf16`, `8bit`, `4bit`, or `all`. Comma-separated for multiple. | `4bit` | +| `--kv CONFIGS` | KV cache config(s) (see [KV Cache Configurations](#kv-cache-configurations)). Comma-separated or `all`. | `none` | +| `--context SIZES` | Comma-separated context sizes (e.g., `128,1024,4096`) | All 11 sizes | +| `--quick` | Quick mode: 128 + 1024 + 4096 + 32768 tokens only | Off | +| `--ppl` | Track per-token perplexity during generation | Off | +| `--kld` | Compute KL divergence vs bf16/8bit baseline | Off | +| `--baseline` | Auto-select highest-fidelity variant that fits in GPU memory | Off | +| `--batch N` | Run N concurrent generations | `1` | +| `--think` | Enable thinking mode for thinking-capable models | Off | +| `--reasoning EFFORT` | Reasoning effort for models that support it (e.g. GPT-OSS). Values: `low`, `medium`, `high`. Ignored by models without a reasoning-effort setting. | `medium` | +| `--ngram SIZE` | N-gram speculative decoding size. `0` disables speculation entirely (pure autoregressive decode). `3` matches the library's typical-use default (trigram matching, 3-token drafts). Higher values require longer repeated sequences in generated text to hit. Disabled by default so benchmarks measure deterministic decode without accept-rate variance. | `0` | +| `-h`, `--help` | Show usage | — | + +**Comma-separated lists** on `--model`, `--method`, `--quant`, and `--kv` produce the full Cartesian product of permutations. Every permutation runs in sequence, and every row lands in the **same** hardware-dated output file (see [Output](#output)), grouped by model. A sweep like: + +```bash +./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b \ + --method simple,summarization --quant 4bit --kv none,turbo4v2 --quick +``` + +runs 2 × 2 × 1 × 2 = 8 permutations and produces one report file covering both models. + +`--quant all` expands to `bf16,8bit,4bit`. `--kv all` expands to `none,affine8,affine4,turbo4,turbo4v2,turbo3`. These can be combined with comma lists on the other dimensions. + +> **Max speed tip:** For pure throughput measurements, omit `--ppl` and `--kld`. Both flags add significant compute overhead — `--ppl` tracks per-token log-probabilities during generation, and `--kld` loads a second baseline model and runs a full forced-decode pass after generation completes. Leave them off when you only care about tok/s and TTFT. + +## Methods + +| Method | Description | Context Scaling | Generation | Pass/Fail | +|--------|-------------|:---:|:---:|:---:| +| `simple` | Basic chat prompt — generation speed + PPL | No | Yes | No | +| `summarization` | Pre-sized prompts across context sizes | Yes | Yes | No | +| `wikitext2` | Standard LM perplexity via forced decode on WikiText-2 | Yes | No | No | +| `niah` | Needle-in-a-haystack retrieval at multiple depths | Yes | Yes | Yes | +| `multi-turn` | Multi-turn conversation with name recall | No | Yes | Yes | +| `tool-calling` | Tool call generation and validation | No | Yes | Yes | + +## Model Families + +All Qwen3.5 models use a hybrid **GatedDeltaNet** architecture: 75% linear attention layers (MambaCache) + 25% standard attention layers (KVCacheSimple), with full attention every 4th layer. + +| Family | Short Name | Quantizations | Architecture | +|--------|------------|---------------|--------------| +| Qwen3.5 0.8B | `qwen35-0.8b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 2B | `qwen35-2b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 4B | `qwen35-4b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 9B | `qwen35-9b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 27B | `qwen35-27b` | bf16, 8bit, 4bit | GatedDeltaNet | +| Qwen3.5 35B A3B | `qwen35-35b-a3b` | bf16, 8bit, 4bit | GatedDeltaNet MoE | +| GPT-OSS 20B | `gpt-oss-20b` | bf16, 4bit | Transformer | +| Nemotron Cascade 2 30B A3B | `nemotron-30b-a3b` (aliases: `nemotron-cascade-2`, `nemotron-cascade-2-30b-a3b`, …) | 8bit, 4bit, nvfp4, mxfp4 | Nemotron H (hybrid Mamba / attention / MoE) | +| Gemma 4 E2B | `gemma4-e2b` | bf16, 8bit, 4bit, mxfp4 | Dense + PLE | +| Gemma 4 E4B | `gemma4-e4b` | bf16, 8bit, 4bit, mxfp4 | Dense + PLE | +| Gemma 4 26B A4B | `gemma4-26b-a4b` | bf16, 8bit, 4bit, mxfp4 | Transformer MoE | +| Gemma 4 31B | `gemma4-31b` | bf16, 8bit, 4bit, mxfp4 | Dense | + +Any HuggingFace repo ID can also be passed directly as `--model org/repo-id`. + +## Model cache and downloads + +Models are downloaded on first use via [`HubClient`](https://github.com/huggingface/swift-huggingface) (through the `#hubDownloader()` macro in [`Tests/Benchmarks/InferenceBenchmark.swift`](../Tests/Benchmarks/InferenceBenchmark.swift)) and cached in the **Python-compatible Hugging Face cache structure**. That means snapshots downloaded by Python's `huggingface-cli` or `huggingface_hub` are read directly by the benchmark harness without re-downloading, and vice versa. + +### Cache resolution order + +`HubClient` picks the cache directory from the first of these that is set: + +1. **`HF_HUB_CACHE`** — absolute path to the cache directory. Highest priority, use this to point at an external drive, a shared team volume, etc. +2. **`HF_HOME`** — HF home directory; the cache is placed at `$HF_HOME/hub`. +3. **Default**: `~/.cache/huggingface/hub` on non-sandboxed macOS. (Sandboxed Apple apps use `Library/Caches/huggingface/hub`; that path does not apply to the benchmark harness, which runs unsandboxed as a test target.) + +### Examples + +```bash +# Use an external SSD as the cache root (takes precedence over ~/.cache) +export HF_HUB_CACHE="/Volumes/FastSSD/hf-cache" +./scripts/benchmark.sh --model qwen35-0.8b + +# Or organise HF state under one parent directory +export HF_HOME="$HOME/work/hf" # cache ends up at $HF_HOME/hub +./scripts/benchmark.sh --model qwen35-0.8b + +# Fall back to the default (~/.cache/huggingface/hub) +unset HF_HUB_CACHE HF_HOME +./scripts/benchmark.sh --model qwen35-0.8b +``` + +If you set `HF_HUB_CACHE` / `HF_HOME` in your shell rc file, every subsequent `benchmark.sh` invocation and every `swift test` subprocess it spawns will inherit the setting. + +### Cache-first behaviour + +Every `download(...)` call routes through `HubClient.downloadSnapshot`, which checks for a complete cached snapshot (`{cache}/models--{org}--{name}/snapshots/{rev}/…`) before making any HTTP calls. If the exact `(repo, revision, file globs)` is already on disk, the call returns the local directory URL immediately — progress jumps to 100%, no network. A missing file triggers a native Swift download via `URLSession`; no Python `huggingface-cli` or other external tooling is required. + +If you want to guarantee offline behaviour (fail rather than download), that's an upstream feature of `HubClient` via `localFilesOnly: true`. The current harness doesn't expose it as a flag — if you need it, open a tracking issue. + +### Private / gated repositories + +Authentication is handled by the same environment conventions as the Python clients: `HF_TOKEN` in your environment (or `$HF_HOME/token`) gets picked up automatically by `HubClient.default`. You do not need to touch benchmark code. + +### What is cached + +Every snapshot download pulls the file globs the model factory asks for — typically `*.safetensors`, `*.json`, and the tokenizer files (`tokenizer.json`, `tokenizer_config.json`, `*.jinja`). Non-matching files in the repo (training artifacts, README images, etc.) are not downloaded. Compressed caches are **not** supported — each snapshot is stored as symlinked blobs under `blobs/` plus a `snapshots/{rev}/` tree, matching the Python client layout. + +## Context Sizes + +Context-scaling methods (`summarization`, `wikitext2`, `niah`) run across 11 sizes by default: + +**128, 256, 512, 1K, 2K, 4K, 8K, 16K, 32K, 64K, 128K** tokens + +Use `--context` to specify a subset, or `--quick` for 128 + 1024 + 4096. + +For non-scaling methods (`simple`, `multi-turn`, `tool-calling`), the context limit is fixed at 4096 tokens, enforced via `RotatingKVCache` (`maxKVSize`) to simulate a realistic chat deployment. + +## KV Cache Configurations + +| Config | Compression | Description | +|--------|-------------|-------------| +| `none` | — | Unquantized FP16 KV cache (baseline) | +| `affine8` | K 8-bit, V 8-bit | MLX affine 8-bit quantization (quantized start at offset 512) | +| `affine4` | K 4-bit, V 4-bit | MLX affine 4-bit quantization (quantized start at offset 512) | +| `turbo8` | K 8-bit, V 8-bit (symmetric) | TurboQuant MSE 8-bit compression (starts at offset 0) | +| `turbo8v4` | K 8-bit, V 4-bit (asymmetric) | TurboQuant asymmetric: 8-bit keys, 4-bit values | +| `turbo8v2` | K 8-bit, V 2-bit (asymmetric) | TurboQuant asymmetric: 8-bit keys, 2-bit values | +| `turbo4` | K 4-bit, V 4-bit (symmetric) | TurboQuant MSE 4-bit compression (starts at offset 0) | +| `turbo4v3` | K 4-bit, V 3-bit (asymmetric) | TurboQuant asymmetric: 4-bit keys, 3-bit values | +| `turbo4v2` | K 4-bit, V 2-bit (asymmetric) | TurboQuant asymmetric: 4-bit keys, 2-bit values | +| `turbo3` | K 3-bit, V 3-bit (symmetric) | TurboQuant MSE 3-bit compression | +| `turbo3v2` | K 3-bit, V 2-bit (asymmetric) | TurboQuant asymmetric: 3-bit keys, 2-bit values | +| `all` | — | Shortcut: expands to `none,affine8,affine4,turbo4,turbo4v2,turbo3` | + +**Affine** configs use MLX's built-in quantized-cache path (per-group scale + zero point) and defer quantization until offset 512 — the first 512 KV slots stay full precision to avoid stomping on the short-context path that matters most for TTFT. **Turbo** configs use the TurboQuant MSE-optimal codebook starting at offset 0. **Asymmetric** turbo variants (`turbo{K}v{V}`) compress values more aggressively than keys, exploiting the fact that value projections tolerate more quantization noise than keys in attention. + +## Methodology + +### System prompts + +Several methods use the **same** short assistant system message (defined in the benchmark suite as `minimalSystemPrompt`): + +> You are a helpful assistant. Keep responses concise. + +That string applies to **`simple`**, **`multi-turn`**, **`tool-calling`**, and **`niah`**. Individual benchmark markdown files link here instead of repeating long user prompts. + +**`summarization`** (including the warmup pass) uses **no** system role — only user messages built from the bundled prompt files (see Summarization below). **`wikitext2`** has no chat template system role; it evaluates raw WikiText-2 continuation. + +### Simple + +Sends a basic chat prompt ("Hello! What is your name and what can you help me with?") to the model with a 4096-token context limit. Measures generation speed, TTFT, and perplexity. Quick single evaluation without context scaling. No pass/fail validation. + +### Summarization + +Loads pre-generated prompt files (excerpts from The Great Gatsby) sized to each target token count. The context limit (`maxKVSize`) matches the target size, so the KV cache is bounded. The model generates a summary response (up to 200 tokens). Measures prefill throughput, generation throughput, TTFT, perplexity, and GPU memory at each context size. No pass/fail validation. + +### WikiText-2 + +Standard LM perplexity evaluation via **forced decode** on the WikiText-2 test dataset. No generation occurs. + +**How it works:** +1. The WikiText-2 test text is tokenized using the model's tokenizer and sliced to the target context size. +2. Tokens are fed through the model in 2048-token chunks, capturing logits at every position. +3. At each position, the log-probability of the actual next token is computed via `log(softmax(logits, axis: -1))`. +4. KV cache quantization (if configured) is applied after each chunk, measuring its impact on prediction quality. +5. **Word-level PPL** (the standard metric per EleutherAI) is computed: `exp(total_NLL / word_count)`, where word count is from the decoded text. This normalizes across different tokenizers, making results comparable across model families. + +Token-level PPL is also computed and logged but the word-level metric is reported in the results table. Expected ranges: ~15-30 for instruct-tuned 0.8B models on raw Wikipedia text (instruct models score higher than base models since they're fine-tuned for conversations, not raw text continuation). + +### Needle-in-a-Haystack (NIAH) + +Tests long-context retrieval by inserting a known fact into filler text at multiple depth positions and asking the model to retrieve it. + +**How it works:** +1. For each context size, filler text (Great Gatsby excerpts from the pre-sized prompt files) is loaded. +2. The needle — `"The special magic verification code is BLUE TIGER 42."` — is inserted at **5 depth positions**: 10%, 25%, 50%, 75%, and 90% of the document. +3. The retrieval question — `"What is the special magic verification code mentioned in the text above? Reply with only the code, nothing else."` — is appended after the filler. +4. Each depth produces a separate benchmark run (5 rows per context size). +5. The KV cache is **unbounded** (no `maxKVSize`) so the model can see the entire prompt. +6. **Pass/fail**: output is checked for the substring "BLUE TIGER 42" (case-insensitive). Results are prefixed `PASS(@50%)` or `FAIL(@50%)` in the Output column. + +This produces a depth × context matrix showing where the model succeeds or fails at retrieval. Small models (0.8B) typically fail at larger contexts and certain depth positions, while larger models (9B+) should pass consistently. + +### Multi-Turn + +Tests context recall across a multi-turn conversation. Two names ("Bob" and "Alice") are introduced early in the conversation, and the model is asked to recall each one. + +**Conversation structure:** +1. User: "Hello, what is your name?" → Assistant responds +2. User: "My name is Bob and my partner's name is Alice." → Assistant acknowledges (without repeating names) +3. Test 1: "What is my name?" → **PASS** if output contains "Bob" +4. Test 2: "What is my partner's name?" → **PASS** if output contains "Alice" + +Each recall test produces a separate row in the results table. The assistant's acknowledgment is kept neutral ("Nice to meet you! What can I help you with?") to avoid leaking answers. + +### Tool Calling + +Tests whether the model correctly generates a tool call when given a tool-use prompt and a tool specification. + +**Setup:** +- Prompt: "What is the current date and time?" +- Tool: `execute_shell` — a mock shell execution tool with a `command` string parameter +- The model is expected to generate a tool call to `execute_shell` with a command containing "date" + +**Pass/fail** (strict validation): +1. The generation stream must produce a `.toolCall` event → otherwise `FAIL(no tool call)` +2. The tool call function name must be `execute_shell` → otherwise `FAIL(wrong tool: )` +3. The command argument must contain "date" → otherwise `FAIL(wrong command: )` +4. All three pass → `PASS` + +### Perplexity (Think PPL / Gen PPL) + +Perplexity is computed as `exp(mean negative log-probability)` over generated tokens. It is tracked separately for the **thinking phase** and the **generation phase**. Lower values indicate higher model confidence in its predictions. + +Thinking is **disabled by default** for maximum speed. Use `--think` to enable it: + +```bash +# Speed benchmark (no thinking overhead) +./scripts/benchmark.sh --model gemma4-e2b --quant 4bit --method summarization --quick --ppl + +# Quality benchmark with thinking separation +./scripts/benchmark.sh --model gemma4-e2b --quant 4bit --method summarization --quick --ppl --think +``` + +When `--think` is enabled for thinking-capable models: +- **Qwen3.5**: Prefills `\n` in the assistant turn; tracks tokens between `` and `` +- **Gemma 4**: Passes `enable_thinking=true` to the chat template; tracks tokens between `<|channel>` and `` +- A thinking budget processor forces the end-think token after 200 thinking tokens and suppresses EOS during thinking to ensure both phases are measured + +For `wikitext2`, the Gen PPL column reports word-level perplexity from the forced-decode evaluation (no thinking phase applies). + +### KL Divergence (Think KLD / Gen KLD) + +When `--kld` is enabled, KL divergence measures how much a deployment configuration (weight quantization + KV cache compression) degrades the model's output distribution compared to the highest-fidelity baseline available for that model family. + +**How it works:** + +1. The target model generates tokens normally with per-token log-probability tracking enabled. +2. After generation completes, the highest-fidelity baseline model (bf16 preferred, 8-bit fallback if bf16 exceeds GPU memory) is loaded without KV cache compression. +3. The target's generated tokens are **forced-decoded** through the baseline model — each token is fed sequentially, and the baseline's log-probability for that token is recorded. +4. KLD is computed per phase as: `mean(target_logprob - baseline_logprob)` (always >= 0). + +Values near **0** indicate negligible quality loss. Higher values indicate greater divergence from the gold standard. + +**KLD decision matrix:** + +| Target Quant | KV Config | Baseline Selected | KLD Runs? | What It Measures | +|--------------|-----------|-------------------|-----------|------------------| +| bf16 | none | — | No | Target IS the baseline | +| bf16 | affine4/turbo | bf16 | Yes | KV compression cost | +| 8bit | none | bf16 | Yes | Weight quantization cost | +| 8bit | affine4/turbo | bf16 | Yes | Weight quant + KV compression | +| 4bit | none | bf16 | Yes | Weight quantization cost | +| 4bit | affine4/turbo | bf16 | Yes | Weight quant + KV compression | + +When bf16 exceeds GPU memory (e.g., 27B models on 48GB): + +| Target Quant | KV Config | Baseline Selected | KLD Runs? | What It Measures | +|--------------|-----------|-------------------|-----------|------------------| +| 8bit | none | 8bit | No | Same config, skipped | +| 8bit | affine4/turbo | 8bit | Yes | KV compression cost | +| 4bit | none | 8bit | Yes | Weight quantization cost | +| 4bit | affine4/turbo | 8bit | Yes | Weight quant + KV compression | + +### GPU Memory (GPU Baseline / GPU Peak / KV Delta) + +Three memory metrics are reported for each benchmark run: + +- **GPU Baseline**: GPU memory after the model weights are loaded but before generation starts. This is the static cost of holding the model in memory. +- **GPU Peak**: High-water mark of GPU memory during the entire run, including transient allocations. Captured via `MLX.Memory.peakMemory`. +- **KV Delta**: The increase in active GPU memory from the KV cache, measured as `activeGPU - baselineGPU` after generation completes. For KV-quantized runs (affine4, turbo4, turbo3), this reflects the compressed cache size. Comparing KV Delta between `none` and a quantized config at the same context shows how much memory the compression saves. + +**Why GPU Peak is much higher than GPU Baseline + KV Delta:** + +The gap is primarily intermediate computation tensors allocated during the forward pass — attention scores, QKV projections, FFN activations, softmax buffers, Conv1d state (for GatedDeltaNet), and recurrent state updates. These are allocated during each forward step and freed afterward, but they contribute to the peak memory high-water mark. + +Key factors: +- **Prefill dominates peak**: Prefill processes the full prompt at once (e.g., 1024 tokens), creating much larger intermediate tensors than single-token generation. The peak is usually hit during prefill. +- **MLX memory pool**: MLX does not immediately return freed memory to the OS — it caches freed allocations for reuse. `peakMemory` reflects the cumulative high-water mark, not just what is actively held. +- **GatedDeltaNet overhead**: The hybrid GatedDeltaNet architecture (used by all Qwen3.5 models) has higher intermediate memory than standard transformers due to simultaneous QKV projections, conv state concatenation, and gated delta updates per layer. + +## Environment Variables + +All configuration is passed via environment variables, enabling any backend to implement the benchmark interface. + +| Env Var | Values | Default | Description | +|---------|--------|---------|-------------| +| `MLX_BENCH_MODEL` | registry name or HF repo (single value — CLI iterates over multiple) | *required* | Model to benchmark | +| `MLX_BENCH_METHOD` | `simple`, `summarization`, `wikitext2`, `niah`, `multi-turn`, `tool-calling` | `simple` | Test method | +| `MLX_BENCH_QUANT` | `bf16`, `8bit`, `4bit` | `4bit` | Weight quantization | +| `MLX_BENCH_KV` | `none`, `affine8`, `affine4`, `turbo8`, `turbo8v4`, `turbo8v2`, `turbo4`, `turbo4v3`, `turbo4v2`, `turbo3`, `turbo3v2` | `none` | KV cache config | +| `MLX_BENCH_CONTEXT` | comma-separated ints (e.g., `128,1024,4096`) | all 11 sizes | Context sizes to test | +| `MLX_BENCH_PPL` | `1` | unset | Enable perplexity tracking | +| `MLX_BENCH_KLD` | `1` | unset | Enable KLD computation | +| `MLX_BENCH_BASELINE` | `1` | unset | Auto-select highest-fidelity variant that fits in GPU memory | +| `MLX_BENCH_BATCH` | integer | `1` | Number of concurrent generations | +| `MLX_BENCH_THINK` | `1` | unset | Enable thinking mode | +| `MLX_BENCH_REASONING` | `low`, `medium`, `high`, or passthrough | unset (falls back to the model family's registered default) | Reasoning effort for models that honour it (GPT-OSS). Plumbed into `GenerateParameters.reasoningEffort`; ignored by models whose chat templates don't consume it. | +| `MLX_BENCH_NGRAM` | non-negative integer | `0` | N-gram speculative-decoding size. Plumbed into both `GenerateParameters.ngramSize` and `maxNgramDraftTokens`. `0` disables speculation entirely; any positive value enables trigram-style drafting with N tokens of history matched and N draft tokens proposed per round. Benchmark default is `0` so measurements are deterministic; the library itself defaults to `3`. | +| `MLX_BENCH_PROMPT` | string | built-in | Override the `simple`-method user prompt | +| `MLX_MAX_OPS_PER_BUFFER` | integer | hardware default (200 on Max/Ultra) | MLX Metal command-buffer commit threshold. Captured into every Parameters block so report readers can see what was in effect. | + +The underlying test binary (`InferenceBenchmark.swift`) reads a **single** model / method / quant / KV permutation per process — one row of the sweep. `benchmark.sh` does the enumeration and re-invokes `swift test` once per permutation. All processes in a single sweep write into the same hardware-dated report file via the JSON state sidecar described in [Output](#output), so the grouping is preserved even though each row lives in its own process. + +## Output + +Benchmark reports are saved as Markdown files in this `benchmarks/` directory, **one file per run, scoped to the hardware and date it was produced on** — not one file per model. A full-matrix sweep across 14 models lives in a single file, making cross-model comparisons and regression diffs easy to eyeball. + +### File naming + +``` +{hardware}-{ram}-{YYYY-MM-DD}.md +``` + +Examples: +- `m1-max-64gb-2026-04-16.md` +- `m5-max-128gb-2026-04-16.md` +- `m3-ultra-192gb-2026-04-30.md` + +If multiple runs happen on the same hardware on the same day, append a run index or a short tag: `m5-max-128gb-2026-04-16-pr45.md`, `m1-max-64gb-2026-04-16-run2.md`. + +### File structure + +Each benchmark file follows this layout, top to bottom: + +1. **Title** — `# Benchmark: {chip} — {YYYY-MM-DD}`. +2. **Environment block** — hardware (chip + unified memory + GPU limit), OS, branch, commit, NAX state, creation timestamp. +3. **`## Models`** — wrapper heading. +4. **`### {Model name}`** per model, each containing: + - `#### Results` — a single table with one row per `(quant / kv / method)` config × context size, in column order: + `Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak` + - `#### Output samples` — fenced code block per config showing the first ~400 characters of the generated output. Proves the run didn't produce garbage. + - `#### Parameters` — one block per config (below the results as per the owner's preference), with the full parameter table: KV strategy, max KV size, KV bits/scheme/group/start, prefill step size, max tokens, temperature, top_p, top_k, min_p, repetition / presence / frequency penalties, reasoning effort, thinking config, per-token data tracking, n-gram speculative settings, PPL / KLD / batch / speculative / `MLX_MAX_OPS_PER_BUFFER`. +5. **`## Methodology`** — single-line pointer back to this README. + +### How rows are written + +Each `(model, quant, kv, method, context)` run appends exactly one row to the results table for its model. Configs within the same model share a single Results table (rows include the Config column so you can eyeball quant/kv/method deltas side-by-side). Configs remain in insertion order — the order `benchmark.sh` visited them during the sweep. + +State of truth lives in a JSON sidecar next to the markdown file: `benchmarks/.{chip}-{ram}-{date}.state.json`. The markdown is re-rendered from the sidecar on every append. This means: + +- Multi-process sweeps (every `swift test` invocation is its own process) accumulate into the same report. +- Editing the markdown by hand is fine for annotation but the sidecar is the authoritative input — next write overrides the markdown from the sidecar. +- If you need a clean slate on a given day, delete both the `.md` and the matching `.state.json`. + +### Content rules + +- **Parameters live beneath their own config's results row (not in a single top-level block).** This keeps parameter deltas visible when a sweep varied quant or KV config across rows of the same model. +- **Output samples stay short.** ~400 characters is enough to verify coherence. Longer outputs bloat diffs and obscure the signal. +- **Don't repeat the methodology in every file.** The Methodology link at the bottom is the single source of truth; individual files should only add notes when they deviate from the defaults documented here. +- **Record hardware-default `MLX_MAX_OPS_PER_BUFFER`** — on M1 Max/Ultra and M5 Max the committed default is 200; the effective value is captured in every Parameters block regardless of whether it was set via env. + +### When to update baselines + +- A material perf delta lands (≥ 5% on prefill or decode, or any peak-memory change > 10%). +- A kernel or framework change affects the row (even if the net delta is small — the new snapshot anchors the "it worked here" state). +- New hardware is added. + +## Directory layout + +``` +benchmarks/ +├── README.md # This file +├── m1-max-64gb-2026-04-16.md # Full-matrix baseline on M1 Max +├── m5-max-128gb-2026-04-16.md # Full-matrix baseline on M5 Max +├── m3-ultra-192gb-2026-04-30.md # Full-matrix baseline on M3 Ultra +``` + diff --git a/benchmarks/m1-max-64gb-2026-04-16.md b/benchmarks/m1-max-64gb-2026-04-16.md new file mode 100644 index 0000000000..51330e0ca5 --- /dev/null +++ b/benchmarks/m1-max-64gb-2026-04-16.md @@ -0,0 +1,518 @@ +# Benchmark: Apple M1 Max (applegpu_g13s) — 2026-04-16 + +**Hardware:** Apple M1 Max (applegpu_g13s), 64GB unified memory (GPU limit 48GB) +**OS:** macOS 15.7.4 +**Branch:** `alpha` +**Commit:** `8491040 adding .claude to gitignore` +**NAX:** ENABLED ✓ +**Created:** 2026-04-16T17:32:32Z + +## Models + +### Qwen3.5 0.8B + +**Model:** `mlx-community/Qwen3.5-0.8B-bf16` + +#### Results + +| Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak | +|--------|----:|-------:|--------------:|-------------:|-----:|----------:|--------:|----------:|--------:|---------:|---------:| +| bf16 / no-quant / summarization | 128 | 109 | 210.8 | 102.2 | 518ms | — | — | — | — | 1.40GB | 1.60GB | +| 4bit / no-quant / summarization | 128 | 109 | 231.2 | 134.2 | 472ms | — | — | — | — | 404MB | 580MB | +| 4bit / no-quant / simple | 4096 | 49 | 133.3 | 116.0 | 369ms | — | — | — | — | 404MB | 613MB | +| 4bit / turbo4v2 / simple | 4096 | 49 | 176.8 | 113.4 | 279ms | — | — | — | — | 404MB | 613MB | +| 8bit / no-quant / simple | 4096 | 49 | 172.3 | 96.9 | 286ms | — | — | — | — | 763MB | 976MB | +| 8bit / turbo4v2 / simple | 4096 | 49 | 149.8 | 121.4 | 329ms | — | — | — | — | 763MB | 962MB | + +#### Output samples + +**bf16 / no-quant / summarization** + +``` +Based on the excerpt you provided, here is a summary: The text opens with a nostalgic and dramatic monologue written by Zelda in response to "Once again to Zelda." The song asks her to wear a golden hat if it moves her, to bounce high even for herself if she can't help it, and to cry with the phrase "Lover, gold-hatted." The lyrics suggest that the characters in the story are a couple seeking em +``` + +**4bit / no-quant / summarization** + +``` +Based on the text you provided, which is a famous excerpt from **The Song of the Golden Rose** written by F. Scott Fitzgerald in 1923, here is a summary of its content: **What the text says:** The excerpt contains an original dialogue between Zelda and a golden hat character. It begins with the dialogue in English (written on page 1, though the formatting suggests it is often associated with page +``` + +**4bit / no-quant / simple** + +``` +Thinking Process: 1. **Analyze the Request:** The user is asking "Hello! What is your name and what can you help me with?". I need to answer this politely. 2. **Identify Key Information:** * My name (as an AI, I'm not human). Wait, the user isn't asking *my* name. The question is in English and informal ("Hello!"). * Actually, since I am an AI (in the context of this prompt), I don +``` + +**4bit / turbo4v2 / simple** + +``` +The user is asking me to introduce myself and help them with what. I am Qwen3.5, my name is Qwen3.5, and I can help with a variety of tasks, including problem-solving, coding assistance, data analysis, creative writing, logical reasoning, and more. I am **Qwen3.5**. I can assist with various tasks like problem-solving, coding assistance, creative writing, logical reasoning, and data anal +``` + +**8bit / no-quant / simple** + +``` +Thinking Process: 1. **Analyze the Request:** The user is asking for my name and what I can help with. 2. **Determine My Role:** I am Qwen3.5, a large language model developed by Tongyi Lab. 3. **Identify Help Capabilities:** I can help with: * Text generation (writing creative stories, coding, explanations). * Question answering. * Problem-solving and logic reasoning. * +``` + +**8bit / turbo4v2 / simple** + +``` +Thinking Process: 1. **Analyze the Request:** The user is asking two things about me (the AI assistant persona) at first: * "What is your name and what can you help me with?" 2. **Identify the Persona:** I am Qwen3.5, a large-scale language model developed by Tongyi Lab. My name is "Qwen3.5". I am an AI assistant and language model developed by Alibaba Cloud. 3. **Identify Capabilities +``` + +#### Parameters + +**bf16 / no-quant / summarization** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 128 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | nil | +| Think end token id | nil | +| Thinking phase prefilled | false | +| Collect per-token data | false | +| Track perplexity | false | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 0 | +| Thinking (effective) | No | +| Perplexity tracking (MLX_BENCH_PPL) | No | +| KL divergence (MLX_BENCH_KLD) | No | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ No system role message; user-only messages per methodology (no full user prompt in this report). + +**4bit / no-quant / summarization** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 128 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | nil | +| Think end token id | nil | +| Thinking phase prefilled | false | +| Collect per-token data | false | +| Track perplexity | false | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 0 | +| Thinking (effective) | No | +| Perplexity tracking (MLX_BENCH_PPL) | No | +| KL divergence (MLX_BENCH_KLD) | No | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ No system role message; user-only messages per methodology (no full user prompt in this report). + +**4bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**4bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +### Qwen3.5 2B + +**Model:** `mlx-community/Qwen3.5-2B-4bit` + +#### Results + +| Config | Ctx | Prompt | Prefill tok/s | Decode tok/s | TTFT | Think PPL | Gen PPL | Think KLD | Gen KLD | GPU Base | GPU Peak | +|--------|----:|-------:|--------------:|-------------:|-----:|----------:|--------:|----------:|--------:|---------:|---------:| +| 4bit / no-quant / simple | 4096 | 49 | 131.5 | 116.4 | 374ms | — | — | — | — | 1010MB | 1.20GB | +| 4bit / turbo4v2 / simple | 4096 | 49 | 125.0 | 102.1 | 393ms | — | — | — | — | 1010MB | 1.20GB | +| 8bit / no-quant / simple | 4096 | 49 | 116.2 | 87.5 | 423ms | — | — | — | — | 1.86GB | 2.07GB | +| 8bit / turbo4v2 / simple | 4096 | 49 | 134.9 | 96.5 | 365ms | — | — | — | — | 1.86GB | 2.07GB | + +#### Output samples + +**4bit / no-quant / simple** + +``` +The user is asking my name and what I can do. I need to respond clearly, confirming I'm Qwen3.5 from Tongyi Lab. I'll keep it concise since the user asked for conciseness first. My identity is clear enough to avoid unnecessary detail upfront. **Response Plan:** 1. State the name: Qwen (specifically Qwen3.5, but I'll stick to Qwen for broader scope) 2. Directly answer the second question about w +``` + +**4bit / turbo4v2 / simple** + +``` + I'm Qwen3.5, developed by Alibaba Cloud's Tongyi Lab. I can assist with tasks like writing, code generation, logical reasoning, and creative content creation. How can I help you today? +``` + +**8bit / no-quant / simple** + +``` +Okay, the user is asking for my name and capabilities. Let me check the system instructions first. I need to make sure they are in line with the guidelines. The user mentioned that if the response is too technical, I should use simple terms. However, this request is straightforward. First, I should state my name clearly. My name is Qwen3.5. Then, list the main features without technical jargon. C +``` + +**8bit / turbo4v2 / simple** + +``` +The user is asking for my introduction and capabilities. I am Qwen3.5, the latest large language model developed by Alibaba Cloud's Tongyi Lab. I should briefly state my identity and clarify what I can help with, keeping the response concise as requested. 1. State identity: Qwen3.5 by Alibaba Cloud's Tongyi Lab. 2. Clarify capabilities: General knowledge, complex tasks (code, analysis), and spe +``` + +#### Parameters + +**4bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**4bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / no-quant / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | None (FP16) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | nil | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +**8bit / turbo4v2 / simple** + +| Parameter | Value | +|-----------|-------| +| KV cache strategy | TurboQuant (turbo4v2) | +| Max KV size | 4096 tokens (RotatingKVCache) | +| KV bits | nil | +| KV scheme | turbo4v2 | +| KV group size | 64 | +| Quantized KV start | 0 | +| Prefill step size | 2048 | +| Max tokens | 400 | +| Temperature | 1.0 | +| Top P | 0.95 | +| Top K | 20 | +| Min P | 0.0 | +| Repetition penalty | 1 | +| Repetition context size | 20 | +| Presence penalty | 1.5 | +| Presence context size | 20 | +| Frequency penalty | nil | +| Frequency context size | 20 | +| Reasoning effort | nil | +| Think start token id | 248068 | +| Think end token id | 248069 | +| Thinking phase prefilled | true | +| Collect per-token data | true | +| Track perplexity | true | +| N-gram size | 3 | +| Max n-gram draft tokens | 3 | +| Additional processors count | 1 | +| Thinking token budget (processor) | 200 | +| Thinking (effective) | Yes | +| Perplexity tracking (MLX_BENCH_PPL) | Yes | +| KL divergence (MLX_BENCH_KLD) | Yes | +| Batch size (MLX_BENCH_BATCH) | 1 | +| Speculative decoding | ngram (size=3, maxDraft=3) | +| Max ops per buffer (MLX_MAX_OPS_PER_BUFFER) | 200 (hardware default, applegpu_g13s) | + +_System prompt:_ Standard assistant system prompt — verbatim text in [benchmarks README](../README.md#system-prompts). + +## Methodology + +See [benchmarks/README.md](README.md#methodology) for method definitions, perplexity / KLD computation, and memory accounting. diff --git a/benchmarks/m5-max-128gb-2026-04-16.md b/benchmarks/m5-max-128gb-2026-04-16.md new file mode 100644 index 0000000000..948db8199a --- /dev/null +++ b/benchmarks/m5-max-128gb-2026-04-16.md @@ -0,0 +1,297 @@ +# Baseline: M5 Max 128GB — 2026-04-16 + +**Hardware:** M5 Max, 128GB unified memory +**OS:** macOS 26.3 (Darwin 25.3.0) +**Branch:** `alpha` with PR #44 (Gemma 4 coherence + real BPE tokenizer) and PR #45 (Gemma 4 26B MoE + Qwen3.5 GDN fused decode) +**NAX:** enabled +**Method:** `MLX_BENCH_METHOD=summarization`, swift mode (native Swift) and bridge mode (`NATIVE_PREFILL=1`, only meaningful for Gemma 4) +**Coverage:** 14 models × 8 context points (128 → 32k) × swift & bridge paths, plus 8k coherency samples + +## TL;DR + +| Model | Prefill @ 1k | Decode @ 1k | Coherent @ 8k | +|-------|-------------:|------------:|---------------| +| **Gemma 4 E2B (2B)** | **20,206** | 195 | ✅ | +| Qwen2.5 3B | 6,930 | 184 | ✅ | +| Llama 3.2 3B | 6,837 | 202 | ✅ | +| Phi-4 Mini | 6,162 | 163 | ✅ | +| Qwen3 4B | 5,641 | 162 | ✅ (thinking) | +| Qwen3-Coder 30B MoE | 3,469 | 107 | ✅ | +| Mistral 7B | 3,434 | 108 | ✅ | +| Nemotron 30B-A3B | 2,727 | 155 | ✅ | +| GPT-OSS 20B | 2,465 | 111 | ✅ (analysis channel) | +| MiniMax M2 (~46B) | 732 | 57 | ✅ | +| Gemma 4 26B A4B | 642 | 53 | ✅ | +| Qwen3.5 2B (GDN) | 659 | 285 | ✅ | +| Qwen3.5 9B (GDN) | 343 | 93 | ✅ (thinking) | +| Qwen3.5 35B-A3B (GDN MoE) | 271 | 135 | ✅ (thinking) | + +**Key findings:** +- **NAX delivers 2–3.5x prefill speedup** across every model. +- **Bridge vs Swift is within noise for every model except Gemma 4** — only Gemma 4 has a real dlopen-based C++ prefill bridge. For all other models the "bridge" path falls through to Swift. +- **Gemma 4 E2B peaks at 20K tok/s prefill** at 1024 context. +- **Gemma 4 26B A4B** now loads and runs — 600 tok/s prefill, stable 50 tok/s decode through 8k. +- **Qwen3.5 GatedDeltaNet decode** now uses the fused `gatedDeltaStepFused` Metal kernel at T=1; decode is +20–34% on 2B/9B and +128–172% on the 35B MoE (GDN + MoE compounds the dispatch-overhead savings). +- All 14 models produce coherent Gatsby summaries at 8k context. + +## Speed — Prefill / Decode (tokens/sec) + +### Llama-3.2-3B-Instruct-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2798.5 | 210.1 | 2934.9 | 210.0 | +| 512 | 5816.8 | 202.1 | 5823.8 | 201.7 | +| 1024 | 6837.0 | 201.8 | 6755.9 | 202.3 | +| 2048 | 8111.3 | 193.6 | 8112.2 | 192.3 | +| 4096 | 7663.5 | 178.4 | 7704.1 | 177.8 | +| 8192 | 6995.8 | 153.9 | 6971.3 | 153.3 | +| 16384 | 5849.0 | 123.0 | 5844.6 | 122.1 | +| 32768 | 4174.7 | 86.5 | 4198.2 | 85.5 | + +### MiniMax-M2.7-ConfigI-MLX + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 195.9 | 60.0 | 196.4 | 60.1 | +| 512 | 563.3 | 58.2 | 558.5 | 58.3 | +| 1024 | 732.5 | 56.8 | 846.1 | 56.9 | +| 2048 | 870.8 | 54.5 | 812.8 | 54.6 | +| 4096 | 861.8 | 51.2 | 928.7 | 51.1 | +| 8192 | 895.5 | 44.6 | 923.0 | 45.0 | +| 16384 | 815.0 | 38.3 | 829.2 | 38.1 | +| 32768 | 522.3 | 29.1 | 672.9 | 29.4 | + +### Mistral-7B-Instruct-v0.3-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 1991.5 | 111.5 | 1993.2 | 111.3 | +| 512 | 3181.7 | 110.8 | 3175.2 | 110.2 | +| 1024 | 3434.1 | 108.3 | 3437.6 | 106.7 | +| 2048 | 3530.8 | 105.8 | 3513.2 | 105.4 | +| 4096 | 3418.9 | 102.4 | 3426.9 | 101.5 | +| 8192 | 3199.7 | 93.1 | 3196.9 | 92.8 | +| 16384 | 2716.2 | 78.5 | 2739.4 | 78.3 | +| 32768 | 2041.4 | 56.5 | 2044.6 | 59.2 | + +### Nemotron-Cascade-2-30B-A3B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 128.4 | 155.1 | 965.7 | 155.5 | +| 512 | 2313.5 | 155.7 | 2349.6 | 154.2 | +| 1024 | 2726.6 | 154.5 | 2711.6 | 152.9 | +| 2048 | 2527.0 | 153.5 | 2514.9 | 152.3 | +| 4096 | 2425.8 | 149.5 | 2430.5 | 152.1 | +| 8192 | 2356.1 | 148.0 | 2368.6 | 148.3 | +| 16384 | 2323.6 | 143.5 | 2323.7 | 143.3 | +| 32768 | 2218.4 | 133.8 | 2223.6 | 134.9 | + +### Phi-4-mini-instruct-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2479.3 | 173.6 | 2405.1 | 172.4 | +| 512 | 5310.7 | 169.4 | 5418.5 | 167.9 | +| 1024 | 6161.8 | 162.9 | 6129.1 | 163.4 | +| 2048 | 6810.8 | 157.4 | 6806.0 | 156.1 | +| 4096 | 6594.3 | 145.3 | 6555.0 | 145.2 | +| 8192 | 6006.0 | 126.7 | 5997.1 | 126.3 | +| 16384 | 5020.7 | 101.3 | 5018.8 | 101.3 | +| 32768 | 3630.3 | 72.3 | 3577.5 | 72.3 | + +### Qwen2.5-3B-Instruct-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2447.7 | 199.0 | 2527.1 | 198.8 | +| 512 | 6466.1 | 190.9 | 6252.3 | 192.3 | +| 1024 | 6929.6 | 183.5 | 7069.8 | 184.1 | +| 2048 | 7845.6 | 178.2 | 7990.8 | 178.2 | +| 4096 | 7763.9 | 176.2 | 7786.4 | 177.6 | +| 8192 | 7181.2 | 163.8 | 7196.7 | 164.6 | +| 16384 | 6089.4 | 140.7 | 6071.6 | 140.8 | +| 32768 | 4628.9 | 113.7 | 4644.2 | 113.9 | + +### Qwen3-4B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 2185.3 | 172.2 | 2135.6 | 171.8 | +| 512 | 5038.4 | 168.2 | 4915.7 | 167.9 | +| 1024 | 5641.3 | 161.6 | 5613.0 | 161.0 | +| 2048 | 5911.1 | 154.1 | 5876.6 | 153.9 | +| 4096 | 5640.3 | 141.2 | 5626.1 | 140.7 | +| 8192 | 5002.1 | 121.9 | 4965.6 | 122.1 | +| 16384 | 4011.4 | 95.5 | 4008.7 | 95.4 | +| 32768 | 2729.4 | 66.8 | 2718.8 | 66.8 | + +### Qwen3-Coder-30B-A3B-Instruct-MLX-6bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 752.0 | 111.9 | 748.8 | 112.2 | +| 512 | 2366.6 | 109.0 | 2404.4 | 108.7 | +| 1024 | 3468.5 | 106.9 | 3499.3 | 106.5 | +| 2048 | 4378.6 | 101.9 | 4378.7 | 102.4 | +| 4096 | 3819.9 | 96.3 | 4267.6 | 96.6 | +| 8192 | 3787.3 | 85.7 | 3805.6 | 86.3 | +| 16384 | 3057.8 | 72.5 | 3075.0 | 72.5 | +| 32768 | 2080.5 | 56.4 | 2072.2 | 56.3 | + +### Qwen3.5-2B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 735.6 | 289.6 | 735.6 | 289.6 | +| 512 | 738.1 | 287.9 | 738.1 | 287.9 | +| 1024 | 658.7 | 284.6 | 658.7 | 284.6 | +| 2048 | 632.6 | 278.9 | 632.6 | 278.9 | +| 4096 | 617.6 | 267.2 | 617.6 | 267.2 | +| 8192 | 639.8 | 247.8 | 639.8 | 247.8 | +| 16384 | 608.9 | 209.7 | 608.9 | 209.7 | +| 32768 | 625.8 | 164.4 | 625.8 | 164.4 | + +### Qwen3.5-35B-A3B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 234.6 | 137.6 | 234.6 | 137.6 | +| 512 | 259.5 | 135.6 | 259.5 | 135.6 | +| 1024 | 270.7 | 134.8 | 270.7 | 134.8 | +| 2048 | 257.9 | 133.0 | 257.9 | 133.0 | +| 4096 | 259.3 | 132.5 | 259.3 | 132.5 | +| 8192 | 258.5 | 126.0 | 258.5 | 126.0 | +| 16384 | 247.6 | 120.9 | 247.6 | 120.9 | +| 32768 | 199.7 | 107.3 | 199.7 | 107.3 | + +### Qwen3.5-9B-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 354.2 | 94.8 | 354.2 | 94.8 | +| 512 | 307.1 | 93.4 | 307.1 | 93.4 | +| 1024 | 342.9 | 92.7 | 342.9 | 92.7 | +| 2048 | 321.9 | 90.6 | 321.9 | 90.6 | +| 4096 | 315.6 | 88.3 | 315.6 | 88.3 | +| 8192 | 322.0 | 85.2 | 322.0 | 85.2 | +| 16384 | 281.0 | 87.6 | 281.0 | 87.6 | +| 32768 | 279.2 | 80.5 | 279.2 | 80.5 | + +### gemma-4-26b-a4b-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 444.2 | 51.6 | 447.5 | 50.3 | +| 512 | 631.1 | 53.0 | 582.4 | 52.0 | +| 1024 | 642.3 | 52.7 | 594.4 | 51.2 | +| 2048 | 631.6 | 51.9 | 627.9 | 50.0 | +| 4096 | 621.6 | 51.7 | 620.9 | 49.6 | +| 8192 | 598.1 | 50.1 | 591.6 | 49.0 | +| 16384 | 547.0 | 47.2 | 569.3 | 47.2 | +| 32768 | 522.1 | 42.6 | — | — | + +### gemma-4-e2b-it-4bit + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 5000.3 | 193.7 | 5531.8 | 200.5 | +| 512 | 17845.7 | 194.4 | 17269.5 | 194.1 | +| 1024 | 20206.1 | 194.8 | 20149.1 | 195.4 | +| 2048 | 16744.6 | 193.5 | 16620.0 | 193.1 | +| 4096 | 13611.2 | 189.1 | 13564.3 | 188.9 | +| 8192 | 13321.7 | 179.7 | 13397.6 | 180.9 | +| 16384 | 12682.6 | 168.6 | 12675.1 | 168.1 | +| 32768 | 11292.0 | 145.0 | 11317.4 | 145.1 | + +### gpt-oss-20b-MXFP4-Q8 + +| Ctx | Prefill (swift) | Decode (swift) | Prefill (bridge) | Decode (bridge) | +|----:|--------:|--------:|--------:|--------:| +| 128 | 379.6 | 113.6 | 969.3 | 111.5 | +| 512 | 2199.5 | 112.5 | 2278.2 | 111.6 | +| 1024 | 2465.3 | 110.7 | 2803.9 | 110.9 | +| 2048 | 3248.4 | 108.8 | 3285.8 | 113.3 | +| 4096 | 2534.4 | 106.9 | 3263.7 | 105.7 | +| 8192 | 2939.7 | 101.9 | 3203.2 | 101.2 | +| 16384 | 2943.7 | 92.1 | 3027.8 | 95.0 | +| 32768 | 2598.6 | 79.2 | 2614.8 | 81.8 | + + +## Coherency — 8k Context Output + +## gemma-4-e2b-it-4bit (swift) +``` +This is a fascinating excerpt from **The Great Gatsby** by F. Scott Fitzgerald, likely narrated by the character **Nick Carraway**. +``` + +## gemma-4-26b-a4b-4bit (swift) +``` +The excerpt is the opening of F. Scott Fitzgerald's *The Great Gatsby*, narrated by Nick Carraway. Nick introduces himself, recalls his father's advice about reserving judgment, and describes his move east to West Egg on Long Island the summer he met Gatsby. +``` + +## gpt-oss-20b-MXFP4-Q8 (swift) +``` +<|channel|>analysis<|message|>We need to summarize the content. The content is a long, somewhat chaotic text that appears to be a mash-up of "The Grea +``` + +## Llama-3.2-3B-Instruct-4bit (swift) +``` +The passage is the opening of F. Scott Fitzgerald's novel "The Great Gatsby". The story is narrated by Nick Carraway, a young man from the Midwest who +``` + +## Mistral-7B-Instruct-v0.3-4bit (swift) +``` +This is the first chapter of "The Great Gatsby" by F. Scott Fitzgerald. The novel is set in the summer of 1922 and follows the story of Nick Carraway, +``` + +## Nemotron-Cascade-2-30B-A3B-4bit (swift) +``` +We need to summarize the content above, which presumably is an excerpt or a parody of The Great Gatsby with a modern twist, but we need to summarize t +``` + +## Phi-4-mini-instruct-4bit (swift) +``` +Nick Carraway, a bond man living in East Egg, New York, recounts a summer evening spent visiting Daisy Buchanan, a distant cousin and a resident of a +``` + +## Qwen2.5-3B-Instruct-4bit (swift) +``` +The passage describes the protagonist's journey to East Egg, where he meets Tom Buchanan and his wife, Daisy. The interaction with Tom and Daisy revea +``` + +## Qwen3-4B-4bit (swift) +``` + +``` + +## Qwen3-Coder-30B-A3B-Instruct-MLX-6bit (swift) +``` +Here's a summary of the first chapter of *The Great Gatsby*: +``` + +## Qwen3.5-2B-4bit (swift) +``` +The provided text is the opening chapter of *The Great Gatsby* by F. Scott Fitzgerald. It is divided into three main sections: +``` + +## Qwen3.5-9B-4bit (swift) +``` +Thinking Process: +``` + +## Qwen3.5-35B-A3B-4bit (swift) +``` +Thinking Process: +``` + +## MiniMax-M2.7-ConfigI-MLX (swift) +``` +The user asks: "Summarize the content above." The content is a passage from The Great Gatsby, Chapter 1. Summarize the content. +``` + + +## Raw Log + +Full timestamped run log in `/tmp/overnight_bench/log.txt` diff --git a/experiments/self_draft_benchmark.py b/experiments/self_draft_benchmark.py new file mode 100644 index 0000000000..291029d4f2 --- /dev/null +++ b/experiments/self_draft_benchmark.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +""" +Self-draft speculative decoding viability test for Qwen3.6-35B-A3B. + +RESULT: NOT VIABLE. Two independent failure modes kill this approach. + +Test methodology: + Phase 1: Best-case acceptance rate (both models get proper cache, same inputs) + Phase 2: Per-token timing (draft cost vs full cost) + Analysis: Theoretical speedup = (1 + N*alpha) / (N*draft_cost/full_cost + 1) + +Architecture: 40 layers, attention at [3,7,11,15,19,23,27,31,35,39], rest GDN. +""" + +import sys +sys.path.insert(0, "/Users/tom/dev/mlx-lm") + +import time +import mlx.core as mx +from mlx_lm import load +from mlx_lm.models.cache import KVCache, ArraysCache +from mlx_lm.models.qwen3_5 import create_attention_mask, create_ssm_mask + +MODEL_PATH = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" +PROMPT = "Explain the key differences between transformer attention and linear attention mechanisms in modern language models. Be specific about computational complexity and memory usage." + + +def early_exit_forward(model, tokens, cache, exit_layer): + """Forward through first exit_layer layers, then norm + lm_head.""" + lm = model.language_model + inner = lm.model + hidden = inner.embed_tokens(tokens) + fa_mask = create_attention_mask(hidden, cache[inner.fa_idx] if inner.fa_idx < exit_layer else None) + ssm_mask = create_ssm_mask(hidden, cache[inner.ssm_idx] if inner.ssm_idx < exit_layer else None) + for i in range(exit_layer): + layer = inner.layers[i] + mask = ssm_mask if layer.is_linear else fa_mask + hidden = layer(hidden, mask=mask, cache=cache[i]) + hidden = inner.norm(hidden) + if lm.args.tie_word_embeddings: + return inner.embed_tokens.as_linear(hidden) + return lm.lm_head(hidden) + + +def phase1_acceptance(model, tokenizer, prompt, exit_layer, max_tokens=150): + """Best-case acceptance rate measurement.""" + tokens = mx.array(tokenizer.encode(prompt)) + full_cache = model.make_cache() + ee_cache = model.make_cache() + + full_logits = model.language_model(tokens[None, :], cache=full_cache) + _ = early_exit_forward(model, tokens[None, :], ee_cache, exit_layer) + full_tok = mx.argmax(full_logits[:, -1, :], axis=-1) + mx.eval(full_tok) + + matches = 0 + total = 0 + for _ in range(max_tokens - 1): + inp = full_tok.reshape(1, 1) + fl = model.language_model(inp, cache=full_cache) + full_tok = mx.argmax(fl[:, -1, :], axis=-1) + eel = early_exit_forward(model, inp, ee_cache, exit_layer) + ee_tok = mx.argmax(eel[:, -1, :], axis=-1) + mx.eval(full_tok, ee_tok) + total += 1 + if full_tok.item() == ee_tok.item(): + matches += 1 + if full_tok.item() == tokenizer.eos_token_id: + break + + return matches / total if total else 0, total + + +def main(): + print("Loading model...") + model, tokenizer = load(MODEL_PATH) + layers = model.language_model.model.layers + attn_idx = [i for i, l in enumerate(layers) if not l.is_linear] + print(f"{len(layers)} layers. Attention at: {attn_idx}") + + print("\n=== Phase 1: Acceptance Rate vs Exit Depth ===") + print(f"{'Exit@':<8} {'Layers skipped':<16} {'Match%':<10}") + print("-" * 40) + for el in [4, 8, 12, 16, 20, 24, 28, 32, 36, 38, 39]: + match_rate, n = phase1_acceptance(model, tokenizer, PROMPT, el, max_tokens=150) + print(f"{el:<8} {40-el:<16} {match_rate*100:<10.1f}") + + print("\n=== Phase 2: Per-Token Timing ===") + tokens = mx.array(tokenizer.encode(PROMPT)) + for el in [32, 36, 38, 39]: + dc = model.make_cache() + fc = model.make_cache() + _ = early_exit_forward(model, tokens[None, :], dc, el) + _ = model.language_model(tokens[None, :], cache=fc) + mx.eval(mx.array(0)) + tok = mx.array([[1]]) + start = time.perf_counter() + for _ in range(50): + l = early_exit_forward(model, tok, dc, el) + mx.eval(mx.argmax(l[:, -1, :], axis=-1)) + dt = (time.perf_counter() - start) / 50 + start = time.perf_counter() + for _ in range(50): + l = model.language_model(tok, cache=fc) + mx.eval(mx.argmax(l[:, -1, :], axis=-1)) + ft = (time.perf_counter() - start) / 50 + print(f" Exit@{el}: draft={dt*1000:.1f}ms, full={ft*1000:.1f}ms, " + f"ratio={dt/ft:.3f}, savings={100*(1-dt/ft):.1f}%") + + +if __name__ == "__main__": + main() + + +""" +═══════════════════════════════════════════════════════════════════════════════ +RESULTS (Qwen3.6-35B-A3B-4bit, M-series GPU, greedy decode, 150 tokens) +═══════════════════════════════════════════════════════════════════════════════ + +Phase 1 — Acceptance Rate: + Exit@4: 0.7% Exit@20: 1.3% Exit@36: 18.1% + Exit@8: 0.7% Exit@24: 1.3% Exit@38: 34.9% + Exit@12: 0.7% Exit@28: 2.0% Exit@39: 71.8% + Exit@16: 0.7% Exit@32: 3.4% + +Phase 2 — Per-Token Timing: + Exit@39: draft=9.9ms, full=10.1ms → 1.8% savings (1 layer skipped) + Exit@38: ~3-4% savings (2 layers skipped) + Exit@32: ~18-20% savings (8 layers skipped) + +Phase 3 — Theoretical Speedup (best case, exit@39, alpha=0.72): + N=3 drafts: speedup = (1 + 3*0.72) / (3*0.98 + 1) = 3.15 / 3.94 = 0.80x ← SLOWER + N=5 drafts: speedup = (1 + 5*0.72) / (5*0.98 + 1) = 4.59 / 5.90 = 0.78x ← SLOWER + +TWO INDEPENDENT FAILURE MODES: + 1. Acceptance cliff: acceptance drops from 72% (skip 1 layer) to 35% (skip 2) + to 3% (skip 8). The LM head cannot read intermediate hidden states. + 2. Cost cliff: skipping 1 layer saves only 2% per draft token. You need to + skip many layers for meaningful savings, but then acceptance goes to zero. + +The two cliffs are complementary: high acceptance requires near-full depth +(no cost savings), and meaningful cost savings require shallow exit (no +acceptance). There is no sweet spot. + +BASELINE PERFORMANCE: 100.5 tok/s (already fast on this hardware) + +RECOMMENDATION: Abandon dynamic self-draft for Qwen3.5/3.6. This approach +requires one of: + a) Trained early-exit heads (lightweight projections at 2-3 depth points) + b) Layer-skip distillation (expensive training, model-specific) + c) A separate small draft model (e.g., Qwen3-0.5B → ~$0 to implement) + d) N-gram / prompt-lookup speculation (already implemented in codebase) + e) Jacobi-style parallel decoding (orthogonal approach, worth investigating) + +Option (c) is the most practical path — the existing SpeculativeTokenIterator +already supports it with zero changes needed. +═══════════════════════════════════════════════════════════════════════════════ +""" diff --git a/experiments/test_decode_path_draft.py b/experiments/test_decode_path_draft.py new file mode 100644 index 0000000000..fb3f85ed26 --- /dev/null +++ b/experiments/test_decode_path_draft.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +""" +Train draft head on DECODE-PATH hidden states (not prefill). + +The key insight: prefill hidden states live in a different distribution +than decode hidden states. EAGLE works because it trains on the decode +trajectory. Let's do the same — run the model autoregressively, collect +(h_t, next_token) pairs from the actual decode path, train the MLP on those. + +Plan: +1. Prefill a prompt +2. Decode 2000 tokens autoregressively, saving (h_t, token_{t+1}) at each step +3. Train MLP on those pairs +4. Measure acceptance on a DIFFERENT prompt's decode trajectory +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + +class DraftHead(nn.Module): + """Tiny MLP: h_t → h_{t+1} prediction, then LM head maps to logits.""" + def __init__(self, D, inner=256): + super().__init__() + self.proj_in = nn.Linear(D, inner, bias=False) + self.proj_out = nn.Linear(inner, D, bias=False) + def __call__(self, h): + return self.proj_out(nn.gelu(self.proj_in(h))) + + +def collect_decode_data(model, tok, prompt, num_tokens=2000): + """Run autoregressive decode, collect (h_t, next_token) pairs.""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + # Decode — collect pairs + h_list = [] + tok_list = [] + + t0 = time.perf_counter() + for step in range(num_tokens): + h_list.append(last_h) + + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + full_pred = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(full_pred, last_h) + + tok_list.append(full_pred.item()) + y = full_pred.squeeze() + + if (step + 1) % 500 == 0: + elapsed = time.perf_counter() - t0 + print(f" collected {step+1}/{num_tokens} ({(step+1)/elapsed:.0f} tok/s)", flush=True) + + t1 = time.perf_counter() + print(f" collected {num_tokens} decode pairs in {t1-t0:.1f}s ({num_tokens/(t1-t0):.0f} tok/s)", flush=True) + + h_train = mx.stack(h_list) # [N, D] + targets = mx.array(tok_list) # [N] + mx.eval(h_train, targets) + return h_train, targets + + +def train_head(draft_head, lm_head, h_train, targets, epochs=5, batch_size=256, lr=1e-3): + """Train draft head on decode-path data.""" + T = h_train.shape[0] + optimizer = optim.Adam(learning_rate=lr) + + def loss_fn(m, hb, tb): + logits = lm_head(m(hb)) + return nn.losses.cross_entropy(logits, tb).mean() + lg = nn.value_and_grad(draft_head, loss_fn) + + for ep in range(epochs): + perm = mx.array(np.random.permutation(T)) + total_loss = 0 + n = 0 + for j in range(0, T, batch_size): + idx = perm[j:j+batch_size] + loss, grads = lg(draft_head, h_train[idx], targets[idx]) + optimizer.update(draft_head, grads) + mx.eval(draft_head.parameters(), optimizer.state) + total_loss += loss.item() + n += 1 + if ep == 0 or (ep+1) % 2 == 0: + print(f" epoch {ep+1}/{epochs}: loss={total_loss/n:.4f}", flush=True) + + +def measure_decode_acceptance(model, draft_head, tok, prompt, num_tokens=200): + """Measure acceptance on a DIFFERENT prompt (held-out).""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + matches = 0 + total = 0 + for _ in range(num_tokens): + # Draft prediction from last_h + h_draft = draft_head(last_h) + draft_logits = lm.lm_head(h_draft[None]) + draft_pred = mx.argmax(draft_logits, axis=-1) + + # Full forward + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + full_logits = lm.lm_head(h) + full_pred = mx.argmax(full_logits[:, -1], axis=-1) + last_h = h[0, -1] + + mx.eval(draft_pred, full_pred, last_h) + if draft_pred.item() == full_pred.item(): + matches += 1 + total += 1 + y = full_pred.squeeze() + + return matches, total + + +if __name__ == "__main__": + print("loading model...", flush=True) + model, tok = load(MODEL) + lm = model.language_model + D = lm.model.layers[0].input_layernorm.weight.shape[0] + print(f"loaded. D={D}", flush=True) + + # Phase 1: collect DECODE-PATH training data + print("\n--- Phase 1: Collect decode-path data ---", flush=True) + train_prompt = ( + "Write a comprehensive essay about the history of artificial intelligence, " + "starting from Alan Turing's foundational work through modern deep learning. " + "Cover key milestones, breakthroughs, and the people behind them." + ) + h_train, targets = collect_decode_data(model, tok, train_prompt, num_tokens=2000) + + # Phase 2: train + evaluate at different configs + test_prompts = [ + "Explain the theory of general relativity in simple terms.", + "Write a Python function that implements binary search.", + "What are the main differences between classical and quantum computing?", + ] + + for inner_dim in [256, 512]: + for epochs in [3, 10]: + print(f"\n--- inner={inner_dim}, epochs={epochs} ---", flush=True) + draft = DraftHead(D, inner=inner_dim) + params = sum(v.size for _, v in tree_flatten(draft.parameters())) + print(f" params: {params/1e6:.1f}M", flush=True) + + t0 = time.perf_counter() + train_head(draft, lm.lm_head, h_train, targets, epochs=epochs) + t1 = time.perf_counter() + print(f" train: {t1-t0:.1f}s", flush=True) + + # Calib match (on training data — decode path) + cp = mx.argmax(lm.lm_head(draft(h_train)), axis=-1) + mx.eval(cp) + cm = (cp == targets).astype(mx.float32).mean().item() + print(f" calib (decode-path): {cm*100:.1f}%", flush=True) + + # Test on held-out prompts + for prompt in test_prompts: + matches, total = measure_decode_acceptance( + model, draft, tok, prompt, num_tokens=100) + short = prompt[:50] + print(f" held-out '{short}...': {matches}/{total} = {matches/total*100:.0f}%", flush=True) + + print("\nDONE") diff --git a/experiments/test_draft_head_50k.py b/experiments/test_draft_head_50k.py new file mode 100644 index 0000000000..b9338112e2 --- /dev/null +++ b/experiments/test_draft_head_50k.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +""" +Scale-up: EAGLE-style draft head training on decode-path data. + +Key changes vs tiny prototype: +1. 10K decode tokens (not 2K) — ~100s collection +2. Bigger MLP (16M params, 2 hidden layers) +3. Input = concat(h_t, embed(token_t)) — gives token identity context +4. More epochs with LR scheduling +5. Test on 3 held-out prompts with 200 tokens each +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + + +class DraftHeadV2(nn.Module): + """2-layer MLP with token embedding concat. ~16M params.""" + def __init__(self, hidden_dim, inner_dim=2048): + super().__init__() + # Input: concat(h_t, embed(token_t)) = 2 * hidden_dim + self.layer1 = nn.Linear(hidden_dim * 2, inner_dim, bias=False) + self.layer2 = nn.Linear(inner_dim, inner_dim, bias=False) + self.proj_out = nn.Linear(inner_dim, hidden_dim, bias=False) + + def __call__(self, h_and_emb): + x = nn.gelu(self.layer1(h_and_emb)) + x = nn.gelu(self.layer2(x)) + return self.proj_out(x) + + +def collect_decode_data(model, tok, prompt, num_tokens=50000): + """Autoregressive decode, collect (h_t, token_t, next_token) triples.""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + h_list = [] + token_list = [] # current token (for embedding concat) + next_tok_list = [] # target + + t0 = time.perf_counter() + for step in range(num_tokens): + h_list.append(last_h) + token_list.append(y.item()) + + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + full_pred = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(full_pred, last_h) + + next_tok_list.append(full_pred.item()) + y = full_pred.squeeze() + + if (step + 1) % 2000 == 0: + elapsed = time.perf_counter() - t0 + print(f" {step+1}/{num_tokens} ({(step+1)/elapsed:.0f} tok/s)", flush=True) + + t1 = time.perf_counter() + print(f" collected {num_tokens} pairs in {t1-t0:.1f}s ({num_tokens/(t1-t0):.0f} tok/s)", flush=True) + + h_data = mx.stack(h_list) + tok_data = mx.array(token_list) + targets = mx.array(next_tok_list) + mx.eval(h_data, tok_data, targets) + return h_data, tok_data, targets + + +def train_head(draft, embed_layer, lm_head, h_data, tok_data, targets, + epochs=20, batch_size=512, lr=3e-4): + """Train with token embedding concatenation.""" + T = h_data.shape[0] + optimizer = optim.Adam(learning_rate=lr) + + def loss_fn(model, h_batch, tok_batch, target_batch): + # Get token embeddings + emb = embed_layer(tok_batch) # [B, D] + # Concat hidden state + token embedding + x = mx.concatenate([h_batch, emb], axis=-1) # [B, 2*D] + h_pred = model(x) + logits = lm_head(h_pred) + return nn.losses.cross_entropy(logits, target_batch).mean() + + lg = nn.value_and_grad(draft, loss_fn) + + for ep in range(epochs): + perm = mx.array(np.random.permutation(T)) + total_loss = 0 + n = 0 + for j in range(0, T, batch_size): + idx = perm[j:j+batch_size] + loss, grads = lg(draft, h_data[idx], tok_data[idx], targets[idx]) + optimizer.update(draft, grads) + mx.eval(draft.parameters(), optimizer.state) + total_loss += loss.item() + n += 1 + avg = total_loss / n + if ep == 0 or (ep + 1) % 5 == 0 or ep == epochs - 1: + print(f" epoch {ep+1}/{epochs}: loss={avg:.4f}", flush=True) + + +def measure_acceptance(model, draft, tok, prompt, num_tokens=200): + """Cache-aware acceptance measurement on held-out prompt.""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + matches = 0 + total = 0 + for _ in range(num_tokens): + # Draft: concat(last_h, embed(y)) → MLP → LM head + emb = inner.embed_tokens(mx.array([y.item()])) # [1, D] + x = mx.concatenate([last_h[None], emb], axis=-1) # [1, 2*D] + h_pred = draft(x) + draft_logits = lm.lm_head(h_pred) + draft_pred = mx.argmax(draft_logits, axis=-1) + + # Full forward + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + full_logits = lm.lm_head(h) + full_pred = mx.argmax(full_logits[:, -1], axis=-1) + last_h = h[0, -1] + + mx.eval(draft_pred, full_pred, last_h) + if draft_pred.item() == full_pred.item(): + matches += 1 + total += 1 + y = full_pred.squeeze() + + return matches, total + + +if __name__ == "__main__": + print("=== EAGLE-style Draft Head (scale-up) ===", flush=True) + print("loading model...", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + print(f"loaded. D={D}\n", flush=True) + + # Phase 1: collect 10K decode tokens + print("--- Phase 1: Collect 10K decode-path tokens ---", flush=True) + prompt = ( + "Write a comprehensive and detailed essay about the complete history " + "of computing, from Charles Babbage's Analytical Engine through modern " + "quantum computers. Cover every major milestone, the key people involved, " + "the technical breakthroughs, and how each era built on the previous one. " + "Include discussion of hardware, software, networking, AI, and the social " + "impact of each development." + ) + h_data, tok_data, targets = collect_decode_data(model, tok, prompt, num_tokens=50000) + + # Phase 2: train + test + test_prompts = [ + "Explain the theory of general relativity in simple terms.", + "Write a Python function that implements quicksort with detailed comments.", + "What are the main causes and effects of climate change?", + ] + + draft = DraftHeadV2(D, inner_dim=2048) + params = sum(v.size for _, v in tree_flatten(draft.parameters())) + print(f"\n--- Phase 2: Train ({params/1e6:.1f}M params, 10K samples) ---", flush=True) + + t0 = time.perf_counter() + train_head(draft, inner.embed_tokens, lm.lm_head, + h_data, tok_data, targets, + epochs=20, batch_size=512, lr=3e-4) + t1 = time.perf_counter() + print(f" training time: {t1-t0:.1f}s", flush=True) + + # Calib + emb_all = inner.embed_tokens(tok_data) + x_all = mx.concatenate([h_data, emb_all], axis=-1) + cp = mx.argmax(lm.lm_head(draft(x_all)), axis=-1) + mx.eval(cp) + cm = (cp == targets).astype(mx.float32).mean().item() + print(f" calib acceptance: {cm*100:.1f}%", flush=True) + + # Held-out + print(f"\n--- Phase 3: Held-out acceptance (200 tokens each) ---", flush=True) + for p in test_prompts: + matches, total = measure_acceptance(model, draft, tok, p, num_tokens=200) + short = p[:55] + print(f" '{short}...': {matches}/{total} = {matches/total*100:.1f}%", flush=True) + + # Save adapter size estimate + adapter_bytes = params * 2 # bf16 + print(f"\n adapter size: {adapter_bytes/1e6:.1f} MB (bf16)", flush=True) + + print("\nDONE") diff --git a/experiments/test_draft_head_high.py b/experiments/test_draft_head_high.py new file mode 100644 index 0000000000..202a4c581d --- /dev/null +++ b/experiments/test_draft_head_high.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +""" +High-quality draft head: EAGLE-scale training. + +- 100K decode tokens (~17 min collection) +- 59M param deep MLP (3-layer, best from prior tests) +- 100 epochs (not 15) +- Cosine LR schedule +- Input: concat(h_t, embed(tok_t)) +- Target: next token via frozen LM head + +If this crosses 40%+ held-out acceptance, we build the tool. +""" +import sys, time, math +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + + +class DeepMLP(nn.Module): + def __init__(self, hidden_dim, inner=4096, num_layers=3): + super().__init__() + self.input_proj = nn.Linear(hidden_dim * 2, inner, bias=False) + self.layers = [nn.Linear(inner, inner, bias=False) for _ in range(num_layers - 1)] + self.output_proj = nn.Linear(inner, hidden_dim, bias=False) + self.norms = [nn.RMSNorm(inner) for _ in range(num_layers)] + + def __call__(self, h): + x = nn.gelu(self.input_proj(h)) + for layer, norm in zip(self.layers, self.norms[1:]): + x = x + nn.gelu(layer(norm(x))) + return self.output_proj(self.norms[0](x)) + + +def collect_decode_data(model, tok, prompts, tokens_per_prompt): + """Collect from MULTIPLE prompts for diversity.""" + lm = model.language_model + inner = lm.model + all_h, all_tok, all_next = [], [], [] + + for pi, prompt in enumerate(prompts): + tokens = mx.array(tok.encode(prompt))[None, :100] + cache = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + t0 = time.perf_counter() + for step in range(tokens_per_prompt): + all_h.append(last_h) + all_tok.append(y.item()) + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + fp = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(fp, last_h) + all_next.append(fp.item()) + y = fp.squeeze() + + elapsed = time.perf_counter() - t0 + total = len(all_h) + print(f" prompt {pi+1}/{len(prompts)}: +{tokens_per_prompt} tokens ({tokens_per_prompt/elapsed:.0f} tok/s), total={total}", flush=True) + + h_data = mx.stack(all_h) + tok_data = mx.array(all_tok) + targets = mx.array(all_next) + mx.eval(h_data, tok_data, targets) + return h_data, tok_data, targets + + +def train(draft, embed_layer, lm_head, h_data, tok_data, targets, + epochs=100, batch_size=512, lr_max=3e-4, lr_min=1e-5): + """Train with cosine LR schedule.""" + T = h_data.shape[0] + steps_per_epoch = (T + batch_size - 1) // batch_size + total_steps = epochs * steps_per_epoch + + optimizer = optim.Adam(learning_rate=lr_max) + + def loss_fn(m, hb, tb, tgt): + emb = embed_layer(tb) + x = mx.concatenate([hb, emb], axis=-1) + logits = lm_head(m(x)) + return nn.losses.cross_entropy(logits, tgt).mean() + lg = nn.value_and_grad(draft, loss_fn) + + step = 0 + t0 = time.perf_counter() + for ep in range(epochs): + perm = mx.array(np.random.permutation(T)) + total_loss = 0 + n = 0 + for j in range(0, T, batch_size): + # Cosine LR + progress = step / total_steps + lr = lr_min + 0.5 * (lr_max - lr_min) * (1 + math.cos(math.pi * progress)) + optimizer.learning_rate = mx.array(lr) + + idx = perm[j:j+batch_size] + loss, grads = lg(draft, h_data[idx], tok_data[idx], targets[idx]) + optimizer.update(draft, grads) + mx.eval(draft.parameters(), optimizer.state) + total_loss += loss.item() + n += 1 + step += 1 + + avg = total_loss / n + if ep == 0 or (ep+1) % 10 == 0: + elapsed = time.perf_counter() - t0 + print(f" epoch {ep+1}/{epochs}: loss={avg:.4f} lr={lr:.1e} ({elapsed:.0f}s)", flush=True) + + print(f" total training: {time.perf_counter()-t0:.0f}s ({step} steps)", flush=True) + + +def measure(model, draft, tok, prompt, num_tokens=300): + lm = model.language_model + inner = lm.model + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + matches = 0 + for _ in range(num_tokens): + emb = inner.embed_tokens(mx.array([y.item()])) + x = mx.concatenate([last_h[None], emb], axis=-1) + dp = mx.argmax(lm.lm_head(draft(x)), axis=-1) + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + fp = mx.argmax(lm.lm_head(h)[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(dp, fp, last_h) + if dp.item() == fp.item(): + matches += 1 + y = fp.squeeze() + return matches, num_tokens + + +if __name__ == "__main__": + print("=== High-Quality Draft Head Training ===\n", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + print(f"D={D}\n", flush=True) + + # Phase 1: collect 100K tokens from 5 diverse prompts + print("--- Phase 1: Collect 100K decode tokens (5 prompts × 20K) ---", flush=True) + prompts = [ + "Write a comprehensive history of artificial intelligence from 1940 to 2026.", + "Explain all of quantum mechanics including the math, starting from first principles.", + "Write a complete implementation of a Redis clone in Python with all data structures.", + "Analyze the complete works of Shakespeare, covering every play and major sonnet.", + "Describe the entire history of space exploration from Sputnik through Mars missions.", + ] + h_data, tok_data, targets = collect_decode_data(model, tok, prompts, tokens_per_prompt=20000) + print(f" total: {h_data.shape[0]} pairs\n", flush=True) + + # Phase 2: train + print("--- Phase 2: Train (59M params, 100 epochs, cosine LR) ---", flush=True) + draft = DeepMLP(D, inner=4096, num_layers=3) + params = sum(v.size for _, v in tree_flatten(draft.parameters())) + print(f" params: {params/1e6:.1f}M", flush=True) + + train(draft, inner.embed_tokens, lm.lm_head, + h_data, tok_data, targets, + epochs=100, batch_size=512, lr_max=3e-4, lr_min=1e-5) + + # Phase 3: test on 5 held-out prompts + print(f"\n--- Phase 3: Held-out acceptance (300 tokens each) ---", flush=True) + test_prompts = [ + "What is the meaning of life according to different philosophical traditions?", + "Implement a B-tree in C++ with insert, delete, and search operations.", + "Explain how nuclear fusion works and why it's hard to achieve on Earth.", + "Write a detailed recipe for French onion soup with wine pairing suggestions.", + "Compare and contrast democracy and authoritarianism across history.", + ] + total_matches = 0 + total_tokens = 0 + for p in test_prompts: + m, t = measure(model, draft, tok, p, num_tokens=300) + total_matches += m + total_tokens += t + print(f" '{p[:55]}...': {m}/{t} = {m/t*100:.1f}%", flush=True) + + avg = total_matches / total_tokens * 100 + print(f"\n OVERALL: {total_matches}/{total_tokens} = {avg:.1f}%", flush=True) + print(f" adapter: {params * 2 / 1e6:.0f} MB (bf16)", flush=True) + + # Speedup estimate + # With near-free drafts (N=4): tokens_per_round ≈ 1/(1-acc) bounded by N + eff = min(1/(1-avg/100), 5) if avg < 100 else 5 + print(f" estimated speedup (N=4 drafts): ~{eff:.1f}x", flush=True) + + print("\nDONE") diff --git a/experiments/test_draft_head_scale.py b/experiments/test_draft_head_scale.py new file mode 100644 index 0000000000..552e181b0f --- /dev/null +++ b/experiments/test_draft_head_scale.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +""" +Scale-up: EAGLE-style draft head training on decode-path data. + +Key changes vs tiny prototype: +1. 10K decode tokens (not 2K) — ~100s collection +2. Bigger MLP (16M params, 2 hidden layers) +3. Input = concat(h_t, embed(token_t)) — gives token identity context +4. More epochs with LR scheduling +5. Test on 3 held-out prompts with 200 tokens each +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + + +class DraftHeadV2(nn.Module): + """2-layer MLP with token embedding concat. ~16M params.""" + def __init__(self, hidden_dim, inner_dim=2048): + super().__init__() + # Input: concat(h_t, embed(token_t)) = 2 * hidden_dim + self.layer1 = nn.Linear(hidden_dim * 2, inner_dim, bias=False) + self.layer2 = nn.Linear(inner_dim, inner_dim, bias=False) + self.proj_out = nn.Linear(inner_dim, hidden_dim, bias=False) + + def __call__(self, h_and_emb): + x = nn.gelu(self.layer1(h_and_emb)) + x = nn.gelu(self.layer2(x)) + return self.proj_out(x) + + +def collect_decode_data(model, tok, prompt, num_tokens=10000): + """Autoregressive decode, collect (h_t, token_t, next_token) triples.""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + h_list = [] + token_list = [] # current token (for embedding concat) + next_tok_list = [] # target + + t0 = time.perf_counter() + for step in range(num_tokens): + h_list.append(last_h) + token_list.append(y.item()) + + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + full_pred = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(full_pred, last_h) + + next_tok_list.append(full_pred.item()) + y = full_pred.squeeze() + + if (step + 1) % 2000 == 0: + elapsed = time.perf_counter() - t0 + print(f" {step+1}/{num_tokens} ({(step+1)/elapsed:.0f} tok/s)", flush=True) + + t1 = time.perf_counter() + print(f" collected {num_tokens} pairs in {t1-t0:.1f}s ({num_tokens/(t1-t0):.0f} tok/s)", flush=True) + + h_data = mx.stack(h_list) + tok_data = mx.array(token_list) + targets = mx.array(next_tok_list) + mx.eval(h_data, tok_data, targets) + return h_data, tok_data, targets + + +def train_head(draft, embed_layer, lm_head, h_data, tok_data, targets, + epochs=20, batch_size=512, lr=3e-4): + """Train with token embedding concatenation.""" + T = h_data.shape[0] + optimizer = optim.Adam(learning_rate=lr) + + def loss_fn(model, h_batch, tok_batch, target_batch): + # Get token embeddings + emb = embed_layer(tok_batch) # [B, D] + # Concat hidden state + token embedding + x = mx.concatenate([h_batch, emb], axis=-1) # [B, 2*D] + h_pred = model(x) + logits = lm_head(h_pred) + return nn.losses.cross_entropy(logits, target_batch).mean() + + lg = nn.value_and_grad(draft, loss_fn) + + for ep in range(epochs): + perm = mx.array(np.random.permutation(T)) + total_loss = 0 + n = 0 + for j in range(0, T, batch_size): + idx = perm[j:j+batch_size] + loss, grads = lg(draft, h_data[idx], tok_data[idx], targets[idx]) + optimizer.update(draft, grads) + mx.eval(draft.parameters(), optimizer.state) + total_loss += loss.item() + n += 1 + avg = total_loss / n + if ep == 0 or (ep + 1) % 5 == 0 or ep == epochs - 1: + print(f" epoch {ep+1}/{epochs}: loss={avg:.4f}", flush=True) + + +def measure_acceptance(model, draft, tok, prompt, num_tokens=200): + """Cache-aware acceptance measurement on held-out prompt.""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + matches = 0 + total = 0 + for _ in range(num_tokens): + # Draft: concat(last_h, embed(y)) → MLP → LM head + emb = inner.embed_tokens(mx.array([y.item()])) # [1, D] + x = mx.concatenate([last_h[None], emb], axis=-1) # [1, 2*D] + h_pred = draft(x) + draft_logits = lm.lm_head(h_pred) + draft_pred = mx.argmax(draft_logits, axis=-1) + + # Full forward + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + full_logits = lm.lm_head(h) + full_pred = mx.argmax(full_logits[:, -1], axis=-1) + last_h = h[0, -1] + + mx.eval(draft_pred, full_pred, last_h) + if draft_pred.item() == full_pred.item(): + matches += 1 + total += 1 + y = full_pred.squeeze() + + return matches, total + + +if __name__ == "__main__": + print("=== EAGLE-style Draft Head (scale-up) ===", flush=True) + print("loading model...", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + print(f"loaded. D={D}\n", flush=True) + + # Phase 1: collect 10K decode tokens + print("--- Phase 1: Collect 10K decode-path tokens ---", flush=True) + prompt = ( + "Write a comprehensive and detailed essay about the complete history " + "of computing, from Charles Babbage's Analytical Engine through modern " + "quantum computers. Cover every major milestone, the key people involved, " + "the technical breakthroughs, and how each era built on the previous one. " + "Include discussion of hardware, software, networking, AI, and the social " + "impact of each development." + ) + h_data, tok_data, targets = collect_decode_data(model, tok, prompt, num_tokens=10000) + + # Phase 2: train + test + test_prompts = [ + "Explain the theory of general relativity in simple terms.", + "Write a Python function that implements quicksort with detailed comments.", + "What are the main causes and effects of climate change?", + ] + + draft = DraftHeadV2(D, inner_dim=2048) + params = sum(v.size for _, v in tree_flatten(draft.parameters())) + print(f"\n--- Phase 2: Train ({params/1e6:.1f}M params, 10K samples) ---", flush=True) + + t0 = time.perf_counter() + train_head(draft, inner.embed_tokens, lm.lm_head, + h_data, tok_data, targets, + epochs=20, batch_size=512, lr=3e-4) + t1 = time.perf_counter() + print(f" training time: {t1-t0:.1f}s", flush=True) + + # Calib + emb_all = inner.embed_tokens(tok_data) + x_all = mx.concatenate([h_data, emb_all], axis=-1) + cp = mx.argmax(lm.lm_head(draft(x_all)), axis=-1) + mx.eval(cp) + cm = (cp == targets).astype(mx.float32).mean().item() + print(f" calib acceptance: {cm*100:.1f}%", flush=True) + + # Held-out + print(f"\n--- Phase 3: Held-out acceptance (200 tokens each) ---", flush=True) + for p in test_prompts: + matches, total = measure_acceptance(model, draft, tok, p, num_tokens=200) + short = p[:55] + print(f" '{short}...': {matches}/{total} = {matches/total*100:.1f}%", flush=True) + + # Save adapter size estimate + adapter_bytes = params * 2 # bf16 + print(f"\n adapter size: {adapter_bytes/1e6:.1f} MB (bf16)", flush=True) + + print("\nDONE") diff --git a/experiments/test_fitted_aligner.py b/experiments/test_fitted_aligner.py new file mode 100644 index 0000000000..94997c0162 --- /dev/null +++ b/experiments/test_fitted_aligner.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +""" +Test: fit a linear aligner from prefill hidden states, measure acceptance. + +1. Prefill ~2048 tokens, capture h_K and h_40 at every position +2. Solve W = lstsq(h_K, h_40) +3. During decode, draft via LM_head(W @ h_K) instead of full forward +4. Measure acceptance rate vs full model at multiple exit depths +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +from mlx_lm import load + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + +# Calibration text — generic, ships with the tool +CALIB_TEXT = ( + "The transformer architecture revolutionized natural language processing. " + "It uses self-attention mechanisms to process sequences in parallel. " + "Each layer applies multi-head attention followed by a feed-forward network. " + "Modern variants include mixture-of-experts models where only a subset of " + "parameters are active per token, reducing compute while scaling capacity. " + "Language models are trained on diverse internet text to predict the next token. " + "During inference, tokens are generated autoregressively one at a time. " + "Speculative decoding accelerates this by drafting multiple tokens cheaply " + "and verifying them in parallel with the full model. " +) * 30 # ~2700 tokens worth + + +def capture_hidden_states(model, tokens, exit_layer): + """Forward pass that captures hidden states at exit_layer AND final layer.""" + lm = model.language_model + inner = lm.model + + h = inner.embed_tokens(tokens) + h_at_k = None + + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=None) + if i == exit_layer - 1: + h_at_k = h + + h_final = inner.norm(h) + h_at_k_normed = inner.norm(h_at_k) # apply same norm for fair comparison + + return h_at_k_normed, h_final + + +def fit_aligner(h_k, h_final): + """Least-squares: find W such that W @ h_k ≈ h_final.""" + # h_k: [T, D], h_final: [T, D] + # W = h_final.T @ h_k @ (h_k.T @ h_k)^(-1) + # Using lstsq: solve h_k @ W.T = h_final for W.T + # mx.linalg.lstsq not available, use normal equations + T, D = h_k.shape + # Add small ridge for stability + XtX = h_k.T @ h_k + mx.eye(D) * 1e-4 # [D, D] + XtY = h_k.T @ h_final # [D, D] + # Solve XtX @ W.T = XtY → W.T = solve(XtX, XtY) + W_T = mx.linalg.solve(XtX, XtY, stream=mx.cpu) # [D, D] + W = W_T.T # [D, D] + mx.eval(W) + return W + + +def measure_acceptance(model, W, exit_layer, num_tokens=200): + """Decode num_tokens, measure how often aligned draft matches full model.""" + lm = model.language_model + inner = lm.model + + prompt = "The capital of France is" + tok = model.language_model # need tokenizer + # Use the tokenizer from load + return None # placeholder + + +def main(): + print("loading model...", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + total_layers = len(inner.layers) + print(f"loaded. {total_layers} layers, hidden_dim={inner.layers[0].input_layernorm.weight.shape[0]}", flush=True) + + # Tokenize calibration text + calib_tokens = mx.array(tok.encode(CALIB_TEXT))[None, :2048] # [1, T] + T = calib_tokens.shape[1] + print(f"calibration: {T} tokens", flush=True) + + # Sweep exit layers + for exit_layer in [32, 34, 36, 38, 39]: + print(f"\n=== exit_layer={exit_layer}/{total_layers} (skip {total_layers - exit_layer}) ===", flush=True) + + # Phase 1: capture hidden states during calibration forward + t0 = time.perf_counter() + h_k, h_final = capture_hidden_states(model, calib_tokens, exit_layer) + mx.eval(h_k, h_final) + t1 = time.perf_counter() + print(f" capture: {t1-t0:.2f}s", flush=True) + + # Reshape: [1, T, D] → [T, D] + h_k_2d = h_k.squeeze(0) + h_final_2d = h_final.squeeze(0) + + # Phase 2: fit aligner + t0 = time.perf_counter() + W = fit_aligner(h_k_2d, h_final_2d) + t1 = time.perf_counter() + print(f" fit aligner: {t1-t0:.3f}s, W shape: {W.shape}", flush=True) + + # Measure fit quality on calibration data + h_aligned = h_k_2d @ W.T # [T, D] + # Get logits from both aligned and original + if lm.lm_head is not None: + logits_aligned = lm.lm_head(h_aligned) # [T, vocab] + logits_full = lm.lm_head(h_final_2d) # [T, vocab] + else: + logits_aligned = inner.embed_tokens.as_linear(h_aligned) + logits_full = inner.embed_tokens.as_linear(h_final_2d) + + # Argmax match rate (on calibration data — optimistic but indicative) + pred_aligned = mx.argmax(logits_aligned, axis=-1) + pred_full = mx.argmax(logits_full, axis=-1) + mx.eval(pred_aligned, pred_full) + match_rate = (pred_aligned == pred_full).astype(mx.float32).mean().item() + print(f" calib argmax match: {match_rate*100:.1f}%", flush=True) + + # Raw (no aligner) comparison + if lm.lm_head is not None: + logits_raw = lm.lm_head(h_k_2d) + else: + logits_raw = inner.embed_tokens.as_linear(h_k_2d) + pred_raw = mx.argmax(logits_raw, axis=-1) + mx.eval(pred_raw) + raw_match = (pred_raw == pred_full).astype(mx.float32).mean().item() + print(f" raw (no aligner) match: {raw_match*100:.1f}%", flush=True) + print(f" improvement: {raw_match*100:.1f}% → {match_rate*100:.1f}%", flush=True) + + # Phase 3: measure on HELD-OUT tokens (decode) + # Generate 100 tokens normally, compare draft-with-aligner vs full + prompt_tokens = mx.array(tok.encode("Explain quantum computing in simple terms."))[None] + cache = model.make_cache() + + # Prefill prompt + logits = model(prompt_tokens, cache=cache) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + + matches = 0 + raw_matches = 0 + total = 0 + for _ in range(100): + # Full forward (single token) + y_input = mx.array([[y.item()]]) + full_logits = model(y_input, cache=cache) + full_pred = mx.argmax(full_logits[:, -1], axis=-1) + + # What would draft predict? Extract h_k from last forward + # We need to re-run partial forward for the draft + h = inner.embed_tokens(mx.array([[y.item()]])) + for i in range(exit_layer): + h = inner.layers[i](h, mask=None, cache=None) + h = inner.norm(h) + + # With aligner + h_aligned_dec = h.squeeze() @ W.T + if lm.lm_head is not None: + draft_logits = lm.lm_head(h_aligned_dec[None]) + else: + draft_logits = inner.embed_tokens.as_linear(h_aligned_dec[None]) + draft_pred = mx.argmax(draft_logits, axis=-1) + + # Without aligner + if lm.lm_head is not None: + raw_logits = lm.lm_head(h.squeeze()[None]) + else: + raw_logits = inner.embed_tokens.as_linear(h.squeeze()[None]) + raw_pred = mx.argmax(raw_logits, axis=-1) + + mx.eval(full_pred, draft_pred, raw_pred) + + if draft_pred.item() == full_pred.item(): + matches += 1 + if raw_pred.item() == full_pred.item(): + raw_matches += 1 + total += 1 + + y = full_pred.squeeze() + + print(f" decode acceptance (aligner): {matches}/{total} = {matches/total*100:.1f}%", flush=True) + print(f" decode acceptance (raw): {raw_matches}/{total} = {raw_matches/total*100:.1f}%", flush=True) + + print("\nDONE") + + +if __name__ == "__main__": + main() diff --git a/experiments/test_selfdraft.py b/experiments/test_selfdraft.py new file mode 100644 index 0000000000..e8e2b0a1b5 --- /dev/null +++ b/experiments/test_selfdraft.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Quick self-draft test via mlx-lm to validate the concept before Swift.""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +from mlx_lm import load + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + +def greedy(logits): + return mx.argmax(logits[:, -1], axis=-1) + +def main(): + print("loading...", flush=True) + model, tok = load(MODEL) + print("loaded", flush=True) + + prompt = "The capital of France is" + tokens = mx.array(tok.encode(prompt))[None] + + # Warmup + cache = model.make_cache() + logits = model(tokens, cache=cache) + mx.eval(logits) + + # --- Baseline: standard autoregressive --- + cache = model.make_cache() + logits = model(tokens, cache=cache) + y = greedy(logits) + mx.eval(y) + + gen_tokens = [y.item()] + t0 = time.perf_counter() + for _ in range(64): + logits = model(y[None], cache=cache) + y = greedy(logits) + mx.eval(y) + gen_tokens.append(y.item()) + t1 = time.perf_counter() + baseline_tps = 64 / (t1 - t0) + print(f"baseline: {baseline_tps:.1f} tok/s") + print(f"text: {tok.decode(gen_tokens[:20])}") + + # --- Self-draft: first K of 40 layers --- + lm = model.language_model + inner = lm.model + total_layers = len(inner.layers) + draft_frac = float(sys.argv[1]) if len(sys.argv) > 1 else 0.25 + draft_layers = max(1, int(total_layers * draft_frac)) + draft_n = 4 + print(f"\nself-draft: {draft_layers}/{total_layers} layers, draft_n={draft_n}") + + cache = model.make_cache() + logits = model(tokens, cache=cache) + y = greedy(logits) + mx.eval(y) + + gen_tokens2 = [y.item()] + total_accepted = 0 + total_rounds = 0 + t0 = time.perf_counter() + + while total_accepted < 64: + # Draft N tokens (stateless — no cache to avoid corruption) + drafts = [] + draft_tok = y + for _ in range(draft_n): + # Partial forward: only first draft_layers layers, no cache + tok_input = mx.array([[draft_tok.item()]]) # [1, 1] int32 + h = inner.embed_tokens(tok_input) + for i in range(draft_layers): + h = inner.layers[i](h, mask=None, cache=None) + h = inner.norm(h) + if lm.lm_head is not None: + draft_logits = lm.lm_head(h) + else: + draft_logits = inner.embed_tokens.as_linear(h) + draft_tok = mx.argmax(draft_logits[:, -1], axis=-1).squeeze() + mx.eval(draft_tok) + drafts.append(draft_tok.item()) + + # Verify: [y, draft0, draft1, draft2, draft3] through full model + verify_input = mx.array([[y.item()] + drafts]) + verify_logits = model(verify_input, cache=cache) + # verify_logits[0, i] = logits for position i+1 + + accepted = 0 + for i in range(4): + target = mx.argmax(verify_logits[0, i], axis=-1) + mx.eval(target) + target_val = target.item() + if target_val == drafts[i]: + gen_tokens2.append(target_val) + accepted += 1 + else: + gen_tokens2.append(target_val) + accepted += 1 + break + + # Bonus token if all matched + if accepted == 4: + bonus = mx.argmax(verify_logits[0, 4], axis=-1) + mx.eval(bonus) + gen_tokens2.append(bonus.item()) + accepted += 1 + + y = mx.array(gen_tokens2[-1]) + total_accepted += accepted + total_rounds += 1 + + t1 = time.perf_counter() + selfdraft_tps = total_accepted / (t1 - t0) + avg_accept = total_accepted / total_rounds + print(f"self-draft: {selfdraft_tps:.1f} tok/s ({total_accepted} tokens in {total_rounds} rounds, avg accept {avg_accept:.1f})") + print(f"text: {tok.decode(gen_tokens2[:20])}") + print(f"\nspeedup: {selfdraft_tps/baseline_tps:.2f}x") + +if __name__ == "__main__": + main() diff --git a/experiments/test_spec_decode_e2e.py b/experiments/test_spec_decode_e2e.py new file mode 100644 index 0000000000..2e1afd754c --- /dev/null +++ b/experiments/test_spec_decode_e2e.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +""" +End-to-end speculative decoding with trained draft head. +Measures ACTUAL tok/s, not just acceptance rate. + +1. Load model + train draft head (reuses collection from prior run if cached) +2. Run baseline autoregressive decode → measure tok/s +3. Run speculative decode → measure tok/s +4. Verify output matches (lossless check) +""" +import sys, time, os +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" +NUM_GEN = 200 # tokens to generate for speed measurement + + +class DeepMLP(nn.Module): + def __init__(self, hidden_dim, inner=4096, num_layers=3): + super().__init__() + self.input_proj = nn.Linear(hidden_dim * 2, inner, bias=False) + self.layers = [nn.Linear(inner, inner, bias=False) for _ in range(num_layers - 1)] + self.output_proj = nn.Linear(inner, hidden_dim, bias=False) + self.norms = [nn.RMSNorm(inner) for _ in range(num_layers)] + + def __call__(self, h): + x = nn.gelu(self.input_proj(h)) + for layer, norm in zip(self.layers, self.norms[1:]): + x = x + nn.gelu(layer(norm(x))) + return self.output_proj(self.norms[0](x)) + + +def baseline_decode(model, tok, prompt, num_tokens): + """Standard autoregressive decode. Returns (tokens, tok/s).""" + lm = model.language_model + inner = lm.model + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + + gen = [y.item()] + t0 = time.perf_counter() + for _ in range(num_tokens - 1): + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + gen.append(y.item()) + t1 = time.perf_counter() + + tps = (num_tokens - 1) / (t1 - t0) + return gen, tps + + +def spec_decode(model, draft, tok, prompt, num_tokens, num_draft=4): + """Speculative decode with draft head. Returns (tokens, tok/s, stats).""" + lm = model.language_model + inner = lm.model + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + gen = [y.item()] + total_accepted = 0 + total_rounds = 0 + total_draft_matches = 0 + + t0 = time.perf_counter() + while len(gen) < num_tokens: + # --- Draft phase: generate N candidate tokens --- + draft_tokens = [] + draft_tok = y + for _ in range(num_draft): + emb = inner.embed_tokens(mx.array([draft_tok.item()])) + x = mx.concatenate([last_h[None], emb], axis=-1) + h_pred = draft(x) + draft_logits = lm.lm_head(h_pred) + draft_tok = mx.argmax(draft_logits, axis=-1).squeeze() + mx.eval(draft_tok) + draft_tokens.append(draft_tok.item()) + + # --- Verify phase: run full model on [y, draft0, ..., draftN-1] --- + verify_input = mx.array([[y.item()] + draft_tokens]) + h = inner.embed_tokens(verify_input) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + verify_logits = lm.lm_head(h) + # verify_logits[0, i] = logits predicting position i+1 + + # --- Accept/reject --- + accepted = 0 + for i in range(num_draft): + target_tok = mx.argmax(verify_logits[0, i], axis=-1) + mx.eval(target_tok) + target_val = target_tok.item() + + if target_val == draft_tokens[i]: + gen.append(target_val) + accepted += 1 + total_draft_matches += 1 + else: + # Mismatch: accept target's correction + gen.append(target_val) + accepted += 1 + break + + # If all drafts matched, get bonus token + if accepted == num_draft: + bonus = mx.argmax(verify_logits[0, num_draft], axis=-1) + mx.eval(bonus) + gen.append(bonus.item()) + accepted += 1 + + # Update state: last accepted token's hidden state + last_accepted_idx = min(accepted, num_draft) + last_h = h[0, last_accepted_idx] + # Set y to last generated token + y_val = gen[-1] + y = mx.array(y_val) + mx.eval(last_h) + + # Trim cache: we verified accepted+1 tokens but only want to keep + # up to last_accepted_idx+1 positions. The verify already pushed all + # tokens into cache. Need to trim excess. + excess = num_draft + 1 - (accepted) + if excess > 0: + for c in cache: + if hasattr(c, 'trim'): + c.trim(excess) + elif hasattr(c, 'offset') and hasattr(c, 'keys') and c.keys is not None: + # KVCache: trim by reducing offset and slicing + c.offset -= excess + if c.keys is not None: + c.keys = c.keys[..., :-excess, :] + c.values = c.values[..., :-excess, :] + + total_accepted += accepted + total_rounds += 1 + + if len(gen) >= num_tokens: + break + + t1 = time.perf_counter() + gen = gen[:num_tokens] + tps = (len(gen) - 1) / (t1 - t0) + acceptance = total_draft_matches / (total_rounds * num_draft) if total_rounds > 0 else 0 + avg_accepted = total_accepted / total_rounds if total_rounds > 0 else 0 + + stats = { + "rounds": total_rounds, + "avg_accepted_per_round": avg_accepted, + "draft_match_rate": acceptance, + } + return gen, tps, stats + + +if __name__ == "__main__": + print("=== End-to-End Speculative Decode Benchmark ===\n", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + + # Quick train (20K tokens, 30 epochs — enough for ~30% acceptance) + print("--- Training draft head (20K tokens, 30 epochs) ---", flush=True) + prompt_train = "Write a comprehensive analysis of machine learning history and applications." + tokens = mx.array(tok.encode(prompt_train))[None, :100] + cache_train = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache_train[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + h_list, tok_list, next_list = [], [], [] + for step in range(20000): + h_list.append(last_h) + tok_list.append(y.item()) + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache_train[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + fp = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(fp, last_h) + next_list.append(fp.item()) + y = fp.squeeze() + if (step+1) % 5000 == 0: + print(f" collected {step+1}/20000", flush=True) + + h_data = mx.stack(h_list) + tok_data = mx.array(tok_list) + targets = mx.array(next_list) + mx.eval(h_data, tok_data, targets) + + draft = DeepMLP(D, inner=4096, num_layers=3) + optimizer = optim.Adam(learning_rate=3e-4) + def loss_fn(m, hb, tb, tgt): + emb = inner.embed_tokens(tb) + x = mx.concatenate([hb, emb], axis=-1) + return nn.losses.cross_entropy(lm.lm_head(m(x)), tgt).mean() + lg = nn.value_and_grad(draft, loss_fn) + + t0 = time.perf_counter() + for ep in range(30): + perm = mx.array(np.random.permutation(20000)) + for j in range(0, 20000, 512): + idx = perm[j:j+512] + loss, grads = lg(draft, h_data[idx], tok_data[idx], targets[idx]) + optimizer.update(draft, grads) + mx.eval(draft.parameters(), optimizer.state) + if (ep+1) % 10 == 0: + print(f" epoch {ep+1}/30: loss={loss.item():.4f}", flush=True) + print(f" training: {time.perf_counter()-t0:.0f}s", flush=True) + + # Benchmark + test_prompt = "Explain the differences between TCP and UDP networking protocols." + + print(f"\n--- Baseline decode ({NUM_GEN} tokens) ---", flush=True) + baseline_tokens, baseline_tps = baseline_decode(model, tok, test_prompt, NUM_GEN) + print(f" {baseline_tps:.1f} tok/s", flush=True) + print(f" text: {tok.decode(baseline_tokens[:30])}", flush=True) + + for N in [2, 4, 6, 8]: + print(f"\n--- Speculative decode N={N} ({NUM_GEN} tokens) ---", flush=True) + spec_tokens, spec_tps, stats = spec_decode(model, draft, tok, test_prompt, NUM_GEN, num_draft=N) + print(f" {spec_tps:.1f} tok/s (speedup: {spec_tps/baseline_tps:.2f}x)", flush=True) + print(f" rounds: {stats['rounds']}, avg accepted: {stats['avg_accepted_per_round']:.1f}, match rate: {stats['draft_match_rate']*100:.1f}%", flush=True) + + # Verify lossless + match = baseline_tokens[:50] == spec_tokens[:50] + print(f" first 50 tokens match baseline: {match}", flush=True) + if not match: + print(f" baseline: {baseline_tokens[:20]}", flush=True) + print(f" spec: {spec_tokens[:20]}", flush=True) + + print("\nDONE") diff --git a/experiments/test_spec_decode_v2.py b/experiments/test_spec_decode_v2.py new file mode 100644 index 0000000000..57bd6fd46d --- /dev/null +++ b/experiments/test_spec_decode_v2.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +""" +Spec decode v2: proper cache snapshot/restore for GDN hybrid models. + +Key fix: snapshot ALL cache state before verify. On partial accept, +restore snapshot and re-feed ONLY accepted tokens through the full model. +This is more expensive but guarantees lossless output. +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +from mlx_lm.models.cache import KVCache +import numpy as np +import copy + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" +NUM_GEN = 200 + +class DeepMLP(nn.Module): + def __init__(self, hidden_dim, inner=4096, num_layers=3): + super().__init__() + self.input_proj = nn.Linear(hidden_dim * 2, inner, bias=False) + self.layers = [nn.Linear(inner, inner, bias=False) for _ in range(num_layers - 1)] + self.output_proj = nn.Linear(inner, hidden_dim, bias=False) + self.norms = [nn.RMSNorm(inner) for _ in range(num_layers)] + def __call__(self, h): + x = nn.gelu(self.input_proj(h)) + for layer, norm in zip(self.layers, self.norms[1:]): + x = x + nn.gelu(layer(norm(x))) + return self.output_proj(self.norms[0](x)) + + +def snapshot_cache(cache): + """Deep copy all cache states.""" + snapshots = [] + for c in cache: + if isinstance(c, KVCache): + snapshots.append({ + 'type': 'kv', + 'keys': mx.array(c.keys) if c.keys is not None else None, + 'values': mx.array(c.values) if c.values is not None else None, + 'offset': c.offset, + }) + else: + # ArraysCache / MambaCache — snapshot the state array + snapshots.append({ + 'type': 'arrays', + 'state': [mx.array(s) if s is not None else None for s in c.state] if c.state else None, + }) + return snapshots + + +def restore_cache(cache, snapshots): + """Restore cache from snapshot.""" + for c, snap in zip(cache, snapshots): + if snap['type'] == 'kv': + c.keys = snap['keys'] + c.values = snap['values'] + c.offset = snap['offset'] + else: + if snap['state'] is not None: + c.state = snap['state'] + + +def full_forward_one_token(model, y, cache): + """Run one token through full model, return (logits, hidden_state).""" + lm = model.language_model + inner = lm.model + y_in = mx.array([[y.item() if hasattr(y, 'item') else y]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + return logits[0, -1], h[0, -1] + + +def spec_decode_v2(model, draft, tok, prompt, num_tokens, num_draft=2): + """Speculative decode with proper snapshot/restore.""" + lm = model.language_model + inner = lm.model + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + gen = [y.item()] + total_rounds = 0 + total_draft_matches = 0 + total_accepted = 0 + + t0 = time.perf_counter() + while len(gen) < num_tokens: + # --- Snapshot cache before draft+verify --- + snap = snapshot_cache(cache) + # Materialize snapshot + to_eval = [] + for s in snap: + if s['type'] == 'kv': + if s['keys'] is not None: to_eval.extend([s['keys'], s['values']]) + else: + if s['state']: + to_eval.extend([x for x in s['state'] if x is not None]) + if to_eval: mx.eval(to_eval) + + # --- Draft N tokens (no cache — stateless, uses draft head) --- + draft_tokens = [] + draft_h = last_h + draft_y = y + for _ in range(num_draft): + emb = inner.embed_tokens(mx.array([draft_y.item()])) + x = mx.concatenate([draft_h[None], emb], axis=-1) + h_pred = draft(x) + draft_logits = lm.lm_head(h_pred) + draft_tok = mx.argmax(draft_logits, axis=-1).squeeze() + mx.eval(draft_tok) + draft_tokens.append(draft_tok.item()) + # For next draft: use predicted h as the "hidden state" + draft_h = h_pred.squeeze() + draft_y = draft_tok + + # --- Verify: feed [y, draft0, ..., draftN-1] through full model --- + # This advances the cache by N+1 positions + verify_input = mx.array([[y.item()] + draft_tokens]) + h = inner.embed_tokens(verify_input) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + verify_logits = lm.lm_head(h) + + # --- Accept/reject --- + accepted = 0 + for i in range(num_draft): + target_tok = mx.argmax(verify_logits[0, i], axis=-1) + mx.eval(target_tok) + if target_tok.item() == draft_tokens[i]: + gen.append(target_tok.item()) + accepted += 1 + total_draft_matches += 1 + else: + gen.append(target_tok.item()) + accepted += 1 + break + + # Bonus token if all matched + all_matched = (accepted == num_draft) + if all_matched: + bonus = mx.argmax(verify_logits[0, num_draft], axis=-1) + mx.eval(bonus) + gen.append(bonus.item()) + accepted += 1 + + total_accepted += accepted + total_rounds += 1 + + # --- Restore cache and replay accepted tokens --- + # The verify pushed all N+1 tokens into cache. We need to undo that + # and only keep the accepted tokens' effect. + restore_cache(cache, snap) + + # Now replay accepted tokens one-by-one through full model + replay_tokens = gen[-(accepted):] + current_y = y + for rt in replay_tokens: + _, last_h = full_forward_one_token(model, current_y, cache) + mx.eval(last_h) + current_y = mx.array(rt) + + y = mx.array(gen[-1]) + mx.eval(y, last_h) + + if len(gen) >= num_tokens: + break + + t1 = time.perf_counter() + gen = gen[:num_tokens] + tps = (len(gen) - 1) / (t1 - t0) + stats = { + "rounds": total_rounds, + "avg_accepted": total_accepted / total_rounds if total_rounds > 0 else 0, + "match_rate": total_draft_matches / (total_rounds * num_draft) if total_rounds > 0 else 0, + } + return gen, tps, stats + + +def baseline_decode(model, tok, prompt, num_tokens): + lm = model.language_model + inner = lm.model + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + gen = [y.item()] + t0 = time.perf_counter() + for _ in range(num_tokens - 1): + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + gen.append(y.item()) + t1 = time.perf_counter() + return gen, (num_tokens - 1) / (t1 - t0) + + +if __name__ == "__main__": + print("=== Spec Decode v2 (snapshot/restore) ===\n", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + + # Quick train + print("--- Training (20K tokens, 30 epochs) ---", flush=True) + prompt_train = "Write a detailed analysis of the history of computing and AI." + tokens = mx.array(tok.encode(prompt_train))[None, :100] + cache_t = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache_t[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + lh = h[0, -1] + mx.eval(y, lh) + + hd, td, nd = [], [], [] + for step in range(20000): + hd.append(lh) + td.append(y.item()) + yi = mx.array([[y.item()]]) + h = inner.embed_tokens(yi) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache_t[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + fp = mx.argmax(logits[:, -1], axis=-1) + lh = h[0, -1] + mx.eval(fp, lh) + nd.append(fp.item()) + y = fp.squeeze() + if (step+1) % 5000 == 0: + print(f" {step+1}/20000", flush=True) + + h_data = mx.stack(hd); tok_data = mx.array(td); targets = mx.array(nd) + mx.eval(h_data, tok_data, targets) + + draft = DeepMLP(D) + opt = optim.Adam(learning_rate=3e-4) + def lf(m, hb, tb, tgt): + emb = inner.embed_tokens(tb) + x = mx.concatenate([hb, emb], axis=-1) + return nn.losses.cross_entropy(lm.lm_head(m(x)), tgt).mean() + lg = nn.value_and_grad(draft, lf) + for ep in range(30): + perm = mx.array(np.random.permutation(20000)) + for j in range(0, 20000, 512): + idx = perm[j:j+512] + loss, grads = lg(draft, h_data[idx], tok_data[idx], targets[idx]) + opt.update(draft, grads) + mx.eval(draft.parameters(), opt.state) + if (ep+1) % 10 == 0: + print(f" epoch {ep+1}: loss={loss.item():.4f}", flush=True) + + # Benchmark + test = "Explain the differences between TCP and UDP networking protocols." + print(f"\n--- Baseline ({NUM_GEN} tokens) ---", flush=True) + bt, btps = baseline_decode(model, tok, test, NUM_GEN) + print(f" {btps:.1f} tok/s", flush=True) + + for N in [2, 4]: + print(f"\n--- Spec decode N={N} ({NUM_GEN} tokens) ---", flush=True) + st, stps, stats = spec_decode_v2(model, draft, tok, test, NUM_GEN, num_draft=N) + print(f" {stps:.1f} tok/s (speedup: {stps/btps:.2f}x)", flush=True) + print(f" rounds: {stats['rounds']}, avg: {stats['avg_accepted']:.1f}, match: {stats['match_rate']*100:.1f}%", flush=True) + match = bt[:50] == st[:50] + print(f" first 50 match baseline: {match}", flush=True) + if not match: + # Find first mismatch + for i in range(min(50, len(bt), len(st))): + if bt[i] != st[i]: + print(f" diverge at pos {i}: baseline={bt[i]}, spec={st[i]}", flush=True) + break + + print("\nDONE") diff --git a/experiments/test_spec_decode_v4.py b/experiments/test_spec_decode_v4.py new file mode 100644 index 0000000000..b1d2fe9b0b --- /dev/null +++ b/experiments/test_spec_decode_v4.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +""" +Spec decode v4: alpha-style snapshot/restore + batch verify. + +Key insight: batch verify costs 1.2x of single forward (not Nx). +GDN kernel amortizes dispatch + state across the T-loop. + +Approach matching alpha's SpeculativeTokenIterator: +1. Snapshot Mamba state before verify +2. Batch verify all N+1 tokens in ONE forward +3. Accept matching prefix +4. Trim KV cache for rejected positions +5. Restore Mamba snapshot on partial rejection +6. Set y = correction token for next round + +The next round's verify naturally feeds the correction token through +the restored Mamba state, rebuilding it. Accepted tokens from the +previous round are "lost" from Mamba state, but KV cache has them. +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +from mlx_lm.models.cache import KVCache +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" +NUM_GEN = 200 + +class DeepMLP(nn.Module): + def __init__(self, hidden_dim, inner=4096, num_layers=3): + super().__init__() + self.input_proj = nn.Linear(hidden_dim * 2, inner, bias=False) + self.layers = [nn.Linear(inner, inner, bias=False) for _ in range(num_layers - 1)] + self.output_proj = nn.Linear(inner, hidden_dim, bias=False) + self.norms = [nn.RMSNorm(inner) for _ in range(num_layers)] + def __call__(self, h): + x = nn.gelu(self.input_proj(h)) + for layer, norm in zip(self.layers, self.norms[1:]): + x = x + nn.gelu(layer(norm(x))) + return self.output_proj(self.norms[0](x)) + + +def snapshot_mamba(cache): + """Save Mamba states. Returns list of (state_arrays_or_None) per cache entry.""" + snaps = [] + for c in cache: + if isinstance(c, KVCache): + snaps.append(None) # KV cache uses trim, not snapshot + else: + # ArraysCache / MambaCache + s = c.state + if s: + snaps.append([mx.array(a) for a in s]) # deep copy + mx.eval(snaps[-1]) + else: + snaps.append(None) + return snaps + + +def restore_mamba(cache, snaps): + """Restore Mamba states from snapshot.""" + for c, snap in zip(cache, snaps): + if snap is not None: + c.state = snap + + +def trim_kv(cache, num_to_trim): + """Trim KV caches (attention layers) by removing last N entries.""" + for c in cache: + if isinstance(c, KVCache) and c.keys is not None and num_to_trim > 0: + c.offset -= num_to_trim + c.keys = c.keys[..., :-num_to_trim, :] + c.values = c.values[..., :-num_to_trim, :] + + +def spec_decode_v4(model, draft, tok, prompt, num_tokens, num_draft=4): + """Spec decode with proper alpha-style cache management.""" + lm = model.language_model + inner = lm.model + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + logits = model(tokens, cache=cache) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + + # Get initial hidden state for draft head + # Re-run to extract h (model() doesn't expose it) + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=None) # Don't double-cache; use separate call + h = inner.norm(h) + last_h = h[0, -1] + mx.eval(last_h) + + # Actually, that double-processes. Let me track h differently. + # For v4: after each verify, capture last_h from the verify logits. + # Use pseudoinverse or just re-run inner model on the last accepted token. + # Simpler: after verify, the hidden state at position 'accepted' is what we need. + # But model() doesn't return hidden states. + # + # COMPROMISE: use the draft head's predicted h as last_h for subsequent drafts. + # Not perfect but avoids the double-forward problem. + + gen = [y.item()] + total_rounds = 0 + total_matches = 0 + total_accepted = 0 + + t0 = time.perf_counter() + while len(gen) < num_tokens: + # --- Snapshot Mamba state --- + snap = snapshot_mamba(cache) + + # --- Draft N tokens with draft head (stateless, no cache) --- + drafts = [] + cur_h = last_h + cur_y = y + for _ in range(num_draft): + emb = inner.embed_tokens(mx.array([cur_y.item()])) + x = mx.concatenate([cur_h[None], emb], axis=-1) + h_pred = draft(x) + d_logits = lm.lm_head(h_pred) + d_tok = mx.argmax(d_logits, axis=-1).squeeze() + mx.eval(d_tok) + drafts.append(d_tok.item()) + cur_h = h_pred.squeeze() + cur_y = d_tok + + # --- Batch verify: [y, d0, ..., dN-1] in ONE forward --- + verify_tokens = mx.array([[y.item()] + drafts]) + verify_logits = model(verify_tokens, cache=cache) + # verify_logits[0, i] predicts position i+1 + + # --- Accept/reject --- + accepted = 0 + for i in range(num_draft): + target = mx.argmax(verify_logits[0, i], axis=-1) + mx.eval(target) + if target.item() == drafts[i]: + gen.append(target.item()) + accepted += 1 + total_matches += 1 + else: + gen.append(target.item()) + accepted += 1 + break + + all_matched = (accepted == num_draft) + if all_matched: + bonus = mx.argmax(verify_logits[0, num_draft], axis=-1) + mx.eval(bonus) + gen.append(bonus.item()) + accepted += 1 + + total_accepted += accepted + total_rounds += 1 + + # --- Cache management --- + num_reject = num_draft + 1 - accepted + if all_matched: + pass # Cache has exactly the right state + else: + # Trim KV for rejected positions + trim_kv(cache, num_reject) + # Restore Mamba to pre-verify state + restore_mamba(cache, snap) + + # Update y and last_h + y = mx.array(gen[-1]) + + # Update last_h: use the draft head's chain prediction + # (This is approximate but avoids an extra full forward) + if all_matched: + # All matched — h_pred from the last draft step IS the hidden state + # after processing all accepted tokens through the draft head + last_h = cur_h + else: + # Partial — use h_pred at the last accepted position + # Approximate: recompute from draft chain up to accepted position + cur_h = last_h # Start from pre-draft last_h + cur_y = y # But y is now the correction token... + # This is imprecise. The correction token may not match draft chain. + # For now, keep last_h stale. It'll be refreshed by the next round's + # first token going through the model. + + # Actually — we need fresh h from the model. Let me extract it. + # The verify pass already processed everything. The hidden state + # at position `accepted-1` in the verify output is what we want. + # But model() doesn't return hidden states, only logits. + + # HACK: re-run just the last accepted token through the model + # to get a fresh hidden state. One extra forward. + last_token = mx.array([[gen[-1]]]) + h = inner.embed_tokens(last_token) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + last_h = h[0, -1] + mx.eval(last_h) + # This also advances the cache by 1, which is correct (the correction token). + + mx.eval(y) + + if len(gen) >= num_tokens: + break + + t1 = time.perf_counter() + gen = gen[:num_tokens] + tps = (len(gen) - 1) / (t1 - t0) + stats = { + 'rounds': total_rounds, + 'avg_accepted': total_accepted / total_rounds, + 'match_rate': total_matches / (total_rounds * num_draft), + } + return gen, tps, stats + + +def baseline_decode(model, tok, prompt, num_tokens): + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + logits = model(tokens, cache=cache) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + gen = [y.item()] + t0 = time.perf_counter() + for _ in range(num_tokens - 1): + logits = model(mx.array([[y.item()]]), cache=cache) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + gen.append(y.item()) + t1 = time.perf_counter() + return gen, (num_tokens - 1) / (t1 - t0) + + +if __name__ == "__main__": + print("=== Spec Decode v4 (batch verify + snapshot/restore) ===\n", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + + # Quick train + print("--- Training (20K/30ep) ---", flush=True) + pt = "Write about computing history." + toks = mx.array(tok.encode(pt))[None, :100] + ct = model.make_cache() + logits = model(toks, cache=ct) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + + # Collect hidden states by running inner model manually + h = inner.embed_tokens(toks) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=None) # separate cache for data collection + h = inner.norm(h) + init_h = h[0, -1] + mx.eval(init_h) + + hd, td, nd = [], [], [] + ct2 = model.make_cache() + logits = model(toks, cache=ct2) + cur_y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(cur_y) + + for step in range(20000): + # Get hidden state from full forward + yi = mx.array([[cur_y.item()]]) + h = inner.embed_tokens(yi) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=ct2[i]) + h = inner.norm(h) + cur_h = h[0, -1] + logits = lm.lm_head(h) + fp = mx.argmax(logits[:, -1], axis=-1) + mx.eval(fp, cur_h) + hd.append(cur_h) + td.append(cur_y.item()) + nd.append(fp.item()) + cur_y = fp.squeeze() + if (step+1) % 5000 == 0: + print(f" {step+1}/20000", flush=True) + + # Fix: hd[i] is the hidden state AFTER processing td[i], and nd[i] is the next token + # For training: input = (hd[i], td[i]) → target = nd[i] + # But draft head takes (last_h, current_token) and predicts next hidden → LM head → next token + # So we need pairs: (h_after_prev, current_token) → next_token + # hd[i] is h after td[i], nd[i] is next. So (hd[i], nd[i-1]) isn't right. + # Actually: hd[i] = h_t (hidden at step i), td[i] = token at step i, nd[i] = token at step i+1 + # Draft head input: (h_{i-1}, tok_i) → predict tok_{i+1} + # So training pairs: (hd[i-1], td[i]) → nd[i] for i >= 1 + + h_data = mx.stack(hd[:-1]) # h_{0..N-2} + tok_data = mx.array(td[1:]) # tok_{1..N-1} + targets = mx.array(nd[1:]) # next_tok_{1..N-1} + + # Wait actually: hd[i] is h AFTER processing token td[i]. + # Draft head should predict: given h after token i, what is token i+1? + # So: (hd[i], embed(nd[i-wait... + # Let me simplify: input = (hd[i], embed(td[i])), target = nd[i] + # This says: given the hidden state from step i and the token at step i, + # predict what comes after step i. That's what we want. + + h_data = mx.stack(hd) + tok_data = mx.array(td) + targets = mx.array(nd) + mx.eval(h_data, tok_data, targets) + + draft = DeepMLP(D) + opt = optim.Adam(learning_rate=3e-4) + def lf(m, hb, tb, tgt): + emb = inner.embed_tokens(tb) + x = mx.concatenate([hb, emb], axis=-1) + return nn.losses.cross_entropy(lm.lm_head(m(x)), tgt).mean() + lg = nn.value_and_grad(draft, lf) + for ep in range(30): + perm = mx.array(np.random.permutation(len(targets))) + for j in range(0, len(targets), 512): + idx = perm[j:j+512] + loss, grads = lg(draft, h_data[idx], tok_data[idx], targets[idx]) + opt.update(draft, grads) + mx.eval(draft.parameters(), opt.state) + if (ep+1) % 10 == 0: + print(f" epoch {ep+1}: loss={loss.item():.4f}", flush=True) + + # Benchmark + test = "Explain the theory of general relativity." + print(f"\n--- Baseline ({NUM_GEN} tokens) ---", flush=True) + bt, btps = baseline_decode(model, tok, test, NUM_GEN) + print(f" {btps:.1f} tok/s", flush=True) + print(f" text: {tok.decode(bt[:30])[:100]}", flush=True) + + for N in [2, 4, 8]: + print(f"\n--- Spec N={N} ({NUM_GEN} tokens) ---", flush=True) + st, stps, stats = spec_decode_v4(model, draft, tok, test, NUM_GEN, num_draft=N) + print(f" {stps:.1f} tok/s (speedup: {stps/btps:.2f}x)", flush=True) + print(f" rounds: {stats['rounds']}, avg: {stats['avg_accepted']:.1f}, match: {stats['match_rate']*100:.1f}%", flush=True) + print(f" text: {tok.decode(st[:30])[:100]}", flush=True) + # Check first divergence + for i in range(min(50, len(bt), len(st))): + if bt[i] != st[i]: + print(f" first diverge: pos {i}", flush=True) + break + else: + print(f" first 50 tokens: MATCH ✓", flush=True) + + print("\nDONE") diff --git a/experiments/test_transformer_draft.py b/experiments/test_transformer_draft.py new file mode 100644 index 0000000000..2dee827362 --- /dev/null +++ b/experiments/test_transformer_draft.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +""" +Go/no-go: transformer draft layer (~100M params) vs MLP. + +EAGLE-style: single transformer decoder layer that takes +concat(h_t, embed(token_t)) and predicts h_{t+1}. +The attention mechanism can learn position-dependent patterns +that the MLP can't. +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + + +class TransformerDraftHead(nn.Module): + """Single transformer layer draft head. ~100M params. + + Architecture (EAGLE-inspired): + - Input projection: concat(h_t, embed(tok_t)) [2*D] → D + - One transformer block: LayerNorm → SelfAttn → Residual → LayerNorm → FFN → Residual + - Output: h_{t+1} prediction (fed to frozen LM head) + + For single-token decode, self-attention is Q@K^T = scalar, so it's + effectively a deep nonlinear transform with learned gating. + """ + def __init__(self, hidden_dim, num_heads=16, ffn_dim=4096): + super().__init__() + self.input_proj = nn.Linear(hidden_dim * 2, hidden_dim, bias=False) + + # Self-attention + self.norm1 = nn.RMSNorm(hidden_dim) + self.q_proj = nn.Linear(hidden_dim, hidden_dim, bias=False) + self.k_proj = nn.Linear(hidden_dim, hidden_dim, bias=False) + self.v_proj = nn.Linear(hidden_dim, hidden_dim, bias=False) + self.o_proj = nn.Linear(hidden_dim, hidden_dim, bias=False) + self.num_heads = num_heads + self.head_dim = hidden_dim // num_heads + + # FFN + self.norm2 = nn.RMSNorm(hidden_dim) + self.gate_proj = nn.Linear(hidden_dim, ffn_dim, bias=False) + self.up_proj = nn.Linear(hidden_dim, ffn_dim, bias=False) + self.down_proj = nn.Linear(ffn_dim, hidden_dim, bias=False) + + def __call__(self, h_and_emb): + # Input projection + x = self.input_proj(h_and_emb) # [B, D] + + # Reshape for "self-attention" (B=batch, T=1 for decode) + if x.ndim == 1: + x = x[None] # [1, D] + + # Self-attention (trivial for T=1, but learned transform) + residual = x + x = self.norm1(x) + B, D = x.shape + + q = self.q_proj(x).reshape(B, self.num_heads, self.head_dim) + k = self.k_proj(x).reshape(B, self.num_heads, self.head_dim) + v = self.v_proj(x).reshape(B, self.num_heads, self.head_dim) + + # For single token: attn = softmax(q@k^T/sqrt(d)) @ v = v (trivially) + # But the projections still learn useful transforms + scale = self.head_dim ** -0.5 + attn = (q * k).sum(-1, keepdims=True) * scale + attn = mx.softmax(attn, axis=-1) + x = (attn * v).reshape(B, D) + x = self.o_proj(x) + x = residual + x + + # FFN (SwiGLU) + residual = x + x = self.norm2(x) + x = nn.silu(self.gate_proj(x)) * self.up_proj(x) + x = self.down_proj(x) + x = residual + x + + return x.squeeze(0) if B == 1 else x + + +class DeepMLP(nn.Module): + """Deeper MLP for comparison. ~100M params.""" + def __init__(self, hidden_dim, inner=4096, num_layers=3): + super().__init__() + self.input_proj = nn.Linear(hidden_dim * 2, inner, bias=False) + self.layers = [nn.Linear(inner, inner, bias=False) for _ in range(num_layers - 1)] + self.output_proj = nn.Linear(inner, hidden_dim, bias=False) + self.norms = [nn.RMSNorm(inner) for _ in range(num_layers)] + + def __call__(self, h): + x = nn.gelu(self.input_proj(h)) + for layer, norm in zip(self.layers, self.norms[1:]): + x = x + nn.gelu(layer(norm(x))) + return self.output_proj(self.norms[0](x)) + + +def collect_decode_data(model, tok, prompt, num_tokens): + lm = model.language_model + inner = lm.model + tokens = mx.array(tok.encode(prompt))[None, :100] + cache = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + h_list, tok_list, next_list = [], [], [] + t0 = time.perf_counter() + for step in range(num_tokens): + h_list.append(last_h) + tok_list.append(y.item()) + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + fp = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(fp, last_h) + next_list.append(fp.item()) + y = fp.squeeze() + if (step+1) % 5000 == 0: + print(f" {step+1}/{num_tokens} ({(step+1)/(time.perf_counter()-t0):.0f} tok/s)", flush=True) + + print(f" collected {num_tokens} pairs in {time.perf_counter()-t0:.0f}s", flush=True) + h_data = mx.stack(h_list) + tok_data = mx.array(tok_list) + targets = mx.array(next_list) + mx.eval(h_data, tok_data, targets) + return h_data, tok_data, targets + + +def train_and_test(name, draft, embed_layer, lm_head, h_data, tok_data, targets, + model, tok, test_prompts, epochs=15, batch_size=512, lr=3e-4): + params = sum(v.size for _, v in tree_flatten(draft.parameters())) + print(f"\n=== {name} ({params/1e6:.1f}M params) ===", flush=True) + + optimizer = optim.Adam(learning_rate=lr) + T = h_data.shape[0] + + def loss_fn(m, hb, tb, tgt): + emb = embed_layer(tb) + x = mx.concatenate([hb, emb], axis=-1) + logits = lm_head(m(x)) + return nn.losses.cross_entropy(logits, tgt).mean() + lg = nn.value_and_grad(draft, loss_fn) + + t0 = time.perf_counter() + for ep in range(epochs): + perm = mx.array(np.random.permutation(T)) + total_loss = 0 + n = 0 + for j in range(0, T, batch_size): + idx = perm[j:j+batch_size] + loss, grads = lg(draft, h_data[idx], tok_data[idx], targets[idx]) + optimizer.update(draft, grads) + mx.eval(draft.parameters(), optimizer.state) + total_loss += loss.item() + n += 1 + if ep == 0 or (ep+1) % 5 == 0: + print(f" epoch {ep+1}/{epochs}: loss={total_loss/n:.4f}", flush=True) + t1 = time.perf_counter() + print(f" training: {t1-t0:.0f}s", flush=True) + + # Held-out test + lm = model.language_model + inner = lm.model + for prompt in test_prompts: + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + matches = 0 + for _ in range(200): + emb = inner.embed_tokens(mx.array([y.item()])) + x = mx.concatenate([last_h[None], emb], axis=-1) + dp = mx.argmax(lm.lm_head(draft(x)), axis=-1) + y_in = mx.array([[y.item()]]) + h = inner.embed_tokens(y_in) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + fp = mx.argmax(lm.lm_head(h)[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(dp, fp, last_h) + if dp.item() == fp.item(): + matches += 1 + y = fp.squeeze() + print(f" '{prompt[:50]}...': {matches}/200 = {matches/200*100:.1f}%", flush=True) + + adapter_mb = params * 2 / 1e6 + print(f" adapter: {adapter_mb:.0f} MB", flush=True) + + +if __name__ == "__main__": + print("=== Transformer vs Deep MLP Draft Head ===", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + print(f"loaded. D={D}\n", flush=True) + + # Collect 20K decode tokens (balance: enough data, not too long) + print("--- Collecting 20K decode-path tokens ---", flush=True) + prompt = ( + "Write an extremely detailed and comprehensive analysis of the complete " + "history and future of artificial intelligence, machine learning, and " + "neural networks. Cover every decade from the 1940s through 2026." + ) + h_data, tok_data, targets = collect_decode_data(model, tok, prompt, num_tokens=20000) + + test_prompts = [ + "Explain quantum computing to a five year old.", + "Write a recursive fibonacci function in Rust with memoization.", + "What caused the fall of the Roman Empire?", + ] + + # Test 1: Transformer draft head (~67M params) + transformer = TransformerDraftHead(D, num_heads=16, ffn_dim=4096) + train_and_test("Transformer (1 layer)", transformer, inner.embed_tokens, + lm.lm_head, h_data, tok_data, targets, model, tok, test_prompts) + + # Test 2: Deep MLP (~100M params) + mlp = DeepMLP(D, inner=4096, num_layers=3) + train_and_test("Deep MLP (3 layer)", mlp, inner.embed_tokens, + lm.lm_head, h_data, tok_data, targets, model, tok, test_prompts) + + print("\nDONE") diff --git a/experiments/v2_parallel_draft.py b/experiments/v2_parallel_draft.py new file mode 100644 index 0000000000..6dad4d5c52 --- /dev/null +++ b/experiments/v2_parallel_draft.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +""" +v2 Block Draft: parallel token generation via multi-position prediction heads. + +Instead of autoregressive drafting (token by token), predict ALL N positions +from the target's hidden state in ONE forward pass. + +Architecture (Medusa-style, simplest parallel generation): +- Input: h_t (target's last hidden state) + embed(token_t) +- N parallel heads, each predicting a different future position +- Head_k: MLP(concat(h_t, embed(tok_t))) → logits for position t+k+1 +- All heads share the input, run in parallel = ONE forward for N predictions + +Training: for each (h_t, tok_t) from decode, supervise head_k with token_{t+k+1}. + +Key question: does parallel prediction from h_t alone achieve 85%+ acceptance +at each position? If acceptance decays with distance (position t+8 harder than +t+1), we may need iterative refinement (diffusion). + +Phase 1: Train + measure per-position acceptance. +Phase 2: If needed, add refinement steps. +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +import mlx.optimizers as optim +from mlx.utils import tree_flatten +from mlx_lm import load +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + + +class ParallelDraftHead(nn.Module): + """N independent prediction heads sharing one backbone. + + backbone: shared MLP that processes (h_t, embed(tok_t)) + heads: N separate Linear layers, each predicting a future position + """ + def __init__(self, D, num_positions=8, backbone_dim=2048): + super().__init__() + self.num_positions = num_positions + # Shared backbone + self.backbone1 = nn.Linear(D * 2, backbone_dim, bias=False) + self.backbone2 = nn.Linear(backbone_dim, backbone_dim, bias=False) + self.backbone_norm = nn.RMSNorm(backbone_dim) + # Per-position prediction heads + self.heads = [nn.Linear(backbone_dim, D, bias=False) for _ in range(num_positions)] + + def __call__(self, h_and_emb): + """Returns list of N hidden states, one per future position.""" + x = nn.gelu(self.backbone1(h_and_emb)) + x = self.backbone_norm(nn.gelu(self.backbone2(x)) + x) # residual + return [head(x) for head in self.heads] + + +def collect_windowed_data(model, tok, prompt, num_tokens, window=8): + """Collect (h_t, tok_t, [tok_{t+1}, ..., tok_{t+window}]) tuples.""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None, :100] + cache = model.make_cache() + logits = model(tokens, cache=cache) + y = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y) + + # Collect with manual forward to get hidden states + h_list = [] + tok_list = [] + + t0 = time.perf_counter() + for step in range(num_tokens + window): + yi = mx.array([[y.item()]]) + h = inner.embed_tokens(yi) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + fp = mx.argmax(logits[:, -1], axis=-1) + ch = h[0, -1] + mx.eval(fp, ch) + h_list.append(ch) + tok_list.append(y.item()) + y = fp.squeeze() + if (step + 1) % 5000 == 0: + print(f" {step+1}/{num_tokens+window}", flush=True) + + # Append final token + tok_list.append(y.item()) + + elapsed = time.perf_counter() - t0 + print(f" collected {num_tokens} pairs in {elapsed:.0f}s ({(num_tokens+window)/elapsed:.0f} tok/s)", flush=True) + + # Build windowed training data + h_data = mx.stack(h_list[:num_tokens]) # [N, D] + tok_data = mx.array(tok_list[:num_tokens]) # [N] - current tokens + # Targets: window of future tokens for each position + target_windows = [] + for k in range(window): + target_windows.append(mx.array(tok_list[k+1:num_tokens+k+1])) # [N] + + mx.eval(h_data, tok_data, *target_windows) + return h_data, tok_data, target_windows + + +def train_parallel(draft, embed, lm_head, h_data, tok_data, target_windows, + epochs=30, batch_size=512, lr=3e-4): + """Train all heads simultaneously.""" + T = h_data.shape[0] + num_pos = len(target_windows) + optimizer = optim.Adam(learning_rate=lr) + + def loss_fn(model, h_batch, tok_batch, *tgt_batches): + emb = embed(tok_batch) + x = mx.concatenate([h_batch, emb], axis=-1) + predictions = model(x) # list of N [B, D] + total = mx.array(0.0) + for k, (pred, tgt) in enumerate(zip(predictions, tgt_batches)): + logits = lm_head(pred) + ce = nn.losses.cross_entropy(logits, tgt).mean() + # Weight closer positions higher (they matter more for acceptance) + weight = 1.0 / (k + 1) + total = total + ce * weight + return total + + lg = nn.value_and_grad(draft, loss_fn) + + t0 = time.perf_counter() + for ep in range(epochs): + perm = mx.array(np.random.permutation(T)) + total_loss = 0 + n = 0 + for j in range(0, T, batch_size): + idx = perm[j:j+batch_size] + args = [draft, h_data[idx], tok_data[idx]] + [tw[idx] for tw in target_windows] + loss, grads = lg(*args) + optimizer.update(draft, grads) + mx.eval(draft.parameters(), optimizer.state) + total_loss += loss.item() + n += 1 + if ep == 0 or (ep + 1) % 10 == 0: + print(f" epoch {ep+1}/{epochs}: loss={total_loss/n:.4f} ({time.perf_counter()-t0:.0f}s)", flush=True) + + +def measure_per_position_acceptance(model, draft, tok, prompt, num_tokens=200, num_pos=8): + """Measure acceptance at each future position independently.""" + lm = model.language_model + inner = lm.model + + tokens = mx.array(tok.encode(prompt))[None] + cache = model.make_cache() + + # Prefill + get h + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y = mx.argmax(logits[:, -1], axis=-1) + last_h = h[0, -1] + mx.eval(y, last_h) + + # Generate tokens and measure acceptance at each position + per_pos_matches = [0] * num_pos + total = 0 + + # Collect true future tokens by running baseline + true_tokens = [y.item()] + for _ in range(num_tokens + num_pos): + yi = mx.array([[y.item()]]) + h = inner.embed_tokens(yi) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache[i]) + h = inner.norm(h) + logits = lm.lm_head(h) + y_next = mx.argmax(logits[:, -1], axis=-1) + mx.eval(y_next) + true_tokens.append(y_next.item()) + y = y_next.squeeze() + + # Now check draft predictions at each position + # Re-run with fresh cache to get hidden states at each position + cache2 = model.make_cache() + h = inner.embed_tokens(tokens) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache2[i]) + h = inner.norm(h) + y2 = mx.argmax(lm.lm_head(h)[:, -1], axis=-1) + last_h2 = h[0, -1] + mx.eval(y2, last_h2) + + for t in range(num_tokens): + # Draft all positions from last_h2 + emb = inner.embed_tokens(mx.array([true_tokens[t]])) + x = mx.concatenate([last_h2[None], emb], axis=-1) + predictions = draft(x) + + for k in range(num_pos): + pred_logits = lm.lm_head(predictions[k]) + pred_tok = mx.argmax(pred_logits, axis=-1) + mx.eval(pred_tok) + if pred_tok.item() == true_tokens[t + k + 1]: + per_pos_matches[k] += 1 + + total += 1 + + # Advance + yi = mx.array([[true_tokens[t]]]) + h = inner.embed_tokens(yi) + for i, layer in enumerate(inner.layers): + h = layer(h, mask=None, cache=cache2[i]) + h = inner.norm(h) + last_h2 = h[0, -1] + mx.eval(last_h2) + + return per_pos_matches, total + + +if __name__ == "__main__": + print("=== v2 Parallel Draft (Medusa-style) ===\n", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + NUM_POS = 8 + + # Collect 20K windowed training data + print("--- Collecting 20K decode tokens with 8-position windows ---", flush=True) + prompt = "Write a comprehensive history of AI from Turing to transformers." + h_data, tok_data, target_windows = collect_windowed_data( + model, tok, prompt, num_tokens=20000, window=NUM_POS) + + # Train parallel draft head + print(f"\n--- Training {NUM_POS}-position parallel draft ---", flush=True) + draft = ParallelDraftHead(D, num_positions=NUM_POS, backbone_dim=2048) + params = sum(v.size for _, v in tree_flatten(draft.parameters())) + print(f" params: {params/1e6:.1f}M", flush=True) + + train_parallel(draft, inner.embed_tokens, lm.lm_head, + h_data, tok_data, target_windows, + epochs=30, batch_size=512, lr=3e-4) + + # Measure PER-POSITION acceptance + print(f"\n--- Per-position acceptance (200 tokens, 3 prompts) ---", flush=True) + test_prompts = [ + "Explain quantum computing simply.", + "Write a Python quicksort implementation.", + "What causes climate change?", + ] + + total_per_pos = [0] * NUM_POS + total_count = 0 + for p in test_prompts: + per_pos, count = measure_per_position_acceptance( + model, draft, tok, p, num_tokens=200, num_pos=NUM_POS) + for k in range(NUM_POS): + total_per_pos[k] += per_pos[k] + total_count += count + short = p[:50] + rates = [f"{per_pos[k]/count*100:.0f}%" for k in range(NUM_POS)] + print(f" '{short}': {', '.join(rates)}", flush=True) + + print(f"\n OVERALL per-position acceptance:", flush=True) + for k in range(NUM_POS): + rate = total_per_pos[k] / total_count * 100 + print(f" pos t+{k+1}: {rate:.1f}%", flush=True) + + # Estimate: probability ALL first K positions match + print(f"\n P(all match) for draft block sizes:", flush=True) + for N in [2, 4, 8]: + p_all = 1.0 + for k in range(N): + p_all *= total_per_pos[k] / total_count + expected_tokens = sum(total_per_pos[k] / total_count for k in range(N)) + 1 + print(f" N={N}: P(all)={p_all*100:.1f}%, E[tokens]={expected_tokens:.1f}", flush=True) + + print(f"\n adapter: {params * 2 / 1e6:.0f} MB", flush=True) + print("DONE") diff --git a/experiments/v2_phase1_separate_gdn.py b/experiments/v2_phase1_separate_gdn.py new file mode 100644 index 0000000000..7a6e78edc0 --- /dev/null +++ b/experiments/v2_phase1_separate_gdn.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +""" +v2 Phase 1: Validate separate GDN draft model fixes Mamba corruption. + +Build a tiny model with its OWN GDN-like recurrent layers + attention. +Key: it has its OWN cache state, independent from the target model. + +Architecture (micro draft model, ~20M params): +- Embedding: reused from target (frozen) +- 4 layers: 3 simplified GDN-like recurrent + 1 attention +- LM head: reused from target (frozen) +- Own cache: own Mamba state + own KV + +The point is NOT acceptance rate (too small to be good). +The point is: does the verification loop produce COHERENT output +when the draft model has its own recurrent state? + +If YES → the architecture is viable, scale up for v2. +If NO → something else is wrong beyond Mamba state. +""" +import sys, time +sys.path.insert(0, "/Users/tom/dev/mlx-lm") +import mlx.core as mx +import mlx.nn as nn +from mlx_lm import load +from mlx_lm.models.cache import KVCache +import numpy as np + +MODEL = "/Users/tom/models/Qwen3.6-35B-A3B-4bit" + + +class MiniRecurrentLayer(nn.Module): + """Simplified GDN-like recurrent layer for draft model. + Maintains its own recurrent state (like Mamba). + """ + def __init__(self, D, state_dim=256): + super().__init__() + self.proj_in = nn.Linear(D, state_dim, bias=False) + self.gate = nn.Linear(D, state_dim, bias=False) + self.proj_out = nn.Linear(state_dim, D, bias=False) + self.norm = nn.RMSNorm(D) + self.state_dim = state_dim + + def __call__(self, x, state=None): + # x: [B, T, D] + B, T, D = x.shape + if state is None: + state = mx.zeros((B, self.state_dim)) + + normed = self.norm(x) + outs = [] + for t in range(T): + xt = normed[:, t] # [B, D] + g = mx.sigmoid(self.gate(xt)) # [B, state_dim] + inp = self.proj_in(xt) # [B, state_dim] + state = g * state + (1 - g) * inp # GRU-like update + out = self.proj_out(state) # [B, D] + outs.append(out) + + y = mx.stack(outs, axis=1) # [B, T, D] + return x + y, state # residual + + +class MiniAttentionLayer(nn.Module): + """Simple attention layer for draft model.""" + def __init__(self, D, num_heads=8): + super().__init__() + self.norm = nn.RMSNorm(D) + self.q_proj = nn.Linear(D, D, bias=False) + self.k_proj = nn.Linear(D, D, bias=False) + self.v_proj = nn.Linear(D, D, bias=False) + self.o_proj = nn.Linear(D, D, bias=False) + self.num_heads = num_heads + self.head_dim = D // num_heads + + def __call__(self, x, kv_cache=None): + B, T, D = x.shape + normed = self.norm(x) + q = self.q_proj(normed).reshape(B, T, self.num_heads, self.head_dim).transpose(0, 2, 1, 3) + k = self.k_proj(normed).reshape(B, T, self.num_heads, self.head_dim).transpose(0, 2, 1, 3) + v = self.v_proj(normed).reshape(B, T, self.num_heads, self.head_dim).transpose(0, 2, 1, 3) + + if kv_cache is not None and kv_cache[0] is not None: + k = mx.concatenate([kv_cache[0], k], axis=2) + v = mx.concatenate([kv_cache[1], v], axis=2) + + scale = self.head_dim ** -0.5 + attn = (q @ k.transpose(0, 1, 3, 2)) * scale + # Causal mask + T_q, T_k = q.shape[2], k.shape[2] + mask = mx.triu(mx.full((T_q, T_k), -1e9), k=T_k - T_q + 1) + attn = attn + mask + attn = mx.softmax(attn, axis=-1) + out = (attn @ v).transpose(0, 2, 1, 3).reshape(B, T, D) + out = self.o_proj(out) + + new_kv = (k, v) + return x + out, new_kv + + +class MiniDraftModel(nn.Module): + """Tiny draft model with own recurrent + attention layers.""" + def __init__(self, D, num_recurrent=3, state_dim=256, num_heads=8): + super().__init__() + self.recurrent_layers = [MiniRecurrentLayer(D, state_dim) for _ in range(num_recurrent)] + self.attn_layer = MiniAttentionLayer(D, num_heads) + self.norm = nn.RMSNorm(D) + + def __call__(self, x, cache=None): + """x: [B, T, D]. cache: dict with 'recurrent_states' and 'kv'.""" + if cache is None: + cache = {'recurrent_states': [None] * len(self.recurrent_layers), 'kv': None} + + new_states = [] + for i, layer in enumerate(self.recurrent_layers): + x, state = layer(x, cache['recurrent_states'][i]) + new_states.append(state) + + x, kv = self.attn_layer(x, cache['kv']) + x = self.norm(x) + + cache['recurrent_states'] = new_states + cache['kv'] = kv + return x, cache + + +def spec_decode_separate(target_model, draft_model, embed, lm_head, tok, prompt, num_tokens, num_draft=4): + """Spec decode with SEPARATE draft model (own cache).""" + inner = target_model.language_model.model + + tokens = mx.array(tok.encode(prompt))[None] + + # Target prefill + target_cache = target_model.make_cache() + target_logits = target_model(tokens, cache=target_cache) + y = mx.argmax(target_logits[:, -1], axis=-1) + mx.eval(y) + + # Draft prefill + draft_cache = {'recurrent_states': [None] * len(draft_model.recurrent_layers), 'kv': None} + draft_emb = embed(tokens) + draft_h, draft_cache = draft_model(draft_emb, draft_cache) + mx.eval([s for s in draft_cache['recurrent_states'] if s is not None]) + + gen = [y.item()] + t0 = time.perf_counter() + matches = 0 + rounds = 0 + + while len(gen) < num_tokens: + # Snapshot target Mamba + target_mamba_snap = [] + for c in target_cache: + if not isinstance(c, KVCache): + s = c.state + target_mamba_snap.append([mx.array(a) for a in s] if s else None) + else: + target_mamba_snap.append(None) + mx.eval([x for snap in target_mamba_snap if snap for x in snap]) + + # Draft N tokens (draft model has OWN cache — no corruption) + drafts = [] + for _ in range(num_draft): + d_emb = embed(mx.array([[y.item() if not drafts else drafts[-1]]])) + d_h, draft_cache = draft_model(d_emb, draft_cache) + d_logits = lm_head(d_h) + d_tok = mx.argmax(d_logits[:, -1], axis=-1) + mx.eval(d_tok) + drafts.append(d_tok.item()) + + # Verify: batch through target + verify = mx.array([[y.item()] + drafts]) + v_logits = target_model(verify, cache=target_cache) + + acc = 0 + for i in range(num_draft): + tt = mx.argmax(v_logits[0, i], axis=-1); mx.eval(tt) + if tt.item() == drafts[i]: + gen.append(tt.item()); acc += 1; matches += 1 + else: + gen.append(tt.item()); acc += 1; break + + if acc == num_draft: + bonus = mx.argmax(v_logits[0, num_draft], axis=-1); mx.eval(bonus) + gen.append(bonus.item()); acc += 1 + + rounds += 1 + + # Restore target Mamba on partial rejection + reject = num_draft + 1 - acc + if reject > 0: + for c, snap in zip(target_cache, target_mamba_snap): + if snap is not None: + c.state = snap + elif isinstance(c, KVCache) and c.keys is not None: + c.offset -= reject + c.keys = c.keys[..., :-reject, :] + c.values = c.values[..., :-reject, :] + + # Draft cache: on partial rejection, we need to "rollback" draft too. + # But draft has recurrent state — same problem? + # KEY DIFFERENCE: draft model is TINY and we can afford to re-process + # the accepted tokens through it. Or just reset and re-feed. + # For now: just let draft state drift (it's a weak predictor anyway). + # The important thing is TARGET state coherency. + + y = mx.array(gen[-1]) + mx.eval(y) + + t1 = time.perf_counter() + gen = gen[:num_tokens] + tps = len(gen) / (t1 - t0) + return gen, tps, matches, rounds + + +if __name__ == "__main__": + print("=== v2 Phase 1: Separate GDN Draft Model ===\n", flush=True) + model, tok = load(MODEL) + lm = model.language_model + inner = lm.model + D = inner.layers[0].input_layernorm.weight.shape[0] + embed = inner.embed_tokens # shared + lm_head = lm.lm_head # shared + + # Build tiny draft model + draft = MiniDraftModel(D, num_recurrent=3, state_dim=256, num_heads=8) + params = sum(v.size for _, v in nn.utils.tree_flatten(draft.parameters())) + print(f"Draft model: {params/1e6:.1f}M params (untrained)\n", flush=True) + + # Baseline + print("--- Baseline ---", flush=True) + tokens = mx.array(tok.encode("Explain quantum computing simply."))[None] + cache = model.make_cache() + logits = model(tokens, cache=cache) + y = mx.argmax(logits[:, -1], axis=-1); mx.eval(y) + base = [y.item()] + t0 = time.perf_counter() + for _ in range(199): + logits = model(mx.array([[y.item()]]), cache=cache) + y = mx.argmax(logits[:, -1], axis=-1); mx.eval(y) + base.append(y.item()) + btps = 199 / (time.perf_counter() - t0) + print(f" {btps:.1f} tok/s", flush=True) + + # Spec decode with separate draft (untrained — expect low match but correct output) + print(f"\n--- Separate draft (untrained, N=2) ---", flush=True) + gen, tps, matches, rounds = spec_decode_separate( + model, draft, embed, lm_head, tok, + "Explain quantum computing simply.", 200, num_draft=2) + print(f" {tps:.1f} tok/s (speedup: {tps/btps:.2f}x)", flush=True) + print(f" match: {matches}/{rounds*2} = {matches/(rounds*2)*100:.1f}%", flush=True) + + # KEY TEST: is output coherent? + spec_text = tok.decode(gen[:200]) + base_text = tok.decode(base[:200]) + print(f"\n=== SPEC OUTPUT ===", flush=True) + print(spec_text[:500], flush=True) + print(f"\n=== BASELINE OUTPUT ===", flush=True) + print(base_text[:500], flush=True) + + # Token match + for i in range(min(50, len(gen), len(base))): + if gen[i] != base[i]: + print(f"\nFirst diverge: pos {i}", flush=True) + break + else: + print(f"\nFirst 50: MATCH ✓", flush=True) + + print("\nDONE") diff --git a/scripts/benchmark.sh b/scripts/benchmark.sh new file mode 100755 index 0000000000..3c1356654a --- /dev/null +++ b/scripts/benchmark.sh @@ -0,0 +1,308 @@ +#!/bin/bash +# Inference Benchmarks — Release Mode +# +# Language-agnostic CLI that drives benchmark backends via environment variables. +# Currently supports the Swift backend (mlx-swift-lm). +# +# Usage: +# ./scripts/benchmark.sh --model qwen35-0.8b # Simple eval (default) +# ./scripts/benchmark.sh --model qwen35-0.8b --method summarization --quick +# ./scripts/benchmark.sh --model qwen35-0.8b --quant all --kv all # Full matrix +# ./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 +# +# --model, --method, --quant, and --kv all accept comma-separated lists. +# All permutations (model × quant × kv × method) run in sequence; every row +# lands in the same hardware-dated file at benchmarks/{chip}-{ram}-{date}.md, +# grouped by model. + +set -e + +# ───────────────────────────────────────────── +# Helpers +# ───────────────────────────────────────────── +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +log_info() { echo -e "${GREEN}[INFO]${NC} $1"; } +log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } +log_error() { echo -e "${RED}[ERROR]${NC} $1"; } + +PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +# ───────────────────────────────────────────── +# Defaults +# ───────────────────────────────────────────── +METHOD="simple" +MODEL="" +QUANT="4bit" +KV="none" +CONTEXT="" +QUICK=false +KLD=false +PPL=false +BASELINE=false +BATCH=1 +THINK=false +REASONING="medium" +NGRAM=0 +QUICK_CONTEXTS="128,1024,4096,32768" + +# ───────────────────────────────────────────── +# Help +# ───────────────────────────────────────────── +show_help() { + cat <<'HELP' +Usage: ./scripts/benchmark.sh --model MODEL [OPTIONS] + +Inference benchmarks in RELEASE mode. Measures throughput, perplexity, TTFT, +KL divergence, and GPU memory. + +Options: + --model MODELS (required) One or more model families / HuggingFace repo IDs + Comma-separated for multiple: qwen35-0.8b,qwen35-2b + --method METHODS Benchmark method(s), comma-separated (default: simple) + simple Basic chat prompt — generation speed + PPL + summarization Context-scaling with pre-sized prompts + wikitext2 Standard LM perplexity via forced decode + niah Needle-in-a-haystack retrieval + multi-turn Multi-turn conversation + tool-calling Tool call generation + --quant QUANTS Weight quantization(s): bf16, 8bit, 4bit, all (default: 4bit) + Comma-separated for multiple: bf16,4bit + --kv CONFIGS KV cache config(s): none, affine8, affine4, turbo4, turbo4v2, + turbo4v3, turbo3, turbo3v2, turbo8, turbo8v2, turbo8v4, all + (default: none). Comma-separated for multiple: none,turbo4v2 + --context SIZE Comma-separated context sizes (default: all 11 sizes for scaling methods) + --quick Quick mode: 128 + 1024 + 4096 + 32768 tokens only + --ppl Track per-token perplexity during generation + --kld Compute KL divergence vs bf16/8bit baseline + --baseline Auto-select highest-fidelity variant (bf16 → 8bit → 4bit) + --batch N Run N concurrent generations (default: 1) + --think Enable thinking mode for thinking-capable models + --reasoning EFFORT Reasoning effort for models that support it (GPT-OSS). + Values: low, medium, high (default: medium). + Maps to MLX_BENCH_REASONING; ignored by models without + a reasoning_effort setting. + --ngram SIZE N-gram speculative decoding size (default: 0 = disabled). + Typical: 3 (trigram matching). Higher values require longer + repeated sequences in generated text to hit. Disabled by + default so benchmarks measure pure autoregressive decode — + set non-zero to evaluate speculative decoding speedup. + -h, --help Show this help + +Model families: + qwen35-0.8b Qwen3.5 0.8B (GatedDeltaNet) + qwen35-2b Qwen3.5 2B (GatedDeltaNet) + qwen35-4b Qwen3.5 4B (GatedDeltaNet) + qwen35-9b Qwen3.5 9B (GatedDeltaNet) + qwen35-27b Qwen3.5 27B (GatedDeltaNet) + qwen35-35b-a3b Qwen3.5 35B A3B (GatedDeltaNet MoE) + gpt-oss-20b GPT-OSS 20B + nemotron-30b-a3b Nemotron Cascade 2 30B A3B (nemotron_h; also: nemotron-cascade-2, + nemotron-cascade2, nemotron-cascade-2-30b-a3b, …) + gemma4-e2b Gemma 4 E2B (Dense, ~2B) + gemma4-e4b Gemma 4 E4B (Dense, ~4B) + gemma4-26b-a4b Gemma 4 26B A4B (MoE, 128 experts) + gemma4-31b Gemma 4 31B (Dense) + Custom HuggingFace model + +Examples: + ./scripts/benchmark.sh --model qwen35-0.8b # Simple eval + ./scripts/benchmark.sh --model qwen35-9b --method summarization --quick # Fast summarization + ./scripts/benchmark.sh --model qwen35-0.8b --method wikitext2 --context 1024 + ./scripts/benchmark.sh --model qwen35-0.8b --quant bf16 --kv none # bf16 baseline + ./scripts/benchmark.sh --model qwen35-0.8b --quant all --kv all --quick # Full matrix + ./scripts/benchmark.sh --model qwen35-9b --kv affine4 --kld # With KLD + ./scripts/benchmark.sh --model qwen35-0.8b,qwen35-2b --kv none,turbo4v2 --quick # Multi-model sweep + ./scripts/benchmark.sh --model qwen35-0.8b --method simple,summarization # Two methods + ./scripts/benchmark.sh --model nemotron-cascade-2 --quant 4bit # Nemotron (alias) + ./scripts/benchmark.sh --model gpt-oss-20b --reasoning high --think --ppl # Harmony reasoning at 'high' + +HELP +} + +# ───────────────────────────────────────────── +# Parse arguments +# ───────────────────────────────────────────── +while [[ $# -gt 0 ]]; do + case "$1" in + --model) MODEL="$2"; shift 2 ;; + --method) METHOD="$2"; shift 2 ;; + --quant) QUANT="$2"; shift 2 ;; + --kv) KV="$2"; shift 2 ;; + --context) CONTEXT="$2"; shift 2 ;; + --quick) QUICK=true; shift ;; + --kld) KLD=true; shift ;; + --ppl) PPL=true; shift ;; + --baseline) BASELINE=true; shift ;; + --batch) BATCH="$2"; shift 2 ;; + --think) THINK=true; shift ;; + --reasoning) REASONING="$2"; shift 2 ;; + --ngram) NGRAM="$2"; shift 2 ;; + -h|--help) show_help; exit 0 ;; + *) log_error "Unknown argument: $1"; show_help; exit 1 ;; + esac +done + +# Validate required args +if [ -z "$MODEL" ]; then + log_error "--model is required" + show_help + exit 1 +fi + +# Build model list (comma-separated for multi-model sweeps) +MODELS=() +IFS=',' read -ra MODELS <<< "$MODEL" + +# Build method list (comma-separated for multi-method sweeps) +METHODS=() +IFS=',' read -ra METHODS <<< "$METHOD" +for m in "${METHODS[@]}"; do + case "$m" in + simple|summarization|wikitext2|niah|multi-turn|tool-calling) ;; + *) log_error "Unknown method: $m"; exit 1 ;; + esac +done + +# Validate reasoning effort — warn rather than error so new model vocabularies +# pass through without requiring a harness change. +case "$REASONING" in + low|medium|high) ;; + *) log_warn "Unusual reasoning effort '$REASONING' (expected low/medium/high); passing through" ;; +esac + +# Validate ngram size — must be a non-negative integer. +if ! [[ "$NGRAM" =~ ^[0-9]+$ ]]; then + log_error "--ngram must be a non-negative integer (got: $NGRAM)" + exit 1 +fi + +# Build quant list +QUANTS=() +if $BASELINE; then + QUANTS=("baseline") +elif [ "$QUANT" = "all" ]; then + QUANTS=("bf16" "8bit" "4bit") +else + IFS=',' read -ra QUANTS <<< "$QUANT" +fi + +# Build KV list +KVS=() +case "$KV" in + all) KVS=("none" "affine8" "affine4" "turbo4" "turbo3" "turbo4v2") ;; + *) IFS=',' read -ra KVS <<< "$KV" ;; +esac + +# Context sizes +CONTEXTS="$CONTEXT" +if $QUICK; then + CONTEXTS="$QUICK_CONTEXTS" +fi + +# ───────────────────────────────────────────── +# Print configuration +# ───────────────────────────────────────────── +echo "" +log_info "╔══════════════════════════════════════════╗" +log_info "║ Inference Benchmarks ║" +log_info "║ RELEASE MODE ║" +log_info "╚══════════════════════════════════════════╝" +log_info "" +log_info "Models: $(IFS=,; echo "${MODELS[*]}")" +log_info "Methods: $(IFS=,; echo "${METHODS[*]}")" +log_info "Quants: $(IFS=,; echo "${QUANTS[*]}")" +log_info "KVs: $(IFS=,; echo "${KVS[*]}")" +$KLD && log_info "KLD: yes" +$PPL && log_info "PPL: yes" +$THINK && log_info "Think: yes (reasoning=$REASONING)" +[ "$NGRAM" -gt 0 ] && log_info "N-gram: size=$NGRAM" +[ "$BATCH" -gt 1 ] && log_info "Batch: $BATCH" +[ -n "$CONTEXTS" ] && log_info "Context: $CONTEXTS" +log_info "" + +# ───────────────────────────────────────────── +# Build in release mode +# ───────────────────────────────────────────── +cd "$PROJECT_ROOT" + +log_info "Building (make build-tests)..." +if ! make -C "$PROJECT_ROOT" build-tests; then + log_error "make build-tests failed. Re-run: make build-tests" + exit 1 +fi + +# ───────────────────────────────────────────── +# Run benchmarks +# ───────────────────────────────────────────── +log_info "Running benchmarks..." +echo "" + +# Common env vars (stable across all permutations). +if [ -n "$CONTEXTS" ]; then export MLX_BENCH_CONTEXT="$CONTEXTS"; else unset MLX_BENCH_CONTEXT; fi +if $KLD; then export MLX_BENCH_KLD=1; else unset MLX_BENCH_KLD; fi +if ${PPL:-false}; then export MLX_BENCH_PPL=1; else unset MLX_BENCH_PPL; fi +if [ "$BATCH" -gt 1 ]; then export MLX_BENCH_BATCH="$BATCH"; else unset MLX_BENCH_BATCH; fi +if $THINK; then export MLX_BENCH_THINK=1; else unset MLX_BENCH_THINK; fi +# Reasoning effort — only set when non-default so unset tells the harness to +# fall back to the model family's registered value. +if [ "$REASONING" != "medium" ]; then export MLX_BENCH_REASONING="$REASONING"; else unset MLX_BENCH_REASONING; fi +# N-gram size — always export so the harness sees an explicit value (0 = off). +# Benchmark default is 0 to measure pure autoregressive decode; set --ngram N +# to evaluate speculative decoding speedup. +export MLX_BENCH_NGRAM="$NGRAM" + +TOTAL_RUNS=$(( ${#MODELS[@]} * ${#METHODS[@]} * ${#QUANTS[@]} * ${#KVS[@]} )) +RUN_INDEX=0 +FAILED_RUNS=() + +for model in "${MODELS[@]}"; do + for method in "${METHODS[@]}"; do + for q in "${QUANTS[@]}"; do + for kv in "${KVS[@]}"; do + RUN_INDEX=$(( RUN_INDEX + 1 )) + + export MLX_BENCH_MODEL="$model" + export MLX_BENCH_METHOD="$method" + export MLX_BENCH_KV="$kv" + + if [ "$q" = "baseline" ]; then + export MLX_BENCH_BASELINE=1 + unset MLX_BENCH_QUANT + else + unset MLX_BENCH_BASELINE + export MLX_BENCH_QUANT="$q" + fi + + log_info "[$RUN_INDEX/$TOTAL_RUNS] model=$model method=$method quant=$q kv=$kv" + + # Stream filtered output in real-time via a PTY (script -q) so Swift Testing + # flushes print() calls mid-test. Full output captured for post-mortem. + TMPOUT=$(mktemp) + script -q /dev/null swift test --skip-build -c release --filter "benchmark" 2>&1 \ + | tee "$TMPOUT" \ + | grep -E --line-buffered "\[ENV\]|\[WARMUP\]|\[BENCH\]|\[MEM\]|\[KLD\]|\[RESULT\]|\[KV-QUANT\]|\[TURBO\]|\[PROGRESS\]|\[HARMONY\]|Test.*passed|Test.*failed|[Ee]rror|[Ff]atal|BenchmarkError|threw|[Ee]xception|issue at" + EXIT_CODE=${PIPESTATUS[0]} + + if [ "$EXIT_CODE" -ne 0 ]; then + log_error "Run failed (exit=$EXIT_CODE model=$model method=$method quant=$q kv=$kv):" + grep -iE "error|fatal|BenchmarkError|threw|exception|exceeds|issue" "$TMPOUT" | tail -20 + FAILED_RUNS+=("$model/$method/$q/$kv") + fi + + rm -f "$TMPOUT" + echo "" + done + done + done +done + +log_info "Benchmark complete! $((TOTAL_RUNS - ${#FAILED_RUNS[@]}))/$TOTAL_RUNS runs succeeded." +if [ ${#FAILED_RUNS[@]} -gt 0 ]; then + log_warn "Failed runs:" + for r in "${FAILED_RUNS[@]}"; do log_warn " - $r"; done +fi +log_info "Results: benchmarks/{chip}-{ram}-$(date +%Y-%m-%d).md" diff --git a/scripts/build-metallib.sh b/scripts/build-metallib.sh new file mode 100755 index 0000000000..fc04579e3a --- /dev/null +++ b/scripts/build-metallib.sh @@ -0,0 +1,111 @@ +#!/bin/bash +# build-metallib.sh +# Compiles MLX Metal shaders into mlx.metallib for SPM builds. +# SPM doesn't compile .metal files automatically, so this must be run once +# before benchmarks or tests can execute. +# +# Usage: ./scripts/build-metallib.sh [release|debug|both] +# +# Produces: .build/arm64-apple-macosx/{config}/mlx.metallib +# .build/arm64-apple-macosx/{config}/{package}Tests.xctest/Contents/MacOS/mlx.metallib + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" + +CONFIG="${1:-release}" + +# Metal source dir: prefer sibling local path dependency, then checkouts. +# Probe a few well-known locations so this works without per-developer edits. +METAL_SRC_DIR="" +for candidate in \ + "$PROJECT_ROOT/../mlx-swift/Source/Cmlx/mlx-generated/metal" \ + "$PROJECT_ROOT/.build/checkouts/mlx-swift/Source/Cmlx/mlx-generated/metal" \ + "${MLX_SWIFT_PATH:-}/Source/Cmlx/mlx-generated/metal"; do + if [ -n "$candidate" ] && [ -d "$candidate" ]; then + METAL_SRC_DIR="$candidate" + break + fi +done + +if [ ! -d "$METAL_SRC_DIR" ]; then + echo "Error: Metal source not found at $METAL_SRC_DIR" + echo "Run 'swift package resolve' first to fetch dependencies." + exit 1 +fi + +# MLX C++ kernel headers (bf16.h, etc.) — needed by generated metal shaders. +# Located two levels up from mlx-generated/metal/ in the Cmlx source tree. +CMLX_BASE="$(cd "$METAL_SRC_DIR/../.." && pwd)" +MLX_KERNEL_INC="$CMLX_BASE/mlx" + +build_metallib_for_config() { + local cfg="$1" + local BUILD_DIR="$PROJECT_ROOT/.build/arm64-apple-macosx/$cfg" + + echo "" + echo "Building mlx.metallib ($cfg)..." + + # Create temp directory for .air files + local AIR_DIR + AIR_DIR=$(mktemp -d) + # shellcheck disable=SC2064 + trap "rm -rf $AIR_DIR" EXIT + + local METAL_FILES + METAL_FILES=$(find "$METAL_SRC_DIR" -name "*.metal" -type f | sort) + local AIR_FILES="" + local count=0 + + while IFS= read -r metal_file; do + local rel_path="${metal_file#$METAL_SRC_DIR/}" + local air_name + air_name=$(echo "$rel_path" | sed 's|/|_|g; s|\.metal$|.air|') + local air_file="$AIR_DIR/$air_name" + + xcrun metal \ + -std=metal3.1 \ + -O2 \ + -I "$METAL_SRC_DIR" \ + -I "$MLX_KERNEL_INC" \ + -c "$metal_file" \ + -o "$air_file" 2>&1 + + AIR_FILES="$AIR_FILES $air_file" + count=$((count + 1)) + done <<< "$METAL_FILES" + + mkdir -p "$BUILD_DIR" + + local OUTPUT="$BUILD_DIR/mlx.metallib" + echo "Linking $count shaders -> $OUTPUT" + # shellcheck disable=SC2086 + xcrun metallib $AIR_FILES -o "$OUTPUT" + echo " Created: $OUTPUT" + + # Also copy into the .xctest bundle if it exists + local XCTEST_MACOS="$BUILD_DIR/mlx-swift-lmPackageTests.xctest/Contents/MacOS" + if [ -d "$XCTEST_MACOS" ]; then + cp "$OUTPUT" "$XCTEST_MACOS/mlx.metallib" + echo " Copied to test bundle: $XCTEST_MACOS/mlx.metallib" + fi +} + +case "$CONFIG" in + both) + build_metallib_for_config "release" + build_metallib_for_config "debug" + ;; + release|debug) + build_metallib_for_config "$CONFIG" + ;; + *) + echo "Error: Unknown config '$CONFIG'. Use: release, debug, or both" + exit 1 + ;; +esac + +echo "" +echo "Metal shaders compiled. Run benchmarks with:" +echo " ./scripts/benchmark.sh --model " diff --git a/scripts/build-prefill-bridge.sh b/scripts/build-prefill-bridge.sh new file mode 100755 index 0000000000..570e16b9e9 --- /dev/null +++ b/scripts/build-prefill-bridge.sh @@ -0,0 +1,46 @@ +#!/bin/bash +# Build the native C++ prefill bridges as standalone dylibs. +# +# Two modes: +# --standalone: Link Cmlx objects INTO the dylib (own MLX copy, max perf) +# (default): Use -undefined dynamic_lookup (share host MLX, safe allocator) +# +# Usage: ./scripts/build-prefill-bridge.sh [--standalone] +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" +SRC_DIR="$PROJECT_ROOT/Sources/NativePrefillBridge" +MLX_SWIFT="${MLX_SWIFT_PATH:-$PROJECT_ROOT/.build/checkouts/mlx-swift}" +MLX_INC="$MLX_SWIFT/Source/Cmlx/mlx" +MLX_C_INC="$MLX_SWIFT/Source/Cmlx/mlx-c" +RELEASE_DIR="$PROJECT_ROOT/.build/arm64-apple-macosx/release" + +STANDALONE=false +[ "${1:-}" = "--standalone" ] && STANDALONE=true + +COMMON="-std=c++20 -O3 -DNDEBUG -fPIC -I$MLX_INC -I$MLX_C_INC -I$SRC_DIR -target arm64-apple-macosx14.0" + +if $STANDALONE; then + CMLX_OBJS=$(find "$RELEASE_DIR/Cmlx.build" -name "*.o" 2>/dev/null) + if [ -z "$CMLX_OBJS" ]; then + echo "ERROR: No Cmlx objects. Run 'swift build -c release' first." + exit 1 + fi + LINK_FLAGS="$CMLX_OBJS -framework Metal -framework Foundation -framework Accelerate" + echo "Building STANDALONE dylibs (embedded MLX)..." +else + LINK_FLAGS="-Wl,-undefined,dynamic_lookup" + echo "Building DYNAMIC dylibs (shared host MLX)..." +fi + +for src in prefill_bridge_gemma prefill_bridge_qwen; do + dylib="$SRC_DIR/lib${src}.dylib" + echo " ${src}.cpp -> $dylib" + clang++ $COMMON -shared $LINK_FLAGS -o "$dylib" "$SRC_DIR/${src}.cpp" + cp "$dylib" "$RELEASE_DIR/" 2>/dev/null || true + TEST_BUNDLE="$RELEASE_DIR/mlx-swift-lmPackageTests.xctest/Contents/MacOS/" + cp "$dylib" "$TEST_BUNDLE" 2>/dev/null || true +done + +echo "Done." +ls -lh "$SRC_DIR"/libprefill_bridge_*.dylib diff --git a/scripts/setup-dev.sh b/scripts/setup-dev.sh new file mode 100755 index 0000000000..4ed5aca35d --- /dev/null +++ b/scripts/setup-dev.sh @@ -0,0 +1,84 @@ +#!/bin/bash +# setup-dev.sh +# Development environment setup for mlx-swift-lm. +# Compiles MLX Metal shaders and builds test targets for benchmarking. +# +# Run once after cloning or after fetching new mlx-swift changes: +# ./scripts/setup-dev.sh + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +ok() { echo -e "${GREEN} ✓${NC} $1"; } +warn() { echo -e "${YELLOW} ⚠${NC} $1"; } +fail() { echo -e "${RED} ✗${NC} $1"; exit 1; } + +echo "" +echo "Setting up mlx-swift-lm development environment..." +echo "" + +# ───────────────────────────────────────────── +# Prerequisites +# ───────────────────────────────────────────── +echo "Checking prerequisites..." + +# Xcode Command Line Tools +if ! xcode-select -p &>/dev/null; then + fail "Xcode Command Line Tools not found. Install with: xcode-select --install" +fi +ok "Xcode CLI tools: $(xcode-select -p)" + +# xcrun (Metal compiler) +if ! xcrun --find metal &>/dev/null 2>&1; then + fail "xcrun metal not found. Install Xcode or Xcode Command Line Tools." +fi +ok "xcrun metal: available" + +# Swift +if ! command -v swift &>/dev/null; then + fail "Swift not found. Install Xcode or Swift toolchain." +fi +SWIFT_VERSION=$(swift --version 2>&1 | grep -oE 'Swift version [0-9]+\.[0-9]+' | head -1) +ok "Swift: $SWIFT_VERSION" + +# ───────────────────────────────────────────── +# Resolve packages +# ───────────────────────────────────────────── +echo "" +echo "Resolving Swift package dependencies..." +cd "$PROJECT_ROOT" +swift package resolve +ok "Packages resolved" + +# ───────────────────────────────────────────── +# Build (SPM + Metal shaders + native dylibs) +# ───────────────────────────────────────────── +echo "" +echo "Building (make build-tests)..." +make -C "$PROJECT_ROOT" build-tests +ok "Build complete — all artifacts in place" + +# ───────────────────────────────────────────── +# Done +# ───────────────────────────────────────────── +echo "" +echo -e "${GREEN}✅ Setup complete!${NC}" +echo "" +echo "Run a quick benchmark:" +echo " ./scripts/benchmark.sh --model qwen35-0.8b --context 128" +echo "" +echo "Run a comprehensive benchmark sweep:" +echo " ./scripts/benchmark.sh --model qwen35-2b --quant all --kv all --quick" +echo "" +echo "See benchmarks/README.md for the full CLI reference." +echo "" +echo "Note: For unit tests (non-benchmark), use xcodebuild:" +echo " xcodebuild test -scheme mlx-swift-lm-Package -destination 'platform=macOS'" +echo ""